File:  [ELWIX - Embedded LightWeight unIX -] / elwix / files / sqlite / dist / sqlite3.c
Revision 1.6: download - view: text, annotated - select for diffs - revision graph
Mon Feb 13 16:52:48 2017 UTC (7 years, 4 months ago) by misho
Branches: MAIN
CVS tags: elwix2_6, HEAD, ELWIX2_5
ELWIX 2.5

    1: /******************************************************************************
    2: ** This file is an amalgamation of many separate C source files from SQLite
    3: ** version 3.14.2.  By combining all the individual C code files into this
    4: ** single large file, the entire code can be compiled as a single translation
    5: ** unit.  This allows many compilers to do optimizations that would not be
    6: ** possible if the files were compiled separately.  Performance improvements
    7: ** of 5% or more are commonly seen when SQLite is compiled as a single
    8: ** translation unit.
    9: **
   10: ** This file is all you need to compile SQLite.  To use SQLite in other
   11: ** programs, you need this file and the "sqlite3.h" header file that defines
   12: ** the programming interface to the SQLite library.  (If you do not have
   13: ** the "sqlite3.h" header file at hand, you will find a copy embedded within
   14: ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
   15: ** of the embedded sqlite3.h header file.) Additional code files may be needed
   16: ** if you want a wrapper to interface SQLite with your choice of programming
   17: ** language. The code for the "sqlite3" command-line shell is also in a
   18: ** separate file. This file contains only code for the core SQLite library.
   19: */
   20: #define SQLITE_CORE 1
   21: #define SQLITE_AMALGAMATION 1
   22: #ifndef SQLITE_PRIVATE
   23: # define SQLITE_PRIVATE static
   24: #endif
   25: /************** Begin file sqliteInt.h ***************************************/
   26: /*
   27: ** 2001 September 15
   28: **
   29: ** The author disclaims copyright to this source code.  In place of
   30: ** a legal notice, here is a blessing:
   31: **
   32: **    May you do good and not evil.
   33: **    May you find forgiveness for yourself and forgive others.
   34: **    May you share freely, never taking more than you give.
   35: **
   36: *************************************************************************
   37: ** Internal interface definitions for SQLite.
   38: **
   39: */
   40: #ifndef SQLITEINT_H
   41: #define SQLITEINT_H
   42: 
   43: /* Special Comments:
   44: **
   45: ** Some comments have special meaning to the tools that measure test
   46: ** coverage:
   47: **
   48: **    NO_TEST                     - The branches on this line are not
   49: **                                  measured by branch coverage.  This is
   50: **                                  used on lines of code that actually
   51: **                                  implement parts of coverage testing.
   52: **
   53: **    OPTIMIZATION-IF-TRUE        - This branch is allowed to alway be false
   54: **                                  and the correct answer is still obtained,
   55: **                                  though perhaps more slowly.
   56: **
   57: **    OPTIMIZATION-IF-FALSE       - This branch is allowed to alway be true
   58: **                                  and the correct answer is still obtained,
   59: **                                  though perhaps more slowly.
   60: **
   61: **    PREVENTS-HARMLESS-OVERREAD  - This branch prevents a buffer overread
   62: **                                  that would be harmless and undetectable
   63: **                                  if it did occur.  
   64: **
   65: ** In all cases, the special comment must be enclosed in the usual
   66: ** slash-asterisk...asterisk-slash comment marks, with no spaces between the 
   67: ** asterisks and the comment text.
   68: */
   69: 
   70: /*
   71: ** Make sure the Tcl calling convention macro is defined.  This macro is
   72: ** only used by test code and Tcl integration code.
   73: */
   74: #ifndef SQLITE_TCLAPI
   75: #  define SQLITE_TCLAPI
   76: #endif
   77: 
   78: /*
   79: ** Make sure that rand_s() is available on Windows systems with MSVC 2005
   80: ** or higher.
   81: */
   82: #if defined(_MSC_VER) && _MSC_VER>=1400
   83: #  define _CRT_RAND_S
   84: #endif
   85: 
   86: /*
   87: ** Include the header file used to customize the compiler options for MSVC.
   88: ** This should be done first so that it can successfully prevent spurious
   89: ** compiler warnings due to subsequent content in this file and other files
   90: ** that are included by this file.
   91: */
   92: /************** Include msvc.h in the middle of sqliteInt.h ******************/
   93: /************** Begin file msvc.h ********************************************/
   94: /*
   95: ** 2015 January 12
   96: **
   97: ** The author disclaims copyright to this source code.  In place of
   98: ** a legal notice, here is a blessing:
   99: **
  100: **    May you do good and not evil.
  101: **    May you find forgiveness for yourself and forgive others.
  102: **    May you share freely, never taking more than you give.
  103: **
  104: ******************************************************************************
  105: **
  106: ** This file contains code that is specific to MSVC.
  107: */
  108: #ifndef SQLITE_MSVC_H
  109: #define SQLITE_MSVC_H
  110: 
  111: #if defined(_MSC_VER)
  112: #pragma warning(disable : 4054)
  113: #pragma warning(disable : 4055)
  114: #pragma warning(disable : 4100)
  115: #pragma warning(disable : 4127)
  116: #pragma warning(disable : 4130)
  117: #pragma warning(disable : 4152)
  118: #pragma warning(disable : 4189)
  119: #pragma warning(disable : 4206)
  120: #pragma warning(disable : 4210)
  121: #pragma warning(disable : 4232)
  122: #pragma warning(disable : 4244)
  123: #pragma warning(disable : 4305)
  124: #pragma warning(disable : 4306)
  125: #pragma warning(disable : 4702)
  126: #pragma warning(disable : 4706)
  127: #endif /* defined(_MSC_VER) */
  128: 
  129: #endif /* SQLITE_MSVC_H */
  130: 
  131: /************** End of msvc.h ************************************************/
  132: /************** Continuing where we left off in sqliteInt.h ******************/
  133: 
  134: /*
  135: ** Special setup for VxWorks
  136: */
  137: /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  138: /************** Begin file vxworks.h *****************************************/
  139: /*
  140: ** 2015-03-02
  141: **
  142: ** The author disclaims copyright to this source code.  In place of
  143: ** a legal notice, here is a blessing:
  144: **
  145: **    May you do good and not evil.
  146: **    May you find forgiveness for yourself and forgive others.
  147: **    May you share freely, never taking more than you give.
  148: **
  149: ******************************************************************************
  150: **
  151: ** This file contains code that is specific to Wind River's VxWorks
  152: */
  153: #if defined(__RTP__) || defined(_WRS_KERNEL)
  154: /* This is VxWorks.  Set up things specially for that OS
  155: */
  156: #include <vxWorks.h>
  157: #include <pthread.h>  /* amalgamator: dontcache */
  158: #define OS_VXWORKS 1
  159: #define SQLITE_OS_OTHER 0
  160: #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  161: #define SQLITE_OMIT_LOAD_EXTENSION 1
  162: #define SQLITE_ENABLE_LOCKING_STYLE 0
  163: #define HAVE_UTIME 1
  164: #else
  165: /* This is not VxWorks. */
  166: #define OS_VXWORKS 0
  167: #define HAVE_FCHOWN 1
  168: #define HAVE_READLINK 1
  169: #define HAVE_LSTAT 1
  170: #endif /* defined(_WRS_KERNEL) */
  171: 
  172: /************** End of vxworks.h *********************************************/
  173: /************** Continuing where we left off in sqliteInt.h ******************/
  174: 
  175: /*
  176: ** These #defines should enable >2GB file support on POSIX if the
  177: ** underlying operating system supports it.  If the OS lacks
  178: ** large file support, or if the OS is windows, these should be no-ops.
  179: **
  180: ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
  181: ** system #includes.  Hence, this block of code must be the very first
  182: ** code in all source files.
  183: **
  184: ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  185: ** on the compiler command line.  This is necessary if you are compiling
  186: ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  187: ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
  188: ** without this option, LFS is enable.  But LFS does not exist in the kernel
  189: ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
  190: ** portability you should omit LFS.
  191: **
  192: ** The previous paragraph was written in 2005.  (This paragraph is written
  193: ** on 2008-11-28.) These days, all Linux kernels support large files, so
  194: ** you should probably leave LFS enabled.  But some embedded platforms might
  195: ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  196: **
  197: ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
  198: */
  199: #ifndef SQLITE_DISABLE_LFS
  200: # define _LARGE_FILE       1
  201: # ifndef _FILE_OFFSET_BITS
  202: #   define _FILE_OFFSET_BITS 64
  203: # endif
  204: # define _LARGEFILE_SOURCE 1
  205: #endif
  206: 
  207: /* What version of GCC is being used.  0 means GCC is not being used */
  208: #ifdef __GNUC__
  209: # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  210: #else
  211: # define GCC_VERSION 0
  212: #endif
  213: 
  214: /* Needed for various definitions... */
  215: #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  216: # define _GNU_SOURCE
  217: #endif
  218: 
  219: #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  220: # define _BSD_SOURCE
  221: #endif
  222: 
  223: /*
  224: ** For MinGW, check to see if we can include the header file containing its
  225: ** version information, among other things.  Normally, this internal MinGW
  226: ** header file would [only] be included automatically by other MinGW header
  227: ** files; however, the contained version information is now required by this
  228: ** header file to work around binary compatibility issues (see below) and
  229: ** this is the only known way to reliably obtain it.  This entire #if block
  230: ** would be completely unnecessary if there was any other way of detecting
  231: ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  232: ** some MinGW-specific macros).  When compiling for MinGW, either the
  233: ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  234: ** defined; otherwise, detection of conditions specific to MinGW will be
  235: ** disabled.
  236: */
  237: #if defined(_HAVE_MINGW_H)
  238: # include "mingw.h"
  239: #elif defined(_HAVE__MINGW_H)
  240: # include "_mingw.h"
  241: #endif
  242: 
  243: /*
  244: ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  245: ** define is required to maintain binary compatibility with the MSVC runtime
  246: ** library in use (e.g. for Windows XP).
  247: */
  248: #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  249:     defined(_WIN32) && !defined(_WIN64) && \
  250:     defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  251:     defined(__MSVCRT__)
  252: # define _USE_32BIT_TIME_T
  253: #endif
  254: 
  255: /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
  256: ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
  257: ** MinGW.
  258: */
  259: /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  260: /************** Begin file sqlite3.h *****************************************/
  261: /*
  262: ** 2001 September 15
  263: **
  264: ** The author disclaims copyright to this source code.  In place of
  265: ** a legal notice, here is a blessing:
  266: **
  267: **    May you do good and not evil.
  268: **    May you find forgiveness for yourself and forgive others.
  269: **    May you share freely, never taking more than you give.
  270: **
  271: *************************************************************************
  272: ** This header file defines the interface that the SQLite library
  273: ** presents to client programs.  If a C-function, structure, datatype,
  274: ** or constant definition does not appear in this file, then it is
  275: ** not a published API of SQLite, is subject to change without
  276: ** notice, and should not be referenced by programs that use SQLite.
  277: **
  278: ** Some of the definitions that are in this file are marked as
  279: ** "experimental".  Experimental interfaces are normally new
  280: ** features recently added to SQLite.  We do not anticipate changes
  281: ** to experimental interfaces but reserve the right to make minor changes
  282: ** if experience from use "in the wild" suggest such changes are prudent.
  283: **
  284: ** The official C-language API documentation for SQLite is derived
  285: ** from comments in this file.  This file is the authoritative source
  286: ** on how SQLite interfaces are supposed to operate.
  287: **
  288: ** The name of this file under configuration management is "sqlite.h.in".
  289: ** The makefile makes some minor changes to this file (such as inserting
  290: ** the version number) and changes its name to "sqlite3.h" as
  291: ** part of the build process.
  292: */
  293: #ifndef SQLITE3_H
  294: #define SQLITE3_H
  295: #include <stdarg.h>     /* Needed for the definition of va_list */
  296: 
  297: /*
  298: ** Make sure we can call this stuff from C++.
  299: */
  300: #if 0
  301: extern "C" {
  302: #endif
  303: 
  304: 
  305: /*
  306: ** Provide the ability to override linkage features of the interface.
  307: */
  308: #ifndef SQLITE_EXTERN
  309: # define SQLITE_EXTERN extern
  310: #endif
  311: #ifndef SQLITE_API
  312: # define SQLITE_API
  313: #endif
  314: #ifndef SQLITE_CDECL
  315: # define SQLITE_CDECL
  316: #endif
  317: #ifndef SQLITE_APICALL
  318: # define SQLITE_APICALL
  319: #endif
  320: #ifndef SQLITE_STDCALL
  321: # define SQLITE_STDCALL SQLITE_APICALL
  322: #endif
  323: #ifndef SQLITE_CALLBACK
  324: # define SQLITE_CALLBACK
  325: #endif
  326: #ifndef SQLITE_SYSAPI
  327: # define SQLITE_SYSAPI
  328: #endif
  329: 
  330: /*
  331: ** These no-op macros are used in front of interfaces to mark those
  332: ** interfaces as either deprecated or experimental.  New applications
  333: ** should not use deprecated interfaces - they are supported for backwards
  334: ** compatibility only.  Application writers should be aware that
  335: ** experimental interfaces are subject to change in point releases.
  336: **
  337: ** These macros used to resolve to various kinds of compiler magic that
  338: ** would generate warning messages when they were used.  But that
  339: ** compiler magic ended up generating such a flurry of bug reports
  340: ** that we have taken it all out and gone back to using simple
  341: ** noop macros.
  342: */
  343: #define SQLITE_DEPRECATED
  344: #define SQLITE_EXPERIMENTAL
  345: 
  346: /*
  347: ** Ensure these symbols were not defined by some previous header file.
  348: */
  349: #ifdef SQLITE_VERSION
  350: # undef SQLITE_VERSION
  351: #endif
  352: #ifdef SQLITE_VERSION_NUMBER
  353: # undef SQLITE_VERSION_NUMBER
  354: #endif
  355: 
  356: /*
  357: ** CAPI3REF: Compile-Time Library Version Numbers
  358: **
  359: ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  360: ** evaluates to a string literal that is the SQLite version in the
  361: ** format "X.Y.Z" where X is the major version number (always 3 for
  362: ** SQLite3) and Y is the minor version number and Z is the release number.)^
  363: ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  364: ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  365: ** numbers used in [SQLITE_VERSION].)^
  366: ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  367: ** be larger than the release from which it is derived.  Either Y will
  368: ** be held constant and Z will be incremented or else Y will be incremented
  369: ** and Z will be reset to zero.
  370: **
  371: ** Since version 3.6.18, SQLite source code has been stored in the
  372: ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  373: ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
  374: ** a string which identifies a particular check-in of SQLite
  375: ** within its configuration management system.  ^The SQLITE_SOURCE_ID
  376: ** string contains the date and time of the check-in (UTC) and an SHA1
  377: ** hash of the entire source tree.
  378: **
  379: ** See also: [sqlite3_libversion()],
  380: ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  381: ** [sqlite_version()] and [sqlite_source_id()].
  382: */
  383: #define SQLITE_VERSION        "3.14.2"
  384: #define SQLITE_VERSION_NUMBER 3014002
  385: #define SQLITE_SOURCE_ID      "2016-09-12 18:50:49 29dbef4b8585f753861a36d6dd102ca634197bd6"
  386: 
  387: /*
  388: ** CAPI3REF: Run-Time Library Version Numbers
  389: ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  390: **
  391: ** These interfaces provide the same information as the [SQLITE_VERSION],
  392: ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  393: ** but are associated with the library instead of the header file.  ^(Cautious
  394: ** programmers might include assert() statements in their application to
  395: ** verify that values returned by these interfaces match the macros in
  396: ** the header, and thus ensure that the application is
  397: ** compiled with matching library and header files.
  398: **
  399: ** <blockquote><pre>
  400: ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  401: ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  402: ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  403: ** </pre></blockquote>)^
  404: **
  405: ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  406: ** macro.  ^The sqlite3_libversion() function returns a pointer to the
  407: ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
  408: ** function is provided for use in DLLs since DLL users usually do not have
  409: ** direct access to string constants within the DLL.  ^The
  410: ** sqlite3_libversion_number() function returns an integer equal to
  411: ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
  412: ** a pointer to a string constant whose value is the same as the 
  413: ** [SQLITE_SOURCE_ID] C preprocessor macro.
  414: **
  415: ** See also: [sqlite_version()] and [sqlite_source_id()].
  416: */
  417: SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  418: SQLITE_API const char *sqlite3_libversion(void);
  419: SQLITE_API const char *sqlite3_sourceid(void);
  420: SQLITE_API int sqlite3_libversion_number(void);
  421: 
  422: /*
  423: ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  424: **
  425: ** ^The sqlite3_compileoption_used() function returns 0 or 1 
  426: ** indicating whether the specified option was defined at 
  427: ** compile time.  ^The SQLITE_ prefix may be omitted from the 
  428: ** option name passed to sqlite3_compileoption_used().  
  429: **
  430: ** ^The sqlite3_compileoption_get() function allows iterating
  431: ** over the list of options that were defined at compile time by
  432: ** returning the N-th compile time option string.  ^If N is out of range,
  433: ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
  434: ** prefix is omitted from any strings returned by 
  435: ** sqlite3_compileoption_get().
  436: **
  437: ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  438: ** and sqlite3_compileoption_get() may be omitted by specifying the 
  439: ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  440: **
  441: ** See also: SQL functions [sqlite_compileoption_used()] and
  442: ** [sqlite_compileoption_get()] and the [compile_options pragma].
  443: */
  444: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  445: SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  446: SQLITE_API const char *sqlite3_compileoption_get(int N);
  447: #endif
  448: 
  449: /*
  450: ** CAPI3REF: Test To See If The Library Is Threadsafe
  451: **
  452: ** ^The sqlite3_threadsafe() function returns zero if and only if
  453: ** SQLite was compiled with mutexing code omitted due to the
  454: ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  455: **
  456: ** SQLite can be compiled with or without mutexes.  When
  457: ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  458: ** are enabled and SQLite is threadsafe.  When the
  459: ** [SQLITE_THREADSAFE] macro is 0, 
  460: ** the mutexes are omitted.  Without the mutexes, it is not safe
  461: ** to use SQLite concurrently from more than one thread.
  462: **
  463: ** Enabling mutexes incurs a measurable performance penalty.
  464: ** So if speed is of utmost importance, it makes sense to disable
  465: ** the mutexes.  But for maximum safety, mutexes should be enabled.
  466: ** ^The default behavior is for mutexes to be enabled.
  467: **
  468: ** This interface can be used by an application to make sure that the
  469: ** version of SQLite that it is linking against was compiled with
  470: ** the desired setting of the [SQLITE_THREADSAFE] macro.
  471: **
  472: ** This interface only reports on the compile-time mutex setting
  473: ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
  474: ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  475: ** can be fully or partially disabled using a call to [sqlite3_config()]
  476: ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  477: ** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
  478: ** sqlite3_threadsafe() function shows only the compile-time setting of
  479: ** thread safety, not any run-time changes to that setting made by
  480: ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  481: ** is unchanged by calls to sqlite3_config().)^
  482: **
  483: ** See the [threading mode] documentation for additional information.
  484: */
  485: SQLITE_API int sqlite3_threadsafe(void);
  486: 
  487: /*
  488: ** CAPI3REF: Database Connection Handle
  489: ** KEYWORDS: {database connection} {database connections}
  490: **
  491: ** Each open SQLite database is represented by a pointer to an instance of
  492: ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
  493: ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
  494: ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  495: ** and [sqlite3_close_v2()] are its destructors.  There are many other
  496: ** interfaces (such as
  497: ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  498: ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  499: ** sqlite3 object.
  500: */
  501: typedef struct sqlite3 sqlite3;
  502: 
  503: /*
  504: ** CAPI3REF: 64-Bit Integer Types
  505: ** KEYWORDS: sqlite_int64 sqlite_uint64
  506: **
  507: ** Because there is no cross-platform way to specify 64-bit integer types
  508: ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  509: **
  510: ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  511: ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  512: ** compatibility only.
  513: **
  514: ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  515: ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
  516: ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
  517: ** between 0 and +18446744073709551615 inclusive.
  518: */
  519: #ifdef SQLITE_INT64_TYPE
  520:   typedef SQLITE_INT64_TYPE sqlite_int64;
  521:   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  522: #elif defined(_MSC_VER) || defined(__BORLANDC__)
  523:   typedef __int64 sqlite_int64;
  524:   typedef unsigned __int64 sqlite_uint64;
  525: #else
  526:   typedef long long int sqlite_int64;
  527:   typedef unsigned long long int sqlite_uint64;
  528: #endif
  529: typedef sqlite_int64 sqlite3_int64;
  530: typedef sqlite_uint64 sqlite3_uint64;
  531: 
  532: /*
  533: ** If compiling for a processor that lacks floating point support,
  534: ** substitute integer for floating-point.
  535: */
  536: #ifdef SQLITE_OMIT_FLOATING_POINT
  537: # define double sqlite3_int64
  538: #endif
  539: 
  540: /*
  541: ** CAPI3REF: Closing A Database Connection
  542: ** DESTRUCTOR: sqlite3
  543: **
  544: ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  545: ** for the [sqlite3] object.
  546: ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  547: ** the [sqlite3] object is successfully destroyed and all associated
  548: ** resources are deallocated.
  549: **
  550: ** ^If the database connection is associated with unfinalized prepared
  551: ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  552: ** will leave the database connection open and return [SQLITE_BUSY].
  553: ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  554: ** and/or unfinished sqlite3_backups, then the database connection becomes
  555: ** an unusable "zombie" which will automatically be deallocated when the
  556: ** last prepared statement is finalized or the last sqlite3_backup is
  557: ** finished.  The sqlite3_close_v2() interface is intended for use with
  558: ** host languages that are garbage collected, and where the order in which
  559: ** destructors are called is arbitrary.
  560: **
  561: ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  562: ** [sqlite3_blob_close | close] all [BLOB handles], and 
  563: ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  564: ** with the [sqlite3] object prior to attempting to close the object.  ^If
  565: ** sqlite3_close_v2() is called on a [database connection] that still has
  566: ** outstanding [prepared statements], [BLOB handles], and/or
  567: ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  568: ** of resources is deferred until all [prepared statements], [BLOB handles],
  569: ** and [sqlite3_backup] objects are also destroyed.
  570: **
  571: ** ^If an [sqlite3] object is destroyed while a transaction is open,
  572: ** the transaction is automatically rolled back.
  573: **
  574: ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  575: ** must be either a NULL
  576: ** pointer or an [sqlite3] object pointer obtained
  577: ** from [sqlite3_open()], [sqlite3_open16()], or
  578: ** [sqlite3_open_v2()], and not previously closed.
  579: ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  580: ** argument is a harmless no-op.
  581: */
  582: SQLITE_API int sqlite3_close(sqlite3*);
  583: SQLITE_API int sqlite3_close_v2(sqlite3*);
  584: 
  585: /*
  586: ** The type for a callback function.
  587: ** This is legacy and deprecated.  It is included for historical
  588: ** compatibility and is not documented.
  589: */
  590: typedef int (*sqlite3_callback)(void*,int,char**, char**);
  591: 
  592: /*
  593: ** CAPI3REF: One-Step Query Execution Interface
  594: ** METHOD: sqlite3
  595: **
  596: ** The sqlite3_exec() interface is a convenience wrapper around
  597: ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  598: ** that allows an application to run multiple statements of SQL
  599: ** without having to use a lot of C code. 
  600: **
  601: ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  602: ** semicolon-separate SQL statements passed into its 2nd argument,
  603: ** in the context of the [database connection] passed in as its 1st
  604: ** argument.  ^If the callback function of the 3rd argument to
  605: ** sqlite3_exec() is not NULL, then it is invoked for each result row
  606: ** coming out of the evaluated SQL statements.  ^The 4th argument to
  607: ** sqlite3_exec() is relayed through to the 1st argument of each
  608: ** callback invocation.  ^If the callback pointer to sqlite3_exec()
  609: ** is NULL, then no callback is ever invoked and result rows are
  610: ** ignored.
  611: **
  612: ** ^If an error occurs while evaluating the SQL statements passed into
  613: ** sqlite3_exec(), then execution of the current statement stops and
  614: ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
  615: ** is not NULL then any error message is written into memory obtained
  616: ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  617: ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  618: ** on error message strings returned through the 5th parameter of
  619: ** sqlite3_exec() after the error message string is no longer needed.
  620: ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  621: ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  622: ** NULL before returning.
  623: **
  624: ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  625: ** routine returns SQLITE_ABORT without invoking the callback again and
  626: ** without running any subsequent SQL statements.
  627: **
  628: ** ^The 2nd argument to the sqlite3_exec() callback function is the
  629: ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
  630: ** callback is an array of pointers to strings obtained as if from
  631: ** [sqlite3_column_text()], one for each column.  ^If an element of a
  632: ** result row is NULL then the corresponding string pointer for the
  633: ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
  634: ** sqlite3_exec() callback is an array of pointers to strings where each
  635: ** entry represents the name of corresponding result column as obtained
  636: ** from [sqlite3_column_name()].
  637: **
  638: ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  639: ** to an empty string, or a pointer that contains only whitespace and/or 
  640: ** SQL comments, then no SQL statements are evaluated and the database
  641: ** is not changed.
  642: **
  643: ** Restrictions:
  644: **
  645: ** <ul>
  646: ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  647: **      is a valid and open [database connection].
  648: ** <li> The application must not close the [database connection] specified by
  649: **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  650: ** <li> The application must not modify the SQL statement text passed into
  651: **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  652: ** </ul>
  653: */
  654: SQLITE_API int sqlite3_exec(
  655:   sqlite3*,                                  /* An open database */
  656:   const char *sql,                           /* SQL to be evaluated */
  657:   int (*callback)(void*,int,char**,char**),  /* Callback function */
  658:   void *,                                    /* 1st argument to callback */
  659:   char **errmsg                              /* Error msg written here */
  660: );
  661: 
  662: /*
  663: ** CAPI3REF: Result Codes
  664: ** KEYWORDS: {result code definitions}
  665: **
  666: ** Many SQLite functions return an integer result code from the set shown
  667: ** here in order to indicate success or failure.
  668: **
  669: ** New error codes may be added in future versions of SQLite.
  670: **
  671: ** See also: [extended result code definitions]
  672: */
  673: #define SQLITE_OK           0   /* Successful result */
  674: /* beginning-of-error-codes */
  675: #define SQLITE_ERROR        1   /* SQL error or missing database */
  676: #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
  677: #define SQLITE_PERM         3   /* Access permission denied */
  678: #define SQLITE_ABORT        4   /* Callback routine requested an abort */
  679: #define SQLITE_BUSY         5   /* The database file is locked */
  680: #define SQLITE_LOCKED       6   /* A table in the database is locked */
  681: #define SQLITE_NOMEM        7   /* A malloc() failed */
  682: #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
  683: #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
  684: #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
  685: #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
  686: #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
  687: #define SQLITE_FULL        13   /* Insertion failed because database is full */
  688: #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
  689: #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
  690: #define SQLITE_EMPTY       16   /* Database is empty */
  691: #define SQLITE_SCHEMA      17   /* The database schema changed */
  692: #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
  693: #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
  694: #define SQLITE_MISMATCH    20   /* Data type mismatch */
  695: #define SQLITE_MISUSE      21   /* Library used incorrectly */
  696: #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
  697: #define SQLITE_AUTH        23   /* Authorization denied */
  698: #define SQLITE_FORMAT      24   /* Auxiliary database format error */
  699: #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
  700: #define SQLITE_NOTADB      26   /* File opened that is not a database file */
  701: #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
  702: #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
  703: #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
  704: #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
  705: /* end-of-error-codes */
  706: 
  707: /*
  708: ** CAPI3REF: Extended Result Codes
  709: ** KEYWORDS: {extended result code definitions}
  710: **
  711: ** In its default configuration, SQLite API routines return one of 30 integer
  712: ** [result codes].  However, experience has shown that many of
  713: ** these result codes are too coarse-grained.  They do not provide as
  714: ** much information about problems as programmers might like.  In an effort to
  715: ** address this, newer versions of SQLite (version 3.3.8 and later) include
  716: ** support for additional result codes that provide more detailed information
  717: ** about errors. These [extended result codes] are enabled or disabled
  718: ** on a per database connection basis using the
  719: ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
  720: ** the most recent error can be obtained using
  721: ** [sqlite3_extended_errcode()].
  722: */
  723: #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
  724: #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
  725: #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
  726: #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
  727: #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
  728: #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
  729: #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
  730: #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
  731: #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
  732: #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
  733: #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
  734: #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
  735: #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
  736: #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  737: #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
  738: #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
  739: #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
  740: #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
  741: #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
  742: #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
  743: #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
  744: #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
  745: #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
  746: #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
  747: #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
  748: #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
  749: #define SQLITE_IOERR_VNODE             (SQLITE_IOERR | (27<<8))
  750: #define SQLITE_IOERR_AUTH              (SQLITE_IOERR | (28<<8))
  751: #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
  752: #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
  753: #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
  754: #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
  755: #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
  756: #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
  757: #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
  758: #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
  759: #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
  760: #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
  761: #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
  762: #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
  763: #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
  764: #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
  765: #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
  766: #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
  767: #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
  768: #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
  769: #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
  770: #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
  771: #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
  772: #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
  773: #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
  774: #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
  775: #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  776: #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
  777: #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
  778: #define SQLITE_OK_LOAD_PERMANENTLY     (SQLITE_OK | (1<<8))
  779: 
  780: /*
  781: ** CAPI3REF: Flags For File Open Operations
  782: **
  783: ** These bit values are intended for use in the
  784: ** 3rd parameter to the [sqlite3_open_v2()] interface and
  785: ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  786: */
  787: #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
  788: #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
  789: #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
  790: #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
  791: #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
  792: #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
  793: #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
  794: #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
  795: #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
  796: #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
  797: #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
  798: #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
  799: #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
  800: #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
  801: #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
  802: #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
  803: #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
  804: #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
  805: #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
  806: #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
  807: 
  808: /* Reserved:                         0x00F00000 */
  809: 
  810: /*
  811: ** CAPI3REF: Device Characteristics
  812: **
  813: ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  814: ** object returns an integer which is a vector of these
  815: ** bit values expressing I/O characteristics of the mass storage
  816: ** device that holds the file that the [sqlite3_io_methods]
  817: ** refers to.
  818: **
  819: ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  820: ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
  821: ** mean that writes of blocks that are nnn bytes in size and
  822: ** are aligned to an address which is an integer multiple of
  823: ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
  824: ** that when data is appended to a file, the data is appended
  825: ** first then the size of the file is extended, never the other
  826: ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
  827: ** information is written to disk in the same order as calls
  828: ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  829: ** after reboot following a crash or power loss, the only bytes in a
  830: ** file that were written at the application level might have changed
  831: ** and that adjacent bytes, even bytes within the same sector are
  832: ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  833: ** flag indicate that a file cannot be deleted when open.  The
  834: ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  835: ** read-only media and cannot be changed even by processes with
  836: ** elevated privileges.
  837: */
  838: #define SQLITE_IOCAP_ATOMIC                 0x00000001
  839: #define SQLITE_IOCAP_ATOMIC512              0x00000002
  840: #define SQLITE_IOCAP_ATOMIC1K               0x00000004
  841: #define SQLITE_IOCAP_ATOMIC2K               0x00000008
  842: #define SQLITE_IOCAP_ATOMIC4K               0x00000010
  843: #define SQLITE_IOCAP_ATOMIC8K               0x00000020
  844: #define SQLITE_IOCAP_ATOMIC16K              0x00000040
  845: #define SQLITE_IOCAP_ATOMIC32K              0x00000080
  846: #define SQLITE_IOCAP_ATOMIC64K              0x00000100
  847: #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
  848: #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
  849: #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
  850: #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
  851: #define SQLITE_IOCAP_IMMUTABLE              0x00002000
  852: 
  853: /*
  854: ** CAPI3REF: File Locking Levels
  855: **
  856: ** SQLite uses one of these integer values as the second
  857: ** argument to calls it makes to the xLock() and xUnlock() methods
  858: ** of an [sqlite3_io_methods] object.
  859: */
  860: #define SQLITE_LOCK_NONE          0
  861: #define SQLITE_LOCK_SHARED        1
  862: #define SQLITE_LOCK_RESERVED      2
  863: #define SQLITE_LOCK_PENDING       3
  864: #define SQLITE_LOCK_EXCLUSIVE     4
  865: 
  866: /*
  867: ** CAPI3REF: Synchronization Type Flags
  868: **
  869: ** When SQLite invokes the xSync() method of an
  870: ** [sqlite3_io_methods] object it uses a combination of
  871: ** these integer values as the second argument.
  872: **
  873: ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  874: ** sync operation only needs to flush data to mass storage.  Inode
  875: ** information need not be flushed. If the lower four bits of the flag
  876: ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  877: ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  878: ** to use Mac OS X style fullsync instead of fsync().
  879: **
  880: ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  881: ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  882: ** settings.  The [synchronous pragma] determines when calls to the
  883: ** xSync VFS method occur and applies uniformly across all platforms.
  884: ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  885: ** energetic or rigorous or forceful the sync operations are and
  886: ** only make a difference on Mac OSX for the default SQLite code.
  887: ** (Third-party VFS implementations might also make the distinction
  888: ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  889: ** operating systems natively supported by SQLite, only Mac OSX
  890: ** cares about the difference.)
  891: */
  892: #define SQLITE_SYNC_NORMAL        0x00002
  893: #define SQLITE_SYNC_FULL          0x00003
  894: #define SQLITE_SYNC_DATAONLY      0x00010
  895: 
  896: /*
  897: ** CAPI3REF: OS Interface Open File Handle
  898: **
  899: ** An [sqlite3_file] object represents an open file in the 
  900: ** [sqlite3_vfs | OS interface layer].  Individual OS interface
  901: ** implementations will
  902: ** want to subclass this object by appending additional fields
  903: ** for their own use.  The pMethods entry is a pointer to an
  904: ** [sqlite3_io_methods] object that defines methods for performing
  905: ** I/O operations on the open file.
  906: */
  907: typedef struct sqlite3_file sqlite3_file;
  908: struct sqlite3_file {
  909:   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
  910: };
  911: 
  912: /*
  913: ** CAPI3REF: OS Interface File Virtual Methods Object
  914: **
  915: ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  916: ** [sqlite3_file] object (or, more commonly, a subclass of the
  917: ** [sqlite3_file] object) with a pointer to an instance of this object.
  918: ** This object defines the methods used to perform various operations
  919: ** against the open file represented by the [sqlite3_file] object.
  920: **
  921: ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
  922: ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  923: ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
  924: ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  925: ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  926: ** to NULL.
  927: **
  928: ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  929: ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
  930: ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
  931: ** flag may be ORed in to indicate that only the data of the file
  932: ** and not its inode needs to be synced.
  933: **
  934: ** The integer values to xLock() and xUnlock() are one of
  935: ** <ul>
  936: ** <li> [SQLITE_LOCK_NONE],
  937: ** <li> [SQLITE_LOCK_SHARED],
  938: ** <li> [SQLITE_LOCK_RESERVED],
  939: ** <li> [SQLITE_LOCK_PENDING], or
  940: ** <li> [SQLITE_LOCK_EXCLUSIVE].
  941: ** </ul>
  942: ** xLock() increases the lock. xUnlock() decreases the lock.
  943: ** The xCheckReservedLock() method checks whether any database connection,
  944: ** either in this process or in some other process, is holding a RESERVED,
  945: ** PENDING, or EXCLUSIVE lock on the file.  It returns true
  946: ** if such a lock exists and false otherwise.
  947: **
  948: ** The xFileControl() method is a generic interface that allows custom
  949: ** VFS implementations to directly control an open file using the
  950: ** [sqlite3_file_control()] interface.  The second "op" argument is an
  951: ** integer opcode.  The third argument is a generic pointer intended to
  952: ** point to a structure that may contain arguments or space in which to
  953: ** write return values.  Potential uses for xFileControl() might be
  954: ** functions to enable blocking locks with timeouts, to change the
  955: ** locking strategy (for example to use dot-file locks), to inquire
  956: ** about the status of a lock, or to break stale locks.  The SQLite
  957: ** core reserves all opcodes less than 100 for its own use.
  958: ** A [file control opcodes | list of opcodes] less than 100 is available.
  959: ** Applications that define a custom xFileControl method should use opcodes
  960: ** greater than 100 to avoid conflicts.  VFS implementations should
  961: ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  962: ** recognize.
  963: **
  964: ** The xSectorSize() method returns the sector size of the
  965: ** device that underlies the file.  The sector size is the
  966: ** minimum write that can be performed without disturbing
  967: ** other bytes in the file.  The xDeviceCharacteristics()
  968: ** method returns a bit vector describing behaviors of the
  969: ** underlying device:
  970: **
  971: ** <ul>
  972: ** <li> [SQLITE_IOCAP_ATOMIC]
  973: ** <li> [SQLITE_IOCAP_ATOMIC512]
  974: ** <li> [SQLITE_IOCAP_ATOMIC1K]
  975: ** <li> [SQLITE_IOCAP_ATOMIC2K]
  976: ** <li> [SQLITE_IOCAP_ATOMIC4K]
  977: ** <li> [SQLITE_IOCAP_ATOMIC8K]
  978: ** <li> [SQLITE_IOCAP_ATOMIC16K]
  979: ** <li> [SQLITE_IOCAP_ATOMIC32K]
  980: ** <li> [SQLITE_IOCAP_ATOMIC64K]
  981: ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  982: ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  983: ** </ul>
  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: ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  997: ** in the unread portions of the buffer with zeros.  A VFS that
  998: ** fails to zero-fill short reads might seem to work.  However,
  999: ** failure to zero-fill short reads will eventually lead to
 1000: ** database corruption.
 1001: */
 1002: typedef struct sqlite3_io_methods sqlite3_io_methods;
 1003: struct sqlite3_io_methods {
 1004:   int iVersion;
 1005:   int (*xClose)(sqlite3_file*);
 1006:   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
 1007:   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
 1008:   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
 1009:   int (*xSync)(sqlite3_file*, int flags);
 1010:   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
 1011:   int (*xLock)(sqlite3_file*, int);
 1012:   int (*xUnlock)(sqlite3_file*, int);
 1013:   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
 1014:   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
 1015:   int (*xSectorSize)(sqlite3_file*);
 1016:   int (*xDeviceCharacteristics)(sqlite3_file*);
 1017:   /* Methods above are valid for version 1 */
 1018:   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
 1019:   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
 1020:   void (*xShmBarrier)(sqlite3_file*);
 1021:   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
 1022:   /* Methods above are valid for version 2 */
 1023:   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
 1024:   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
 1025:   /* Methods above are valid for version 3 */
 1026:   /* Additional methods may be added in future releases */
 1027: };
 1028: 
 1029: /*
 1030: ** CAPI3REF: Standard File Control Opcodes
 1031: ** KEYWORDS: {file control opcodes} {file control opcode}
 1032: **
 1033: ** These integer constants are opcodes for the xFileControl method
 1034: ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
 1035: ** interface.
 1036: **
 1037: ** <ul>
 1038: ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
 1039: ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
 1040: ** opcode causes the xFileControl method to write the current state of
 1041: ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
 1042: ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
 1043: ** into an integer that the pArg argument points to. This capability
 1044: ** is used during testing and is only available when the SQLITE_TEST
 1045: ** compile-time option is used.
 1046: **
 1047: ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
 1048: ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
 1049: ** layer a hint of how large the database file will grow to be during the
 1050: ** current transaction.  This hint is not guaranteed to be accurate but it
 1051: ** is often close.  The underlying VFS might choose to preallocate database
 1052: ** file space based on this hint in order to help writes to the database
 1053: ** file run faster.
 1054: **
 1055: ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
 1056: ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
 1057: ** extends and truncates the database file in chunks of a size specified
 1058: ** by the user. The fourth argument to [sqlite3_file_control()] should 
 1059: ** point to an integer (type int) containing the new chunk-size to use
 1060: ** for the nominated database. Allocating database file space in large
 1061: ** chunks (say 1MB at a time), may reduce file-system fragmentation and
 1062: ** improve performance on some systems.
 1063: **
 1064: ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
 1065: ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
 1066: ** to the [sqlite3_file] object associated with a particular database
 1067: ** connection.  See also [SQLITE_FCNTL_JOURNAL_POINTER].
 1068: **
 1069: ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
 1070: ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
 1071: ** to the [sqlite3_file] object associated with the journal file (either
 1072: ** the [rollback journal] or the [write-ahead log]) for a particular database
 1073: ** connection.  See also [SQLITE_FCNTL_FILE_POINTER].
 1074: **
 1075: ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
 1076: ** No longer in use.
 1077: **
 1078: ** <li>[[SQLITE_FCNTL_SYNC]]
 1079: ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
 1080: ** sent to the VFS immediately before the xSync method is invoked on a
 1081: ** database file descriptor. Or, if the xSync method is not invoked 
 1082: ** because the user has configured SQLite with 
 1083: ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place 
 1084: ** of the xSync method. In most cases, the pointer argument passed with
 1085: ** this file-control is NULL. However, if the database file is being synced
 1086: ** as part of a multi-database commit, the argument points to a nul-terminated
 1087: ** string containing the transactions master-journal file name. VFSes that 
 1088: ** do not need this signal should silently ignore this opcode. Applications 
 1089: ** should not call [sqlite3_file_control()] with this opcode as doing so may 
 1090: ** disrupt the operation of the specialized VFSes that do require it.  
 1091: **
 1092: ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
 1093: ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
 1094: ** and sent to the VFS after a transaction has been committed immediately
 1095: ** but before the database is unlocked. VFSes that do not need this signal
 1096: ** should silently ignore this opcode. Applications should not call
 1097: ** [sqlite3_file_control()] with this opcode as doing so may disrupt the 
 1098: ** operation of the specialized VFSes that do require it.  
 1099: **
 1100: ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
 1101: ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
 1102: ** retry counts and intervals for certain disk I/O operations for the
 1103: ** windows [VFS] in order to provide robustness in the presence of
 1104: ** anti-virus programs.  By default, the windows VFS will retry file read,
 1105: ** file write, and file delete operations up to 10 times, with a delay
 1106: ** of 25 milliseconds before the first retry and with the delay increasing
 1107: ** by an additional 25 milliseconds with each subsequent retry.  This
 1108: ** opcode allows these two values (10 retries and 25 milliseconds of delay)
 1109: ** to be adjusted.  The values are changed for all database connections
 1110: ** within the same process.  The argument is a pointer to an array of two
 1111: ** integers where the first integer i the new retry count and the second
 1112: ** integer is the delay.  If either integer is negative, then the setting
 1113: ** is not changed but instead the prior value of that setting is written
 1114: ** into the array entry, allowing the current retry settings to be
 1115: ** interrogated.  The zDbName parameter is ignored.
 1116: **
 1117: ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
 1118: ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
 1119: ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
 1120: ** write ahead log and shared memory files used for transaction control
 1121: ** are automatically deleted when the latest connection to the database
 1122: ** closes.  Setting persistent WAL mode causes those files to persist after
 1123: ** close.  Persisting the files is useful when other processes that do not
 1124: ** have write permission on the directory containing the database file want
 1125: ** to read the database file, as the WAL and shared memory files must exist
 1126: ** in order for the database to be readable.  The fourth parameter to
 1127: ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
 1128: ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
 1129: ** WAL mode.  If the integer is -1, then it is overwritten with the current
 1130: ** WAL persistence setting.
 1131: **
 1132: ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
 1133: ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
 1134: ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
 1135: ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
 1136: ** xDeviceCharacteristics methods. The fourth parameter to
 1137: ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
 1138: ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
 1139: ** mode.  If the integer is -1, then it is overwritten with the current
 1140: ** zero-damage mode setting.
 1141: **
 1142: ** <li>[[SQLITE_FCNTL_OVERWRITE]]
 1143: ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
 1144: ** a write transaction to indicate that, unless it is rolled back for some
 1145: ** reason, the entire database file will be overwritten by the current 
 1146: ** transaction. This is used by VACUUM operations.
 1147: **
 1148: ** <li>[[SQLITE_FCNTL_VFSNAME]]
 1149: ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
 1150: ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
 1151: ** final bottom-level VFS are written into memory obtained from 
 1152: ** [sqlite3_malloc()] and the result is stored in the char* variable
 1153: ** that the fourth parameter of [sqlite3_file_control()] points to.
 1154: ** The caller is responsible for freeing the memory when done.  As with
 1155: ** all file-control actions, there is no guarantee that this will actually
 1156: ** do anything.  Callers should initialize the char* variable to a NULL
 1157: ** pointer in case this file-control is not implemented.  This file-control
 1158: ** is intended for diagnostic use only.
 1159: **
 1160: ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
 1161: ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
 1162: ** [VFSes] currently in use.  ^(The argument X in
 1163: ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
 1164: ** of type "[sqlite3_vfs] **".  This opcodes will set *X
 1165: ** to a pointer to the top-level VFS.)^
 1166: ** ^When there are multiple VFS shims in the stack, this opcode finds the
 1167: ** upper-most shim only.
 1168: **
 1169: ** <li>[[SQLITE_FCNTL_PRAGMA]]
 1170: ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
 1171: ** file control is sent to the open [sqlite3_file] object corresponding
 1172: ** to the database file to which the pragma statement refers. ^The argument
 1173: ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
 1174: ** pointers to strings (char**) in which the second element of the array
 1175: ** is the name of the pragma and the third element is the argument to the
 1176: ** pragma or NULL if the pragma has no argument.  ^The handler for an
 1177: ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
 1178: ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
 1179: ** or the equivalent and that string will become the result of the pragma or
 1180: ** the error message if the pragma fails. ^If the
 1181: ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
 1182: ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
 1183: ** file control returns [SQLITE_OK], then the parser assumes that the
 1184: ** VFS has handled the PRAGMA itself and the parser generates a no-op
 1185: ** prepared statement if result string is NULL, or that returns a copy
 1186: ** of the result string if the string is non-NULL.
 1187: ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
 1188: ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
 1189: ** that the VFS encountered an error while handling the [PRAGMA] and the
 1190: ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
 1191: ** file control occurs at the beginning of pragma statement analysis and so
 1192: ** it is able to override built-in [PRAGMA] statements.
 1193: **
 1194: ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
 1195: ** ^The [SQLITE_FCNTL_BUSYHANDLER]
 1196: ** file-control may be invoked by SQLite on the database file handle
 1197: ** shortly after it is opened in order to provide a custom VFS with access
 1198: ** to the connections busy-handler callback. The argument is of type (void **)
 1199: ** - an array of two (void *) values. The first (void *) actually points
 1200: ** to a function of type (int (*)(void *)). In order to invoke the connections
 1201: ** busy-handler, this function should be invoked with the second (void *) in
 1202: ** the array as the only argument. If it returns non-zero, then the operation
 1203: ** should be retried. If it returns zero, the custom VFS should abandon the
 1204: ** current operation.
 1205: **
 1206: ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
 1207: ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
 1208: ** to have SQLite generate a
 1209: ** temporary filename using the same algorithm that is followed to generate
 1210: ** temporary filenames for TEMP tables and other internal uses.  The
 1211: ** argument should be a char** which will be filled with the filename
 1212: ** written into memory obtained from [sqlite3_malloc()].  The caller should
 1213: ** invoke [sqlite3_free()] on the result to avoid a memory leak.
 1214: **
 1215: ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
 1216: ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
 1217: ** maximum number of bytes that will be used for memory-mapped I/O.
 1218: ** The argument is a pointer to a value of type sqlite3_int64 that
 1219: ** is an advisory maximum number of bytes in the file to memory map.  The
 1220: ** pointer is overwritten with the old value.  The limit is not changed if
 1221: ** the value originally pointed to is negative, and so the current limit 
 1222: ** can be queried by passing in a pointer to a negative number.  This
 1223: ** file-control is used internally to implement [PRAGMA mmap_size].
 1224: **
 1225: ** <li>[[SQLITE_FCNTL_TRACE]]
 1226: ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
 1227: ** to the VFS about what the higher layers of the SQLite stack are doing.
 1228: ** This file control is used by some VFS activity tracing [shims].
 1229: ** The argument is a zero-terminated string.  Higher layers in the
 1230: ** SQLite stack may generate instances of this file control if
 1231: ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
 1232: **
 1233: ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
 1234: ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
 1235: ** pointer to an integer and it writes a boolean into that integer depending
 1236: ** on whether or not the file has been renamed, moved, or deleted since it
 1237: ** was first opened.
 1238: **
 1239: ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
 1240: ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
 1241: ** opcode causes the xFileControl method to swap the file handle with the one
 1242: ** pointed to by the pArg argument.  This capability is used during testing
 1243: ** and only needs to be supported when SQLITE_TEST is defined.
 1244: **
 1245: ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
 1246: ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
 1247: ** be advantageous to block on the next WAL lock if the lock is not immediately
 1248: ** available.  The WAL subsystem issues this signal during rare
 1249: ** circumstances in order to fix a problem with priority inversion.
 1250: ** Applications should <em>not</em> use this file-control.
 1251: **
 1252: ** <li>[[SQLITE_FCNTL_ZIPVFS]]
 1253: ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
 1254: ** VFS should return SQLITE_NOTFOUND for this opcode.
 1255: **
 1256: ** <li>[[SQLITE_FCNTL_RBU]]
 1257: ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
 1258: ** the RBU extension only.  All other VFS should return SQLITE_NOTFOUND for
 1259: ** this opcode.  
 1260: ** </ul>
 1261: */
 1262: #define SQLITE_FCNTL_LOCKSTATE               1
 1263: #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
 1264: #define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
 1265: #define SQLITE_FCNTL_LAST_ERRNO              4
 1266: #define SQLITE_FCNTL_SIZE_HINT               5
 1267: #define SQLITE_FCNTL_CHUNK_SIZE              6
 1268: #define SQLITE_FCNTL_FILE_POINTER            7
 1269: #define SQLITE_FCNTL_SYNC_OMITTED            8
 1270: #define SQLITE_FCNTL_WIN32_AV_RETRY          9
 1271: #define SQLITE_FCNTL_PERSIST_WAL            10
 1272: #define SQLITE_FCNTL_OVERWRITE              11
 1273: #define SQLITE_FCNTL_VFSNAME                12
 1274: #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
 1275: #define SQLITE_FCNTL_PRAGMA                 14
 1276: #define SQLITE_FCNTL_BUSYHANDLER            15
 1277: #define SQLITE_FCNTL_TEMPFILENAME           16
 1278: #define SQLITE_FCNTL_MMAP_SIZE              18
 1279: #define SQLITE_FCNTL_TRACE                  19
 1280: #define SQLITE_FCNTL_HAS_MOVED              20
 1281: #define SQLITE_FCNTL_SYNC                   21
 1282: #define SQLITE_FCNTL_COMMIT_PHASETWO        22
 1283: #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
 1284: #define SQLITE_FCNTL_WAL_BLOCK              24
 1285: #define SQLITE_FCNTL_ZIPVFS                 25
 1286: #define SQLITE_FCNTL_RBU                    26
 1287: #define SQLITE_FCNTL_VFS_POINTER            27
 1288: #define SQLITE_FCNTL_JOURNAL_POINTER        28
 1289: 
 1290: /* deprecated names */
 1291: #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
 1292: #define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
 1293: #define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
 1294: 
 1295: 
 1296: /*
 1297: ** CAPI3REF: Mutex Handle
 1298: **
 1299: ** The mutex module within SQLite defines [sqlite3_mutex] to be an
 1300: ** abstract type for a mutex object.  The SQLite core never looks
 1301: ** at the internal representation of an [sqlite3_mutex].  It only
 1302: ** deals with pointers to the [sqlite3_mutex] object.
 1303: **
 1304: ** Mutexes are created using [sqlite3_mutex_alloc()].
 1305: */
 1306: typedef struct sqlite3_mutex sqlite3_mutex;
 1307: 
 1308: /*
 1309: ** CAPI3REF: Loadable Extension Thunk
 1310: **
 1311: ** A pointer to the opaque sqlite3_api_routines structure is passed as
 1312: ** the third parameter to entry points of [loadable extensions].  This
 1313: ** structure must be typedefed in order to work around compiler warnings
 1314: ** on some platforms.
 1315: */
 1316: typedef struct sqlite3_api_routines sqlite3_api_routines;
 1317: 
 1318: /*
 1319: ** CAPI3REF: OS Interface Object
 1320: **
 1321: ** An instance of the sqlite3_vfs object defines the interface between
 1322: ** the SQLite core and the underlying operating system.  The "vfs"
 1323: ** in the name of the object stands for "virtual file system".  See
 1324: ** the [VFS | VFS documentation] for further information.
 1325: **
 1326: ** The value of the iVersion field is initially 1 but may be larger in
 1327: ** future versions of SQLite.  Additional fields may be appended to this
 1328: ** object when the iVersion value is increased.  Note that the structure
 1329: ** of the sqlite3_vfs object changes in the transaction between
 1330: ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
 1331: ** modified.
 1332: **
 1333: ** The szOsFile field is the size of the subclassed [sqlite3_file]
 1334: ** structure used by this VFS.  mxPathname is the maximum length of
 1335: ** a pathname in this VFS.
 1336: **
 1337: ** Registered sqlite3_vfs objects are kept on a linked list formed by
 1338: ** the pNext pointer.  The [sqlite3_vfs_register()]
 1339: ** and [sqlite3_vfs_unregister()] interfaces manage this list
 1340: ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
 1341: ** searches the list.  Neither the application code nor the VFS
 1342: ** implementation should use the pNext pointer.
 1343: **
 1344: ** The pNext field is the only field in the sqlite3_vfs
 1345: ** structure that SQLite will ever modify.  SQLite will only access
 1346: ** or modify this field while holding a particular static mutex.
 1347: ** The application should never modify anything within the sqlite3_vfs
 1348: ** object once the object has been registered.
 1349: **
 1350: ** The zName field holds the name of the VFS module.  The name must
 1351: ** be unique across all VFS modules.
 1352: **
 1353: ** [[sqlite3_vfs.xOpen]]
 1354: ** ^SQLite guarantees that the zFilename parameter to xOpen
 1355: ** is either a NULL pointer or string obtained
 1356: ** from xFullPathname() with an optional suffix added.
 1357: ** ^If a suffix is added to the zFilename parameter, it will
 1358: ** consist of a single "-" character followed by no more than
 1359: ** 11 alphanumeric and/or "-" characters.
 1360: ** ^SQLite further guarantees that
 1361: ** the string will be valid and unchanged until xClose() is
 1362: ** called. Because of the previous sentence,
 1363: ** the [sqlite3_file] can safely store a pointer to the
 1364: ** filename if it needs to remember the filename for some reason.
 1365: ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
 1366: ** must invent its own temporary name for the file.  ^Whenever the 
 1367: ** xFilename parameter is NULL it will also be the case that the
 1368: ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
 1369: **
 1370: ** The flags argument to xOpen() includes all bits set in
 1371: ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
 1372: ** or [sqlite3_open16()] is used, then flags includes at least
 1373: ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
 1374: ** If xOpen() opens a file read-only then it sets *pOutFlags to
 1375: ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
 1376: **
 1377: ** ^(SQLite will also add one of the following flags to the xOpen()
 1378: ** call, depending on the object being opened:
 1379: **
 1380: ** <ul>
 1381: ** <li>  [SQLITE_OPEN_MAIN_DB]
 1382: ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
 1383: ** <li>  [SQLITE_OPEN_TEMP_DB]
 1384: ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
 1385: ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
 1386: ** <li>  [SQLITE_OPEN_SUBJOURNAL]
 1387: ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
 1388: ** <li>  [SQLITE_OPEN_WAL]
 1389: ** </ul>)^
 1390: **
 1391: ** The file I/O implementation can use the object type flags to
 1392: ** change the way it deals with files.  For example, an application
 1393: ** that does not care about crash recovery or rollback might make
 1394: ** the open of a journal file a no-op.  Writes to this journal would
 1395: ** also be no-ops, and any attempt to read the journal would return
 1396: ** SQLITE_IOERR.  Or the implementation might recognize that a database
 1397: ** file will be doing page-aligned sector reads and writes in a random
 1398: ** order and set up its I/O subsystem accordingly.
 1399: **
 1400: ** SQLite might also add one of the following flags to the xOpen method:
 1401: **
 1402: ** <ul>
 1403: ** <li> [SQLITE_OPEN_DELETEONCLOSE]
 1404: ** <li> [SQLITE_OPEN_EXCLUSIVE]
 1405: ** </ul>
 1406: **
 1407: ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
 1408: ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
 1409: ** will be set for TEMP databases and their journals, transient
 1410: ** databases, and subjournals.
 1411: **
 1412: ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
 1413: ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
 1414: ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
 1415: ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
 1416: ** SQLITE_OPEN_CREATE, is used to indicate that file should always
 1417: ** be created, and that it is an error if it already exists.
 1418: ** It is <i>not</i> used to indicate the file should be opened 
 1419: ** for exclusive access.
 1420: **
 1421: ** ^At least szOsFile bytes of memory are allocated by SQLite
 1422: ** to hold the  [sqlite3_file] structure passed as the third
 1423: ** argument to xOpen.  The xOpen method does not have to
 1424: ** allocate the structure; it should just fill it in.  Note that
 1425: ** the xOpen method must set the sqlite3_file.pMethods to either
 1426: ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
 1427: ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
 1428: ** element will be valid after xOpen returns regardless of the success
 1429: ** or failure of the xOpen call.
 1430: **
 1431: ** [[sqlite3_vfs.xAccess]]
 1432: ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
 1433: ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
 1434: ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
 1435: ** to test whether a file is at least readable.   The file can be a
 1436: ** directory.
 1437: **
 1438: ** ^SQLite will always allocate at least mxPathname+1 bytes for the
 1439: ** output buffer xFullPathname.  The exact size of the output buffer
 1440: ** is also passed as a parameter to both  methods. If the output buffer
 1441: ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
 1442: ** handled as a fatal error by SQLite, vfs implementations should endeavor
 1443: ** to prevent this by setting mxPathname to a sufficiently large value.
 1444: **
 1445: ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
 1446: ** interfaces are not strictly a part of the filesystem, but they are
 1447: ** included in the VFS structure for completeness.
 1448: ** The xRandomness() function attempts to return nBytes bytes
 1449: ** of good-quality randomness into zOut.  The return value is
 1450: ** the actual number of bytes of randomness obtained.
 1451: ** The xSleep() method causes the calling thread to sleep for at
 1452: ** least the number of microseconds given.  ^The xCurrentTime()
 1453: ** method returns a Julian Day Number for the current date and time as
 1454: ** a floating point value.
 1455: ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
 1456: ** Day Number multiplied by 86400000 (the number of milliseconds in 
 1457: ** a 24-hour day).  
 1458: ** ^SQLite will use the xCurrentTimeInt64() method to get the current
 1459: ** date and time if that method is available (if iVersion is 2 or 
 1460: ** greater and the function pointer is not NULL) and will fall back
 1461: ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
 1462: **
 1463: ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
 1464: ** are not used by the SQLite core.  These optional interfaces are provided
 1465: ** by some VFSes to facilitate testing of the VFS code. By overriding 
 1466: ** system calls with functions under its control, a test program can
 1467: ** simulate faults and error conditions that would otherwise be difficult
 1468: ** or impossible to induce.  The set of system calls that can be overridden
 1469: ** varies from one VFS to another, and from one version of the same VFS to the
 1470: ** next.  Applications that use these interfaces must be prepared for any
 1471: ** or all of these interfaces to be NULL or for their behavior to change
 1472: ** from one release to the next.  Applications must not attempt to access
 1473: ** any of these methods if the iVersion of the VFS is less than 3.
 1474: */
 1475: typedef struct sqlite3_vfs sqlite3_vfs;
 1476: typedef void (*sqlite3_syscall_ptr)(void);
 1477: struct sqlite3_vfs {
 1478:   int iVersion;            /* Structure version number (currently 3) */
 1479:   int szOsFile;            /* Size of subclassed sqlite3_file */
 1480:   int mxPathname;          /* Maximum file pathname length */
 1481:   sqlite3_vfs *pNext;      /* Next registered VFS */
 1482:   const char *zName;       /* Name of this virtual file system */
 1483:   void *pAppData;          /* Pointer to application-specific data */
 1484:   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
 1485:                int flags, int *pOutFlags);
 1486:   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
 1487:   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
 1488:   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
 1489:   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
 1490:   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
 1491:   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
 1492:   void (*xDlClose)(sqlite3_vfs*, void*);
 1493:   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
 1494:   int (*xSleep)(sqlite3_vfs*, int microseconds);
 1495:   int (*xCurrentTime)(sqlite3_vfs*, double*);
 1496:   int (*xGetLastError)(sqlite3_vfs*, int, char *);
 1497:   /*
 1498:   ** The methods above are in version 1 of the sqlite_vfs object
 1499:   ** definition.  Those that follow are added in version 2 or later
 1500:   */
 1501:   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
 1502:   /*
 1503:   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
 1504:   ** Those below are for version 3 and greater.
 1505:   */
 1506:   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
 1507:   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
 1508:   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
 1509:   /*
 1510:   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
 1511:   ** New fields may be appended in future versions.  The iVersion
 1512:   ** value will increment whenever this happens. 
 1513:   */
 1514: };
 1515: 
 1516: /*
 1517: ** CAPI3REF: Flags for the xAccess VFS method
 1518: **
 1519: ** These integer constants can be used as the third parameter to
 1520: ** the xAccess method of an [sqlite3_vfs] object.  They determine
 1521: ** what kind of permissions the xAccess method is looking for.
 1522: ** With SQLITE_ACCESS_EXISTS, the xAccess method
 1523: ** simply checks whether the file exists.
 1524: ** With SQLITE_ACCESS_READWRITE, the xAccess method
 1525: ** checks whether the named directory is both readable and writable
 1526: ** (in other words, if files can be added, removed, and renamed within
 1527: ** the directory).
 1528: ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
 1529: ** [temp_store_directory pragma], though this could change in a future
 1530: ** release of SQLite.
 1531: ** With SQLITE_ACCESS_READ, the xAccess method
 1532: ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
 1533: ** currently unused, though it might be used in a future release of
 1534: ** SQLite.
 1535: */
 1536: #define SQLITE_ACCESS_EXISTS    0
 1537: #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
 1538: #define SQLITE_ACCESS_READ      2   /* Unused */
 1539: 
 1540: /*
 1541: ** CAPI3REF: Flags for the xShmLock VFS method
 1542: **
 1543: ** These integer constants define the various locking operations
 1544: ** allowed by the xShmLock method of [sqlite3_io_methods].  The
 1545: ** following are the only legal combinations of flags to the
 1546: ** xShmLock method:
 1547: **
 1548: ** <ul>
 1549: ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
 1550: ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
 1551: ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
 1552: ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
 1553: ** </ul>
 1554: **
 1555: ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
 1556: ** was given on the corresponding lock.  
 1557: **
 1558: ** The xShmLock method can transition between unlocked and SHARED or
 1559: ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
 1560: ** and EXCLUSIVE.
 1561: */
 1562: #define SQLITE_SHM_UNLOCK       1
 1563: #define SQLITE_SHM_LOCK         2
 1564: #define SQLITE_SHM_SHARED       4
 1565: #define SQLITE_SHM_EXCLUSIVE    8
 1566: 
 1567: /*
 1568: ** CAPI3REF: Maximum xShmLock index
 1569: **
 1570: ** The xShmLock method on [sqlite3_io_methods] may use values
 1571: ** between 0 and this upper bound as its "offset" argument.
 1572: ** The SQLite core will never attempt to acquire or release a
 1573: ** lock outside of this range
 1574: */
 1575: #define SQLITE_SHM_NLOCK        8
 1576: 
 1577: 
 1578: /*
 1579: ** CAPI3REF: Initialize The SQLite Library
 1580: **
 1581: ** ^The sqlite3_initialize() routine initializes the
 1582: ** SQLite library.  ^The sqlite3_shutdown() routine
 1583: ** deallocates any resources that were allocated by sqlite3_initialize().
 1584: ** These routines are designed to aid in process initialization and
 1585: ** shutdown on embedded systems.  Workstation applications using
 1586: ** SQLite normally do not need to invoke either of these routines.
 1587: **
 1588: ** A call to sqlite3_initialize() is an "effective" call if it is
 1589: ** the first time sqlite3_initialize() is invoked during the lifetime of
 1590: ** the process, or if it is the first time sqlite3_initialize() is invoked
 1591: ** following a call to sqlite3_shutdown().  ^(Only an effective call
 1592: ** of sqlite3_initialize() does any initialization.  All other calls
 1593: ** are harmless no-ops.)^
 1594: **
 1595: ** A call to sqlite3_shutdown() is an "effective" call if it is the first
 1596: ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
 1597: ** an effective call to sqlite3_shutdown() does any deinitialization.
 1598: ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
 1599: **
 1600: ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
 1601: ** is not.  The sqlite3_shutdown() interface must only be called from a
 1602: ** single thread.  All open [database connections] must be closed and all
 1603: ** other SQLite resources must be deallocated prior to invoking
 1604: ** sqlite3_shutdown().
 1605: **
 1606: ** Among other things, ^sqlite3_initialize() will invoke
 1607: ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
 1608: ** will invoke sqlite3_os_end().
 1609: **
 1610: ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
 1611: ** ^If for some reason, sqlite3_initialize() is unable to initialize
 1612: ** the library (perhaps it is unable to allocate a needed resource such
 1613: ** as a mutex) it returns an [error code] other than [SQLITE_OK].
 1614: **
 1615: ** ^The sqlite3_initialize() routine is called internally by many other
 1616: ** SQLite interfaces so that an application usually does not need to
 1617: ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
 1618: ** calls sqlite3_initialize() so the SQLite library will be automatically
 1619: ** initialized when [sqlite3_open()] is called if it has not be initialized
 1620: ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
 1621: ** compile-time option, then the automatic calls to sqlite3_initialize()
 1622: ** are omitted and the application must call sqlite3_initialize() directly
 1623: ** prior to using any other SQLite interface.  For maximum portability,
 1624: ** it is recommended that applications always invoke sqlite3_initialize()
 1625: ** directly prior to using any other SQLite interface.  Future releases
 1626: ** of SQLite may require this.  In other words, the behavior exhibited
 1627: ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
 1628: ** default behavior in some future release of SQLite.
 1629: **
 1630: ** The sqlite3_os_init() routine does operating-system specific
 1631: ** initialization of the SQLite library.  The sqlite3_os_end()
 1632: ** routine undoes the effect of sqlite3_os_init().  Typical tasks
 1633: ** performed by these routines include allocation or deallocation
 1634: ** of static resources, initialization of global variables,
 1635: ** setting up a default [sqlite3_vfs] module, or setting up
 1636: ** a default configuration using [sqlite3_config()].
 1637: **
 1638: ** The application should never invoke either sqlite3_os_init()
 1639: ** or sqlite3_os_end() directly.  The application should only invoke
 1640: ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
 1641: ** interface is called automatically by sqlite3_initialize() and
 1642: ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
 1643: ** implementations for sqlite3_os_init() and sqlite3_os_end()
 1644: ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
 1645: ** When [custom builds | built for other platforms]
 1646: ** (using the [SQLITE_OS_OTHER=1] compile-time
 1647: ** option) the application must supply a suitable implementation for
 1648: ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
 1649: ** implementation of sqlite3_os_init() or sqlite3_os_end()
 1650: ** must return [SQLITE_OK] on success and some other [error code] upon
 1651: ** failure.
 1652: */
 1653: SQLITE_API int sqlite3_initialize(void);
 1654: SQLITE_API int sqlite3_shutdown(void);
 1655: SQLITE_API int sqlite3_os_init(void);
 1656: SQLITE_API int sqlite3_os_end(void);
 1657: 
 1658: /*
 1659: ** CAPI3REF: Configuring The SQLite Library
 1660: **
 1661: ** The sqlite3_config() interface is used to make global configuration
 1662: ** changes to SQLite in order to tune SQLite to the specific needs of
 1663: ** the application.  The default configuration is recommended for most
 1664: ** applications and so this routine is usually not necessary.  It is
 1665: ** provided to support rare applications with unusual needs.
 1666: **
 1667: ** <b>The sqlite3_config() interface is not threadsafe. The application
 1668: ** must ensure that no other SQLite interfaces are invoked by other
 1669: ** threads while sqlite3_config() is running.</b>
 1670: **
 1671: ** The sqlite3_config() interface
 1672: ** may only be invoked prior to library initialization using
 1673: ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
 1674: ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
 1675: ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
 1676: ** Note, however, that ^sqlite3_config() can be called as part of the
 1677: ** implementation of an application-defined [sqlite3_os_init()].
 1678: **
 1679: ** The first argument to sqlite3_config() is an integer
 1680: ** [configuration option] that determines
 1681: ** what property of SQLite is to be configured.  Subsequent arguments
 1682: ** vary depending on the [configuration option]
 1683: ** in the first argument.
 1684: **
 1685: ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
 1686: ** ^If the option is unknown or SQLite is unable to set the option
 1687: ** then this routine returns a non-zero [error code].
 1688: */
 1689: SQLITE_API int sqlite3_config(int, ...);
 1690: 
 1691: /*
 1692: ** CAPI3REF: Configure database connections
 1693: ** METHOD: sqlite3
 1694: **
 1695: ** The sqlite3_db_config() interface is used to make configuration
 1696: ** changes to a [database connection].  The interface is similar to
 1697: ** [sqlite3_config()] except that the changes apply to a single
 1698: ** [database connection] (specified in the first argument).
 1699: **
 1700: ** The second argument to sqlite3_db_config(D,V,...)  is the
 1701: ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
 1702: ** that indicates what aspect of the [database connection] is being configured.
 1703: ** Subsequent arguments vary depending on the configuration verb.
 1704: **
 1705: ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
 1706: ** the call is considered successful.
 1707: */
 1708: SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
 1709: 
 1710: /*
 1711: ** CAPI3REF: Memory Allocation Routines
 1712: **
 1713: ** An instance of this object defines the interface between SQLite
 1714: ** and low-level memory allocation routines.
 1715: **
 1716: ** This object is used in only one place in the SQLite interface.
 1717: ** A pointer to an instance of this object is the argument to
 1718: ** [sqlite3_config()] when the configuration option is
 1719: ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
 1720: ** By creating an instance of this object
 1721: ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
 1722: ** during configuration, an application can specify an alternative
 1723: ** memory allocation subsystem for SQLite to use for all of its
 1724: ** dynamic memory needs.
 1725: **
 1726: ** Note that SQLite comes with several [built-in memory allocators]
 1727: ** that are perfectly adequate for the overwhelming majority of applications
 1728: ** and that this object is only useful to a tiny minority of applications
 1729: ** with specialized memory allocation requirements.  This object is
 1730: ** also used during testing of SQLite in order to specify an alternative
 1731: ** memory allocator that simulates memory out-of-memory conditions in
 1732: ** order to verify that SQLite recovers gracefully from such
 1733: ** conditions.
 1734: **
 1735: ** The xMalloc, xRealloc, and xFree methods must work like the
 1736: ** malloc(), realloc() and free() functions from the standard C library.
 1737: ** ^SQLite guarantees that the second argument to
 1738: ** xRealloc is always a value returned by a prior call to xRoundup.
 1739: **
 1740: ** xSize should return the allocated size of a memory allocation
 1741: ** previously obtained from xMalloc or xRealloc.  The allocated size
 1742: ** is always at least as big as the requested size but may be larger.
 1743: **
 1744: ** The xRoundup method returns what would be the allocated size of
 1745: ** a memory allocation given a particular requested size.  Most memory
 1746: ** allocators round up memory allocations at least to the next multiple
 1747: ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
 1748: ** Every memory allocation request coming in through [sqlite3_malloc()]
 1749: ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
 1750: ** that causes the corresponding memory allocation to fail.
 1751: **
 1752: ** The xInit method initializes the memory allocator.  For example,
 1753: ** it might allocate any require mutexes or initialize internal data
 1754: ** structures.  The xShutdown method is invoked (indirectly) by
 1755: ** [sqlite3_shutdown()] and should deallocate any resources acquired
 1756: ** by xInit.  The pAppData pointer is used as the only parameter to
 1757: ** xInit and xShutdown.
 1758: **
 1759: ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
 1760: ** the xInit method, so the xInit method need not be threadsafe.  The
 1761: ** xShutdown method is only called from [sqlite3_shutdown()] so it does
 1762: ** not need to be threadsafe either.  For all other methods, SQLite
 1763: ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
 1764: ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
 1765: ** it is by default) and so the methods are automatically serialized.
 1766: ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
 1767: ** methods must be threadsafe or else make their own arrangements for
 1768: ** serialization.
 1769: **
 1770: ** SQLite will never invoke xInit() more than once without an intervening
 1771: ** call to xShutdown().
 1772: */
 1773: typedef struct sqlite3_mem_methods sqlite3_mem_methods;
 1774: struct sqlite3_mem_methods {
 1775:   void *(*xMalloc)(int);         /* Memory allocation function */
 1776:   void (*xFree)(void*);          /* Free a prior allocation */
 1777:   void *(*xRealloc)(void*,int);  /* Resize an allocation */
 1778:   int (*xSize)(void*);           /* Return the size of an allocation */
 1779:   int (*xRoundup)(int);          /* Round up request size to allocation size */
 1780:   int (*xInit)(void*);           /* Initialize the memory allocator */
 1781:   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
 1782:   void *pAppData;                /* Argument to xInit() and xShutdown() */
 1783: };
 1784: 
 1785: /*
 1786: ** CAPI3REF: Configuration Options
 1787: ** KEYWORDS: {configuration option}
 1788: **
 1789: ** These constants are the available integer configuration options that
 1790: ** can be passed as the first argument to the [sqlite3_config()] interface.
 1791: **
 1792: ** New configuration options may be added in future releases of SQLite.
 1793: ** Existing configuration options might be discontinued.  Applications
 1794: ** should check the return code from [sqlite3_config()] to make sure that
 1795: ** the call worked.  The [sqlite3_config()] interface will return a
 1796: ** non-zero [error code] if a discontinued or unsupported configuration option
 1797: ** is invoked.
 1798: **
 1799: ** <dl>
 1800: ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
 1801: ** <dd>There are no arguments to this option.  ^This option sets the
 1802: ** [threading mode] to Single-thread.  In other words, it disables
 1803: ** all mutexing and puts SQLite into a mode where it can only be used
 1804: ** by a single thread.   ^If SQLite is compiled with
 1805: ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
 1806: ** it is not possible to change the [threading mode] from its default
 1807: ** value of Single-thread and so [sqlite3_config()] will return 
 1808: ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
 1809: ** configuration option.</dd>
 1810: **
 1811: ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
 1812: ** <dd>There are no arguments to this option.  ^This option sets the
 1813: ** [threading mode] to Multi-thread.  In other words, it disables
 1814: ** mutexing on [database connection] and [prepared statement] objects.
 1815: ** The application is responsible for serializing access to
 1816: ** [database connections] and [prepared statements].  But other mutexes
 1817: ** are enabled so that SQLite will be safe to use in a multi-threaded
 1818: ** environment as long as no two threads attempt to use the same
 1819: ** [database connection] at the same time.  ^If SQLite is compiled with
 1820: ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
 1821: ** it is not possible to set the Multi-thread [threading mode] and
 1822: ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
 1823: ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
 1824: **
 1825: ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
 1826: ** <dd>There are no arguments to this option.  ^This option sets the
 1827: ** [threading mode] to Serialized. In other words, this option enables
 1828: ** all mutexes including the recursive
 1829: ** mutexes on [database connection] and [prepared statement] objects.
 1830: ** In this mode (which is the default when SQLite is compiled with
 1831: ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
 1832: ** to [database connections] and [prepared statements] so that the
 1833: ** application is free to use the same [database connection] or the
 1834: ** same [prepared statement] in different threads at the same time.
 1835: ** ^If SQLite is compiled with
 1836: ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
 1837: ** it is not possible to set the Serialized [threading mode] and
 1838: ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
 1839: ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
 1840: **
 1841: ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
 1842: ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is 
 1843: ** a pointer to an instance of the [sqlite3_mem_methods] structure.
 1844: ** The argument specifies
 1845: ** alternative low-level memory allocation routines to be used in place of
 1846: ** the memory allocation routines built into SQLite.)^ ^SQLite makes
 1847: ** its own private copy of the content of the [sqlite3_mem_methods] structure
 1848: ** before the [sqlite3_config()] call returns.</dd>
 1849: **
 1850: ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
 1851: ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
 1852: ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
 1853: ** The [sqlite3_mem_methods]
 1854: ** structure is filled with the currently defined memory allocation routines.)^
 1855: ** This option can be used to overload the default memory allocation
 1856: ** routines with a wrapper that simulations memory allocation failure or
 1857: ** tracks memory usage, for example. </dd>
 1858: **
 1859: ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
 1860: ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
 1861: ** interpreted as a boolean, which enables or disables the collection of
 1862: ** memory allocation statistics. ^(When memory allocation statistics are
 1863: ** disabled, the following SQLite interfaces become non-operational:
 1864: **   <ul>
 1865: **   <li> [sqlite3_memory_used()]
 1866: **   <li> [sqlite3_memory_highwater()]
 1867: **   <li> [sqlite3_soft_heap_limit64()]
 1868: **   <li> [sqlite3_status64()]
 1869: **   </ul>)^
 1870: ** ^Memory allocation statistics are enabled by default unless SQLite is
 1871: ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
 1872: ** allocation statistics are disabled by default.
 1873: ** </dd>
 1874: **
 1875: ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
 1876: ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
 1877: ** that SQLite can use for scratch memory.  ^(There are three arguments
 1878: ** to SQLITE_CONFIG_SCRATCH:  A pointer an 8-byte
 1879: ** aligned memory buffer from which the scratch allocations will be
 1880: ** drawn, the size of each scratch allocation (sz),
 1881: ** and the maximum number of scratch allocations (N).)^
 1882: ** The first argument must be a pointer to an 8-byte aligned buffer
 1883: ** of at least sz*N bytes of memory.
 1884: ** ^SQLite will not use more than one scratch buffers per thread.
 1885: ** ^SQLite will never request a scratch buffer that is more than 6
 1886: ** times the database page size.
 1887: ** ^If SQLite needs needs additional
 1888: ** scratch memory beyond what is provided by this configuration option, then 
 1889: ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
 1890: ** ^When the application provides any amount of scratch memory using
 1891: ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
 1892: ** [sqlite3_malloc|heap allocations].
 1893: ** This can help [Robson proof|prevent memory allocation failures] due to heap
 1894: ** fragmentation in low-memory embedded systems.
 1895: ** </dd>
 1896: **
 1897: ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
 1898: ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
 1899: ** that SQLite can use for the database page cache with the default page
 1900: ** cache implementation.  
 1901: ** This configuration option is a no-op if an application-define page
 1902: ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
 1903: ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
 1904: ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
 1905: ** and the number of cache lines (N).
 1906: ** The sz argument should be the size of the largest database page
 1907: ** (a power of two between 512 and 65536) plus some extra bytes for each
 1908: ** page header.  ^The number of extra bytes needed by the page header
 1909: ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
 1910: ** ^It is harmless, apart from the wasted memory,
 1911: ** for the sz parameter to be larger than necessary.  The pMem
 1912: ** argument must be either a NULL pointer or a pointer to an 8-byte
 1913: ** aligned block of memory of at least sz*N bytes, otherwise
 1914: ** subsequent behavior is undefined.
 1915: ** ^When pMem is not NULL, SQLite will strive to use the memory provided
 1916: ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
 1917: ** a page cache line is larger than sz bytes or if all of the pMem buffer
 1918: ** is exhausted.
 1919: ** ^If pMem is NULL and N is non-zero, then each database connection
 1920: ** does an initial bulk allocation for page cache memory
 1921: ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
 1922: ** of -1024*N bytes if N is negative, . ^If additional
 1923: ** page cache memory is needed beyond what is provided by the initial
 1924: ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
 1925: ** additional cache line. </dd>
 1926: **
 1927: ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
 1928: ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer 
 1929: ** that SQLite will use for all of its dynamic memory allocation needs
 1930: ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
 1931: ** [SQLITE_CONFIG_PAGECACHE].
 1932: ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
 1933: ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
 1934: ** [SQLITE_ERROR] if invoked otherwise.
 1935: ** ^There are three arguments to SQLITE_CONFIG_HEAP:
 1936: ** An 8-byte aligned pointer to the memory,
 1937: ** the number of bytes in the memory buffer, and the minimum allocation size.
 1938: ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
 1939: ** to using its default memory allocator (the system malloc() implementation),
 1940: ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
 1941: ** memory pointer is not NULL then the alternative memory
 1942: ** allocator is engaged to handle all of SQLites memory allocation needs.
 1943: ** The first pointer (the memory pointer) must be aligned to an 8-byte
 1944: ** boundary or subsequent behavior of SQLite will be undefined.
 1945: ** The minimum allocation size is capped at 2**12. Reasonable values
 1946: ** for the minimum allocation size are 2**5 through 2**8.</dd>
 1947: **
 1948: ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
 1949: ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
 1950: ** pointer to an instance of the [sqlite3_mutex_methods] structure.
 1951: ** The argument specifies alternative low-level mutex routines to be used
 1952: ** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
 1953: ** the content of the [sqlite3_mutex_methods] structure before the call to
 1954: ** [sqlite3_config()] returns. ^If SQLite is compiled with
 1955: ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
 1956: ** the entire mutexing subsystem is omitted from the build and hence calls to
 1957: ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
 1958: ** return [SQLITE_ERROR].</dd>
 1959: **
 1960: ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
 1961: ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
 1962: ** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
 1963: ** [sqlite3_mutex_methods]
 1964: ** structure is filled with the currently defined mutex routines.)^
 1965: ** This option can be used to overload the default mutex allocation
 1966: ** routines with a wrapper used to track mutex usage for performance
 1967: ** profiling or testing, for example.   ^If SQLite is compiled with
 1968: ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
 1969: ** the entire mutexing subsystem is omitted from the build and hence calls to
 1970: ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
 1971: ** return [SQLITE_ERROR].</dd>
 1972: **
 1973: ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
 1974: ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
 1975: ** the default size of lookaside memory on each [database connection].
 1976: ** The first argument is the
 1977: ** size of each lookaside buffer slot and the second is the number of
 1978: ** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
 1979: ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
 1980: ** option to [sqlite3_db_config()] can be used to change the lookaside
 1981: ** configuration on individual connections.)^ </dd>
 1982: **
 1983: ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
 1984: ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is 
 1985: ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
 1986: ** the interface to a custom page cache implementation.)^
 1987: ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
 1988: **
 1989: ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
 1990: ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
 1991: ** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
 1992: ** the current page cache implementation into that object.)^ </dd>
 1993: **
 1994: ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
 1995: ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
 1996: ** global [error log].
 1997: ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
 1998: ** function with a call signature of void(*)(void*,int,const char*), 
 1999: ** and a pointer to void. ^If the function pointer is not NULL, it is
 2000: ** invoked by [sqlite3_log()] to process each logging event.  ^If the
 2001: ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
 2002: ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
 2003: ** passed through as the first parameter to the application-defined logger
 2004: ** function whenever that function is invoked.  ^The second parameter to
 2005: ** the logger function is a copy of the first parameter to the corresponding
 2006: ** [sqlite3_log()] call and is intended to be a [result code] or an
 2007: ** [extended result code].  ^The third parameter passed to the logger is
 2008: ** log message after formatting via [sqlite3_snprintf()].
 2009: ** The SQLite logging interface is not reentrant; the logger function
 2010: ** supplied by the application must not invoke any SQLite interface.
 2011: ** In a multi-threaded application, the application-defined logger
 2012: ** function must be threadsafe. </dd>
 2013: **
 2014: ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
 2015: ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
 2016: ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
 2017: ** then URI handling is globally disabled.)^ ^If URI handling is globally
 2018: ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
 2019: ** [sqlite3_open16()] or
 2020: ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
 2021: ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
 2022: ** connection is opened. ^If it is globally disabled, filenames are
 2023: ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
 2024: ** database connection is opened. ^(By default, URI handling is globally
 2025: ** disabled. The default value may be changed by compiling with the
 2026: ** [SQLITE_USE_URI] symbol defined.)^
 2027: **
 2028: ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
 2029: ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
 2030: ** argument which is interpreted as a boolean in order to enable or disable
 2031: ** the use of covering indices for full table scans in the query optimizer.
 2032: ** ^The default setting is determined
 2033: ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
 2034: ** if that compile-time option is omitted.
 2035: ** The ability to disable the use of covering indices for full table scans
 2036: ** is because some incorrectly coded legacy applications might malfunction
 2037: ** when the optimization is enabled.  Providing the ability to
 2038: ** disable the optimization allows the older, buggy application code to work
 2039: ** without change even with newer versions of SQLite.
 2040: **
 2041: ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
 2042: ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
 2043: ** <dd> These options are obsolete and should not be used by new code.
 2044: ** They are retained for backwards compatibility but are now no-ops.
 2045: ** </dd>
 2046: **
 2047: ** [[SQLITE_CONFIG_SQLLOG]]
 2048: ** <dt>SQLITE_CONFIG_SQLLOG
 2049: ** <dd>This option is only available if sqlite is compiled with the
 2050: ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
 2051: ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
 2052: ** The second should be of type (void*). The callback is invoked by the library
 2053: ** in three separate circumstances, identified by the value passed as the
 2054: ** fourth parameter. If the fourth parameter is 0, then the database connection
 2055: ** passed as the second argument has just been opened. The third argument
 2056: ** points to a buffer containing the name of the main database file. If the
 2057: ** fourth parameter is 1, then the SQL statement that the third parameter
 2058: ** points to has just been executed. Or, if the fourth parameter is 2, then
 2059: ** the connection being passed as the second parameter is being closed. The
 2060: ** third parameter is passed NULL In this case.  An example of using this
 2061: ** configuration option can be seen in the "test_sqllog.c" source file in
 2062: ** the canonical SQLite source tree.</dd>
 2063: **
 2064: ** [[SQLITE_CONFIG_MMAP_SIZE]]
 2065: ** <dt>SQLITE_CONFIG_MMAP_SIZE
 2066: ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
 2067: ** that are the default mmap size limit (the default setting for
 2068: ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
 2069: ** ^The default setting can be overridden by each database connection using
 2070: ** either the [PRAGMA mmap_size] command, or by using the
 2071: ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
 2072: ** will be silently truncated if necessary so that it does not exceed the
 2073: ** compile-time maximum mmap size set by the
 2074: ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
 2075: ** ^If either argument to this option is negative, then that argument is
 2076: ** changed to its compile-time default.
 2077: **
 2078: ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
 2079: ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
 2080: ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
 2081: ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
 2082: ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
 2083: ** that specifies the maximum size of the created heap.
 2084: **
 2085: ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
 2086: ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
 2087: ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
 2088: ** is a pointer to an integer and writes into that integer the number of extra
 2089: ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
 2090: ** The amount of extra space required can change depending on the compiler,
 2091: ** target platform, and SQLite version.
 2092: **
 2093: ** [[SQLITE_CONFIG_PMASZ]]
 2094: ** <dt>SQLITE_CONFIG_PMASZ
 2095: ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
 2096: ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
 2097: ** sorter to that integer.  The default minimum PMA Size is set by the
 2098: ** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
 2099: ** to help with sort operations when multithreaded sorting
 2100: ** is enabled (using the [PRAGMA threads] command) and the amount of content
 2101: ** to be sorted exceeds the page size times the minimum of the
 2102: ** [PRAGMA cache_size] setting and this value.
 2103: **
 2104: ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
 2105: ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
 2106: ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
 2107: ** becomes the [statement journal] spill-to-disk threshold.  
 2108: ** [Statement journals] are held in memory until their size (in bytes)
 2109: ** exceeds this threshold, at which point they are written to disk.
 2110: ** Or if the threshold is -1, statement journals are always held
 2111: ** exclusively in memory.
 2112: ** Since many statement journals never become large, setting the spill
 2113: ** threshold to a value such as 64KiB can greatly reduce the amount of
 2114: ** I/O required to support statement rollback.
 2115: ** The default value for this setting is controlled by the
 2116: ** [SQLITE_STMTJRNL_SPILL] compile-time option.
 2117: ** </dl>
 2118: */
 2119: #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
 2120: #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
 2121: #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
 2122: #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
 2123: #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
 2124: #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
 2125: #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
 2126: #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
 2127: #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
 2128: #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
 2129: #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
 2130: /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
 2131: #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
 2132: #define SQLITE_CONFIG_PCACHE       14  /* no-op */
 2133: #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
 2134: #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
 2135: #define SQLITE_CONFIG_URI          17  /* int */
 2136: #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
 2137: #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
 2138: #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
 2139: #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
 2140: #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
 2141: #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
 2142: #define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
 2143: #define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
 2144: #define SQLITE_CONFIG_STMTJRNL_SPILL      26  /* int nByte */
 2145: 
 2146: /*
 2147: ** CAPI3REF: Database Connection Configuration Options
 2148: **
 2149: ** These constants are the available integer configuration options that
 2150: ** can be passed as the second argument to the [sqlite3_db_config()] interface.
 2151: **
 2152: ** New configuration options may be added in future releases of SQLite.
 2153: ** Existing configuration options might be discontinued.  Applications
 2154: ** should check the return code from [sqlite3_db_config()] to make sure that
 2155: ** the call worked.  ^The [sqlite3_db_config()] interface will return a
 2156: ** non-zero [error code] if a discontinued or unsupported configuration option
 2157: ** is invoked.
 2158: **
 2159: ** <dl>
 2160: ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
 2161: ** <dd> ^This option takes three additional arguments that determine the 
 2162: ** [lookaside memory allocator] configuration for the [database connection].
 2163: ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
 2164: ** pointer to a memory buffer to use for lookaside memory.
 2165: ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
 2166: ** may be NULL in which case SQLite will allocate the
 2167: ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
 2168: ** size of each lookaside buffer slot.  ^The third argument is the number of
 2169: ** slots.  The size of the buffer in the first argument must be greater than
 2170: ** or equal to the product of the second and third arguments.  The buffer
 2171: ** must be aligned to an 8-byte boundary.  ^If the second argument to
 2172: ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
 2173: ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
 2174: ** configuration for a database connection can only be changed when that
 2175: ** connection is not currently using lookaside memory, or in other words
 2176: ** when the "current value" returned by
 2177: ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
 2178: ** Any attempt to change the lookaside memory configuration when lookaside
 2179: ** memory is in use leaves the configuration unchanged and returns 
 2180: ** [SQLITE_BUSY].)^</dd>
 2181: **
 2182: ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
 2183: ** <dd> ^This option is used to enable or disable the enforcement of
 2184: ** [foreign key constraints].  There should be two additional arguments.
 2185: ** The first argument is an integer which is 0 to disable FK enforcement,
 2186: ** positive to enable FK enforcement or negative to leave FK enforcement
 2187: ** unchanged.  The second parameter is a pointer to an integer into which
 2188: ** is written 0 or 1 to indicate whether FK enforcement is off or on
 2189: ** following this call.  The second parameter may be a NULL pointer, in
 2190: ** which case the FK enforcement setting is not reported back. </dd>
 2191: **
 2192: ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
 2193: ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
 2194: ** There should be two additional arguments.
 2195: ** The first argument is an integer which is 0 to disable triggers,
 2196: ** positive to enable triggers or negative to leave the setting unchanged.
 2197: ** The second parameter is a pointer to an integer into which
 2198: ** is written 0 or 1 to indicate whether triggers are disabled or enabled
 2199: ** following this call.  The second parameter may be a NULL pointer, in
 2200: ** which case the trigger setting is not reported back. </dd>
 2201: **
 2202: ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
 2203: ** <dd> ^This option is used to enable or disable the two-argument
 2204: ** version of the [fts3_tokenizer()] function which is part of the
 2205: ** [FTS3] full-text search engine extension.
 2206: ** There should be two additional arguments.
 2207: ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
 2208: ** positive to enable fts3_tokenizer() or negative to leave the setting
 2209: ** unchanged.
 2210: ** The second parameter is a pointer to an integer into which
 2211: ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
 2212: ** following this call.  The second parameter may be a NULL pointer, in
 2213: ** which case the new setting is not reported back. </dd>
 2214: **
 2215: ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
 2216: ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
 2217: ** interface independently of the [load_extension()] SQL function.
 2218: ** The [sqlite3_enable_load_extension()] API enables or disables both the
 2219: ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
 2220: ** There should be two additional arguments.
 2221: ** When the first argument to this interface is 1, then only the C-API is
 2222: ** enabled and the SQL function remains disabled.  If the first argument to
 2223: ** this interface is 0, then both the C-API and the SQL function are disabled.
 2224: ** If the first argument is -1, then no changes are made to state of either the
 2225: ** C-API or the SQL function.
 2226: ** The second parameter is a pointer to an integer into which
 2227: ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
 2228: ** is disabled or enabled following this call.  The second parameter may
 2229: ** be a NULL pointer, in which case the new setting is not reported back.
 2230: ** </dd>
 2231: **
 2232: ** </dl>
 2233: */
 2234: #define SQLITE_DBCONFIG_LOOKASIDE             1001 /* void* int int */
 2235: #define SQLITE_DBCONFIG_ENABLE_FKEY           1002 /* int int* */
 2236: #define SQLITE_DBCONFIG_ENABLE_TRIGGER        1003 /* int int* */
 2237: #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
 2238: #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
 2239: 
 2240: 
 2241: /*
 2242: ** CAPI3REF: Enable Or Disable Extended Result Codes
 2243: ** METHOD: sqlite3
 2244: **
 2245: ** ^The sqlite3_extended_result_codes() routine enables or disables the
 2246: ** [extended result codes] feature of SQLite. ^The extended result
 2247: ** codes are disabled by default for historical compatibility.
 2248: */
 2249: SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
 2250: 
 2251: /*
 2252: ** CAPI3REF: Last Insert Rowid
 2253: ** METHOD: sqlite3
 2254: **
 2255: ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
 2256: ** has a unique 64-bit signed
 2257: ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
 2258: ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
 2259: ** names are not also used by explicitly declared columns. ^If
 2260: ** the table has a column of type [INTEGER PRIMARY KEY] then that column
 2261: ** is another alias for the rowid.
 2262: **
 2263: ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the 
 2264: ** most recent successful [INSERT] into a rowid table or [virtual table]
 2265: ** on database connection D.
 2266: ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
 2267: ** ^If no successful [INSERT]s into rowid tables
 2268: ** have ever occurred on the database connection D, 
 2269: ** then sqlite3_last_insert_rowid(D) returns zero.
 2270: **
 2271: ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
 2272: ** method, then this routine will return the [rowid] of the inserted
 2273: ** row as long as the trigger or virtual table method is running.
 2274: ** But once the trigger or virtual table method ends, the value returned 
 2275: ** by this routine reverts to what it was before the trigger or virtual
 2276: ** table method began.)^
 2277: **
 2278: ** ^An [INSERT] that fails due to a constraint violation is not a
 2279: ** successful [INSERT] and does not change the value returned by this
 2280: ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
 2281: ** and INSERT OR ABORT make no changes to the return value of this
 2282: ** routine when their insertion fails.  ^(When INSERT OR REPLACE
 2283: ** encounters a constraint violation, it does not fail.  The
 2284: ** INSERT continues to completion after deleting rows that caused
 2285: ** the constraint problem so INSERT OR REPLACE will always change
 2286: ** the return value of this interface.)^
 2287: **
 2288: ** ^For the purposes of this routine, an [INSERT] is considered to
 2289: ** be successful even if it is subsequently rolled back.
 2290: **
 2291: ** This function is accessible to SQL statements via the
 2292: ** [last_insert_rowid() SQL function].
 2293: **
 2294: ** If a separate thread performs a new [INSERT] on the same
 2295: ** database connection while the [sqlite3_last_insert_rowid()]
 2296: ** function is running and thus changes the last insert [rowid],
 2297: ** then the value returned by [sqlite3_last_insert_rowid()] is
 2298: ** unpredictable and might not equal either the old or the new
 2299: ** last insert [rowid].
 2300: */
 2301: SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
 2302: 
 2303: /*
 2304: ** CAPI3REF: Count The Number Of Rows Modified
 2305: ** METHOD: sqlite3
 2306: **
 2307: ** ^This function returns the number of rows modified, inserted or
 2308: ** deleted by the most recently completed INSERT, UPDATE or DELETE
 2309: ** statement on the database connection specified by the only parameter.
 2310: ** ^Executing any other type of SQL statement does not modify the value
 2311: ** returned by this function.
 2312: **
 2313: ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
 2314: ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], 
 2315: ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
 2316: ** 
 2317: ** Changes to a view that are intercepted by 
 2318: ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value 
 2319: ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or 
 2320: ** DELETE statement run on a view is always zero. Only changes made to real 
 2321: ** tables are counted.
 2322: **
 2323: ** Things are more complicated if the sqlite3_changes() function is
 2324: ** executed while a trigger program is running. This may happen if the
 2325: ** program uses the [changes() SQL function], or if some other callback
 2326: ** function invokes sqlite3_changes() directly. Essentially:
 2327: ** 
 2328: ** <ul>
 2329: **   <li> ^(Before entering a trigger program the value returned by
 2330: **        sqlite3_changes() function is saved. After the trigger program 
 2331: **        has finished, the original value is restored.)^
 2332: ** 
 2333: **   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE 
 2334: **        statement sets the value returned by sqlite3_changes() 
 2335: **        upon completion as normal. Of course, this value will not include 
 2336: **        any changes performed by sub-triggers, as the sqlite3_changes() 
 2337: **        value will be saved and restored after each sub-trigger has run.)^
 2338: ** </ul>
 2339: ** 
 2340: ** ^This means that if the changes() SQL function (or similar) is used
 2341: ** by the first INSERT, UPDATE or DELETE statement within a trigger, it 
 2342: ** returns the value as set when the calling statement began executing.
 2343: ** ^If it is used by the second or subsequent such statement within a trigger 
 2344: ** program, the value returned reflects the number of rows modified by the 
 2345: ** previous INSERT, UPDATE or DELETE statement within the same trigger.
 2346: **
 2347: ** See also the [sqlite3_total_changes()] interface, the
 2348: ** [count_changes pragma], and the [changes() SQL function].
 2349: **
 2350: ** If a separate thread makes changes on the same database connection
 2351: ** while [sqlite3_changes()] is running then the value returned
 2352: ** is unpredictable and not meaningful.
 2353: */
 2354: SQLITE_API int sqlite3_changes(sqlite3*);
 2355: 
 2356: /*
 2357: ** CAPI3REF: Total Number Of Rows Modified
 2358: ** METHOD: sqlite3
 2359: **
 2360: ** ^This function returns the total number of rows inserted, modified or
 2361: ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
 2362: ** since the database connection was opened, including those executed as
 2363: ** part of trigger programs. ^Executing any other type of SQL statement
 2364: ** does not affect the value returned by sqlite3_total_changes().
 2365: ** 
 2366: ** ^Changes made as part of [foreign key actions] are included in the
 2367: ** count, but those made as part of REPLACE constraint resolution are
 2368: ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers 
 2369: ** are not counted.
 2370: ** 
 2371: ** See also the [sqlite3_changes()] interface, the
 2372: ** [count_changes pragma], and the [total_changes() SQL function].
 2373: **
 2374: ** If a separate thread makes changes on the same database connection
 2375: ** while [sqlite3_total_changes()] is running then the value
 2376: ** returned is unpredictable and not meaningful.
 2377: */
 2378: SQLITE_API int sqlite3_total_changes(sqlite3*);
 2379: 
 2380: /*
 2381: ** CAPI3REF: Interrupt A Long-Running Query
 2382: ** METHOD: sqlite3
 2383: **
 2384: ** ^This function causes any pending database operation to abort and
 2385: ** return at its earliest opportunity. This routine is typically
 2386: ** called in response to a user action such as pressing "Cancel"
 2387: ** or Ctrl-C where the user wants a long query operation to halt
 2388: ** immediately.
 2389: **
 2390: ** ^It is safe to call this routine from a thread different from the
 2391: ** thread that is currently running the database operation.  But it
 2392: ** is not safe to call this routine with a [database connection] that
 2393: ** is closed or might close before sqlite3_interrupt() returns.
 2394: **
 2395: ** ^If an SQL operation is very nearly finished at the time when
 2396: ** sqlite3_interrupt() is called, then it might not have an opportunity
 2397: ** to be interrupted and might continue to completion.
 2398: **
 2399: ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
 2400: ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
 2401: ** that is inside an explicit transaction, then the entire transaction
 2402: ** will be rolled back automatically.
 2403: **
 2404: ** ^The sqlite3_interrupt(D) call is in effect until all currently running
 2405: ** SQL statements on [database connection] D complete.  ^Any new SQL statements
 2406: ** that are started after the sqlite3_interrupt() call and before the 
 2407: ** running statements reaches zero are interrupted as if they had been
 2408: ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
 2409: ** that are started after the running statement count reaches zero are
 2410: ** not effected by the sqlite3_interrupt().
 2411: ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
 2412: ** SQL statements is a no-op and has no effect on SQL statements
 2413: ** that are started after the sqlite3_interrupt() call returns.
 2414: **
 2415: ** If the database connection closes while [sqlite3_interrupt()]
 2416: ** is running then bad things will likely happen.
 2417: */
 2418: SQLITE_API void sqlite3_interrupt(sqlite3*);
 2419: 
 2420: /*
 2421: ** CAPI3REF: Determine If An SQL Statement Is Complete
 2422: **
 2423: ** These routines are useful during command-line input to determine if the
 2424: ** currently entered text seems to form a complete SQL statement or
 2425: ** if additional input is needed before sending the text into
 2426: ** SQLite for parsing.  ^These routines return 1 if the input string
 2427: ** appears to be a complete SQL statement.  ^A statement is judged to be
 2428: ** complete if it ends with a semicolon token and is not a prefix of a
 2429: ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
 2430: ** string literals or quoted identifier names or comments are not
 2431: ** independent tokens (they are part of the token in which they are
 2432: ** embedded) and thus do not count as a statement terminator.  ^Whitespace
 2433: ** and comments that follow the final semicolon are ignored.
 2434: **
 2435: ** ^These routines return 0 if the statement is incomplete.  ^If a
 2436: ** memory allocation fails, then SQLITE_NOMEM is returned.
 2437: **
 2438: ** ^These routines do not parse the SQL statements thus
 2439: ** will not detect syntactically incorrect SQL.
 2440: **
 2441: ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
 2442: ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
 2443: ** automatically by sqlite3_complete16().  If that initialization fails,
 2444: ** then the return value from sqlite3_complete16() will be non-zero
 2445: ** regardless of whether or not the input SQL is complete.)^
 2446: **
 2447: ** The input to [sqlite3_complete()] must be a zero-terminated
 2448: ** UTF-8 string.
 2449: **
 2450: ** The input to [sqlite3_complete16()] must be a zero-terminated
 2451: ** UTF-16 string in native byte order.
 2452: */
 2453: SQLITE_API int sqlite3_complete(const char *sql);
 2454: SQLITE_API int sqlite3_complete16(const void *sql);
 2455: 
 2456: /*
 2457: ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
 2458: ** KEYWORDS: {busy-handler callback} {busy handler}
 2459: ** METHOD: sqlite3
 2460: **
 2461: ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
 2462: ** that might be invoked with argument P whenever
 2463: ** an attempt is made to access a database table associated with
 2464: ** [database connection] D when another thread
 2465: ** or process has the table locked.
 2466: ** The sqlite3_busy_handler() interface is used to implement
 2467: ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
 2468: **
 2469: ** ^If the busy callback is NULL, then [SQLITE_BUSY]
 2470: ** is returned immediately upon encountering the lock.  ^If the busy callback
 2471: ** is not NULL, then the callback might be invoked with two arguments.
 2472: **
 2473: ** ^The first argument to the busy handler is a copy of the void* pointer which
 2474: ** is the third argument to sqlite3_busy_handler().  ^The second argument to
 2475: ** the busy handler callback is the number of times that the busy handler has
 2476: ** been invoked previously for the same locking event.  ^If the
 2477: ** busy callback returns 0, then no additional attempts are made to
 2478: ** access the database and [SQLITE_BUSY] is returned
 2479: ** to the application.
 2480: ** ^If the callback returns non-zero, then another attempt
 2481: ** is made to access the database and the cycle repeats.
 2482: **
 2483: ** The presence of a busy handler does not guarantee that it will be invoked
 2484: ** when there is lock contention. ^If SQLite determines that invoking the busy
 2485: ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
 2486: ** to the application instead of invoking the 
 2487: ** busy handler.
 2488: ** Consider a scenario where one process is holding a read lock that
 2489: ** it is trying to promote to a reserved lock and
 2490: ** a second process is holding a reserved lock that it is trying
 2491: ** to promote to an exclusive lock.  The first process cannot proceed
 2492: ** because it is blocked by the second and the second process cannot
 2493: ** proceed because it is blocked by the first.  If both processes
 2494: ** invoke the busy handlers, neither will make any progress.  Therefore,
 2495: ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
 2496: ** will induce the first process to release its read lock and allow
 2497: ** the second process to proceed.
 2498: **
 2499: ** ^The default busy callback is NULL.
 2500: **
 2501: ** ^(There can only be a single busy handler defined for each
 2502: ** [database connection].  Setting a new busy handler clears any
 2503: ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
 2504: ** or evaluating [PRAGMA busy_timeout=N] will change the
 2505: ** busy handler and thus clear any previously set busy handler.
 2506: **
 2507: ** The busy callback should not take any actions which modify the
 2508: ** database connection that invoked the busy handler.  In other words,
 2509: ** the busy handler is not reentrant.  Any such actions
 2510: ** result in undefined behavior.
 2511: ** 
 2512: ** A busy handler must not close the database connection
 2513: ** or [prepared statement] that invoked the busy handler.
 2514: */
 2515: SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
 2516: 
 2517: /*
 2518: ** CAPI3REF: Set A Busy Timeout
 2519: ** METHOD: sqlite3
 2520: **
 2521: ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
 2522: ** for a specified amount of time when a table is locked.  ^The handler
 2523: ** will sleep multiple times until at least "ms" milliseconds of sleeping
 2524: ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
 2525: ** the handler returns 0 which causes [sqlite3_step()] to return
 2526: ** [SQLITE_BUSY].
 2527: **
 2528: ** ^Calling this routine with an argument less than or equal to zero
 2529: ** turns off all busy handlers.
 2530: **
 2531: ** ^(There can only be a single busy handler for a particular
 2532: ** [database connection] at any given moment.  If another busy handler
 2533: ** was defined  (using [sqlite3_busy_handler()]) prior to calling
 2534: ** this routine, that other busy handler is cleared.)^
 2535: **
 2536: ** See also:  [PRAGMA busy_timeout]
 2537: */
 2538: SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
 2539: 
 2540: /*
 2541: ** CAPI3REF: Convenience Routines For Running Queries
 2542: ** METHOD: sqlite3
 2543: **
 2544: ** This is a legacy interface that is preserved for backwards compatibility.
 2545: ** Use of this interface is not recommended.
 2546: **
 2547: ** Definition: A <b>result table</b> is memory data structure created by the
 2548: ** [sqlite3_get_table()] interface.  A result table records the
 2549: ** complete query results from one or more queries.
 2550: **
 2551: ** The table conceptually has a number of rows and columns.  But
 2552: ** these numbers are not part of the result table itself.  These
 2553: ** numbers are obtained separately.  Let N be the number of rows
 2554: ** and M be the number of columns.
 2555: **
 2556: ** A result table is an array of pointers to zero-terminated UTF-8 strings.
 2557: ** There are (N+1)*M elements in the array.  The first M pointers point
 2558: ** to zero-terminated strings that  contain the names of the columns.
 2559: ** The remaining entries all point to query results.  NULL values result
 2560: ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
 2561: ** string representation as returned by [sqlite3_column_text()].
 2562: **
 2563: ** A result table might consist of one or more memory allocations.
 2564: ** It is not safe to pass a result table directly to [sqlite3_free()].
 2565: ** A result table should be deallocated using [sqlite3_free_table()].
 2566: **
 2567: ** ^(As an example of the result table format, suppose a query result
 2568: ** is as follows:
 2569: **
 2570: ** <blockquote><pre>
 2571: **        Name        | Age
 2572: **        -----------------------
 2573: **        Alice       | 43
 2574: **        Bob         | 28
 2575: **        Cindy       | 21
 2576: ** </pre></blockquote>
 2577: **
 2578: ** There are two column (M==2) and three rows (N==3).  Thus the
 2579: ** result table has 8 entries.  Suppose the result table is stored
 2580: ** in an array names azResult.  Then azResult holds this content:
 2581: **
 2582: ** <blockquote><pre>
 2583: **        azResult&#91;0] = "Name";
 2584: **        azResult&#91;1] = "Age";
 2585: **        azResult&#91;2] = "Alice";
 2586: **        azResult&#91;3] = "43";
 2587: **        azResult&#91;4] = "Bob";
 2588: **        azResult&#91;5] = "28";
 2589: **        azResult&#91;6] = "Cindy";
 2590: **        azResult&#91;7] = "21";
 2591: ** </pre></blockquote>)^
 2592: **
 2593: ** ^The sqlite3_get_table() function evaluates one or more
 2594: ** semicolon-separated SQL statements in the zero-terminated UTF-8
 2595: ** string of its 2nd parameter and returns a result table to the
 2596: ** pointer given in its 3rd parameter.
 2597: **
 2598: ** After the application has finished with the result from sqlite3_get_table(),
 2599: ** it must pass the result table pointer to sqlite3_free_table() in order to
 2600: ** release the memory that was malloced.  Because of the way the
 2601: ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
 2602: ** function must not try to call [sqlite3_free()] directly.  Only
 2603: ** [sqlite3_free_table()] is able to release the memory properly and safely.
 2604: **
 2605: ** The sqlite3_get_table() interface is implemented as a wrapper around
 2606: ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
 2607: ** to any internal data structures of SQLite.  It uses only the public
 2608: ** interface defined here.  As a consequence, errors that occur in the
 2609: ** wrapper layer outside of the internal [sqlite3_exec()] call are not
 2610: ** reflected in subsequent calls to [sqlite3_errcode()] or
 2611: ** [sqlite3_errmsg()].
 2612: */
 2613: SQLITE_API int sqlite3_get_table(
 2614:   sqlite3 *db,          /* An open database */
 2615:   const char *zSql,     /* SQL to be evaluated */
 2616:   char ***pazResult,    /* Results of the query */
 2617:   int *pnRow,           /* Number of result rows written here */
 2618:   int *pnColumn,        /* Number of result columns written here */
 2619:   char **pzErrmsg       /* Error msg written here */
 2620: );
 2621: SQLITE_API void sqlite3_free_table(char **result);
 2622: 
 2623: /*
 2624: ** CAPI3REF: Formatted String Printing Functions
 2625: **
 2626: ** These routines are work-alikes of the "printf()" family of functions
 2627: ** from the standard C library.
 2628: ** These routines understand most of the common K&R formatting options,
 2629: ** plus some additional non-standard formats, detailed below.
 2630: ** Note that some of the more obscure formatting options from recent
 2631: ** C-library standards are omitted from this implementation.
 2632: **
 2633: ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
 2634: ** results into memory obtained from [sqlite3_malloc()].
 2635: ** The strings returned by these two routines should be
 2636: ** released by [sqlite3_free()].  ^Both routines return a
 2637: ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
 2638: ** memory to hold the resulting string.
 2639: **
 2640: ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
 2641: ** the standard C library.  The result is written into the
 2642: ** buffer supplied as the second parameter whose size is given by
 2643: ** the first parameter. Note that the order of the
 2644: ** first two parameters is reversed from snprintf().)^  This is an
 2645: ** historical accident that cannot be fixed without breaking
 2646: ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
 2647: ** returns a pointer to its buffer instead of the number of
 2648: ** characters actually written into the buffer.)^  We admit that
 2649: ** the number of characters written would be a more useful return
 2650: ** value but we cannot change the implementation of sqlite3_snprintf()
 2651: ** now without breaking compatibility.
 2652: **
 2653: ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
 2654: ** guarantees that the buffer is always zero-terminated.  ^The first
 2655: ** parameter "n" is the total size of the buffer, including space for
 2656: ** the zero terminator.  So the longest string that can be completely
 2657: ** written will be n-1 characters.
 2658: **
 2659: ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
 2660: **
 2661: ** These routines all implement some additional formatting
 2662: ** options that are useful for constructing SQL statements.
 2663: ** All of the usual printf() formatting options apply.  In addition, there
 2664: ** is are "%q", "%Q", "%w" and "%z" options.
 2665: **
 2666: ** ^(The %q option works like %s in that it substitutes a nul-terminated
 2667: ** string from the argument list.  But %q also doubles every '\'' character.
 2668: ** %q is designed for use inside a string literal.)^  By doubling each '\''
 2669: ** character it escapes that character and allows it to be inserted into
 2670: ** the string.
 2671: **
 2672: ** For example, assume the string variable zText contains text as follows:
 2673: **
 2674: ** <blockquote><pre>
 2675: **  char *zText = "It's a happy day!";
 2676: ** </pre></blockquote>
 2677: **
 2678: ** One can use this text in an SQL statement as follows:
 2679: **
 2680: ** <blockquote><pre>
 2681: **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
 2682: **  sqlite3_exec(db, zSQL, 0, 0, 0);
 2683: **  sqlite3_free(zSQL);
 2684: ** </pre></blockquote>
 2685: **
 2686: ** Because the %q format string is used, the '\'' character in zText
 2687: ** is escaped and the SQL generated is as follows:
 2688: **
 2689: ** <blockquote><pre>
 2690: **  INSERT INTO table1 VALUES('It''s a happy day!')
 2691: ** </pre></blockquote>
 2692: **
 2693: ** This is correct.  Had we used %s instead of %q, the generated SQL
 2694: ** would have looked like this:
 2695: **
 2696: ** <blockquote><pre>
 2697: **  INSERT INTO table1 VALUES('It's a happy day!');
 2698: ** </pre></blockquote>
 2699: **
 2700: ** This second example is an SQL syntax error.  As a general rule you should
 2701: ** always use %q instead of %s when inserting text into a string literal.
 2702: **
 2703: ** ^(The %Q option works like %q except it also adds single quotes around
 2704: ** the outside of the total string.  Additionally, if the parameter in the
 2705: ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
 2706: ** single quotes).)^  So, for example, one could say:
 2707: **
 2708: ** <blockquote><pre>
 2709: **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
 2710: **  sqlite3_exec(db, zSQL, 0, 0, 0);
 2711: **  sqlite3_free(zSQL);
 2712: ** </pre></blockquote>
 2713: **
 2714: ** The code above will render a correct SQL statement in the zSQL
 2715: ** variable even if the zText variable is a NULL pointer.
 2716: **
 2717: ** ^(The "%w" formatting option is like "%q" except that it expects to
 2718: ** be contained within double-quotes instead of single quotes, and it
 2719: ** escapes the double-quote character instead of the single-quote
 2720: ** character.)^  The "%w" formatting option is intended for safely inserting
 2721: ** table and column names into a constructed SQL statement.
 2722: **
 2723: ** ^(The "%z" formatting option works like "%s" but with the
 2724: ** addition that after the string has been read and copied into
 2725: ** the result, [sqlite3_free()] is called on the input string.)^
 2726: */
 2727: SQLITE_API char *sqlite3_mprintf(const char*,...);
 2728: SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
 2729: SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
 2730: SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
 2731: 
 2732: /*
 2733: ** CAPI3REF: Memory Allocation Subsystem
 2734: **
 2735: ** The SQLite core uses these three routines for all of its own
 2736: ** internal memory allocation needs. "Core" in the previous sentence
 2737: ** does not include operating-system specific VFS implementation.  The
 2738: ** Windows VFS uses native malloc() and free() for some operations.
 2739: **
 2740: ** ^The sqlite3_malloc() routine returns a pointer to a block
 2741: ** of memory at least N bytes in length, where N is the parameter.
 2742: ** ^If sqlite3_malloc() is unable to obtain sufficient free
 2743: ** memory, it returns a NULL pointer.  ^If the parameter N to
 2744: ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
 2745: ** a NULL pointer.
 2746: **
 2747: ** ^The sqlite3_malloc64(N) routine works just like
 2748: ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
 2749: ** of a signed 32-bit integer.
 2750: **
 2751: ** ^Calling sqlite3_free() with a pointer previously returned
 2752: ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
 2753: ** that it might be reused.  ^The sqlite3_free() routine is
 2754: ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
 2755: ** to sqlite3_free() is harmless.  After being freed, memory
 2756: ** should neither be read nor written.  Even reading previously freed
 2757: ** memory might result in a segmentation fault or other severe error.
 2758: ** Memory corruption, a segmentation fault, or other severe error
 2759: ** might result if sqlite3_free() is called with a non-NULL pointer that
 2760: ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
 2761: **
 2762: ** ^The sqlite3_realloc(X,N) interface attempts to resize a
 2763: ** prior memory allocation X to be at least N bytes.
 2764: ** ^If the X parameter to sqlite3_realloc(X,N)
 2765: ** is a NULL pointer then its behavior is identical to calling
 2766: ** sqlite3_malloc(N).
 2767: ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
 2768: ** negative then the behavior is exactly the same as calling
 2769: ** sqlite3_free(X).
 2770: ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
 2771: ** of at least N bytes in size or NULL if insufficient memory is available.
 2772: ** ^If M is the size of the prior allocation, then min(N,M) bytes
 2773: ** of the prior allocation are copied into the beginning of buffer returned
 2774: ** by sqlite3_realloc(X,N) and the prior allocation is freed.
 2775: ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
 2776: ** prior allocation is not freed.
 2777: **
 2778: ** ^The sqlite3_realloc64(X,N) interfaces works the same as
 2779: ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
 2780: ** of a 32-bit signed integer.
 2781: **
 2782: ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
 2783: ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
 2784: ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
 2785: ** ^The value returned by sqlite3_msize(X) might be larger than the number
 2786: ** of bytes requested when X was allocated.  ^If X is a NULL pointer then
 2787: ** sqlite3_msize(X) returns zero.  If X points to something that is not
 2788: ** the beginning of memory allocation, or if it points to a formerly
 2789: ** valid memory allocation that has now been freed, then the behavior
 2790: ** of sqlite3_msize(X) is undefined and possibly harmful.
 2791: **
 2792: ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
 2793: ** sqlite3_malloc64(), and sqlite3_realloc64()
 2794: ** is always aligned to at least an 8 byte boundary, or to a
 2795: ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
 2796: ** option is used.
 2797: **
 2798: ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
 2799: ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
 2800: ** implementation of these routines to be omitted.  That capability
 2801: ** is no longer provided.  Only built-in memory allocators can be used.
 2802: **
 2803: ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
 2804: ** the system malloc() and free() directly when converting
 2805: ** filenames between the UTF-8 encoding used by SQLite
 2806: ** and whatever filename encoding is used by the particular Windows
 2807: ** installation.  Memory allocation errors were detected, but
 2808: ** they were reported back as [SQLITE_CANTOPEN] or
 2809: ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
 2810: **
 2811: ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
 2812: ** must be either NULL or else pointers obtained from a prior
 2813: ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
 2814: ** not yet been released.
 2815: **
 2816: ** The application must not read or write any part of
 2817: ** a block of memory after it has been released using
 2818: ** [sqlite3_free()] or [sqlite3_realloc()].
 2819: */
 2820: SQLITE_API void *sqlite3_malloc(int);
 2821: SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
 2822: SQLITE_API void *sqlite3_realloc(void*, int);
 2823: SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
 2824: SQLITE_API void sqlite3_free(void*);
 2825: SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
 2826: 
 2827: /*
 2828: ** CAPI3REF: Memory Allocator Statistics
 2829: **
 2830: ** SQLite provides these two interfaces for reporting on the status
 2831: ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
 2832: ** routines, which form the built-in memory allocation subsystem.
 2833: **
 2834: ** ^The [sqlite3_memory_used()] routine returns the number of bytes
 2835: ** of memory currently outstanding (malloced but not freed).
 2836: ** ^The [sqlite3_memory_highwater()] routine returns the maximum
 2837: ** value of [sqlite3_memory_used()] since the high-water mark
 2838: ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
 2839: ** [sqlite3_memory_highwater()] include any overhead
 2840: ** added by SQLite in its implementation of [sqlite3_malloc()],
 2841: ** but not overhead added by the any underlying system library
 2842: ** routines that [sqlite3_malloc()] may call.
 2843: **
 2844: ** ^The memory high-water mark is reset to the current value of
 2845: ** [sqlite3_memory_used()] if and only if the parameter to
 2846: ** [sqlite3_memory_highwater()] is true.  ^The value returned
 2847: ** by [sqlite3_memory_highwater(1)] is the high-water mark
 2848: ** prior to the reset.
 2849: */
 2850: SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
 2851: SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
 2852: 
 2853: /*
 2854: ** CAPI3REF: Pseudo-Random Number Generator
 2855: **
 2856: ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
 2857: ** select random [ROWID | ROWIDs] when inserting new records into a table that
 2858: ** already uses the largest possible [ROWID].  The PRNG is also used for
 2859: ** the build-in random() and randomblob() SQL functions.  This interface allows
 2860: ** applications to access the same PRNG for other purposes.
 2861: **
 2862: ** ^A call to this routine stores N bytes of randomness into buffer P.
 2863: ** ^The P parameter can be a NULL pointer.
 2864: **
 2865: ** ^If this routine has not been previously called or if the previous
 2866: ** call had N less than one or a NULL pointer for P, then the PRNG is
 2867: ** seeded using randomness obtained from the xRandomness method of
 2868: ** the default [sqlite3_vfs] object.
 2869: ** ^If the previous call to this routine had an N of 1 or more and a
 2870: ** non-NULL P then the pseudo-randomness is generated
 2871: ** internally and without recourse to the [sqlite3_vfs] xRandomness
 2872: ** method.
 2873: */
 2874: SQLITE_API void sqlite3_randomness(int N, void *P);
 2875: 
 2876: /*
 2877: ** CAPI3REF: Compile-Time Authorization Callbacks
 2878: ** METHOD: sqlite3
 2879: **
 2880: ** ^This routine registers an authorizer callback with a particular
 2881: ** [database connection], supplied in the first argument.
 2882: ** ^The authorizer callback is invoked as SQL statements are being compiled
 2883: ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
 2884: ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
 2885: ** points during the compilation process, as logic is being created
 2886: ** to perform various actions, the authorizer callback is invoked to
 2887: ** see if those actions are allowed.  ^The authorizer callback should
 2888: ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
 2889: ** specific action but allow the SQL statement to continue to be
 2890: ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
 2891: ** rejected with an error.  ^If the authorizer callback returns
 2892: ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
 2893: ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
 2894: ** the authorizer will fail with an error message.
 2895: **
 2896: ** When the callback returns [SQLITE_OK], that means the operation
 2897: ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
 2898: ** [sqlite3_prepare_v2()] or equivalent call that triggered the
 2899: ** authorizer will fail with an error message explaining that
 2900: ** access is denied. 
 2901: **
 2902: ** ^The first parameter to the authorizer callback is a copy of the third
 2903: ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
 2904: ** to the callback is an integer [SQLITE_COPY | action code] that specifies
 2905: ** the particular action to be authorized. ^The third through sixth parameters
 2906: ** to the callback are zero-terminated strings that contain additional
 2907: ** details about the action to be authorized.
 2908: **
 2909: ** ^If the action code is [SQLITE_READ]
 2910: ** and the callback returns [SQLITE_IGNORE] then the
 2911: ** [prepared statement] statement is constructed to substitute
 2912: ** a NULL value in place of the table column that would have
 2913: ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
 2914: ** return can be used to deny an untrusted user access to individual
 2915: ** columns of a table.
 2916: ** ^If the action code is [SQLITE_DELETE] and the callback returns
 2917: ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
 2918: ** [truncate optimization] is disabled and all rows are deleted individually.
 2919: **
 2920: ** An authorizer is used when [sqlite3_prepare | preparing]
 2921: ** SQL statements from an untrusted source, to ensure that the SQL statements
 2922: ** do not try to access data they are not allowed to see, or that they do not
 2923: ** try to execute malicious statements that damage the database.  For
 2924: ** example, an application may allow a user to enter arbitrary
 2925: ** SQL queries for evaluation by a database.  But the application does
 2926: ** not want the user to be able to make arbitrary changes to the
 2927: ** database.  An authorizer could then be put in place while the
 2928: ** user-entered SQL is being [sqlite3_prepare | prepared] that
 2929: ** disallows everything except [SELECT] statements.
 2930: **
 2931: ** Applications that need to process SQL from untrusted sources
 2932: ** might also consider lowering resource limits using [sqlite3_limit()]
 2933: ** and limiting database size using the [max_page_count] [PRAGMA]
 2934: ** in addition to using an authorizer.
 2935: **
 2936: ** ^(Only a single authorizer can be in place on a database connection
 2937: ** at a time.  Each call to sqlite3_set_authorizer overrides the
 2938: ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
 2939: ** The authorizer is disabled by default.
 2940: **
 2941: ** The authorizer callback must not do anything that will modify
 2942: ** the database connection that invoked the authorizer callback.
 2943: ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
 2944: ** database connections for the meaning of "modify" in this paragraph.
 2945: **
 2946: ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
 2947: ** statement might be re-prepared during [sqlite3_step()] due to a 
 2948: ** schema change.  Hence, the application should ensure that the
 2949: ** correct authorizer callback remains in place during the [sqlite3_step()].
 2950: **
 2951: ** ^Note that the authorizer callback is invoked only during
 2952: ** [sqlite3_prepare()] or its variants.  Authorization is not
 2953: ** performed during statement evaluation in [sqlite3_step()], unless
 2954: ** as stated in the previous paragraph, sqlite3_step() invokes
 2955: ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
 2956: */
 2957: SQLITE_API int sqlite3_set_authorizer(
 2958:   sqlite3*,
 2959:   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
 2960:   void *pUserData
 2961: );
 2962: 
 2963: /*
 2964: ** CAPI3REF: Authorizer Return Codes
 2965: **
 2966: ** The [sqlite3_set_authorizer | authorizer callback function] must
 2967: ** return either [SQLITE_OK] or one of these two constants in order
 2968: ** to signal SQLite whether or not the action is permitted.  See the
 2969: ** [sqlite3_set_authorizer | authorizer documentation] for additional
 2970: ** information.
 2971: **
 2972: ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
 2973: ** returned from the [sqlite3_vtab_on_conflict()] interface.
 2974: */
 2975: #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
 2976: #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
 2977: 
 2978: /*
 2979: ** CAPI3REF: Authorizer Action Codes
 2980: **
 2981: ** The [sqlite3_set_authorizer()] interface registers a callback function
 2982: ** that is invoked to authorize certain SQL statement actions.  The
 2983: ** second parameter to the callback is an integer code that specifies
 2984: ** what action is being authorized.  These are the integer action codes that
 2985: ** the authorizer callback may be passed.
 2986: **
 2987: ** These action code values signify what kind of operation is to be
 2988: ** authorized.  The 3rd and 4th parameters to the authorization
 2989: ** callback function will be parameters or NULL depending on which of these
 2990: ** codes is used as the second parameter.  ^(The 5th parameter to the
 2991: ** authorizer callback is the name of the database ("main", "temp",
 2992: ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
 2993: ** is the name of the inner-most trigger or view that is responsible for
 2994: ** the access attempt or NULL if this access attempt is directly from
 2995: ** top-level SQL code.
 2996: */
 2997: /******************************************* 3rd ************ 4th ***********/
 2998: #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
 2999: #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
 3000: #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
 3001: #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
 3002: #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
 3003: #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
 3004: #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
 3005: #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
 3006: #define SQLITE_DELETE                9   /* Table Name      NULL            */
 3007: #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
 3008: #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
 3009: #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
 3010: #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
 3011: #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
 3012: #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
 3013: #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
 3014: #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
 3015: #define SQLITE_INSERT               18   /* Table Name      NULL            */
 3016: #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
 3017: #define SQLITE_READ                 20   /* Table Name      Column Name     */
 3018: #define SQLITE_SELECT               21   /* NULL            NULL            */
 3019: #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
 3020: #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
 3021: #define SQLITE_ATTACH               24   /* Filename        NULL            */
 3022: #define SQLITE_DETACH               25   /* Database Name   NULL            */
 3023: #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
 3024: #define SQLITE_REINDEX              27   /* Index Name      NULL            */
 3025: #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
 3026: #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
 3027: #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
 3028: #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
 3029: #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
 3030: #define SQLITE_COPY                  0   /* No longer used */
 3031: #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
 3032: 
 3033: /*
 3034: ** CAPI3REF: Tracing And Profiling Functions
 3035: ** METHOD: sqlite3
 3036: **
 3037: ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
 3038: ** instead of the routines described here.
 3039: **
 3040: ** These routines register callback functions that can be used for
 3041: ** tracing and profiling the execution of SQL statements.
 3042: **
 3043: ** ^The callback function registered by sqlite3_trace() is invoked at
 3044: ** various times when an SQL statement is being run by [sqlite3_step()].
 3045: ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
 3046: ** SQL statement text as the statement first begins executing.
 3047: ** ^(Additional sqlite3_trace() callbacks might occur
 3048: ** as each triggered subprogram is entered.  The callbacks for triggers
 3049: ** contain a UTF-8 SQL comment that identifies the trigger.)^
 3050: **
 3051: ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
 3052: ** the length of [bound parameter] expansion in the output of sqlite3_trace().
 3053: **
 3054: ** ^The callback function registered by sqlite3_profile() is invoked
 3055: ** as each SQL statement finishes.  ^The profile callback contains
 3056: ** the original statement text and an estimate of wall-clock time
 3057: ** of how long that statement took to run.  ^The profile callback
 3058: ** time is in units of nanoseconds, however the current implementation
 3059: ** is only capable of millisecond resolution so the six least significant
 3060: ** digits in the time are meaningless.  Future versions of SQLite
 3061: ** might provide greater resolution on the profiler callback.  The
 3062: ** sqlite3_profile() function is considered experimental and is
 3063: ** subject to change in future versions of SQLite.
 3064: */
 3065: SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
 3066:    void(*xTrace)(void*,const char*), void*);
 3067: SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
 3068:    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
 3069: 
 3070: /*
 3071: ** CAPI3REF: SQL Trace Event Codes
 3072: ** KEYWORDS: SQLITE_TRACE
 3073: **
 3074: ** These constants identify classes of events that can be monitored
 3075: ** using the [sqlite3_trace_v2()] tracing logic.  The third argument
 3076: ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
 3077: ** the following constants.  ^The first argument to the trace callback
 3078: ** is one of the following constants.
 3079: **
 3080: ** New tracing constants may be added in future releases.
 3081: **
 3082: ** ^A trace callback has four arguments: xCallback(T,C,P,X).
 3083: ** ^The T argument is one of the integer type codes above.
 3084: ** ^The C argument is a copy of the context pointer passed in as the
 3085: ** fourth argument to [sqlite3_trace_v2()].
 3086: ** The P and X arguments are pointers whose meanings depend on T.
 3087: **
 3088: ** <dl>
 3089: ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
 3090: ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
 3091: ** first begins running and possibly at other times during the
 3092: ** execution of the prepared statement, such as at the start of each
 3093: ** trigger subprogram. ^The P argument is a pointer to the
 3094: ** [prepared statement]. ^The X argument is a pointer to a string which
 3095: ** is the unexpanded SQL text of the prepared statement or an SQL comment 
 3096: ** that indicates the invocation of a trigger.  ^The callback can compute
 3097: ** the same text that would have been returned by the legacy [sqlite3_trace()]
 3098: ** interface by using the X argument when X begins with "--" and invoking
 3099: ** [sqlite3_expanded_sql(P)] otherwise.
 3100: **
 3101: ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
 3102: ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
 3103: ** information as is provided by the [sqlite3_profile()] callback.
 3104: ** ^The P argument is a pointer to the [prepared statement] and the
 3105: ** X argument points to a 64-bit integer which is the estimated of
 3106: ** the number of nanosecond that the prepared statement took to run.
 3107: ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
 3108: **
 3109: ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
 3110: ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
 3111: ** statement generates a single row of result.  
 3112: ** ^The P argument is a pointer to the [prepared statement] and the
 3113: ** X argument is unused.
 3114: **
 3115: ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
 3116: ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
 3117: ** connection closes.
 3118: ** ^The P argument is a pointer to the [database connection] object
 3119: ** and the X argument is unused.
 3120: ** </dl>
 3121: */
 3122: #define SQLITE_TRACE_STMT       0x01
 3123: #define SQLITE_TRACE_PROFILE    0x02
 3124: #define SQLITE_TRACE_ROW        0x04
 3125: #define SQLITE_TRACE_CLOSE      0x08
 3126: 
 3127: /*
 3128: ** CAPI3REF: SQL Trace Hook
 3129: ** METHOD: sqlite3
 3130: **
 3131: ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
 3132: ** function X against [database connection] D, using property mask M
 3133: ** and context pointer P.  ^If the X callback is
 3134: ** NULL or if the M mask is zero, then tracing is disabled.  The
 3135: ** M argument should be the bitwise OR-ed combination of
 3136: ** zero or more [SQLITE_TRACE] constants.
 3137: **
 3138: ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides 
 3139: ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
 3140: **
 3141: ** ^The X callback is invoked whenever any of the events identified by 
 3142: ** mask M occur.  ^The integer return value from the callback is currently
 3143: ** ignored, though this may change in future releases.  Callback
 3144: ** implementations should return zero to ensure future compatibility.
 3145: **
 3146: ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
 3147: ** ^The T argument is one of the [SQLITE_TRACE]
 3148: ** constants to indicate why the callback was invoked.
 3149: ** ^The C argument is a copy of the context pointer.
 3150: ** The P and X arguments are pointers whose meanings depend on T.
 3151: **
 3152: ** The sqlite3_trace_v2() interface is intended to replace the legacy
 3153: ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
 3154: ** are deprecated.
 3155: */
 3156: SQLITE_API int sqlite3_trace_v2(
 3157:   sqlite3*,
 3158:   unsigned uMask,
 3159:   int(*xCallback)(unsigned,void*,void*,void*),
 3160:   void *pCtx
 3161: );
 3162: 
 3163: /*
 3164: ** CAPI3REF: Query Progress Callbacks
 3165: ** METHOD: sqlite3
 3166: **
 3167: ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
 3168: ** function X to be invoked periodically during long running calls to
 3169: ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
 3170: ** database connection D.  An example use for this
 3171: ** interface is to keep a GUI updated during a large query.
 3172: **
 3173: ** ^The parameter P is passed through as the only parameter to the 
 3174: ** callback function X.  ^The parameter N is the approximate number of 
 3175: ** [virtual machine instructions] that are evaluated between successive
 3176: ** invocations of the callback X.  ^If N is less than one then the progress
 3177: ** handler is disabled.
 3178: **
 3179: ** ^Only a single progress handler may be defined at one time per
 3180: ** [database connection]; setting a new progress handler cancels the
 3181: ** old one.  ^Setting parameter X to NULL disables the progress handler.
 3182: ** ^The progress handler is also disabled by setting N to a value less
 3183: ** than 1.
 3184: **
 3185: ** ^If the progress callback returns non-zero, the operation is
 3186: ** interrupted.  This feature can be used to implement a
 3187: ** "Cancel" button on a GUI progress dialog box.
 3188: **
 3189: ** The progress handler callback must not do anything that will modify
 3190: ** the database connection that invoked the progress handler.
 3191: ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
 3192: ** database connections for the meaning of "modify" in this paragraph.
 3193: **
 3194: */
 3195: SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
 3196: 
 3197: /*
 3198: ** CAPI3REF: Opening A New Database Connection
 3199: ** CONSTRUCTOR: sqlite3
 3200: **
 3201: ** ^These routines open an SQLite database file as specified by the 
 3202: ** filename argument. ^The filename argument is interpreted as UTF-8 for
 3203: ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
 3204: ** order for sqlite3_open16(). ^(A [database connection] handle is usually
 3205: ** returned in *ppDb, even if an error occurs.  The only exception is that
 3206: ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
 3207: ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
 3208: ** object.)^ ^(If the database is opened (and/or created) successfully, then
 3209: ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
 3210: ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
 3211: ** an English language description of the error following a failure of any
 3212: ** of the sqlite3_open() routines.
 3213: **
 3214: ** ^The default encoding will be UTF-8 for databases created using
 3215: ** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
 3216: ** created using sqlite3_open16() will be UTF-16 in the native byte order.
 3217: **
 3218: ** Whether or not an error occurs when it is opened, resources
 3219: ** associated with the [database connection] handle should be released by
 3220: ** passing it to [sqlite3_close()] when it is no longer required.
 3221: **
 3222: ** The sqlite3_open_v2() interface works like sqlite3_open()
 3223: ** except that it accepts two additional parameters for additional control
 3224: ** over the new database connection.  ^(The flags parameter to
 3225: ** sqlite3_open_v2() can take one of
 3226: ** the following three values, optionally combined with the 
 3227: ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
 3228: ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
 3229: **
 3230: ** <dl>
 3231: ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
 3232: ** <dd>The database is opened in read-only mode.  If the database does not
 3233: ** already exist, an error is returned.</dd>)^
 3234: **
 3235: ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
 3236: ** <dd>The database is opened for reading and writing if possible, or reading
 3237: ** only if the file is write protected by the operating system.  In either
 3238: ** case the database must already exist, otherwise an error is returned.</dd>)^
 3239: **
 3240: ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
 3241: ** <dd>The database is opened for reading and writing, and is created if
 3242: ** it does not already exist. This is the behavior that is always used for
 3243: ** sqlite3_open() and sqlite3_open16().</dd>)^
 3244: ** </dl>
 3245: **
 3246: ** If the 3rd parameter to sqlite3_open_v2() is not one of the
 3247: ** combinations shown above optionally combined with other
 3248: ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
 3249: ** then the behavior is undefined.
 3250: **
 3251: ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
 3252: ** opens in the multi-thread [threading mode] as long as the single-thread
 3253: ** mode has not been set at compile-time or start-time.  ^If the
 3254: ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
 3255: ** in the serialized [threading mode] unless single-thread was
 3256: ** previously selected at compile-time or start-time.
 3257: ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
 3258: ** eligible to use [shared cache mode], regardless of whether or not shared
 3259: ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
 3260: ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
 3261: ** participate in [shared cache mode] even if it is enabled.
 3262: **
 3263: ** ^The fourth parameter to sqlite3_open_v2() is the name of the
 3264: ** [sqlite3_vfs] object that defines the operating system interface that
 3265: ** the new database connection should use.  ^If the fourth parameter is
 3266: ** a NULL pointer then the default [sqlite3_vfs] object is used.
 3267: **
 3268: ** ^If the filename is ":memory:", then a private, temporary in-memory database
 3269: ** is created for the connection.  ^This in-memory database will vanish when
 3270: ** the database connection is closed.  Future versions of SQLite might
 3271: ** make use of additional special filenames that begin with the ":" character.
 3272: ** It is recommended that when a database filename actually does begin with
 3273: ** a ":" character you should prefix the filename with a pathname such as
 3274: ** "./" to avoid ambiguity.
 3275: **
 3276: ** ^If the filename is an empty string, then a private, temporary
 3277: ** on-disk database will be created.  ^This private database will be
 3278: ** automatically deleted as soon as the database connection is closed.
 3279: **
 3280: ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
 3281: **
 3282: ** ^If [URI filename] interpretation is enabled, and the filename argument
 3283: ** begins with "file:", then the filename is interpreted as a URI. ^URI
 3284: ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
 3285: ** set in the fourth argument to sqlite3_open_v2(), or if it has
 3286: ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
 3287: ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
 3288: ** As of SQLite version 3.7.7, URI filename interpretation is turned off
 3289: ** by default, but future releases of SQLite might enable URI filename
 3290: ** interpretation by default.  See "[URI filenames]" for additional
 3291: ** information.
 3292: **
 3293: ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
 3294: ** authority, then it must be either an empty string or the string 
 3295: ** "localhost". ^If the authority is not an empty string or "localhost", an 
 3296: ** error is returned to the caller. ^The fragment component of a URI, if 
 3297: ** present, is ignored.
 3298: **
 3299: ** ^SQLite uses the path component of the URI as the name of the disk file
 3300: ** which contains the database. ^If the path begins with a '/' character, 
 3301: ** then it is interpreted as an absolute path. ^If the path does not begin 
 3302: ** with a '/' (meaning that the authority section is omitted from the URI)
 3303: ** then the path is interpreted as a relative path. 
 3304: ** ^(On windows, the first component of an absolute path 
 3305: ** is a drive specification (e.g. "C:").)^
 3306: **
 3307: ** [[core URI query parameters]]
 3308: ** The query component of a URI may contain parameters that are interpreted
 3309: ** either by SQLite itself, or by a [VFS | custom VFS implementation].
 3310: ** SQLite and its built-in [VFSes] interpret the
 3311: ** following query parameters:
 3312: **
 3313: ** <ul>
 3314: **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
 3315: **     a VFS object that provides the operating system interface that should
 3316: **     be used to access the database file on disk. ^If this option is set to
 3317: **     an empty string the default VFS object is used. ^Specifying an unknown
 3318: **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
 3319: **     present, then the VFS specified by the option takes precedence over
 3320: **     the value passed as the fourth parameter to sqlite3_open_v2().
 3321: **
 3322: **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
 3323: **     "rwc", or "memory". Attempting to set it to any other value is
 3324: **     an error)^. 
 3325: **     ^If "ro" is specified, then the database is opened for read-only 
 3326: **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
 3327: **     third argument to sqlite3_open_v2(). ^If the mode option is set to 
 3328: **     "rw", then the database is opened for read-write (but not create) 
 3329: **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
 3330: **     been set. ^Value "rwc" is equivalent to setting both 
 3331: **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
 3332: **     set to "memory" then a pure [in-memory database] that never reads
 3333: **     or writes from disk is used. ^It is an error to specify a value for
 3334: **     the mode parameter that is less restrictive than that specified by
 3335: **     the flags passed in the third parameter to sqlite3_open_v2().
 3336: **
 3337: **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
 3338: **     "private". ^Setting it to "shared" is equivalent to setting the
 3339: **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
 3340: **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
 3341: **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
 3342: **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
 3343: **     a URI filename, its value overrides any behavior requested by setting
 3344: **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
 3345: **
 3346: **  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
 3347: **     [powersafe overwrite] property does or does not apply to the
 3348: **     storage media on which the database file resides.
 3349: **
 3350: **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
 3351: **     which if set disables file locking in rollback journal modes.  This
 3352: **     is useful for accessing a database on a filesystem that does not
 3353: **     support locking.  Caution:  Database corruption might result if two
 3354: **     or more processes write to the same database and any one of those
 3355: **     processes uses nolock=1.
 3356: **
 3357: **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
 3358: **     parameter that indicates that the database file is stored on
 3359: **     read-only media.  ^When immutable is set, SQLite assumes that the
 3360: **     database file cannot be changed, even by a process with higher
 3361: **     privilege, and so the database is opened read-only and all locking
 3362: **     and change detection is disabled.  Caution: Setting the immutable
 3363: **     property on a database file that does in fact change can result
 3364: **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
 3365: **     See also: [SQLITE_IOCAP_IMMUTABLE].
 3366: **       
 3367: ** </ul>
 3368: **
 3369: ** ^Specifying an unknown parameter in the query component of a URI is not an
 3370: ** error.  Future versions of SQLite might understand additional query
 3371: ** parameters.  See "[query parameters with special meaning to SQLite]" for
 3372: ** additional information.
 3373: **
 3374: ** [[URI filename examples]] <h3>URI filename examples</h3>
 3375: **
 3376: ** <table border="1" align=center cellpadding=5>
 3377: ** <tr><th> URI filenames <th> Results
 3378: ** <tr><td> file:data.db <td> 
 3379: **          Open the file "data.db" in the current directory.
 3380: ** <tr><td> file:/home/fred/data.db<br>
 3381: **          file:///home/fred/data.db <br> 
 3382: **          file://localhost/home/fred/data.db <br> <td> 
 3383: **          Open the database file "/home/fred/data.db".
 3384: ** <tr><td> file://darkstar/home/fred/data.db <td> 
 3385: **          An error. "darkstar" is not a recognized authority.
 3386: ** <tr><td style="white-space:nowrap"> 
 3387: **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
 3388: **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
 3389: **          C:. Note that the %20 escaping in this example is not strictly 
 3390: **          necessary - space characters can be used literally
 3391: **          in URI filenames.
 3392: ** <tr><td> file:data.db?mode=ro&cache=private <td> 
 3393: **          Open file "data.db" in the current directory for read-only access.
 3394: **          Regardless of whether or not shared-cache mode is enabled by
 3395: **          default, use a private cache.
 3396: ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
 3397: **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
 3398: **          that uses dot-files in place of posix advisory locking.
 3399: ** <tr><td> file:data.db?mode=readonly <td> 
 3400: **          An error. "readonly" is not a valid option for the "mode" parameter.
 3401: ** </table>
 3402: **
 3403: ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
 3404: ** query components of a URI. A hexadecimal escape sequence consists of a
 3405: ** percent sign - "%" - followed by exactly two hexadecimal digits 
 3406: ** specifying an octet value. ^Before the path or query components of a
 3407: ** URI filename are interpreted, they are encoded using UTF-8 and all 
 3408: ** hexadecimal escape sequences replaced by a single byte containing the
 3409: ** corresponding octet. If this process generates an invalid UTF-8 encoding,
 3410: ** the results are undefined.
 3411: **
 3412: ** <b>Note to Windows users:</b>  The encoding used for the filename argument
 3413: ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
 3414: ** codepage is currently defined.  Filenames containing international
 3415: ** characters must be converted to UTF-8 prior to passing them into
 3416: ** sqlite3_open() or sqlite3_open_v2().
 3417: **
 3418: ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
 3419: ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
 3420: ** features that require the use of temporary files may fail.
 3421: **
 3422: ** See also: [sqlite3_temp_directory]
 3423: */
 3424: SQLITE_API int sqlite3_open(
 3425:   const char *filename,   /* Database filename (UTF-8) */
 3426:   sqlite3 **ppDb          /* OUT: SQLite db handle */
 3427: );
 3428: SQLITE_API int sqlite3_open16(
 3429:   const void *filename,   /* Database filename (UTF-16) */
 3430:   sqlite3 **ppDb          /* OUT: SQLite db handle */
 3431: );
 3432: SQLITE_API int sqlite3_open_v2(
 3433:   const char *filename,   /* Database filename (UTF-8) */
 3434:   sqlite3 **ppDb,         /* OUT: SQLite db handle */
 3435:   int flags,              /* Flags */
 3436:   const char *zVfs        /* Name of VFS module to use */
 3437: );
 3438: 
 3439: /*
 3440: ** CAPI3REF: Obtain Values For URI Parameters
 3441: **
 3442: ** These are utility routines, useful to VFS implementations, that check
 3443: ** to see if a database file was a URI that contained a specific query 
 3444: ** parameter, and if so obtains the value of that query parameter.
 3445: **
 3446: ** If F is the database filename pointer passed into the xOpen() method of 
 3447: ** a VFS implementation when the flags parameter to xOpen() has one or 
 3448: ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
 3449: ** P is the name of the query parameter, then
 3450: ** sqlite3_uri_parameter(F,P) returns the value of the P
 3451: ** parameter if it exists or a NULL pointer if P does not appear as a 
 3452: ** query parameter on F.  If P is a query parameter of F
 3453: ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
 3454: ** a pointer to an empty string.
 3455: **
 3456: ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
 3457: ** parameter and returns true (1) or false (0) according to the value
 3458: ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
 3459: ** value of query parameter P is one of "yes", "true", or "on" in any
 3460: ** case or if the value begins with a non-zero number.  The 
 3461: ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
 3462: ** query parameter P is one of "no", "false", or "off" in any case or
 3463: ** if the value begins with a numeric zero.  If P is not a query
 3464: ** parameter on F or if the value of P is does not match any of the
 3465: ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
 3466: **
 3467: ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
 3468: ** 64-bit signed integer and returns that integer, or D if P does not
 3469: ** exist.  If the value of P is something other than an integer, then
 3470: ** zero is returned.
 3471: ** 
 3472: ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
 3473: ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
 3474: ** is not a database file pathname pointer that SQLite passed into the xOpen
 3475: ** VFS method, then the behavior of this routine is undefined and probably
 3476: ** undesirable.
 3477: */
 3478: SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
 3479: SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
 3480: SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
 3481: 
 3482: 
 3483: /*
 3484: ** CAPI3REF: Error Codes And Messages
 3485: ** METHOD: sqlite3
 3486: **
 3487: ** ^If the most recent sqlite3_* API call associated with 
 3488: ** [database connection] D failed, then the sqlite3_errcode(D) interface
 3489: ** returns the numeric [result code] or [extended result code] for that
 3490: ** API call.
 3491: ** If the most recent API call was successful,
 3492: ** then the return value from sqlite3_errcode() is undefined.
 3493: ** ^The sqlite3_extended_errcode()
 3494: ** interface is the same except that it always returns the 
 3495: ** [extended result code] even when extended result codes are
 3496: ** disabled.
 3497: **
 3498: ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
 3499: ** text that describes the error, as either UTF-8 or UTF-16 respectively.
 3500: ** ^(Memory to hold the error message string is managed internally.
 3501: ** The application does not need to worry about freeing the result.
 3502: ** However, the error string might be overwritten or deallocated by
 3503: ** subsequent calls to other SQLite interface functions.)^
 3504: **
 3505: ** ^The sqlite3_errstr() interface returns the English-language text
 3506: ** that describes the [result code], as UTF-8.
 3507: ** ^(Memory to hold the error message string is managed internally
 3508: ** and must not be freed by the application)^.
 3509: **
 3510: ** When the serialized [threading mode] is in use, it might be the
 3511: ** case that a second error occurs on a separate thread in between
 3512: ** the time of the first error and the call to these interfaces.
 3513: ** When that happens, the second error will be reported since these
 3514: ** interfaces always report the most recent result.  To avoid
 3515: ** this, each thread can obtain exclusive use of the [database connection] D
 3516: ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
 3517: ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
 3518: ** all calls to the interfaces listed here are completed.
 3519: **
 3520: ** If an interface fails with SQLITE_MISUSE, that means the interface
 3521: ** was invoked incorrectly by the application.  In that case, the
 3522: ** error code and message may or may not be set.
 3523: */
 3524: SQLITE_API int sqlite3_errcode(sqlite3 *db);
 3525: SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
 3526: SQLITE_API const char *sqlite3_errmsg(sqlite3*);
 3527: SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
 3528: SQLITE_API const char *sqlite3_errstr(int);
 3529: 
 3530: /*
 3531: ** CAPI3REF: Prepared Statement Object
 3532: ** KEYWORDS: {prepared statement} {prepared statements}
 3533: **
 3534: ** An instance of this object represents a single SQL statement that
 3535: ** has been compiled into binary form and is ready to be evaluated.
 3536: **
 3537: ** Think of each SQL statement as a separate computer program.  The
 3538: ** original SQL text is source code.  A prepared statement object 
 3539: ** is the compiled object code.  All SQL must be converted into a
 3540: ** prepared statement before it can be run.
 3541: **
 3542: ** The life-cycle of a prepared statement object usually goes like this:
 3543: **
 3544: ** <ol>
 3545: ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
 3546: ** <li> Bind values to [parameters] using the sqlite3_bind_*()
 3547: **      interfaces.
 3548: ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
 3549: ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
 3550: **      to step 2.  Do this zero or more times.
 3551: ** <li> Destroy the object using [sqlite3_finalize()].
 3552: ** </ol>
 3553: */
 3554: typedef struct sqlite3_stmt sqlite3_stmt;
 3555: 
 3556: /*
 3557: ** CAPI3REF: Run-time Limits
 3558: ** METHOD: sqlite3
 3559: **
 3560: ** ^(This interface allows the size of various constructs to be limited
 3561: ** on a connection by connection basis.  The first parameter is the
 3562: ** [database connection] whose limit is to be set or queried.  The
 3563: ** second parameter is one of the [limit categories] that define a
 3564: ** class of constructs to be size limited.  The third parameter is the
 3565: ** new limit for that construct.)^
 3566: **
 3567: ** ^If the new limit is a negative number, the limit is unchanged.
 3568: ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
 3569: ** [limits | hard upper bound]
 3570: ** set at compile-time by a C preprocessor macro called
 3571: ** [limits | SQLITE_MAX_<i>NAME</i>].
 3572: ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
 3573: ** ^Attempts to increase a limit above its hard upper bound are
 3574: ** silently truncated to the hard upper bound.
 3575: **
 3576: ** ^Regardless of whether or not the limit was changed, the 
 3577: ** [sqlite3_limit()] interface returns the prior value of the limit.
 3578: ** ^Hence, to find the current value of a limit without changing it,
 3579: ** simply invoke this interface with the third parameter set to -1.
 3580: **
 3581: ** Run-time limits are intended for use in applications that manage
 3582: ** both their own internal database and also databases that are controlled
 3583: ** by untrusted external sources.  An example application might be a
 3584: ** web browser that has its own databases for storing history and
 3585: ** separate databases controlled by JavaScript applications downloaded
 3586: ** off the Internet.  The internal databases can be given the
 3587: ** large, default limits.  Databases managed by external sources can
 3588: ** be given much smaller limits designed to prevent a denial of service
 3589: ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
 3590: ** interface to further control untrusted SQL.  The size of the database
 3591: ** created by an untrusted script can be contained using the
 3592: ** [max_page_count] [PRAGMA].
 3593: **
 3594: ** New run-time limit categories may be added in future releases.
 3595: */
 3596: SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
 3597: 
 3598: /*
 3599: ** CAPI3REF: Run-Time Limit Categories
 3600: ** KEYWORDS: {limit category} {*limit categories}
 3601: **
 3602: ** These constants define various performance limits
 3603: ** that can be lowered at run-time using [sqlite3_limit()].
 3604: ** The synopsis of the meanings of the various limits is shown below.
 3605: ** Additional information is available at [limits | Limits in SQLite].
 3606: **
 3607: ** <dl>
 3608: ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
 3609: ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
 3610: **
 3611: ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
 3612: ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
 3613: **
 3614: ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
 3615: ** <dd>The maximum number of columns in a table definition or in the
 3616: ** result set of a [SELECT] or the maximum number of columns in an index
 3617: ** or in an ORDER BY or GROUP BY clause.</dd>)^
 3618: **
 3619: ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
 3620: ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
 3621: **
 3622: ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
 3623: ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
 3624: **
 3625: ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
 3626: ** <dd>The maximum number of instructions in a virtual machine program
 3627: ** used to implement an SQL statement.  This limit is not currently
 3628: ** enforced, though that might be added in some future release of
 3629: ** SQLite.</dd>)^
 3630: **
 3631: ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
 3632: ** <dd>The maximum number of arguments on a function.</dd>)^
 3633: **
 3634: ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
 3635: ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
 3636: **
 3637: ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
 3638: ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
 3639: ** <dd>The maximum length of the pattern argument to the [LIKE] or
 3640: ** [GLOB] operators.</dd>)^
 3641: **
 3642: ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
 3643: ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
 3644: ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
 3645: **
 3646: ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
 3647: ** <dd>The maximum depth of recursion for triggers.</dd>)^
 3648: **
 3649: ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
 3650: ** <dd>The maximum number of auxiliary worker threads that a single
 3651: ** [prepared statement] may start.</dd>)^
 3652: ** </dl>
 3653: */
 3654: #define SQLITE_LIMIT_LENGTH                    0
 3655: #define SQLITE_LIMIT_SQL_LENGTH                1
 3656: #define SQLITE_LIMIT_COLUMN                    2
 3657: #define SQLITE_LIMIT_EXPR_DEPTH                3
 3658: #define SQLITE_LIMIT_COMPOUND_SELECT           4
 3659: #define SQLITE_LIMIT_VDBE_OP                   5
 3660: #define SQLITE_LIMIT_FUNCTION_ARG              6
 3661: #define SQLITE_LIMIT_ATTACHED                  7
 3662: #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
 3663: #define SQLITE_LIMIT_VARIABLE_NUMBER           9
 3664: #define SQLITE_LIMIT_TRIGGER_DEPTH            10
 3665: #define SQLITE_LIMIT_WORKER_THREADS           11
 3666: 
 3667: /*
 3668: ** CAPI3REF: Compiling An SQL Statement
 3669: ** KEYWORDS: {SQL statement compiler}
 3670: ** METHOD: sqlite3
 3671: ** CONSTRUCTOR: sqlite3_stmt
 3672: **
 3673: ** To execute an SQL query, it must first be compiled into a byte-code
 3674: ** program using one of these routines.
 3675: **
 3676: ** The first argument, "db", is a [database connection] obtained from a
 3677: ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
 3678: ** [sqlite3_open16()].  The database connection must not have been closed.
 3679: **
 3680: ** The second argument, "zSql", is the statement to be compiled, encoded
 3681: ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
 3682: ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
 3683: ** use UTF-16.
 3684: **
 3685: ** ^If the nByte argument is negative, then zSql is read up to the
 3686: ** first zero terminator. ^If nByte is positive, then it is the
 3687: ** number of bytes read from zSql.  ^If nByte is zero, then no prepared
 3688: ** statement is generated.
 3689: ** If the caller knows that the supplied string is nul-terminated, then
 3690: ** there is a small performance advantage to passing an nByte parameter that
 3691: ** is the number of bytes in the input string <i>including</i>
 3692: ** the nul-terminator.
 3693: **
 3694: ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
 3695: ** past the end of the first SQL statement in zSql.  These routines only
 3696: ** compile the first statement in zSql, so *pzTail is left pointing to
 3697: ** what remains uncompiled.
 3698: **
 3699: ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
 3700: ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
 3701: ** to NULL.  ^If the input text contains no SQL (if the input is an empty
 3702: ** string or a comment) then *ppStmt is set to NULL.
 3703: ** The calling procedure is responsible for deleting the compiled
 3704: ** SQL statement using [sqlite3_finalize()] after it has finished with it.
 3705: ** ppStmt may not be NULL.
 3706: **
 3707: ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
 3708: ** otherwise an [error code] is returned.
 3709: **
 3710: ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
 3711: ** recommended for all new programs. The two older interfaces are retained
 3712: ** for backwards compatibility, but their use is discouraged.
 3713: ** ^In the "v2" interfaces, the prepared statement
 3714: ** that is returned (the [sqlite3_stmt] object) contains a copy of the
 3715: ** original SQL text. This causes the [sqlite3_step()] interface to
 3716: ** behave differently in three ways:
 3717: **
 3718: ** <ol>
 3719: ** <li>
 3720: ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
 3721: ** always used to do, [sqlite3_step()] will automatically recompile the SQL
 3722: ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
 3723: ** retries will occur before sqlite3_step() gives up and returns an error.
 3724: ** </li>
 3725: **
 3726: ** <li>
 3727: ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
 3728: ** [error codes] or [extended error codes].  ^The legacy behavior was that
 3729: ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
 3730: ** and the application would have to make a second call to [sqlite3_reset()]
 3731: ** in order to find the underlying cause of the problem. With the "v2" prepare
 3732: ** interfaces, the underlying reason for the error is returned immediately.
 3733: ** </li>
 3734: **
 3735: ** <li>
 3736: ** ^If the specific value bound to [parameter | host parameter] in the 
 3737: ** WHERE clause might influence the choice of query plan for a statement,
 3738: ** then the statement will be automatically recompiled, as if there had been 
 3739: ** a schema change, on the first  [sqlite3_step()] call following any change
 3740: ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
 3741: ** ^The specific value of WHERE-clause [parameter] might influence the 
 3742: ** choice of query plan if the parameter is the left-hand side of a [LIKE]
 3743: ** or [GLOB] operator or if the parameter is compared to an indexed column
 3744: ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
 3745: ** </li>
 3746: ** </ol>
 3747: */
 3748: SQLITE_API int sqlite3_prepare(
 3749:   sqlite3 *db,            /* Database handle */
 3750:   const char *zSql,       /* SQL statement, UTF-8 encoded */
 3751:   int nByte,              /* Maximum length of zSql in bytes. */
 3752:   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
 3753:   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
 3754: );
 3755: SQLITE_API int sqlite3_prepare_v2(
 3756:   sqlite3 *db,            /* Database handle */
 3757:   const char *zSql,       /* SQL statement, UTF-8 encoded */
 3758:   int nByte,              /* Maximum length of zSql in bytes. */
 3759:   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
 3760:   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
 3761: );
 3762: SQLITE_API int sqlite3_prepare16(
 3763:   sqlite3 *db,            /* Database handle */
 3764:   const void *zSql,       /* SQL statement, UTF-16 encoded */
 3765:   int nByte,              /* Maximum length of zSql in bytes. */
 3766:   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
 3767:   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
 3768: );
 3769: SQLITE_API int sqlite3_prepare16_v2(
 3770:   sqlite3 *db,            /* Database handle */
 3771:   const void *zSql,       /* SQL statement, UTF-16 encoded */
 3772:   int nByte,              /* Maximum length of zSql in bytes. */
 3773:   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
 3774:   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
 3775: );
 3776: 
 3777: /*
 3778: ** CAPI3REF: Retrieving Statement SQL
 3779: ** METHOD: sqlite3_stmt
 3780: **
 3781: ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
 3782: ** SQL text used to create [prepared statement] P if P was
 3783: ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
 3784: ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
 3785: ** string containing the SQL text of prepared statement P with
 3786: ** [bound parameters] expanded.
 3787: **
 3788: ** ^(For example, if a prepared statement is created using the SQL
 3789: ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
 3790: ** and parameter :xyz is unbound, then sqlite3_sql() will return
 3791: ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
 3792: ** will return "SELECT 2345,NULL".)^
 3793: **
 3794: ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
 3795: ** is available to hold the result, or if the result would exceed the
 3796: ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
 3797: **
 3798: ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
 3799: ** bound parameter expansions.  ^The [SQLITE_OMIT_TRACE] compile-time
 3800: ** option causes sqlite3_expanded_sql() to always return NULL.
 3801: **
 3802: ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
 3803: ** automatically freed when the prepared statement is finalized.
 3804: ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
 3805: ** is obtained from [sqlite3_malloc()] and must be free by the application
 3806: ** by passing it to [sqlite3_free()].
 3807: */
 3808: SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
 3809: SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
 3810: 
 3811: /*
 3812: ** CAPI3REF: Determine If An SQL Statement Writes The Database
 3813: ** METHOD: sqlite3_stmt
 3814: **
 3815: ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
 3816: ** and only if the [prepared statement] X makes no direct changes to
 3817: ** the content of the database file.
 3818: **
 3819: ** Note that [application-defined SQL functions] or
 3820: ** [virtual tables] might change the database indirectly as a side effect.  
 3821: ** ^(For example, if an application defines a function "eval()" that 
 3822: ** calls [sqlite3_exec()], then the following SQL statement would
 3823: ** change the database file through side-effects:
 3824: **
 3825: ** <blockquote><pre>
 3826: **    SELECT eval('DELETE FROM t1') FROM t2;
 3827: ** </pre></blockquote>
 3828: **
 3829: ** But because the [SELECT] statement does not change the database file
 3830: ** directly, sqlite3_stmt_readonly() would still return true.)^
 3831: **
 3832: ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
 3833: ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
 3834: ** since the statements themselves do not actually modify the database but
 3835: ** rather they control the timing of when other statements modify the 
 3836: ** database.  ^The [ATTACH] and [DETACH] statements also cause
 3837: ** sqlite3_stmt_readonly() to return true since, while those statements
 3838: ** change the configuration of a database connection, they do not make 
 3839: ** changes to the content of the database files on disk.
 3840: */
 3841: SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
 3842: 
 3843: /*
 3844: ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
 3845: ** METHOD: sqlite3_stmt
 3846: **
 3847: ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
 3848: ** [prepared statement] S has been stepped at least once using 
 3849: ** [sqlite3_step(S)] but has neither run to completion (returned
 3850: ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
 3851: ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
 3852: ** interface returns false if S is a NULL pointer.  If S is not a 
 3853: ** NULL pointer and is not a pointer to a valid [prepared statement]
 3854: ** object, then the behavior is undefined and probably undesirable.
 3855: **
 3856: ** This interface can be used in combination [sqlite3_next_stmt()]
 3857: ** to locate all prepared statements associated with a database 
 3858: ** connection that are in need of being reset.  This can be used,
 3859: ** for example, in diagnostic routines to search for prepared 
 3860: ** statements that are holding a transaction open.
 3861: */
 3862: SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
 3863: 
 3864: /*
 3865: ** CAPI3REF: Dynamically Typed Value Object
 3866: ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
 3867: **
 3868: ** SQLite uses the sqlite3_value object to represent all values
 3869: ** that can be stored in a database table. SQLite uses dynamic typing
 3870: ** for the values it stores.  ^Values stored in sqlite3_value objects
 3871: ** can be integers, floating point values, strings, BLOBs, or NULL.
 3872: **
 3873: ** An sqlite3_value object may be either "protected" or "unprotected".
 3874: ** Some interfaces require a protected sqlite3_value.  Other interfaces
 3875: ** will accept either a protected or an unprotected sqlite3_value.
 3876: ** Every interface that accepts sqlite3_value arguments specifies
 3877: ** whether or not it requires a protected sqlite3_value.  The
 3878: ** [sqlite3_value_dup()] interface can be used to construct a new 
 3879: ** protected sqlite3_value from an unprotected sqlite3_value.
 3880: **
 3881: ** The terms "protected" and "unprotected" refer to whether or not
 3882: ** a mutex is held.  An internal mutex is held for a protected
 3883: ** sqlite3_value object but no mutex is held for an unprotected
 3884: ** sqlite3_value object.  If SQLite is compiled to be single-threaded
 3885: ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
 3886: ** or if SQLite is run in one of reduced mutex modes 
 3887: ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
 3888: ** then there is no distinction between protected and unprotected
 3889: ** sqlite3_value objects and they can be used interchangeably.  However,
 3890: ** for maximum code portability it is recommended that applications
 3891: ** still make the distinction between protected and unprotected
 3892: ** sqlite3_value objects even when not strictly required.
 3893: **
 3894: ** ^The sqlite3_value objects that are passed as parameters into the
 3895: ** implementation of [application-defined SQL functions] are protected.
 3896: ** ^The sqlite3_value object returned by
 3897: ** [sqlite3_column_value()] is unprotected.
 3898: ** Unprotected sqlite3_value objects may only be used with
 3899: ** [sqlite3_result_value()] and [sqlite3_bind_value()].
 3900: ** The [sqlite3_value_blob | sqlite3_value_type()] family of
 3901: ** interfaces require protected sqlite3_value objects.
 3902: */
 3903: typedef struct Mem sqlite3_value;
 3904: 
 3905: /*
 3906: ** CAPI3REF: SQL Function Context Object
 3907: **
 3908: ** The context in which an SQL function executes is stored in an
 3909: ** sqlite3_context object.  ^A pointer to an sqlite3_context object
 3910: ** is always first parameter to [application-defined SQL functions].
 3911: ** The application-defined SQL function implementation will pass this
 3912: ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
 3913: ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
 3914: ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
 3915: ** and/or [sqlite3_set_auxdata()].
 3916: */
 3917: typedef struct sqlite3_context sqlite3_context;
 3918: 
 3919: /*
 3920: ** CAPI3REF: Binding Values To Prepared Statements
 3921: ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
 3922: ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
 3923: ** METHOD: sqlite3_stmt
 3924: **
 3925: ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
 3926: ** literals may be replaced by a [parameter] that matches one of following
 3927: ** templates:
 3928: **
 3929: ** <ul>
 3930: ** <li>  ?
 3931: ** <li>  ?NNN
 3932: ** <li>  :VVV
 3933: ** <li>  @VVV
 3934: ** <li>  $VVV
 3935: ** </ul>
 3936: **
 3937: ** In the templates above, NNN represents an integer literal,
 3938: ** and VVV represents an alphanumeric identifier.)^  ^The values of these
 3939: ** parameters (also called "host parameter names" or "SQL parameters")
 3940: ** can be set using the sqlite3_bind_*() routines defined here.
 3941: **
 3942: ** ^The first argument to the sqlite3_bind_*() routines is always
 3943: ** a pointer to the [sqlite3_stmt] object returned from
 3944: ** [sqlite3_prepare_v2()] or its variants.
 3945: **
 3946: ** ^The second argument is the index of the SQL parameter to be set.
 3947: ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
 3948: ** SQL parameter is used more than once, second and subsequent
 3949: ** occurrences have the same index as the first occurrence.
 3950: ** ^The index for named parameters can be looked up using the
 3951: ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
 3952: ** for "?NNN" parameters is the value of NNN.
 3953: ** ^The NNN value must be between 1 and the [sqlite3_limit()]
 3954: ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
 3955: **
 3956: ** ^The third argument is the value to bind to the parameter.
 3957: ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
 3958: ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
 3959: ** is ignored and the end result is the same as sqlite3_bind_null().
 3960: **
 3961: ** ^(In those routines that have a fourth argument, its value is the
 3962: ** number of bytes in the parameter.  To be clear: the value is the
 3963: ** number of <u>bytes</u> in the value, not the number of characters.)^
 3964: ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
 3965: ** is negative, then the length of the string is
 3966: ** the number of bytes up to the first zero terminator.
 3967: ** If the fourth parameter to sqlite3_bind_blob() is negative, then
 3968: ** the behavior is undefined.
 3969: ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
 3970: ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
 3971: ** that parameter must be the byte offset
 3972: ** where the NUL terminator would occur assuming the string were NUL
 3973: ** terminated.  If any NUL characters occur at byte offsets less than 
 3974: ** the value of the fourth parameter then the resulting string value will
 3975: ** contain embedded NULs.  The result of expressions involving strings
 3976: ** with embedded NULs is undefined.
 3977: **
 3978: ** ^The fifth argument to the BLOB and string binding interfaces
 3979: ** is a destructor used to dispose of the BLOB or
 3980: ** string after SQLite has finished with it.  ^The destructor is called
 3981: ** to dispose of the BLOB or string even if the call to bind API fails.
 3982: ** ^If the fifth argument is
 3983: ** the special value [SQLITE_STATIC], then SQLite assumes that the
 3984: ** information is in static, unmanaged space and does not need to be freed.
 3985: ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
 3986: ** SQLite makes its own private copy of the data immediately, before
 3987: ** the sqlite3_bind_*() routine returns.
 3988: **
 3989: ** ^The sixth argument to sqlite3_bind_text64() must be one of
 3990: ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
 3991: ** to specify the encoding of the text in the third parameter.  If
 3992: ** the sixth argument to sqlite3_bind_text64() is not one of the
 3993: ** allowed values shown above, or if the text encoding is different
 3994: ** from the encoding specified by the sixth parameter, then the behavior
 3995: ** is undefined.
 3996: **
 3997: ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
 3998: ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
 3999: ** (just an integer to hold its size) while it is being processed.
 4000: ** Zeroblobs are intended to serve as placeholders for BLOBs whose
 4001: ** content is later written using
 4002: ** [sqlite3_blob_open | incremental BLOB I/O] routines.
 4003: ** ^A negative value for the zeroblob results in a zero-length BLOB.
 4004: **
 4005: ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
 4006: ** for the [prepared statement] or with a prepared statement for which
 4007: ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
 4008: ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
 4009: ** routine is passed a [prepared statement] that has been finalized, the
 4010: ** result is undefined and probably harmful.
 4011: **
 4012: ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
 4013: ** ^Unbound parameters are interpreted as NULL.
 4014: **
 4015: ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
 4016: ** [error code] if anything goes wrong.
 4017: ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
 4018: ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
 4019: ** [SQLITE_MAX_LENGTH].
 4020: ** ^[SQLITE_RANGE] is returned if the parameter
 4021: ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
 4022: **
 4023: ** See also: [sqlite3_bind_parameter_count()],
 4024: ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
 4025: */
 4026: SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
 4027: SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
 4028:                         void(*)(void*));
 4029: SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
 4030: SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
 4031: SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
 4032: SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
 4033: SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
 4034: SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
 4035: SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
 4036:                          void(*)(void*), unsigned char encoding);
 4037: SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
 4038: SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
 4039: SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
 4040: 
 4041: /*
 4042: ** CAPI3REF: Number Of SQL Parameters
 4043: ** METHOD: sqlite3_stmt
 4044: **
 4045: ** ^This routine can be used to find the number of [SQL parameters]
 4046: ** in a [prepared statement].  SQL parameters are tokens of the
 4047: ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
 4048: ** placeholders for values that are [sqlite3_bind_blob | bound]
 4049: ** to the parameters at a later time.
 4050: **
 4051: ** ^(This routine actually returns the index of the largest (rightmost)
 4052: ** parameter. For all forms except ?NNN, this will correspond to the
 4053: ** number of unique parameters.  If parameters of the ?NNN form are used,
 4054: ** there may be gaps in the list.)^
 4055: **
 4056: ** See also: [sqlite3_bind_blob|sqlite3_bind()],
 4057: ** [sqlite3_bind_parameter_name()], and
 4058: ** [sqlite3_bind_parameter_index()].
 4059: */
 4060: SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
 4061: 
 4062: /*
 4063: ** CAPI3REF: Name Of A Host Parameter
 4064: ** METHOD: sqlite3_stmt
 4065: **
 4066: ** ^The sqlite3_bind_parameter_name(P,N) interface returns
 4067: ** the name of the N-th [SQL parameter] in the [prepared statement] P.
 4068: ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
 4069: ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
 4070: ** respectively.
 4071: ** In other words, the initial ":" or "$" or "@" or "?"
 4072: ** is included as part of the name.)^
 4073: ** ^Parameters of the form "?" without a following integer have no name
 4074: ** and are referred to as "nameless" or "anonymous parameters".
 4075: **
 4076: ** ^The first host parameter has an index of 1, not 0.
 4077: **
 4078: ** ^If the value N is out of range or if the N-th parameter is
 4079: ** nameless, then NULL is returned.  ^The returned string is
 4080: ** always in UTF-8 encoding even if the named parameter was
 4081: ** originally specified as UTF-16 in [sqlite3_prepare16()] or
 4082: ** [sqlite3_prepare16_v2()].
 4083: **
 4084: ** See also: [sqlite3_bind_blob|sqlite3_bind()],
 4085: ** [sqlite3_bind_parameter_count()], and
 4086: ** [sqlite3_bind_parameter_index()].
 4087: */
 4088: SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
 4089: 
 4090: /*
 4091: ** CAPI3REF: Index Of A Parameter With A Given Name
 4092: ** METHOD: sqlite3_stmt
 4093: **
 4094: ** ^Return the index of an SQL parameter given its name.  ^The
 4095: ** index value returned is suitable for use as the second
 4096: ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
 4097: ** is returned if no matching parameter is found.  ^The parameter
 4098: ** name must be given in UTF-8 even if the original statement
 4099: ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
 4100: **
 4101: ** See also: [sqlite3_bind_blob|sqlite3_bind()],
 4102: ** [sqlite3_bind_parameter_count()], and
 4103: ** [sqlite3_bind_parameter_name()].
 4104: */
 4105: SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
 4106: 
 4107: /*
 4108: ** CAPI3REF: Reset All Bindings On A Prepared Statement
 4109: ** METHOD: sqlite3_stmt
 4110: **
 4111: ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
 4112: ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
 4113: ** ^Use this routine to reset all host parameters to NULL.
 4114: */
 4115: SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
 4116: 
 4117: /*
 4118: ** CAPI3REF: Number Of Columns In A Result Set
 4119: ** METHOD: sqlite3_stmt
 4120: **
 4121: ** ^Return the number of columns in the result set returned by the
 4122: ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
 4123: ** statement that does not return data (for example an [UPDATE]).
 4124: **
 4125: ** See also: [sqlite3_data_count()]
 4126: */
 4127: SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
 4128: 
 4129: /*
 4130: ** CAPI3REF: Column Names In A Result Set
 4131: ** METHOD: sqlite3_stmt
 4132: **
 4133: ** ^These routines return the name assigned to a particular column
 4134: ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
 4135: ** interface returns a pointer to a zero-terminated UTF-8 string
 4136: ** and sqlite3_column_name16() returns a pointer to a zero-terminated
 4137: ** UTF-16 string.  ^The first parameter is the [prepared statement]
 4138: ** that implements the [SELECT] statement. ^The second parameter is the
 4139: ** column number.  ^The leftmost column is number 0.
 4140: **
 4141: ** ^The returned string pointer is valid until either the [prepared statement]
 4142: ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
 4143: ** reprepared by the first call to [sqlite3_step()] for a particular run
 4144: ** or until the next call to
 4145: ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
 4146: **
 4147: ** ^If sqlite3_malloc() fails during the processing of either routine
 4148: ** (for example during a conversion from UTF-8 to UTF-16) then a
 4149: ** NULL pointer is returned.
 4150: **
 4151: ** ^The name of a result column is the value of the "AS" clause for
 4152: ** that column, if there is an AS clause.  If there is no AS clause
 4153: ** then the name of the column is unspecified and may change from
 4154: ** one release of SQLite to the next.
 4155: */
 4156: SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
 4157: SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
 4158: 
 4159: /*
 4160: ** CAPI3REF: Source Of Data In A Query Result
 4161: ** METHOD: sqlite3_stmt
 4162: **
 4163: ** ^These routines provide a means to determine the database, table, and
 4164: ** table column that is the origin of a particular result column in
 4165: ** [SELECT] statement.
 4166: ** ^The name of the database or table or column can be returned as
 4167: ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
 4168: ** the database name, the _table_ routines return the table name, and
 4169: ** the origin_ routines return the column name.
 4170: ** ^The returned string is valid until the [prepared statement] is destroyed
 4171: ** using [sqlite3_finalize()] or until the statement is automatically
 4172: ** reprepared by the first call to [sqlite3_step()] for a particular run
 4173: ** or until the same information is requested
 4174: ** again in a different encoding.
 4175: **
 4176: ** ^The names returned are the original un-aliased names of the
 4177: ** database, table, and column.
 4178: **
 4179: ** ^The first argument to these interfaces is a [prepared statement].
 4180: ** ^These functions return information about the Nth result column returned by
 4181: ** the statement, where N is the second function argument.
 4182: ** ^The left-most column is column 0 for these routines.
 4183: **
 4184: ** ^If the Nth column returned by the statement is an expression or
 4185: ** subquery and is not a column value, then all of these functions return
 4186: ** NULL.  ^These routine might also return NULL if a memory allocation error
 4187: ** occurs.  ^Otherwise, they return the name of the attached database, table,
 4188: ** or column that query result column was extracted from.
 4189: **
 4190: ** ^As with all other SQLite APIs, those whose names end with "16" return
 4191: ** UTF-16 encoded strings and the other functions return UTF-8.
 4192: **
 4193: ** ^These APIs are only available if the library was compiled with the
 4194: ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
 4195: **
 4196: ** If two or more threads call one or more of these routines against the same
 4197: ** prepared statement and column at the same time then the results are
 4198: ** undefined.
 4199: **
 4200: ** If two or more threads call one or more
 4201: ** [sqlite3_column_database_name | column metadata interfaces]
 4202: ** for the same [prepared statement] and result column
 4203: ** at the same time then the results are undefined.
 4204: */
 4205: SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
 4206: SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
 4207: SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
 4208: SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
 4209: SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
 4210: SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
 4211: 
 4212: /*
 4213: ** CAPI3REF: Declared Datatype Of A Query Result
 4214: ** METHOD: sqlite3_stmt
 4215: **
 4216: ** ^(The first parameter is a [prepared statement].
 4217: ** If this statement is a [SELECT] statement and the Nth column of the
 4218: ** returned result set of that [SELECT] is a table column (not an
 4219: ** expression or subquery) then the declared type of the table
 4220: ** column is returned.)^  ^If the Nth column of the result set is an
 4221: ** expression or subquery, then a NULL pointer is returned.
 4222: ** ^The returned string is always UTF-8 encoded.
 4223: **
 4224: ** ^(For example, given the database schema:
 4225: **
 4226: ** CREATE TABLE t1(c1 VARIANT);
 4227: **
 4228: ** and the following statement to be compiled:
 4229: **
 4230: ** SELECT c1 + 1, c1 FROM t1;
 4231: **
 4232: ** this routine would return the string "VARIANT" for the second result
 4233: ** column (i==1), and a NULL pointer for the first result column (i==0).)^
 4234: **
 4235: ** ^SQLite uses dynamic run-time typing.  ^So just because a column
 4236: ** is declared to contain a particular type does not mean that the
 4237: ** data stored in that column is of the declared type.  SQLite is
 4238: ** strongly typed, but the typing is dynamic not static.  ^Type
 4239: ** is associated with individual values, not with the containers
 4240: ** used to hold those values.
 4241: */
 4242: SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
 4243: SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
 4244: 
 4245: /*
 4246: ** CAPI3REF: Evaluate An SQL Statement
 4247: ** METHOD: sqlite3_stmt
 4248: **
 4249: ** After a [prepared statement] has been prepared using either
 4250: ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
 4251: ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
 4252: ** must be called one or more times to evaluate the statement.
 4253: **
 4254: ** The details of the behavior of the sqlite3_step() interface depend
 4255: ** on whether the statement was prepared using the newer "v2" interface
 4256: ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
 4257: ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
 4258: ** new "v2" interface is recommended for new applications but the legacy
 4259: ** interface will continue to be supported.
 4260: **
 4261: ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
 4262: ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
 4263: ** ^With the "v2" interface, any of the other [result codes] or
 4264: ** [extended result codes] might be returned as well.
 4265: **
 4266: ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
 4267: ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
 4268: ** or occurs outside of an explicit transaction, then you can retry the
 4269: ** statement.  If the statement is not a [COMMIT] and occurs within an
 4270: ** explicit transaction then you should rollback the transaction before
 4271: ** continuing.
 4272: **
 4273: ** ^[SQLITE_DONE] means that the statement has finished executing
 4274: ** successfully.  sqlite3_step() should not be called again on this virtual
 4275: ** machine without first calling [sqlite3_reset()] to reset the virtual
 4276: ** machine back to its initial state.
 4277: **
 4278: ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
 4279: ** is returned each time a new row of data is ready for processing by the
 4280: ** caller. The values may be accessed using the [column access functions].
 4281: ** sqlite3_step() is called again to retrieve the next row of data.
 4282: **
 4283: ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
 4284: ** violation) has occurred.  sqlite3_step() should not be called again on
 4285: ** the VM. More information may be found by calling [sqlite3_errmsg()].
 4286: ** ^With the legacy interface, a more specific error code (for example,
 4287: ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
 4288: ** can be obtained by calling [sqlite3_reset()] on the
 4289: ** [prepared statement].  ^In the "v2" interface,
 4290: ** the more specific error code is returned directly by sqlite3_step().
 4291: **
 4292: ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
 4293: ** Perhaps it was called on a [prepared statement] that has
 4294: ** already been [sqlite3_finalize | finalized] or on one that had
 4295: ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
 4296: ** be the case that the same database connection is being used by two or
 4297: ** more threads at the same moment in time.
 4298: **
 4299: ** For all versions of SQLite up to and including 3.6.23.1, a call to
 4300: ** [sqlite3_reset()] was required after sqlite3_step() returned anything
 4301: ** other than [SQLITE_ROW] before any subsequent invocation of
 4302: ** sqlite3_step().  Failure to reset the prepared statement using 
 4303: ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
 4304: ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
 4305: ** calling [sqlite3_reset()] automatically in this circumstance rather
 4306: ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
 4307: ** break because any application that ever receives an SQLITE_MISUSE error
 4308: ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
 4309: ** can be used to restore the legacy behavior.
 4310: **
 4311: ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
 4312: ** API always returns a generic error code, [SQLITE_ERROR], following any
 4313: ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
 4314: ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
 4315: ** specific [error codes] that better describes the error.
 4316: ** We admit that this is a goofy design.  The problem has been fixed
 4317: ** with the "v2" interface.  If you prepare all of your SQL statements
 4318: ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
 4319: ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
 4320: ** then the more specific [error codes] are returned directly
 4321: ** by sqlite3_step().  The use of the "v2" interface is recommended.
 4322: */
 4323: SQLITE_API int sqlite3_step(sqlite3_stmt*);
 4324: 
 4325: /*
 4326: ** CAPI3REF: Number of columns in a result set
 4327: ** METHOD: sqlite3_stmt
 4328: **
 4329: ** ^The sqlite3_data_count(P) interface returns the number of columns in the
 4330: ** current row of the result set of [prepared statement] P.
 4331: ** ^If prepared statement P does not have results ready to return
 4332: ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
 4333: ** interfaces) then sqlite3_data_count(P) returns 0.
 4334: ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
 4335: ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
 4336: ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
 4337: ** will return non-zero if previous call to [sqlite3_step](P) returned
 4338: ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
 4339: ** where it always returns zero since each step of that multi-step
 4340: ** pragma returns 0 columns of data.
 4341: **
 4342: ** See also: [sqlite3_column_count()]
 4343: */
 4344: SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
 4345: 
 4346: /*
 4347: ** CAPI3REF: Fundamental Datatypes
 4348: ** KEYWORDS: SQLITE_TEXT
 4349: **
 4350: ** ^(Every value in SQLite has one of five fundamental datatypes:
 4351: **
 4352: ** <ul>
 4353: ** <li> 64-bit signed integer
 4354: ** <li> 64-bit IEEE floating point number
 4355: ** <li> string
 4356: ** <li> BLOB
 4357: ** <li> NULL
 4358: ** </ul>)^
 4359: **
 4360: ** These constants are codes for each of those types.
 4361: **
 4362: ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
 4363: ** for a completely different meaning.  Software that links against both
 4364: ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
 4365: ** SQLITE_TEXT.
 4366: */
 4367: #define SQLITE_INTEGER  1
 4368: #define SQLITE_FLOAT    2
 4369: #define SQLITE_BLOB     4
 4370: #define SQLITE_NULL     5
 4371: #ifdef SQLITE_TEXT
 4372: # undef SQLITE_TEXT
 4373: #else
 4374: # define SQLITE_TEXT     3
 4375: #endif
 4376: #define SQLITE3_TEXT     3
 4377: 
 4378: /*
 4379: ** CAPI3REF: Result Values From A Query
 4380: ** KEYWORDS: {column access functions}
 4381: ** METHOD: sqlite3_stmt
 4382: **
 4383: ** ^These routines return information about a single column of the current
 4384: ** result row of a query.  ^In every case the first argument is a pointer
 4385: ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
 4386: ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
 4387: ** and the second argument is the index of the column for which information
 4388: ** should be returned. ^The leftmost column of the result set has the index 0.
 4389: ** ^The number of columns in the result can be determined using
 4390: ** [sqlite3_column_count()].
 4391: **
 4392: ** If the SQL statement does not currently point to a valid row, or if the
 4393: ** column index is out of range, the result is undefined.
 4394: ** These routines may only be called when the most recent call to
 4395: ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
 4396: ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
 4397: ** If any of these routines are called after [sqlite3_reset()] or
 4398: ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
 4399: ** something other than [SQLITE_ROW], the results are undefined.
 4400: ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
 4401: ** are called from a different thread while any of these routines
 4402: ** are pending, then the results are undefined.
 4403: **
 4404: ** ^The sqlite3_column_type() routine returns the
 4405: ** [SQLITE_INTEGER | datatype code] for the initial data type
 4406: ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
 4407: ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
 4408: ** returned by sqlite3_column_type() is only meaningful if no type
 4409: ** conversions have occurred as described below.  After a type conversion,
 4410: ** the value returned by sqlite3_column_type() is undefined.  Future
 4411: ** versions of SQLite may change the behavior of sqlite3_column_type()
 4412: ** following a type conversion.
 4413: **
 4414: ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
 4415: ** routine returns the number of bytes in that BLOB or string.
 4416: ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
 4417: ** the string to UTF-8 and then returns the number of bytes.
 4418: ** ^If the result is a numeric value then sqlite3_column_bytes() uses
 4419: ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
 4420: ** the number of bytes in that string.
 4421: ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
 4422: **
 4423: ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
 4424: ** routine returns the number of bytes in that BLOB or string.
 4425: ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
 4426: ** the string to UTF-16 and then returns the number of bytes.
 4427: ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
 4428: ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
 4429: ** the number of bytes in that string.
 4430: ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
 4431: **
 4432: ** ^The values returned by [sqlite3_column_bytes()] and 
 4433: ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
 4434: ** of the string.  ^For clarity: the values returned by
 4435: ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
 4436: ** bytes in the string, not the number of characters.
 4437: **
 4438: ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
 4439: ** even empty strings, are always zero-terminated.  ^The return
 4440: ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
 4441: **
 4442: ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
 4443: ** [unprotected sqlite3_value] object.  In a multithreaded environment,
 4444: ** an unprotected sqlite3_value object may only be used safely with
 4445: ** [sqlite3_bind_value()] and [sqlite3_result_value()].
 4446: ** If the [unprotected sqlite3_value] object returned by
 4447: ** [sqlite3_column_value()] is used in any other way, including calls
 4448: ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
 4449: ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
 4450: **
 4451: ** These routines attempt to convert the value where appropriate.  ^For
 4452: ** example, if the internal representation is FLOAT and a text result
 4453: ** is requested, [sqlite3_snprintf()] is used internally to perform the
 4454: ** conversion automatically.  ^(The following table details the conversions
 4455: ** that are applied:
 4456: **
 4457: ** <blockquote>
 4458: ** <table border="1">
 4459: ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
 4460: **
 4461: ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
 4462: ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
 4463: ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
 4464: ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
 4465: ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
 4466: ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
 4467: ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
 4468: ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
 4469: ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
 4470: ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
 4471: ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
 4472: ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
 4473: ** <tr><td>  TEXT    <td>   BLOB    <td> No change
 4474: ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
 4475: ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
 4476: ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
 4477: ** </table>
 4478: ** </blockquote>)^
 4479: **
 4480: ** Note that when type conversions occur, pointers returned by prior
 4481: ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
 4482: ** sqlite3_column_text16() may be invalidated.
 4483: ** Type conversions and pointer invalidations might occur
 4484: ** in the following cases:
 4485: **
 4486: ** <ul>
 4487: ** <li> The initial content is a BLOB and sqlite3_column_text() or
 4488: **      sqlite3_column_text16() is called.  A zero-terminator might
 4489: **      need to be added to the string.</li>
 4490: ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
 4491: **      sqlite3_column_text16() is called.  The content must be converted
 4492: **      to UTF-16.</li>
 4493: ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
 4494: **      sqlite3_column_text() is called.  The content must be converted
 4495: **      to UTF-8.</li>
 4496: ** </ul>
 4497: **
 4498: ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
 4499: ** not invalidate a prior pointer, though of course the content of the buffer
 4500: ** that the prior pointer references will have been modified.  Other kinds
 4501: ** of conversion are done in place when it is possible, but sometimes they
 4502: ** are not possible and in those cases prior pointers are invalidated.
 4503: **
 4504: ** The safest policy is to invoke these routines
 4505: ** in one of the following ways:
 4506: **
 4507: ** <ul>
 4508: **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
 4509: **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
 4510: **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
 4511: ** </ul>
 4512: **
 4513: ** In other words, you should call sqlite3_column_text(),
 4514: ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
 4515: ** into the desired format, then invoke sqlite3_column_bytes() or
 4516: ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
 4517: ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
 4518: ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
 4519: ** with calls to sqlite3_column_bytes().
 4520: **
 4521: ** ^The pointers returned are valid until a type conversion occurs as
 4522: ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
 4523: ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
 4524: ** and BLOBs is freed automatically.  Do <em>not</em> pass the pointers returned
 4525: ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
 4526: ** [sqlite3_free()].
 4527: **
 4528: ** ^(If a memory allocation error occurs during the evaluation of any
 4529: ** of these routines, a default value is returned.  The default value
 4530: ** is either the integer 0, the floating point number 0.0, or a NULL
 4531: ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
 4532: ** [SQLITE_NOMEM].)^
 4533: */
 4534: SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
 4535: SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
 4536: SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
 4537: SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
 4538: SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
 4539: SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
 4540: SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
 4541: SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
 4542: SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
 4543: SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
 4544: 
 4545: /*
 4546: ** CAPI3REF: Destroy A Prepared Statement Object
 4547: ** DESTRUCTOR: sqlite3_stmt
 4548: **
 4549: ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
 4550: ** ^If the most recent evaluation of the statement encountered no errors
 4551: ** or if the statement is never been evaluated, then sqlite3_finalize() returns
 4552: ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
 4553: ** sqlite3_finalize(S) returns the appropriate [error code] or
 4554: ** [extended error code].
 4555: **
 4556: ** ^The sqlite3_finalize(S) routine can be called at any point during
 4557: ** the life cycle of [prepared statement] S:
 4558: ** before statement S is ever evaluated, after
 4559: ** one or more calls to [sqlite3_reset()], or after any call
 4560: ** to [sqlite3_step()] regardless of whether or not the statement has
 4561: ** completed execution.
 4562: **
 4563: ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
 4564: **
 4565: ** The application must finalize every [prepared statement] in order to avoid
 4566: ** resource leaks.  It is a grievous error for the application to try to use
 4567: ** a prepared statement after it has been finalized.  Any use of a prepared
 4568: ** statement after it has been finalized can result in undefined and
 4569: ** undesirable behavior such as segfaults and heap corruption.
 4570: */
 4571: SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
 4572: 
 4573: /*
 4574: ** CAPI3REF: Reset A Prepared Statement Object
 4575: ** METHOD: sqlite3_stmt
 4576: **
 4577: ** The sqlite3_reset() function is called to reset a [prepared statement]
 4578: ** object back to its initial state, ready to be re-executed.
 4579: ** ^Any SQL statement variables that had values bound to them using
 4580: ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
 4581: ** Use [sqlite3_clear_bindings()] to reset the bindings.
 4582: **
 4583: ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
 4584: ** back to the beginning of its program.
 4585: **
 4586: ** ^If the most recent call to [sqlite3_step(S)] for the
 4587: ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
 4588: ** or if [sqlite3_step(S)] has never before been called on S,
 4589: ** then [sqlite3_reset(S)] returns [SQLITE_OK].
 4590: **
 4591: ** ^If the most recent call to [sqlite3_step(S)] for the
 4592: ** [prepared statement] S indicated an error, then
 4593: ** [sqlite3_reset(S)] returns an appropriate [error code].
 4594: **
 4595: ** ^The [sqlite3_reset(S)] interface does not change the values
 4596: ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
 4597: */
 4598: SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
 4599: 
 4600: /*
 4601: ** CAPI3REF: Create Or Redefine SQL Functions
 4602: ** KEYWORDS: {function creation routines}
 4603: ** KEYWORDS: {application-defined SQL function}
 4604: ** KEYWORDS: {application-defined SQL functions}
 4605: ** METHOD: sqlite3
 4606: **
 4607: ** ^These functions (collectively known as "function creation routines")
 4608: ** are used to add SQL functions or aggregates or to redefine the behavior
 4609: ** of existing SQL functions or aggregates.  The only differences between
 4610: ** these routines are the text encoding expected for
 4611: ** the second parameter (the name of the function being created)
 4612: ** and the presence or absence of a destructor callback for
 4613: ** the application data pointer.
 4614: **
 4615: ** ^The first parameter is the [database connection] to which the SQL
 4616: ** function is to be added.  ^If an application uses more than one database
 4617: ** connection then application-defined SQL functions must be added
 4618: ** to each database connection separately.
 4619: **
 4620: ** ^The second parameter is the name of the SQL function to be created or
 4621: ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
 4622: ** representation, exclusive of the zero-terminator.  ^Note that the name
 4623: ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
 4624: ** ^Any attempt to create a function with a longer name
 4625: ** will result in [SQLITE_MISUSE] being returned.
 4626: **
 4627: ** ^The third parameter (nArg)
 4628: ** is the number of arguments that the SQL function or
 4629: ** aggregate takes. ^If this parameter is -1, then the SQL function or
 4630: ** aggregate may take any number of arguments between 0 and the limit
 4631: ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
 4632: ** parameter is less than -1 or greater than 127 then the behavior is
 4633: ** undefined.
 4634: **
 4635: ** ^The fourth parameter, eTextRep, specifies what
 4636: ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
 4637: ** its parameters.  The application should set this parameter to
 4638: ** [SQLITE_UTF16LE] if the function implementation invokes 
 4639: ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
 4640: ** implementation invokes [sqlite3_value_text16be()] on an input, or
 4641: ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
 4642: ** otherwise.  ^The same SQL function may be registered multiple times using
 4643: ** different preferred text encodings, with different implementations for
 4644: ** each encoding.
 4645: ** ^When multiple implementations of the same function are available, SQLite
 4646: ** will pick the one that involves the least amount of data conversion.
 4647: **
 4648: ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
 4649: ** to signal that the function will always return the same result given
 4650: ** the same inputs within a single SQL statement.  Most SQL functions are
 4651: ** deterministic.  The built-in [random()] SQL function is an example of a
 4652: ** function that is not deterministic.  The SQLite query planner is able to
 4653: ** perform additional optimizations on deterministic functions, so use
 4654: ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
 4655: **
 4656: ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
 4657: ** function can gain access to this pointer using [sqlite3_user_data()].)^
 4658: **
 4659: ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
 4660: ** pointers to C-language functions that implement the SQL function or
 4661: ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
 4662: ** callback only; NULL pointers must be passed as the xStep and xFinal
 4663: ** parameters. ^An aggregate SQL function requires an implementation of xStep
 4664: ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
 4665: ** SQL function or aggregate, pass NULL pointers for all three function
 4666: ** callbacks.
 4667: **
 4668: ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
 4669: ** then it is destructor for the application data pointer. 
 4670: ** The destructor is invoked when the function is deleted, either by being
 4671: ** overloaded or when the database connection closes.)^
 4672: ** ^The destructor is also invoked if the call to
 4673: ** sqlite3_create_function_v2() fails.
 4674: ** ^When the destructor callback of the tenth parameter is invoked, it
 4675: ** is passed a single argument which is a copy of the application data 
 4676: ** pointer which was the fifth parameter to sqlite3_create_function_v2().
 4677: **
 4678: ** ^It is permitted to register multiple implementations of the same
 4679: ** functions with the same name but with either differing numbers of
 4680: ** arguments or differing preferred text encodings.  ^SQLite will use
 4681: ** the implementation that most closely matches the way in which the
 4682: ** SQL function is used.  ^A function implementation with a non-negative
 4683: ** nArg parameter is a better match than a function implementation with
 4684: ** a negative nArg.  ^A function where the preferred text encoding
 4685: ** matches the database encoding is a better
 4686: ** match than a function where the encoding is different.  
 4687: ** ^A function where the encoding difference is between UTF16le and UTF16be
 4688: ** is a closer match than a function where the encoding difference is
 4689: ** between UTF8 and UTF16.
 4690: **
 4691: ** ^Built-in functions may be overloaded by new application-defined functions.
 4692: **
 4693: ** ^An application-defined function is permitted to call other
 4694: ** SQLite interfaces.  However, such calls must not
 4695: ** close the database connection nor finalize or reset the prepared
 4696: ** statement in which the function is running.
 4697: */
 4698: SQLITE_API int sqlite3_create_function(
 4699:   sqlite3 *db,
 4700:   const char *zFunctionName,
 4701:   int nArg,
 4702:   int eTextRep,
 4703:   void *pApp,
 4704:   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
 4705:   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
 4706:   void (*xFinal)(sqlite3_context*)
 4707: );
 4708: SQLITE_API int sqlite3_create_function16(
 4709:   sqlite3 *db,
 4710:   const void *zFunctionName,
 4711:   int nArg,
 4712:   int eTextRep,
 4713:   void *pApp,
 4714:   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
 4715:   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
 4716:   void (*xFinal)(sqlite3_context*)
 4717: );
 4718: SQLITE_API int sqlite3_create_function_v2(
 4719:   sqlite3 *db,
 4720:   const char *zFunctionName,
 4721:   int nArg,
 4722:   int eTextRep,
 4723:   void *pApp,
 4724:   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
 4725:   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
 4726:   void (*xFinal)(sqlite3_context*),
 4727:   void(*xDestroy)(void*)
 4728: );
 4729: 
 4730: /*
 4731: ** CAPI3REF: Text Encodings
 4732: **
 4733: ** These constant define integer codes that represent the various
 4734: ** text encodings supported by SQLite.
 4735: */
 4736: #define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
 4737: #define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
 4738: #define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
 4739: #define SQLITE_UTF16          4    /* Use native byte order */
 4740: #define SQLITE_ANY            5    /* Deprecated */
 4741: #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
 4742: 
 4743: /*
 4744: ** CAPI3REF: Function Flags
 4745: **
 4746: ** These constants may be ORed together with the 
 4747: ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
 4748: ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
 4749: ** [sqlite3_create_function_v2()].
 4750: */
 4751: #define SQLITE_DETERMINISTIC    0x800
 4752: 
 4753: /*
 4754: ** CAPI3REF: Deprecated Functions
 4755: ** DEPRECATED
 4756: **
 4757: ** These functions are [deprecated].  In order to maintain
 4758: ** backwards compatibility with older code, these functions continue 
 4759: ** to be supported.  However, new applications should avoid
 4760: ** the use of these functions.  To encourage programmers to avoid
 4761: ** these functions, we will not explain what they do.
 4762: */
 4763: #ifndef SQLITE_OMIT_DEPRECATED
 4764: SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
 4765: SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
 4766: SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
 4767: SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
 4768: SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
 4769: SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
 4770:                       void*,sqlite3_int64);
 4771: #endif
 4772: 
 4773: /*
 4774: ** CAPI3REF: Obtaining SQL Values
 4775: ** METHOD: sqlite3_value
 4776: **
 4777: ** The C-language implementation of SQL functions and aggregates uses
 4778: ** this set of interface routines to access the parameter values on
 4779: ** the function or aggregate.  
 4780: **
 4781: ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
 4782: ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
 4783: ** define callbacks that implement the SQL functions and aggregates.
 4784: ** The 3rd parameter to these callbacks is an array of pointers to
 4785: ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
 4786: ** each parameter to the SQL function.  These routines are used to
 4787: ** extract values from the [sqlite3_value] objects.
 4788: **
 4789: ** These routines work only with [protected sqlite3_value] objects.
 4790: ** Any attempt to use these routines on an [unprotected sqlite3_value]
 4791: ** object results in undefined behavior.
 4792: **
 4793: ** ^These routines work just like the corresponding [column access functions]
 4794: ** except that these routines take a single [protected sqlite3_value] object
 4795: ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
 4796: **
 4797: ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
 4798: ** in the native byte-order of the host machine.  ^The
 4799: ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
 4800: ** extract UTF-16 strings as big-endian and little-endian respectively.
 4801: **
 4802: ** ^(The sqlite3_value_numeric_type() interface attempts to apply
 4803: ** numeric affinity to the value.  This means that an attempt is
 4804: ** made to convert the value to an integer or floating point.  If
 4805: ** such a conversion is possible without loss of information (in other
 4806: ** words, if the value is a string that looks like a number)
 4807: ** then the conversion is performed.  Otherwise no conversion occurs.
 4808: ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
 4809: **
 4810: ** Please pay particular attention to the fact that the pointer returned
 4811: ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
 4812: ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
 4813: ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
 4814: ** or [sqlite3_value_text16()].
 4815: **
 4816: ** These routines must be called from the same thread as
 4817: ** the SQL function that supplied the [sqlite3_value*] parameters.
 4818: */
 4819: SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
 4820: SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
 4821: SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
 4822: SQLITE_API double sqlite3_value_double(sqlite3_value*);
 4823: SQLITE_API int sqlite3_value_int(sqlite3_value*);
 4824: SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
 4825: SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
 4826: SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
 4827: SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
 4828: SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
 4829: SQLITE_API int sqlite3_value_type(sqlite3_value*);
 4830: SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
 4831: 
 4832: /*
 4833: ** CAPI3REF: Finding The Subtype Of SQL Values
 4834: ** METHOD: sqlite3_value
 4835: **
 4836: ** The sqlite3_value_subtype(V) function returns the subtype for
 4837: ** an [application-defined SQL function] argument V.  The subtype
 4838: ** information can be used to pass a limited amount of context from
 4839: ** one SQL function to another.  Use the [sqlite3_result_subtype()]
 4840: ** routine to set the subtype for the return value of an SQL function.
 4841: **
 4842: ** SQLite makes no use of subtype itself.  It merely passes the subtype
 4843: ** from the result of one [application-defined SQL function] into the
 4844: ** input of another.
 4845: */
 4846: SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
 4847: 
 4848: /*
 4849: ** CAPI3REF: Copy And Free SQL Values
 4850: ** METHOD: sqlite3_value
 4851: **
 4852: ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
 4853: ** object D and returns a pointer to that copy.  ^The [sqlite3_value] returned
 4854: ** is a [protected sqlite3_value] object even if the input is not.
 4855: ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
 4856: ** memory allocation fails.
 4857: **
 4858: ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
 4859: ** previously obtained from [sqlite3_value_dup()].  ^If V is a NULL pointer
 4860: ** then sqlite3_value_free(V) is a harmless no-op.
 4861: */
 4862: SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
 4863: SQLITE_API void sqlite3_value_free(sqlite3_value*);
 4864: 
 4865: /*
 4866: ** CAPI3REF: Obtain Aggregate Function Context
 4867: ** METHOD: sqlite3_context
 4868: **
 4869: ** Implementations of aggregate SQL functions use this
 4870: ** routine to allocate memory for storing their state.
 4871: **
 4872: ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
 4873: ** for a particular aggregate function, SQLite
 4874: ** allocates N of memory, zeroes out that memory, and returns a pointer
 4875: ** to the new memory. ^On second and subsequent calls to
 4876: ** sqlite3_aggregate_context() for the same aggregate function instance,
 4877: ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
 4878: ** called once for each invocation of the xStep callback and then one
 4879: ** last time when the xFinal callback is invoked.  ^(When no rows match
 4880: ** an aggregate query, the xStep() callback of the aggregate function
 4881: ** implementation is never called and xFinal() is called exactly once.
 4882: ** In those cases, sqlite3_aggregate_context() might be called for the
 4883: ** first time from within xFinal().)^
 4884: **
 4885: ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
 4886: ** when first called if N is less than or equal to zero or if a memory
 4887: ** allocate error occurs.
 4888: **
 4889: ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
 4890: ** determined by the N parameter on first successful call.  Changing the
 4891: ** value of N in subsequent call to sqlite3_aggregate_context() within
 4892: ** the same aggregate function instance will not resize the memory
 4893: ** allocation.)^  Within the xFinal callback, it is customary to set
 4894: ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
 4895: ** pointless memory allocations occur.
 4896: **
 4897: ** ^SQLite automatically frees the memory allocated by 
 4898: ** sqlite3_aggregate_context() when the aggregate query concludes.
 4899: **
 4900: ** The first parameter must be a copy of the
 4901: ** [sqlite3_context | SQL function context] that is the first parameter
 4902: ** to the xStep or xFinal callback routine that implements the aggregate
 4903: ** function.
 4904: **
 4905: ** This routine must be called from the same thread in which
 4906: ** the aggregate SQL function is running.
 4907: */
 4908: SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
 4909: 
 4910: /*
 4911: ** CAPI3REF: User Data For Functions
 4912: ** METHOD: sqlite3_context
 4913: **
 4914: ** ^The sqlite3_user_data() interface returns a copy of
 4915: ** the pointer that was the pUserData parameter (the 5th parameter)
 4916: ** of the [sqlite3_create_function()]
 4917: ** and [sqlite3_create_function16()] routines that originally
 4918: ** registered the application defined function.
 4919: **
 4920: ** This routine must be called from the same thread in which
 4921: ** the application-defined function is running.
 4922: */
 4923: SQLITE_API void *sqlite3_user_data(sqlite3_context*);
 4924: 
 4925: /*
 4926: ** CAPI3REF: Database Connection For Functions
 4927: ** METHOD: sqlite3_context
 4928: **
 4929: ** ^The sqlite3_context_db_handle() interface returns a copy of
 4930: ** the pointer to the [database connection] (the 1st parameter)
 4931: ** of the [sqlite3_create_function()]
 4932: ** and [sqlite3_create_function16()] routines that originally
 4933: ** registered the application defined function.
 4934: */
 4935: SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
 4936: 
 4937: /*
 4938: ** CAPI3REF: Function Auxiliary Data
 4939: ** METHOD: sqlite3_context
 4940: **
 4941: ** These functions may be used by (non-aggregate) SQL functions to
 4942: ** associate metadata with argument values. If the same value is passed to
 4943: ** multiple invocations of the same SQL function during query execution, under
 4944: ** some circumstances the associated metadata may be preserved.  An example
 4945: ** of where this might be useful is in a regular-expression matching
 4946: ** function. The compiled version of the regular expression can be stored as
 4947: ** metadata associated with the pattern string.  
 4948: ** Then as long as the pattern string remains the same,
 4949: ** the compiled regular expression can be reused on multiple
 4950: ** invocations of the same function.
 4951: **
 4952: ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
 4953: ** associated by the sqlite3_set_auxdata() function with the Nth argument
 4954: ** value to the application-defined function. ^If there is no metadata
 4955: ** associated with the function argument, this sqlite3_get_auxdata() interface
 4956: ** returns a NULL pointer.
 4957: **
 4958: ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
 4959: ** argument of the application-defined function.  ^Subsequent
 4960: ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
 4961: ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
 4962: ** NULL if the metadata has been discarded.
 4963: ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
 4964: ** SQLite will invoke the destructor function X with parameter P exactly
 4965: ** once, when the metadata is discarded.
 4966: ** SQLite is free to discard the metadata at any time, including: <ul>
 4967: ** <li> ^(when the corresponding function parameter changes)^, or
 4968: ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
 4969: **      SQL statement)^, or
 4970: ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
 4971: **       parameter)^, or
 4972: ** <li> ^(during the original sqlite3_set_auxdata() call when a memory 
 4973: **      allocation error occurs.)^ </ul>
 4974: **
 4975: ** Note the last bullet in particular.  The destructor X in 
 4976: ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
 4977: ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
 4978: ** should be called near the end of the function implementation and the
 4979: ** function implementation should not make any use of P after
 4980: ** sqlite3_set_auxdata() has been called.
 4981: **
 4982: ** ^(In practice, metadata is preserved between function calls for
 4983: ** function parameters that are compile-time constants, including literal
 4984: ** values and [parameters] and expressions composed from the same.)^
 4985: **
 4986: ** These routines must be called from the same thread in which
 4987: ** the SQL function is running.
 4988: */
 4989: SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
 4990: SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
 4991: 
 4992: 
 4993: /*
 4994: ** CAPI3REF: Constants Defining Special Destructor Behavior
 4995: **
 4996: ** These are special values for the destructor that is passed in as the
 4997: ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
 4998: ** argument is SQLITE_STATIC, it means that the content pointer is constant
 4999: ** and will never change.  It does not need to be destroyed.  ^The
 5000: ** SQLITE_TRANSIENT value means that the content will likely change in
 5001: ** the near future and that SQLite should make its own private copy of
 5002: ** the content before returning.
 5003: **
 5004: ** The typedef is necessary to work around problems in certain
 5005: ** C++ compilers.
 5006: */
 5007: typedef void (*sqlite3_destructor_type)(void*);
 5008: #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
 5009: #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
 5010: 
 5011: /*
 5012: ** CAPI3REF: Setting The Result Of An SQL Function
 5013: ** METHOD: sqlite3_context
 5014: **
 5015: ** These routines are used by the xFunc or xFinal callbacks that
 5016: ** implement SQL functions and aggregates.  See
 5017: ** [sqlite3_create_function()] and [sqlite3_create_function16()]
 5018: ** for additional information.
 5019: **
 5020: ** These functions work very much like the [parameter binding] family of
 5021: ** functions used to bind values to host parameters in prepared statements.
 5022: ** Refer to the [SQL parameter] documentation for additional information.
 5023: **
 5024: ** ^The sqlite3_result_blob() interface sets the result from
 5025: ** an application-defined function to be the BLOB whose content is pointed
 5026: ** to by the second parameter and which is N bytes long where N is the
 5027: ** third parameter.
 5028: **
 5029: ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
 5030: ** interfaces set the result of the application-defined function to be
 5031: ** a BLOB containing all zero bytes and N bytes in size.
 5032: **
 5033: ** ^The sqlite3_result_double() interface sets the result from
 5034: ** an application-defined function to be a floating point value specified
 5035: ** by its 2nd argument.
 5036: **
 5037: ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
 5038: ** cause the implemented SQL function to throw an exception.
 5039: ** ^SQLite uses the string pointed to by the
 5040: ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
 5041: ** as the text of an error message.  ^SQLite interprets the error
 5042: ** message string from sqlite3_result_error() as UTF-8. ^SQLite
 5043: ** interprets the string from sqlite3_result_error16() as UTF-16 in native
 5044: ** byte order.  ^If the third parameter to sqlite3_result_error()
 5045: ** or sqlite3_result_error16() is negative then SQLite takes as the error
 5046: ** message all text up through the first zero character.
 5047: ** ^If the third parameter to sqlite3_result_error() or
 5048: ** sqlite3_result_error16() is non-negative then SQLite takes that many
 5049: ** bytes (not characters) from the 2nd parameter as the error message.
 5050: ** ^The sqlite3_result_error() and sqlite3_result_error16()
 5051: ** routines make a private copy of the error message text before
 5052: ** they return.  Hence, the calling function can deallocate or
 5053: ** modify the text after they return without harm.
 5054: ** ^The sqlite3_result_error_code() function changes the error code
 5055: ** returned by SQLite as a result of an error in a function.  ^By default,
 5056: ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
 5057: ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
 5058: **
 5059: ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
 5060: ** error indicating that a string or BLOB is too long to represent.
 5061: **
 5062: ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
 5063: ** error indicating that a memory allocation failed.
 5064: **
 5065: ** ^The sqlite3_result_int() interface sets the return value
 5066: ** of the application-defined function to be the 32-bit signed integer
 5067: ** value given in the 2nd argument.
 5068: ** ^The sqlite3_result_int64() interface sets the return value
 5069: ** of the application-defined function to be the 64-bit signed integer
 5070: ** value given in the 2nd argument.
 5071: **
 5072: ** ^The sqlite3_result_null() interface sets the return value
 5073: ** of the application-defined function to be NULL.
 5074: **
 5075: ** ^The sqlite3_result_text(), sqlite3_result_text16(),
 5076: ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
 5077: ** set the return value of the application-defined function to be
 5078: ** a text string which is represented as UTF-8, UTF-16 native byte order,
 5079: ** UTF-16 little endian, or UTF-16 big endian, respectively.
 5080: ** ^The sqlite3_result_text64() interface sets the return value of an
 5081: ** application-defined function to be a text string in an encoding
 5082: ** specified by the fifth (and last) parameter, which must be one
 5083: ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
 5084: ** ^SQLite takes the text result from the application from
 5085: ** the 2nd parameter of the sqlite3_result_text* interfaces.
 5086: ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
 5087: ** is negative, then SQLite takes result text from the 2nd parameter
 5088: ** through the first zero character.
 5089: ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
 5090: ** is non-negative, then as many bytes (not characters) of the text
 5091: ** pointed to by the 2nd parameter are taken as the application-defined
 5092: ** function result.  If the 3rd parameter is non-negative, then it
 5093: ** must be the byte offset into the string where the NUL terminator would
 5094: ** appear if the string where NUL terminated.  If any NUL characters occur
 5095: ** in the string at a byte offset that is less than the value of the 3rd
 5096: ** parameter, then the resulting string will contain embedded NULs and the
 5097: ** result of expressions operating on strings with embedded NULs is undefined.
 5098: ** ^If the 4th parameter to the sqlite3_result_text* interfaces
 5099: ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
 5100: ** function as the destructor on the text or BLOB result when it has
 5101: ** finished using that result.
 5102: ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
 5103: ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
 5104: ** assumes that the text or BLOB result is in constant space and does not
 5105: ** copy the content of the parameter nor call a destructor on the content
 5106: ** when it has finished using that result.
 5107: ** ^If the 4th parameter to the sqlite3_result_text* interfaces
 5108: ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
 5109: ** then SQLite makes a copy of the result into space obtained from
 5110: ** from [sqlite3_malloc()] before it returns.
 5111: **
 5112: ** ^The sqlite3_result_value() interface sets the result of
 5113: ** the application-defined function to be a copy of the
 5114: ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
 5115: ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
 5116: ** so that the [sqlite3_value] specified in the parameter may change or
 5117: ** be deallocated after sqlite3_result_value() returns without harm.
 5118: ** ^A [protected sqlite3_value] object may always be used where an
 5119: ** [unprotected sqlite3_value] object is required, so either
 5120: ** kind of [sqlite3_value] object can be used with this interface.
 5121: **
 5122: ** If these routines are called from within the different thread
 5123: ** than the one containing the application-defined function that received
 5124: ** the [sqlite3_context] pointer, the results are undefined.
 5125: */
 5126: SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
 5127: SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
 5128:                            sqlite3_uint64,void(*)(void*));
 5129: SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
 5130: SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
 5131: SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
 5132: SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
 5133: SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
 5134: SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
 5135: SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
 5136: SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
 5137: SQLITE_API void sqlite3_result_null(sqlite3_context*);
 5138: SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
 5139: SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
 5140:                            void(*)(void*), unsigned char encoding);
 5141: SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
 5142: SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
 5143: SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
 5144: SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
 5145: SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
 5146: SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
 5147: 
 5148: 
 5149: /*
 5150: ** CAPI3REF: Setting The Subtype Of An SQL Function
 5151: ** METHOD: sqlite3_context
 5152: **
 5153: ** The sqlite3_result_subtype(C,T) function causes the subtype of
 5154: ** the result from the [application-defined SQL function] with 
 5155: ** [sqlite3_context] C to be the value T.  Only the lower 8 bits 
 5156: ** of the subtype T are preserved in current versions of SQLite;
 5157: ** higher order bits are discarded.
 5158: ** The number of subtype bytes preserved by SQLite might increase
 5159: ** in future releases of SQLite.
 5160: */
 5161: SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
 5162: 
 5163: /*
 5164: ** CAPI3REF: Define New Collating Sequences
 5165: ** METHOD: sqlite3
 5166: **
 5167: ** ^These functions add, remove, or modify a [collation] associated
 5168: ** with the [database connection] specified as the first argument.
 5169: **
 5170: ** ^The name of the collation is a UTF-8 string
 5171: ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
 5172: ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
 5173: ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
 5174: ** considered to be the same name.
 5175: **
 5176: ** ^(The third argument (eTextRep) must be one of the constants:
 5177: ** <ul>
 5178: ** <li> [SQLITE_UTF8],
 5179: ** <li> [SQLITE_UTF16LE],
 5180: ** <li> [SQLITE_UTF16BE],
 5181: ** <li> [SQLITE_UTF16], or
 5182: ** <li> [SQLITE_UTF16_ALIGNED].
 5183: ** </ul>)^
 5184: ** ^The eTextRep argument determines the encoding of strings passed
 5185: ** to the collating function callback, xCallback.
 5186: ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
 5187: ** force strings to be UTF16 with native byte order.
 5188: ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
 5189: ** on an even byte address.
 5190: **
 5191: ** ^The fourth argument, pArg, is an application data pointer that is passed
 5192: ** through as the first argument to the collating function callback.
 5193: **
 5194: ** ^The fifth argument, xCallback, is a pointer to the collating function.
 5195: ** ^Multiple collating functions can be registered using the same name but
 5196: ** with different eTextRep parameters and SQLite will use whichever
 5197: ** function requires the least amount of data transformation.
 5198: ** ^If the xCallback argument is NULL then the collating function is
 5199: ** deleted.  ^When all collating functions having the same name are deleted,
 5200: ** that collation is no longer usable.
 5201: **
 5202: ** ^The collating function callback is invoked with a copy of the pArg 
 5203: ** application data pointer and with two strings in the encoding specified
 5204: ** by the eTextRep argument.  The collating function must return an
 5205: ** integer that is negative, zero, or positive
 5206: ** if the first string is less than, equal to, or greater than the second,
 5207: ** respectively.  A collating function must always return the same answer
 5208: ** given the same inputs.  If two or more collating functions are registered
 5209: ** to the same collation name (using different eTextRep values) then all
 5210: ** must give an equivalent answer when invoked with equivalent strings.
 5211: ** The collating function must obey the following properties for all
 5212: ** strings A, B, and C:
 5213: **
 5214: ** <ol>
 5215: ** <li> If A==B then B==A.
 5216: ** <li> If A==B and B==C then A==C.
 5217: ** <li> If A&lt;B THEN B&gt;A.
 5218: ** <li> If A&lt;B and B&lt;C then A&lt;C.
 5219: ** </ol>
 5220: **
 5221: ** If a collating function fails any of the above constraints and that
 5222: ** collating function is  registered and used, then the behavior of SQLite
 5223: ** is undefined.
 5224: **
 5225: ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
 5226: ** with the addition that the xDestroy callback is invoked on pArg when
 5227: ** the collating function is deleted.
 5228: ** ^Collating functions are deleted when they are overridden by later
 5229: ** calls to the collation creation functions or when the
 5230: ** [database connection] is closed using [sqlite3_close()].
 5231: **
 5232: ** ^The xDestroy callback is <u>not</u> called if the 
 5233: ** sqlite3_create_collation_v2() function fails.  Applications that invoke
 5234: ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
 5235: ** check the return code and dispose of the application data pointer
 5236: ** themselves rather than expecting SQLite to deal with it for them.
 5237: ** This is different from every other SQLite interface.  The inconsistency 
 5238: ** is unfortunate but cannot be changed without breaking backwards 
 5239: ** compatibility.
 5240: **
 5241: ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
 5242: */
 5243: SQLITE_API int sqlite3_create_collation(
 5244:   sqlite3*, 
 5245:   const char *zName, 
 5246:   int eTextRep, 
 5247:   void *pArg,
 5248:   int(*xCompare)(void*,int,const void*,int,const void*)
 5249: );
 5250: SQLITE_API int sqlite3_create_collation_v2(
 5251:   sqlite3*, 
 5252:   const char *zName, 
 5253:   int eTextRep, 
 5254:   void *pArg,
 5255:   int(*xCompare)(void*,int,const void*,int,const void*),
 5256:   void(*xDestroy)(void*)
 5257: );
 5258: SQLITE_API int sqlite3_create_collation16(
 5259:   sqlite3*, 
 5260:   const void *zName,
 5261:   int eTextRep, 
 5262:   void *pArg,
 5263:   int(*xCompare)(void*,int,const void*,int,const void*)
 5264: );
 5265: 
 5266: /*
 5267: ** CAPI3REF: Collation Needed Callbacks
 5268: ** METHOD: sqlite3
 5269: **
 5270: ** ^To avoid having to register all collation sequences before a database
 5271: ** can be used, a single callback function may be registered with the
 5272: ** [database connection] to be invoked whenever an undefined collation
 5273: ** sequence is required.
 5274: **
 5275: ** ^If the function is registered using the sqlite3_collation_needed() API,
 5276: ** then it is passed the names of undefined collation sequences as strings
 5277: ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
 5278: ** the names are passed as UTF-16 in machine native byte order.
 5279: ** ^A call to either function replaces the existing collation-needed callback.
 5280: **
 5281: ** ^(When the callback is invoked, the first argument passed is a copy
 5282: ** of the second argument to sqlite3_collation_needed() or
 5283: ** sqlite3_collation_needed16().  The second argument is the database
 5284: ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
 5285: ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
 5286: ** sequence function required.  The fourth parameter is the name of the
 5287: ** required collation sequence.)^
 5288: **
 5289: ** The callback function should register the desired collation using
 5290: ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
 5291: ** [sqlite3_create_collation_v2()].
 5292: */
 5293: SQLITE_API int sqlite3_collation_needed(
 5294:   sqlite3*, 
 5295:   void*, 
 5296:   void(*)(void*,sqlite3*,int eTextRep,const char*)
 5297: );
 5298: SQLITE_API int sqlite3_collation_needed16(
 5299:   sqlite3*, 
 5300:   void*,
 5301:   void(*)(void*,sqlite3*,int eTextRep,const void*)
 5302: );
 5303: 
 5304: #ifdef SQLITE_HAS_CODEC
 5305: /*
 5306: ** Specify the key for an encrypted database.  This routine should be
 5307: ** called right after sqlite3_open().
 5308: **
 5309: ** The code to implement this API is not available in the public release
 5310: ** of SQLite.
 5311: */
 5312: SQLITE_API int sqlite3_key(
 5313:   sqlite3 *db,                   /* Database to be rekeyed */
 5314:   const void *pKey, int nKey     /* The key */
 5315: );
 5316: SQLITE_API int sqlite3_key_v2(
 5317:   sqlite3 *db,                   /* Database to be rekeyed */
 5318:   const char *zDbName,           /* Name of the database */
 5319:   const void *pKey, int nKey     /* The key */
 5320: );
 5321: 
 5322: /*
 5323: ** Change the key on an open database.  If the current database is not
 5324: ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
 5325: ** database is decrypted.
 5326: **
 5327: ** The code to implement this API is not available in the public release
 5328: ** of SQLite.
 5329: */
 5330: SQLITE_API int sqlite3_rekey(
 5331:   sqlite3 *db,                   /* Database to be rekeyed */
 5332:   const void *pKey, int nKey     /* The new key */
 5333: );
 5334: SQLITE_API int sqlite3_rekey_v2(
 5335:   sqlite3 *db,                   /* Database to be rekeyed */
 5336:   const char *zDbName,           /* Name of the database */
 5337:   const void *pKey, int nKey     /* The new key */
 5338: );
 5339: 
 5340: /*
 5341: ** Specify the activation key for a SEE database.  Unless 
 5342: ** activated, none of the SEE routines will work.
 5343: */
 5344: SQLITE_API void sqlite3_activate_see(
 5345:   const char *zPassPhrase        /* Activation phrase */
 5346: );
 5347: #endif
 5348: 
 5349: #ifdef SQLITE_ENABLE_CEROD
 5350: /*
 5351: ** Specify the activation key for a CEROD database.  Unless 
 5352: ** activated, none of the CEROD routines will work.
 5353: */
 5354: SQLITE_API void sqlite3_activate_cerod(
 5355:   const char *zPassPhrase        /* Activation phrase */
 5356: );
 5357: #endif
 5358: 
 5359: /*
 5360: ** CAPI3REF: Suspend Execution For A Short Time
 5361: **
 5362: ** The sqlite3_sleep() function causes the current thread to suspend execution
 5363: ** for at least a number of milliseconds specified in its parameter.
 5364: **
 5365: ** If the operating system does not support sleep requests with
 5366: ** millisecond time resolution, then the time will be rounded up to
 5367: ** the nearest second. The number of milliseconds of sleep actually
 5368: ** requested from the operating system is returned.
 5369: **
 5370: ** ^SQLite implements this interface by calling the xSleep()
 5371: ** method of the default [sqlite3_vfs] object.  If the xSleep() method
 5372: ** of the default VFS is not implemented correctly, or not implemented at
 5373: ** all, then the behavior of sqlite3_sleep() may deviate from the description
 5374: ** in the previous paragraphs.
 5375: */
 5376: SQLITE_API int sqlite3_sleep(int);
 5377: 
 5378: /*
 5379: ** CAPI3REF: Name Of The Folder Holding Temporary Files
 5380: **
 5381: ** ^(If this global variable is made to point to a string which is
 5382: ** the name of a folder (a.k.a. directory), then all temporary files
 5383: ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
 5384: ** will be placed in that directory.)^  ^If this variable
 5385: ** is a NULL pointer, then SQLite performs a search for an appropriate
 5386: ** temporary file directory.
 5387: **
 5388: ** Applications are strongly discouraged from using this global variable.
 5389: ** It is required to set a temporary folder on Windows Runtime (WinRT).
 5390: ** But for all other platforms, it is highly recommended that applications
 5391: ** neither read nor write this variable.  This global variable is a relic
 5392: ** that exists for backwards compatibility of legacy applications and should
 5393: ** be avoided in new projects.
 5394: **
 5395: ** It is not safe to read or modify this variable in more than one
 5396: ** thread at a time.  It is not safe to read or modify this variable
 5397: ** if a [database connection] is being used at the same time in a separate
 5398: ** thread.
 5399: ** It is intended that this variable be set once
 5400: ** as part of process initialization and before any SQLite interface
 5401: ** routines have been called and that this variable remain unchanged
 5402: ** thereafter.
 5403: **
 5404: ** ^The [temp_store_directory pragma] may modify this variable and cause
 5405: ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
 5406: ** the [temp_store_directory pragma] always assumes that any string
 5407: ** that this variable points to is held in memory obtained from 
 5408: ** [sqlite3_malloc] and the pragma may attempt to free that memory
 5409: ** using [sqlite3_free].
 5410: ** Hence, if this variable is modified directly, either it should be
 5411: ** made NULL or made to point to memory obtained from [sqlite3_malloc]
 5412: ** or else the use of the [temp_store_directory pragma] should be avoided.
 5413: ** Except when requested by the [temp_store_directory pragma], SQLite
 5414: ** does not free the memory that sqlite3_temp_directory points to.  If
 5415: ** the application wants that memory to be freed, it must do
 5416: ** so itself, taking care to only do so after all [database connection]
 5417: ** objects have been destroyed.
 5418: **
 5419: ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
 5420: ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
 5421: ** features that require the use of temporary files may fail.  Here is an
 5422: ** example of how to do this using C++ with the Windows Runtime:
 5423: **
 5424: ** <blockquote><pre>
 5425: ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
 5426: ** &nbsp;     TemporaryFolder->Path->Data();
 5427: ** char zPathBuf&#91;MAX_PATH + 1&#93;;
 5428: ** memset(zPathBuf, 0, sizeof(zPathBuf));
 5429: ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
 5430: ** &nbsp;     NULL, NULL);
 5431: ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
 5432: ** </pre></blockquote>
 5433: */
 5434: SQLITE_API char *sqlite3_temp_directory;
 5435: 
 5436: /*
 5437: ** CAPI3REF: Name Of The Folder Holding Database Files
 5438: **
 5439: ** ^(If this global variable is made to point to a string which is
 5440: ** the name of a folder (a.k.a. directory), then all database files
 5441: ** specified with a relative pathname and created or accessed by
 5442: ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
 5443: ** to be relative to that directory.)^ ^If this variable is a NULL
 5444: ** pointer, then SQLite assumes that all database files specified
 5445: ** with a relative pathname are relative to the current directory
 5446: ** for the process.  Only the windows VFS makes use of this global
 5447: ** variable; it is ignored by the unix VFS.
 5448: **
 5449: ** Changing the value of this variable while a database connection is
 5450: ** open can result in a corrupt database.
 5451: **
 5452: ** It is not safe to read or modify this variable in more than one
 5453: ** thread at a time.  It is not safe to read or modify this variable
 5454: ** if a [database connection] is being used at the same time in a separate
 5455: ** thread.
 5456: ** It is intended that this variable be set once
 5457: ** as part of process initialization and before any SQLite interface
 5458: ** routines have been called and that this variable remain unchanged
 5459: ** thereafter.
 5460: **
 5461: ** ^The [data_store_directory pragma] may modify this variable and cause
 5462: ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
 5463: ** the [data_store_directory pragma] always assumes that any string
 5464: ** that this variable points to is held in memory obtained from 
 5465: ** [sqlite3_malloc] and the pragma may attempt to free that memory
 5466: ** using [sqlite3_free].
 5467: ** Hence, if this variable is modified directly, either it should be
 5468: ** made NULL or made to point to memory obtained from [sqlite3_malloc]
 5469: ** or else the use of the [data_store_directory pragma] should be avoided.
 5470: */
 5471: SQLITE_API char *sqlite3_data_directory;
 5472: 
 5473: /*
 5474: ** CAPI3REF: Test For Auto-Commit Mode
 5475: ** KEYWORDS: {autocommit mode}
 5476: ** METHOD: sqlite3
 5477: **
 5478: ** ^The sqlite3_get_autocommit() interface returns non-zero or
 5479: ** zero if the given database connection is or is not in autocommit mode,
 5480: ** respectively.  ^Autocommit mode is on by default.
 5481: ** ^Autocommit mode is disabled by a [BEGIN] statement.
 5482: ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
 5483: **
 5484: ** If certain kinds of errors occur on a statement within a multi-statement
 5485: ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
 5486: ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
 5487: ** transaction might be rolled back automatically.  The only way to
 5488: ** find out whether SQLite automatically rolled back the transaction after
 5489: ** an error is to use this function.
 5490: **
 5491: ** If another thread changes the autocommit status of the database
 5492: ** connection while this routine is running, then the return value
 5493: ** is undefined.
 5494: */
 5495: SQLITE_API int sqlite3_get_autocommit(sqlite3*);
 5496: 
 5497: /*
 5498: ** CAPI3REF: Find The Database Handle Of A Prepared Statement
 5499: ** METHOD: sqlite3_stmt
 5500: **
 5501: ** ^The sqlite3_db_handle interface returns the [database connection] handle
 5502: ** to which a [prepared statement] belongs.  ^The [database connection]
 5503: ** returned by sqlite3_db_handle is the same [database connection]
 5504: ** that was the first argument
 5505: ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
 5506: ** create the statement in the first place.
 5507: */
 5508: SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
 5509: 
 5510: /*
 5511: ** CAPI3REF: Return The Filename For A Database Connection
 5512: ** METHOD: sqlite3
 5513: **
 5514: ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
 5515: ** associated with database N of connection D.  ^The main database file
 5516: ** has the name "main".  If there is no attached database N on the database
 5517: ** connection D, or if database N is a temporary or in-memory database, then
 5518: ** a NULL pointer is returned.
 5519: **
 5520: ** ^The filename returned by this function is the output of the
 5521: ** xFullPathname method of the [VFS].  ^In other words, the filename
 5522: ** will be an absolute pathname, even if the filename used
 5523: ** to open the database originally was a URI or relative pathname.
 5524: */
 5525: SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
 5526: 
 5527: /*
 5528: ** CAPI3REF: Determine if a database is read-only
 5529: ** METHOD: sqlite3
 5530: **
 5531: ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
 5532: ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
 5533: ** the name of a database on connection D.
 5534: */
 5535: SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
 5536: 
 5537: /*
 5538: ** CAPI3REF: Find the next prepared statement
 5539: ** METHOD: sqlite3
 5540: **
 5541: ** ^This interface returns a pointer to the next [prepared statement] after
 5542: ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
 5543: ** then this interface returns a pointer to the first prepared statement
 5544: ** associated with the database connection pDb.  ^If no prepared statement
 5545: ** satisfies the conditions of this routine, it returns NULL.
 5546: **
 5547: ** The [database connection] pointer D in a call to
 5548: ** [sqlite3_next_stmt(D,S)] must refer to an open database
 5549: ** connection and in particular must not be a NULL pointer.
 5550: */
 5551: SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
 5552: 
 5553: /*
 5554: ** CAPI3REF: Commit And Rollback Notification Callbacks
 5555: ** METHOD: sqlite3
 5556: **
 5557: ** ^The sqlite3_commit_hook() interface registers a callback
 5558: ** function to be invoked whenever a transaction is [COMMIT | committed].
 5559: ** ^Any callback set by a previous call to sqlite3_commit_hook()
 5560: ** for the same database connection is overridden.
 5561: ** ^The sqlite3_rollback_hook() interface registers a callback
 5562: ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
 5563: ** ^Any callback set by a previous call to sqlite3_rollback_hook()
 5564: ** for the same database connection is overridden.
 5565: ** ^The pArg argument is passed through to the callback.
 5566: ** ^If the callback on a commit hook function returns non-zero,
 5567: ** then the commit is converted into a rollback.
 5568: **
 5569: ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
 5570: ** return the P argument from the previous call of the same function
 5571: ** on the same [database connection] D, or NULL for
 5572: ** the first call for each function on D.
 5573: **
 5574: ** The commit and rollback hook callbacks are not reentrant.
 5575: ** The callback implementation must not do anything that will modify
 5576: ** the database connection that invoked the callback.  Any actions
 5577: ** to modify the database connection must be deferred until after the
 5578: ** completion of the [sqlite3_step()] call that triggered the commit
 5579: ** or rollback hook in the first place.
 5580: ** Note that running any other SQL statements, including SELECT statements,
 5581: ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
 5582: ** the database connections for the meaning of "modify" in this paragraph.
 5583: **
 5584: ** ^Registering a NULL function disables the callback.
 5585: **
 5586: ** ^When the commit hook callback routine returns zero, the [COMMIT]
 5587: ** operation is allowed to continue normally.  ^If the commit hook
 5588: ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
 5589: ** ^The rollback hook is invoked on a rollback that results from a commit
 5590: ** hook returning non-zero, just as it would be with any other rollback.
 5591: **
 5592: ** ^For the purposes of this API, a transaction is said to have been
 5593: ** rolled back if an explicit "ROLLBACK" statement is executed, or
 5594: ** an error or constraint causes an implicit rollback to occur.
 5595: ** ^The rollback callback is not invoked if a transaction is
 5596: ** automatically rolled back because the database connection is closed.
 5597: **
 5598: ** See also the [sqlite3_update_hook()] interface.
 5599: */
 5600: SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
 5601: SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
 5602: 
 5603: /*
 5604: ** CAPI3REF: Data Change Notification Callbacks
 5605: ** METHOD: sqlite3
 5606: **
 5607: ** ^The sqlite3_update_hook() interface registers a callback function
 5608: ** with the [database connection] identified by the first argument
 5609: ** to be invoked whenever a row is updated, inserted or deleted in
 5610: ** a [rowid table].
 5611: ** ^Any callback set by a previous call to this function
 5612: ** for the same database connection is overridden.
 5613: **
 5614: ** ^The second argument is a pointer to the function to invoke when a
 5615: ** row is updated, inserted or deleted in a rowid table.
 5616: ** ^The first argument to the callback is a copy of the third argument
 5617: ** to sqlite3_update_hook().
 5618: ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
 5619: ** or [SQLITE_UPDATE], depending on the operation that caused the callback
 5620: ** to be invoked.
 5621: ** ^The third and fourth arguments to the callback contain pointers to the
 5622: ** database and table name containing the affected row.
 5623: ** ^The final callback parameter is the [rowid] of the row.
 5624: ** ^In the case of an update, this is the [rowid] after the update takes place.
 5625: **
 5626: ** ^(The update hook is not invoked when internal system tables are
 5627: ** modified (i.e. sqlite_master and sqlite_sequence).)^
 5628: ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
 5629: **
 5630: ** ^In the current implementation, the update hook
 5631: ** is not invoked when duplication rows are deleted because of an
 5632: ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
 5633: ** invoked when rows are deleted using the [truncate optimization].
 5634: ** The exceptions defined in this paragraph might change in a future
 5635: ** release of SQLite.
 5636: **
 5637: ** The update hook implementation must not do anything that will modify
 5638: ** the database connection that invoked the update hook.  Any actions
 5639: ** to modify the database connection must be deferred until after the
 5640: ** completion of the [sqlite3_step()] call that triggered the update hook.
 5641: ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
 5642: ** database connections for the meaning of "modify" in this paragraph.
 5643: **
 5644: ** ^The sqlite3_update_hook(D,C,P) function
 5645: ** returns the P argument from the previous call
 5646: ** on the same [database connection] D, or NULL for
 5647: ** the first call on D.
 5648: **
 5649: ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
 5650: ** and [sqlite3_preupdate_hook()] interfaces.
 5651: */
 5652: SQLITE_API void *sqlite3_update_hook(
 5653:   sqlite3*, 
 5654:   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
 5655:   void*
 5656: );
 5657: 
 5658: /*
 5659: ** CAPI3REF: Enable Or Disable Shared Pager Cache
 5660: **
 5661: ** ^(This routine enables or disables the sharing of the database cache
 5662: ** and schema data structures between [database connection | connections]
 5663: ** to the same database. Sharing is enabled if the argument is true
 5664: ** and disabled if the argument is false.)^
 5665: **
 5666: ** ^Cache sharing is enabled and disabled for an entire process.
 5667: ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
 5668: ** sharing was enabled or disabled for each thread separately.
 5669: **
 5670: ** ^(The cache sharing mode set by this interface effects all subsequent
 5671: ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
 5672: ** Existing database connections continue use the sharing mode
 5673: ** that was in effect at the time they were opened.)^
 5674: **
 5675: ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
 5676: ** successfully.  An [error code] is returned otherwise.)^
 5677: **
 5678: ** ^Shared cache is disabled by default. But this might change in
 5679: ** future releases of SQLite.  Applications that care about shared
 5680: ** cache setting should set it explicitly.
 5681: **
 5682: ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
 5683: ** and will always return SQLITE_MISUSE. On those systems, 
 5684: ** shared cache mode should be enabled per-database connection via 
 5685: ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
 5686: **
 5687: ** This interface is threadsafe on processors where writing a
 5688: ** 32-bit integer is atomic.
 5689: **
 5690: ** See Also:  [SQLite Shared-Cache Mode]
 5691: */
 5692: SQLITE_API int sqlite3_enable_shared_cache(int);
 5693: 
 5694: /*
 5695: ** CAPI3REF: Attempt To Free Heap Memory
 5696: **
 5697: ** ^The sqlite3_release_memory() interface attempts to free N bytes
 5698: ** of heap memory by deallocating non-essential memory allocations
 5699: ** held by the database library.   Memory used to cache database
 5700: ** pages to improve performance is an example of non-essential memory.
 5701: ** ^sqlite3_release_memory() returns the number of bytes actually freed,
 5702: ** which might be more or less than the amount requested.
 5703: ** ^The sqlite3_release_memory() routine is a no-op returning zero
 5704: ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
 5705: **
 5706: ** See also: [sqlite3_db_release_memory()]
 5707: */
 5708: SQLITE_API int sqlite3_release_memory(int);
 5709: 
 5710: /*
 5711: ** CAPI3REF: Free Memory Used By A Database Connection
 5712: ** METHOD: sqlite3
 5713: **
 5714: ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
 5715: ** memory as possible from database connection D. Unlike the
 5716: ** [sqlite3_release_memory()] interface, this interface is in effect even
 5717: ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
 5718: ** omitted.
 5719: **
 5720: ** See also: [sqlite3_release_memory()]
 5721: */
 5722: SQLITE_API int sqlite3_db_release_memory(sqlite3*);
 5723: 
 5724: /*
 5725: ** CAPI3REF: Impose A Limit On Heap Size
 5726: **
 5727: ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
 5728: ** soft limit on the amount of heap memory that may be allocated by SQLite.
 5729: ** ^SQLite strives to keep heap memory utilization below the soft heap
 5730: ** limit by reducing the number of pages held in the page cache
 5731: ** as heap memory usages approaches the limit.
 5732: ** ^The soft heap limit is "soft" because even though SQLite strives to stay
 5733: ** below the limit, it will exceed the limit rather than generate
 5734: ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
 5735: ** is advisory only.
 5736: **
 5737: ** ^The return value from sqlite3_soft_heap_limit64() is the size of
 5738: ** the soft heap limit prior to the call, or negative in the case of an
 5739: ** error.  ^If the argument N is negative
 5740: ** then no change is made to the soft heap limit.  Hence, the current
 5741: ** size of the soft heap limit can be determined by invoking
 5742: ** sqlite3_soft_heap_limit64() with a negative argument.
 5743: **
 5744: ** ^If the argument N is zero then the soft heap limit is disabled.
 5745: **
 5746: ** ^(The soft heap limit is not enforced in the current implementation
 5747: ** if one or more of following conditions are true:
 5748: **
 5749: ** <ul>
 5750: ** <li> The soft heap limit is set to zero.
 5751: ** <li> Memory accounting is disabled using a combination of the
 5752: **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
 5753: **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
 5754: ** <li> An alternative page cache implementation is specified using
 5755: **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
 5756: ** <li> The page cache allocates from its own memory pool supplied
 5757: **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
 5758: **      from the heap.
 5759: ** </ul>)^
 5760: **
 5761: ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
 5762: ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
 5763: ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
 5764: ** the soft heap limit is enforced on every memory allocation.  Without
 5765: ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
 5766: ** when memory is allocated by the page cache.  Testing suggests that because
 5767: ** the page cache is the predominate memory user in SQLite, most
 5768: ** applications will achieve adequate soft heap limit enforcement without
 5769: ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
 5770: **
 5771: ** The circumstances under which SQLite will enforce the soft heap limit may
 5772: ** changes in future releases of SQLite.
 5773: */
 5774: SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
 5775: 
 5776: /*
 5777: ** CAPI3REF: Deprecated Soft Heap Limit Interface
 5778: ** DEPRECATED
 5779: **
 5780: ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
 5781: ** interface.  This routine is provided for historical compatibility
 5782: ** only.  All new applications should use the
 5783: ** [sqlite3_soft_heap_limit64()] interface rather than this one.
 5784: */
 5785: SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
 5786: 
 5787: 
 5788: /*
 5789: ** CAPI3REF: Extract Metadata About A Column Of A Table
 5790: ** METHOD: sqlite3
 5791: **
 5792: ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
 5793: ** information about column C of table T in database D
 5794: ** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
 5795: ** interface returns SQLITE_OK and fills in the non-NULL pointers in
 5796: ** the final five arguments with appropriate values if the specified
 5797: ** column exists.  ^The sqlite3_table_column_metadata() interface returns
 5798: ** SQLITE_ERROR and if the specified column does not exist.
 5799: ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
 5800: ** NULL pointer, then this routine simply checks for the existence of the
 5801: ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
 5802: ** does not.
 5803: **
 5804: ** ^The column is identified by the second, third and fourth parameters to
 5805: ** this function. ^(The second parameter is either the name of the database
 5806: ** (i.e. "main", "temp", or an attached database) containing the specified
 5807: ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
 5808: ** for the table using the same algorithm used by the database engine to
 5809: ** resolve unqualified table references.
 5810: **
 5811: ** ^The third and fourth parameters to this function are the table and column
 5812: ** name of the desired column, respectively.
 5813: **
 5814: ** ^Metadata is returned by writing to the memory locations passed as the 5th
 5815: ** and subsequent parameters to this function. ^Any of these arguments may be
 5816: ** NULL, in which case the corresponding element of metadata is omitted.
 5817: **
 5818: ** ^(<blockquote>
 5819: ** <table border="1">
 5820: ** <tr><th> Parameter <th> Output<br>Type <th>  Description
 5821: **
 5822: ** <tr><td> 5th <td> const char* <td> Data type
 5823: ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
 5824: ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
 5825: ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
 5826: ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
 5827: ** </table>
 5828: ** </blockquote>)^
 5829: **
 5830: ** ^The memory pointed to by the character pointers returned for the
 5831: ** declaration type and collation sequence is valid until the next
 5832: ** call to any SQLite API function.
 5833: **
 5834: ** ^If the specified table is actually a view, an [error code] is returned.
 5835: **
 5836: ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table 
 5837: ** is not a [WITHOUT ROWID] table and an
 5838: ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
 5839: ** parameters are set for the explicitly declared column. ^(If there is no
 5840: ** [INTEGER PRIMARY KEY] column, then the outputs
 5841: ** for the [rowid] are set as follows:
 5842: **
 5843: ** <pre>
 5844: **     data type: "INTEGER"
 5845: **     collation sequence: "BINARY"
 5846: **     not null: 0
 5847: **     primary key: 1
 5848: **     auto increment: 0
 5849: ** </pre>)^
 5850: **
 5851: ** ^This function causes all database schemas to be read from disk and
 5852: ** parsed, if that has not already been done, and returns an error if
 5853: ** any errors are encountered while loading the schema.
 5854: */
 5855: SQLITE_API int sqlite3_table_column_metadata(
 5856:   sqlite3 *db,                /* Connection handle */
 5857:   const char *zDbName,        /* Database name or NULL */
 5858:   const char *zTableName,     /* Table name */
 5859:   const char *zColumnName,    /* Column name */
 5860:   char const **pzDataType,    /* OUTPUT: Declared data type */
 5861:   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
 5862:   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
 5863:   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
 5864:   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
 5865: );
 5866: 
 5867: /*
 5868: ** CAPI3REF: Load An Extension
 5869: ** METHOD: sqlite3
 5870: **
 5871: ** ^This interface loads an SQLite extension library from the named file.
 5872: **
 5873: ** ^The sqlite3_load_extension() interface attempts to load an
 5874: ** [SQLite extension] library contained in the file zFile.  If
 5875: ** the file cannot be loaded directly, attempts are made to load
 5876: ** with various operating-system specific extensions added.
 5877: ** So for example, if "samplelib" cannot be loaded, then names like
 5878: ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
 5879: ** be tried also.
 5880: **
 5881: ** ^The entry point is zProc.
 5882: ** ^(zProc may be 0, in which case SQLite will try to come up with an
 5883: ** entry point name on its own.  It first tries "sqlite3_extension_init".
 5884: ** If that does not work, it constructs a name "sqlite3_X_init" where the
 5885: ** X is consists of the lower-case equivalent of all ASCII alphabetic
 5886: ** characters in the filename from the last "/" to the first following
 5887: ** "." and omitting any initial "lib".)^
 5888: ** ^The sqlite3_load_extension() interface returns
 5889: ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
 5890: ** ^If an error occurs and pzErrMsg is not 0, then the
 5891: ** [sqlite3_load_extension()] interface shall attempt to
 5892: ** fill *pzErrMsg with error message text stored in memory
 5893: ** obtained from [sqlite3_malloc()]. The calling function
 5894: ** should free this memory by calling [sqlite3_free()].
 5895: **
 5896: ** ^Extension loading must be enabled using
 5897: ** [sqlite3_enable_load_extension()] or
 5898: ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
 5899: ** prior to calling this API,
 5900: ** otherwise an error will be returned.
 5901: **
 5902: ** <b>Security warning:</b> It is recommended that the 
 5903: ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
 5904: ** interface.  The use of the [sqlite3_enable_load_extension()] interface
 5905: ** should be avoided.  This will keep the SQL function [load_extension()]
 5906: ** disabled and prevent SQL injections from giving attackers
 5907: ** access to extension loading capabilities.
 5908: **
 5909: ** See also the [load_extension() SQL function].
 5910: */
 5911: SQLITE_API int sqlite3_load_extension(
 5912:   sqlite3 *db,          /* Load the extension into this database connection */
 5913:   const char *zFile,    /* Name of the shared library containing extension */
 5914:   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
 5915:   char **pzErrMsg       /* Put error message here if not 0 */
 5916: );
 5917: 
 5918: /*
 5919: ** CAPI3REF: Enable Or Disable Extension Loading
 5920: ** METHOD: sqlite3
 5921: **
 5922: ** ^So as not to open security holes in older applications that are
 5923: ** unprepared to deal with [extension loading], and as a means of disabling
 5924: ** [extension loading] while evaluating user-entered SQL, the following API
 5925: ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
 5926: **
 5927: ** ^Extension loading is off by default.
 5928: ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
 5929: ** to turn extension loading on and call it with onoff==0 to turn
 5930: ** it back off again.
 5931: **
 5932: ** ^This interface enables or disables both the C-API
 5933: ** [sqlite3_load_extension()] and the SQL function [load_extension()].
 5934: ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
 5935: ** to enable or disable only the C-API.)^
 5936: **
 5937: ** <b>Security warning:</b> It is recommended that extension loading
 5938: ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
 5939: ** rather than this interface, so the [load_extension()] SQL function
 5940: ** remains disabled. This will prevent SQL injections from giving attackers
 5941: ** access to extension loading capabilities.
 5942: */
 5943: SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
 5944: 
 5945: /*
 5946: ** CAPI3REF: Automatically Load Statically Linked Extensions
 5947: **
 5948: ** ^This interface causes the xEntryPoint() function to be invoked for
 5949: ** each new [database connection] that is created.  The idea here is that
 5950: ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
 5951: ** that is to be automatically loaded into all new database connections.
 5952: **
 5953: ** ^(Even though the function prototype shows that xEntryPoint() takes
 5954: ** no arguments and returns void, SQLite invokes xEntryPoint() with three
 5955: ** arguments and expects an integer result as if the signature of the
 5956: ** entry point where as follows:
 5957: **
 5958: ** <blockquote><pre>
 5959: ** &nbsp;  int xEntryPoint(
 5960: ** &nbsp;    sqlite3 *db,
 5961: ** &nbsp;    const char **pzErrMsg,
 5962: ** &nbsp;    const struct sqlite3_api_routines *pThunk
 5963: ** &nbsp;  );
 5964: ** </pre></blockquote>)^
 5965: **
 5966: ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
 5967: ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
 5968: ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
 5969: ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
 5970: ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
 5971: ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
 5972: ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
 5973: **
 5974: ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
 5975: ** on the list of automatic extensions is a harmless no-op. ^No entry point
 5976: ** will be called more than once for each database connection that is opened.
 5977: **
 5978: ** See also: [sqlite3_reset_auto_extension()]
 5979: ** and [sqlite3_cancel_auto_extension()]
 5980: */
 5981: SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
 5982: 
 5983: /*
 5984: ** CAPI3REF: Cancel Automatic Extension Loading
 5985: **
 5986: ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
 5987: ** initialization routine X that was registered using a prior call to
 5988: ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
 5989: ** routine returns 1 if initialization routine X was successfully 
 5990: ** unregistered and it returns 0 if X was not on the list of initialization
 5991: ** routines.
 5992: */
 5993: SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
 5994: 
 5995: /*
 5996: ** CAPI3REF: Reset Automatic Extension Loading
 5997: **
 5998: ** ^This interface disables all automatic extensions previously
 5999: ** registered using [sqlite3_auto_extension()].
 6000: */
 6001: SQLITE_API void sqlite3_reset_auto_extension(void);
 6002: 
 6003: /*
 6004: ** The interface to the virtual-table mechanism is currently considered
 6005: ** to be experimental.  The interface might change in incompatible ways.
 6006: ** If this is a problem for you, do not use the interface at this time.
 6007: **
 6008: ** When the virtual-table mechanism stabilizes, we will declare the
 6009: ** interface fixed, support it indefinitely, and remove this comment.
 6010: */
 6011: 
 6012: /*
 6013: ** Structures used by the virtual table interface
 6014: */
 6015: typedef struct sqlite3_vtab sqlite3_vtab;
 6016: typedef struct sqlite3_index_info sqlite3_index_info;
 6017: typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
 6018: typedef struct sqlite3_module sqlite3_module;
 6019: 
 6020: /*
 6021: ** CAPI3REF: Virtual Table Object
 6022: ** KEYWORDS: sqlite3_module {virtual table module}
 6023: **
 6024: ** This structure, sometimes called a "virtual table module", 
 6025: ** defines the implementation of a [virtual tables].  
 6026: ** This structure consists mostly of methods for the module.
 6027: **
 6028: ** ^A virtual table module is created by filling in a persistent
 6029: ** instance of this structure and passing a pointer to that instance
 6030: ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
 6031: ** ^The registration remains valid until it is replaced by a different
 6032: ** module or until the [database connection] closes.  The content
 6033: ** of this structure must not change while it is registered with
 6034: ** any database connection.
 6035: */
 6036: struct sqlite3_module {
 6037:   int iVersion;
 6038:   int (*xCreate)(sqlite3*, void *pAux,
 6039:                int argc, const char *const*argv,
 6040:                sqlite3_vtab **ppVTab, char**);
 6041:   int (*xConnect)(sqlite3*, void *pAux,
 6042:                int argc, const char *const*argv,
 6043:                sqlite3_vtab **ppVTab, char**);
 6044:   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
 6045:   int (*xDisconnect)(sqlite3_vtab *pVTab);
 6046:   int (*xDestroy)(sqlite3_vtab *pVTab);
 6047:   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
 6048:   int (*xClose)(sqlite3_vtab_cursor*);
 6049:   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
 6050:                 int argc, sqlite3_value **argv);
 6051:   int (*xNext)(sqlite3_vtab_cursor*);
 6052:   int (*xEof)(sqlite3_vtab_cursor*);
 6053:   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
 6054:   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
 6055:   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
 6056:   int (*xBegin)(sqlite3_vtab *pVTab);
 6057:   int (*xSync)(sqlite3_vtab *pVTab);
 6058:   int (*xCommit)(sqlite3_vtab *pVTab);
 6059:   int (*xRollback)(sqlite3_vtab *pVTab);
 6060:   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
 6061:                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
 6062:                        void **ppArg);
 6063:   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
 6064:   /* The methods above are in version 1 of the sqlite_module object. Those 
 6065:   ** below are for version 2 and greater. */
 6066:   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
 6067:   int (*xRelease)(sqlite3_vtab *pVTab, int);
 6068:   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
 6069: };
 6070: 
 6071: /*
 6072: ** CAPI3REF: Virtual Table Indexing Information
 6073: ** KEYWORDS: sqlite3_index_info
 6074: **
 6075: ** The sqlite3_index_info structure and its substructures is used as part
 6076: ** of the [virtual table] interface to
 6077: ** pass information into and receive the reply from the [xBestIndex]
 6078: ** method of a [virtual table module].  The fields under **Inputs** are the
 6079: ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
 6080: ** results into the **Outputs** fields.
 6081: **
 6082: ** ^(The aConstraint[] array records WHERE clause constraints of the form:
 6083: **
 6084: ** <blockquote>column OP expr</blockquote>
 6085: **
 6086: ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
 6087: ** stored in aConstraint[].op using one of the
 6088: ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
 6089: ** ^(The index of the column is stored in
 6090: ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
 6091: ** expr on the right-hand side can be evaluated (and thus the constraint
 6092: ** is usable) and false if it cannot.)^
 6093: **
 6094: ** ^The optimizer automatically inverts terms of the form "expr OP column"
 6095: ** and makes other simplifications to the WHERE clause in an attempt to
 6096: ** get as many WHERE clause terms into the form shown above as possible.
 6097: ** ^The aConstraint[] array only reports WHERE clause terms that are
 6098: ** relevant to the particular virtual table being queried.
 6099: **
 6100: ** ^Information about the ORDER BY clause is stored in aOrderBy[].
 6101: ** ^Each term of aOrderBy records a column of the ORDER BY clause.
 6102: **
 6103: ** The colUsed field indicates which columns of the virtual table may be
 6104: ** required by the current scan. Virtual table columns are numbered from
 6105: ** zero in the order in which they appear within the CREATE TABLE statement
 6106: ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
 6107: ** the corresponding bit is set within the colUsed mask if the column may be
 6108: ** required by SQLite. If the table has at least 64 columns and any column
 6109: ** to the right of the first 63 is required, then bit 63 of colUsed is also
 6110: ** set. In other words, column iCol may be required if the expression
 6111: ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to 
 6112: ** non-zero.
 6113: **
 6114: ** The [xBestIndex] method must fill aConstraintUsage[] with information
 6115: ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
 6116: ** the right-hand side of the corresponding aConstraint[] is evaluated
 6117: ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
 6118: ** is true, then the constraint is assumed to be fully handled by the
 6119: ** virtual table and is not checked again by SQLite.)^
 6120: **
 6121: ** ^The idxNum and idxPtr values are recorded and passed into the
 6122: ** [xFilter] method.
 6123: ** ^[sqlite3_free()] is used to free idxPtr if and only if
 6124: ** needToFreeIdxPtr is true.
 6125: **
 6126: ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
 6127: ** the correct order to satisfy the ORDER BY clause so that no separate
 6128: ** sorting step is required.
 6129: **
 6130: ** ^The estimatedCost value is an estimate of the cost of a particular
 6131: ** strategy. A cost of N indicates that the cost of the strategy is similar
 6132: ** to a linear scan of an SQLite table with N rows. A cost of log(N) 
 6133: ** indicates that the expense of the operation is similar to that of a
 6134: ** binary search on a unique indexed field of an SQLite table with N rows.
 6135: **
 6136: ** ^The estimatedRows value is an estimate of the number of rows that
 6137: ** will be returned by the strategy.
 6138: **
 6139: ** The xBestIndex method may optionally populate the idxFlags field with a 
 6140: ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
 6141: ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
 6142: ** assumes that the strategy may visit at most one row. 
 6143: **
 6144: ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
 6145: ** SQLite also assumes that if a call to the xUpdate() method is made as
 6146: ** part of the same statement to delete or update a virtual table row and the
 6147: ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
 6148: ** any database changes. In other words, if the xUpdate() returns
 6149: ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
 6150: ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
 6151: ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
 6152: ** the xUpdate method are automatically rolled back by SQLite.
 6153: **
 6154: ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
 6155: ** structure for SQLite version 3.8.2. If a virtual table extension is
 6156: ** used with an SQLite version earlier than 3.8.2, the results of attempting 
 6157: ** to read or write the estimatedRows field are undefined (but are likely 
 6158: ** to included crashing the application). The estimatedRows field should
 6159: ** therefore only be used if [sqlite3_libversion_number()] returns a
 6160: ** value greater than or equal to 3008002. Similarly, the idxFlags field
 6161: ** was added for version 3.9.0. It may therefore only be used if
 6162: ** sqlite3_libversion_number() returns a value greater than or equal to
 6163: ** 3009000.
 6164: */
 6165: struct sqlite3_index_info {
 6166:   /* Inputs */
 6167:   int nConstraint;           /* Number of entries in aConstraint */
 6168:   struct sqlite3_index_constraint {
 6169:      int iColumn;              /* Column constrained.  -1 for ROWID */
 6170:      unsigned char op;         /* Constraint operator */
 6171:      unsigned char usable;     /* True if this constraint is usable */
 6172:      int iTermOffset;          /* Used internally - xBestIndex should ignore */
 6173:   } *aConstraint;            /* Table of WHERE clause constraints */
 6174:   int nOrderBy;              /* Number of terms in the ORDER BY clause */
 6175:   struct sqlite3_index_orderby {
 6176:      int iColumn;              /* Column number */
 6177:      unsigned char desc;       /* True for DESC.  False for ASC. */
 6178:   } *aOrderBy;               /* The ORDER BY clause */
 6179:   /* Outputs */
 6180:   struct sqlite3_index_constraint_usage {
 6181:     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
 6182:     unsigned char omit;      /* Do not code a test for this constraint */
 6183:   } *aConstraintUsage;
 6184:   int idxNum;                /* Number used to identify the index */
 6185:   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
 6186:   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
 6187:   int orderByConsumed;       /* True if output is already ordered */
 6188:   double estimatedCost;           /* Estimated cost of using this index */
 6189:   /* Fields below are only available in SQLite 3.8.2 and later */
 6190:   sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
 6191:   /* Fields below are only available in SQLite 3.9.0 and later */
 6192:   int idxFlags;              /* Mask of SQLITE_INDEX_SCAN_* flags */
 6193:   /* Fields below are only available in SQLite 3.10.0 and later */
 6194:   sqlite3_uint64 colUsed;    /* Input: Mask of columns used by statement */
 6195: };
 6196: 
 6197: /*
 6198: ** CAPI3REF: Virtual Table Scan Flags
 6199: */
 6200: #define SQLITE_INDEX_SCAN_UNIQUE      1     /* Scan visits at most 1 row */
 6201: 
 6202: /*
 6203: ** CAPI3REF: Virtual Table Constraint Operator Codes
 6204: **
 6205: ** These macros defined the allowed values for the
 6206: ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
 6207: ** an operator that is part of a constraint term in the wHERE clause of
 6208: ** a query that uses a [virtual table].
 6209: */
 6210: #define SQLITE_INDEX_CONSTRAINT_EQ      2
 6211: #define SQLITE_INDEX_CONSTRAINT_GT      4
 6212: #define SQLITE_INDEX_CONSTRAINT_LE      8
 6213: #define SQLITE_INDEX_CONSTRAINT_LT     16
 6214: #define SQLITE_INDEX_CONSTRAINT_GE     32
 6215: #define SQLITE_INDEX_CONSTRAINT_MATCH  64
 6216: #define SQLITE_INDEX_CONSTRAINT_LIKE   65
 6217: #define SQLITE_INDEX_CONSTRAINT_GLOB   66
 6218: #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
 6219: 
 6220: /*
 6221: ** CAPI3REF: Register A Virtual Table Implementation
 6222: ** METHOD: sqlite3
 6223: **
 6224: ** ^These routines are used to register a new [virtual table module] name.
 6225: ** ^Module names must be registered before
 6226: ** creating a new [virtual table] using the module and before using a
 6227: ** preexisting [virtual table] for the module.
 6228: **
 6229: ** ^The module name is registered on the [database connection] specified
 6230: ** by the first parameter.  ^The name of the module is given by the 
 6231: ** second parameter.  ^The third parameter is a pointer to
 6232: ** the implementation of the [virtual table module].   ^The fourth
 6233: ** parameter is an arbitrary client data pointer that is passed through
 6234: ** into the [xCreate] and [xConnect] methods of the virtual table module
 6235: ** when a new virtual table is be being created or reinitialized.
 6236: **
 6237: ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
 6238: ** is a pointer to a destructor for the pClientData.  ^SQLite will
 6239: ** invoke the destructor function (if it is not NULL) when SQLite
 6240: ** no longer needs the pClientData pointer.  ^The destructor will also
 6241: ** be invoked if the call to sqlite3_create_module_v2() fails.
 6242: ** ^The sqlite3_create_module()
 6243: ** interface is equivalent to sqlite3_create_module_v2() with a NULL
 6244: ** destructor.
 6245: */
 6246: SQLITE_API int sqlite3_create_module(
 6247:   sqlite3 *db,               /* SQLite connection to register module with */
 6248:   const char *zName,         /* Name of the module */
 6249:   const sqlite3_module *p,   /* Methods for the module */
 6250:   void *pClientData          /* Client data for xCreate/xConnect */
 6251: );
 6252: SQLITE_API int sqlite3_create_module_v2(
 6253:   sqlite3 *db,               /* SQLite connection to register module with */
 6254:   const char *zName,         /* Name of the module */
 6255:   const sqlite3_module *p,   /* Methods for the module */
 6256:   void *pClientData,         /* Client data for xCreate/xConnect */
 6257:   void(*xDestroy)(void*)     /* Module destructor function */
 6258: );
 6259: 
 6260: /*
 6261: ** CAPI3REF: Virtual Table Instance Object
 6262: ** KEYWORDS: sqlite3_vtab
 6263: **
 6264: ** Every [virtual table module] implementation uses a subclass
 6265: ** of this object to describe a particular instance
 6266: ** of the [virtual table].  Each subclass will
 6267: ** be tailored to the specific needs of the module implementation.
 6268: ** The purpose of this superclass is to define certain fields that are
 6269: ** common to all module implementations.
 6270: **
 6271: ** ^Virtual tables methods can set an error message by assigning a
 6272: ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
 6273: ** take care that any prior string is freed by a call to [sqlite3_free()]
 6274: ** prior to assigning a new string to zErrMsg.  ^After the error message
 6275: ** is delivered up to the client application, the string will be automatically
 6276: ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
 6277: */
 6278: struct sqlite3_vtab {
 6279:   const sqlite3_module *pModule;  /* The module for this virtual table */
 6280:   int nRef;                       /* Number of open cursors */
 6281:   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
 6282:   /* Virtual table implementations will typically add additional fields */
 6283: };
 6284: 
 6285: /*
 6286: ** CAPI3REF: Virtual Table Cursor Object
 6287: ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
 6288: **
 6289: ** Every [virtual table module] implementation uses a subclass of the
 6290: ** following structure to describe cursors that point into the
 6291: ** [virtual table] and are used
 6292: ** to loop through the virtual table.  Cursors are created using the
 6293: ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
 6294: ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
 6295: ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
 6296: ** of the module.  Each module implementation will define
 6297: ** the content of a cursor structure to suit its own needs.
 6298: **
 6299: ** This superclass exists in order to define fields of the cursor that
 6300: ** are common to all implementations.
 6301: */
 6302: struct sqlite3_vtab_cursor {
 6303:   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
 6304:   /* Virtual table implementations will typically add additional fields */
 6305: };
 6306: 
 6307: /*
 6308: ** CAPI3REF: Declare The Schema Of A Virtual Table
 6309: **
 6310: ** ^The [xCreate] and [xConnect] methods of a
 6311: ** [virtual table module] call this interface
 6312: ** to declare the format (the names and datatypes of the columns) of
 6313: ** the virtual tables they implement.
 6314: */
 6315: SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
 6316: 
 6317: /*
 6318: ** CAPI3REF: Overload A Function For A Virtual Table
 6319: ** METHOD: sqlite3
 6320: **
 6321: ** ^(Virtual tables can provide alternative implementations of functions
 6322: ** using the [xFindFunction] method of the [virtual table module].  
 6323: ** But global versions of those functions
 6324: ** must exist in order to be overloaded.)^
 6325: **
 6326: ** ^(This API makes sure a global version of a function with a particular
 6327: ** name and number of parameters exists.  If no such function exists
 6328: ** before this API is called, a new function is created.)^  ^The implementation
 6329: ** of the new function always causes an exception to be thrown.  So
 6330: ** the new function is not good for anything by itself.  Its only
 6331: ** purpose is to be a placeholder function that can be overloaded
 6332: ** by a [virtual table].
 6333: */
 6334: SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
 6335: 
 6336: /*
 6337: ** The interface to the virtual-table mechanism defined above (back up
 6338: ** to a comment remarkably similar to this one) is currently considered
 6339: ** to be experimental.  The interface might change in incompatible ways.
 6340: ** If this is a problem for you, do not use the interface at this time.
 6341: **
 6342: ** When the virtual-table mechanism stabilizes, we will declare the
 6343: ** interface fixed, support it indefinitely, and remove this comment.
 6344: */
 6345: 
 6346: /*
 6347: ** CAPI3REF: A Handle To An Open BLOB
 6348: ** KEYWORDS: {BLOB handle} {BLOB handles}
 6349: **
 6350: ** An instance of this object represents an open BLOB on which
 6351: ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
 6352: ** ^Objects of this type are created by [sqlite3_blob_open()]
 6353: ** and destroyed by [sqlite3_blob_close()].
 6354: ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
 6355: ** can be used to read or write small subsections of the BLOB.
 6356: ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
 6357: */
 6358: typedef struct sqlite3_blob sqlite3_blob;
 6359: 
 6360: /*
 6361: ** CAPI3REF: Open A BLOB For Incremental I/O
 6362: ** METHOD: sqlite3
 6363: ** CONSTRUCTOR: sqlite3_blob
 6364: **
 6365: ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
 6366: ** in row iRow, column zColumn, table zTable in database zDb;
 6367: ** in other words, the same BLOB that would be selected by:
 6368: **
 6369: ** <pre>
 6370: **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
 6371: ** </pre>)^
 6372: **
 6373: ** ^(Parameter zDb is not the filename that contains the database, but 
 6374: ** rather the symbolic name of the database. For attached databases, this is
 6375: ** the name that appears after the AS keyword in the [ATTACH] statement.
 6376: ** For the main database file, the database name is "main". For TEMP
 6377: ** tables, the database name is "temp".)^
 6378: **
 6379: ** ^If the flags parameter is non-zero, then the BLOB is opened for read
 6380: ** and write access. ^If the flags parameter is zero, the BLOB is opened for
 6381: ** read-only access.
 6382: **
 6383: ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
 6384: ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
 6385: ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
 6386: ** the API is not misused, it is always safe to call [sqlite3_blob_close()] 
 6387: ** on *ppBlob after this function it returns.
 6388: **
 6389: ** This function fails with SQLITE_ERROR if any of the following are true:
 6390: ** <ul>
 6391: **   <li> ^(Database zDb does not exist)^, 
 6392: **   <li> ^(Table zTable does not exist within database zDb)^, 
 6393: **   <li> ^(Table zTable is a WITHOUT ROWID table)^, 
 6394: **   <li> ^(Column zColumn does not exist)^,
 6395: **   <li> ^(Row iRow is not present in the table)^,
 6396: **   <li> ^(The specified column of row iRow contains a value that is not
 6397: **         a TEXT or BLOB value)^,
 6398: **   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE 
 6399: **         constraint and the blob is being opened for read/write access)^,
 6400: **   <li> ^([foreign key constraints | Foreign key constraints] are enabled, 
 6401: **         column zColumn is part of a [child key] definition and the blob is
 6402: **         being opened for read/write access)^.
 6403: ** </ul>
 6404: **
 6405: ** ^Unless it returns SQLITE_MISUSE, this function sets the 
 6406: ** [database connection] error code and message accessible via 
 6407: ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
 6408: **
 6409: **
 6410: ** ^(If the row that a BLOB handle points to is modified by an
 6411: ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
 6412: ** then the BLOB handle is marked as "expired".
 6413: ** This is true if any column of the row is changed, even a column
 6414: ** other than the one the BLOB handle is open on.)^
 6415: ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
 6416: ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
 6417: ** ^(Changes written into a BLOB prior to the BLOB expiring are not
 6418: ** rolled back by the expiration of the BLOB.  Such changes will eventually
 6419: ** commit if the transaction continues to completion.)^
 6420: **
 6421: ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
 6422: ** the opened blob.  ^The size of a blob may not be changed by this
 6423: ** interface.  Use the [UPDATE] SQL command to change the size of a
 6424: ** blob.
 6425: **
 6426: ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
 6427: ** and the built-in [zeroblob] SQL function may be used to create a 
 6428: ** zero-filled blob to read or write using the incremental-blob interface.
 6429: **
 6430: ** To avoid a resource leak, every open [BLOB handle] should eventually
 6431: ** be released by a call to [sqlite3_blob_close()].
 6432: */
 6433: SQLITE_API int sqlite3_blob_open(
 6434:   sqlite3*,
 6435:   const char *zDb,
 6436:   const char *zTable,
 6437:   const char *zColumn,
 6438:   sqlite3_int64 iRow,
 6439:   int flags,
 6440:   sqlite3_blob **ppBlob
 6441: );
 6442: 
 6443: /*
 6444: ** CAPI3REF: Move a BLOB Handle to a New Row
 6445: ** METHOD: sqlite3_blob
 6446: **
 6447: ** ^This function is used to move an existing blob handle so that it points
 6448: ** to a different row of the same database table. ^The new row is identified
 6449: ** by the rowid value passed as the second argument. Only the row can be
 6450: ** changed. ^The database, table and column on which the blob handle is open
 6451: ** remain the same. Moving an existing blob handle to a new row can be
 6452: ** faster than closing the existing handle and opening a new one.
 6453: **
 6454: ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
 6455: ** it must exist and there must be either a blob or text value stored in
 6456: ** the nominated column.)^ ^If the new row is not present in the table, or if
 6457: ** it does not contain a blob or text value, or if another error occurs, an
 6458: ** SQLite error code is returned and the blob handle is considered aborted.
 6459: ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
 6460: ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
 6461: ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
 6462: ** always returns zero.
 6463: **
 6464: ** ^This function sets the database handle error code and message.
 6465: */
 6466: SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
 6467: 
 6468: /*
 6469: ** CAPI3REF: Close A BLOB Handle
 6470: ** DESTRUCTOR: sqlite3_blob
 6471: **
 6472: ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
 6473: ** unconditionally.  Even if this routine returns an error code, the 
 6474: ** handle is still closed.)^
 6475: **
 6476: ** ^If the blob handle being closed was opened for read-write access, and if
 6477: ** the database is in auto-commit mode and there are no other open read-write
 6478: ** blob handles or active write statements, the current transaction is
 6479: ** committed. ^If an error occurs while committing the transaction, an error
 6480: ** code is returned and the transaction rolled back.
 6481: **
 6482: ** Calling this function with an argument that is not a NULL pointer or an
 6483: ** open blob handle results in undefined behaviour. ^Calling this routine 
 6484: ** with a null pointer (such as would be returned by a failed call to 
 6485: ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
 6486: ** is passed a valid open blob handle, the values returned by the 
 6487: ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
 6488: */
 6489: SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
 6490: 
 6491: /*
 6492: ** CAPI3REF: Return The Size Of An Open BLOB
 6493: ** METHOD: sqlite3_blob
 6494: **
 6495: ** ^Returns the size in bytes of the BLOB accessible via the 
 6496: ** successfully opened [BLOB handle] in its only argument.  ^The
 6497: ** incremental blob I/O routines can only read or overwriting existing
 6498: ** blob content; they cannot change the size of a blob.
 6499: **
 6500: ** This routine only works on a [BLOB handle] which has been created
 6501: ** by a prior successful call to [sqlite3_blob_open()] and which has not
 6502: ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
 6503: ** to this routine results in undefined and probably undesirable behavior.
 6504: */
 6505: SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
 6506: 
 6507: /*
 6508: ** CAPI3REF: Read Data From A BLOB Incrementally
 6509: ** METHOD: sqlite3_blob
 6510: **
 6511: ** ^(This function is used to read data from an open [BLOB handle] into a
 6512: ** caller-supplied buffer. N bytes of data are copied into buffer Z
 6513: ** from the open BLOB, starting at offset iOffset.)^
 6514: **
 6515: ** ^If offset iOffset is less than N bytes from the end of the BLOB,
 6516: ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
 6517: ** less than zero, [SQLITE_ERROR] is returned and no data is read.
 6518: ** ^The size of the blob (and hence the maximum value of N+iOffset)
 6519: ** can be determined using the [sqlite3_blob_bytes()] interface.
 6520: **
 6521: ** ^An attempt to read from an expired [BLOB handle] fails with an
 6522: ** error code of [SQLITE_ABORT].
 6523: **
 6524: ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
 6525: ** Otherwise, an [error code] or an [extended error code] is returned.)^
 6526: **
 6527: ** This routine only works on a [BLOB handle] which has been created
 6528: ** by a prior successful call to [sqlite3_blob_open()] and which has not
 6529: ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
 6530: ** to this routine results in undefined and probably undesirable behavior.
 6531: **
 6532: ** See also: [sqlite3_blob_write()].
 6533: */
 6534: SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
 6535: 
 6536: /*
 6537: ** CAPI3REF: Write Data Into A BLOB Incrementally
 6538: ** METHOD: sqlite3_blob
 6539: **
 6540: ** ^(This function is used to write data into an open [BLOB handle] from a
 6541: ** caller-supplied buffer. N bytes of data are copied from the buffer Z
 6542: ** into the open BLOB, starting at offset iOffset.)^
 6543: **
 6544: ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
 6545: ** Otherwise, an  [error code] or an [extended error code] is returned.)^
 6546: ** ^Unless SQLITE_MISUSE is returned, this function sets the 
 6547: ** [database connection] error code and message accessible via 
 6548: ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
 6549: **
 6550: ** ^If the [BLOB handle] passed as the first argument was not opened for
 6551: ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
 6552: ** this function returns [SQLITE_READONLY].
 6553: **
 6554: ** This function may only modify the contents of the BLOB; it is
 6555: ** not possible to increase the size of a BLOB using this API.
 6556: ** ^If offset iOffset is less than N bytes from the end of the BLOB,
 6557: ** [SQLITE_ERROR] is returned and no data is written. The size of the 
 6558: ** BLOB (and hence the maximum value of N+iOffset) can be determined 
 6559: ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less 
 6560: ** than zero [SQLITE_ERROR] is returned and no data is written.
 6561: **
 6562: ** ^An attempt to write to an expired [BLOB handle] fails with an
 6563: ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
 6564: ** before the [BLOB handle] expired are not rolled back by the
 6565: ** expiration of the handle, though of course those changes might
 6566: ** have been overwritten by the statement that expired the BLOB handle
 6567: ** or by other independent statements.
 6568: **
 6569: ** This routine only works on a [BLOB handle] which has been created
 6570: ** by a prior successful call to [sqlite3_blob_open()] and which has not
 6571: ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
 6572: ** to this routine results in undefined and probably undesirable behavior.
 6573: **
 6574: ** See also: [sqlite3_blob_read()].
 6575: */
 6576: SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
 6577: 
 6578: /*
 6579: ** CAPI3REF: Virtual File System Objects
 6580: **
 6581: ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
 6582: ** that SQLite uses to interact
 6583: ** with the underlying operating system.  Most SQLite builds come with a
 6584: ** single default VFS that is appropriate for the host computer.
 6585: ** New VFSes can be registered and existing VFSes can be unregistered.
 6586: ** The following interfaces are provided.
 6587: **
 6588: ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
 6589: ** ^Names are case sensitive.
 6590: ** ^Names are zero-terminated UTF-8 strings.
 6591: ** ^If there is no match, a NULL pointer is returned.
 6592: ** ^If zVfsName is NULL then the default VFS is returned.
 6593: **
 6594: ** ^New VFSes are registered with sqlite3_vfs_register().
 6595: ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
 6596: ** ^The same VFS can be registered multiple times without injury.
 6597: ** ^To make an existing VFS into the default VFS, register it again
 6598: ** with the makeDflt flag set.  If two different VFSes with the
 6599: ** same name are registered, the behavior is undefined.  If a
 6600: ** VFS is registered with a name that is NULL or an empty string,
 6601: ** then the behavior is undefined.
 6602: **
 6603: ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
 6604: ** ^(If the default VFS is unregistered, another VFS is chosen as
 6605: ** the default.  The choice for the new VFS is arbitrary.)^
 6606: */
 6607: SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
 6608: SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
 6609: SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
 6610: 
 6611: /*
 6612: ** CAPI3REF: Mutexes
 6613: **
 6614: ** The SQLite core uses these routines for thread
 6615: ** synchronization. Though they are intended for internal
 6616: ** use by SQLite, code that links against SQLite is
 6617: ** permitted to use any of these routines.
 6618: **
 6619: ** The SQLite source code contains multiple implementations
 6620: ** of these mutex routines.  An appropriate implementation
 6621: ** is selected automatically at compile-time.  The following
 6622: ** implementations are available in the SQLite core:
 6623: **
 6624: ** <ul>
 6625: ** <li>   SQLITE_MUTEX_PTHREADS
 6626: ** <li>   SQLITE_MUTEX_W32
 6627: ** <li>   SQLITE_MUTEX_NOOP
 6628: ** </ul>
 6629: **
 6630: ** The SQLITE_MUTEX_NOOP implementation is a set of routines
 6631: ** that does no real locking and is appropriate for use in
 6632: ** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
 6633: ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
 6634: ** and Windows.
 6635: **
 6636: ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
 6637: ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
 6638: ** implementation is included with the library. In this case the
 6639: ** application must supply a custom mutex implementation using the
 6640: ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
 6641: ** before calling sqlite3_initialize() or any other public sqlite3_
 6642: ** function that calls sqlite3_initialize().
 6643: **
 6644: ** ^The sqlite3_mutex_alloc() routine allocates a new
 6645: ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
 6646: ** routine returns NULL if it is unable to allocate the requested
 6647: ** mutex.  The argument to sqlite3_mutex_alloc() must one of these
 6648: ** integer constants:
 6649: **
 6650: ** <ul>
 6651: ** <li>  SQLITE_MUTEX_FAST
 6652: ** <li>  SQLITE_MUTEX_RECURSIVE
 6653: ** <li>  SQLITE_MUTEX_STATIC_MASTER
 6654: ** <li>  SQLITE_MUTEX_STATIC_MEM
 6655: ** <li>  SQLITE_MUTEX_STATIC_OPEN
 6656: ** <li>  SQLITE_MUTEX_STATIC_PRNG
 6657: ** <li>  SQLITE_MUTEX_STATIC_LRU
 6658: ** <li>  SQLITE_MUTEX_STATIC_PMEM
 6659: ** <li>  SQLITE_MUTEX_STATIC_APP1
 6660: ** <li>  SQLITE_MUTEX_STATIC_APP2
 6661: ** <li>  SQLITE_MUTEX_STATIC_APP3
 6662: ** <li>  SQLITE_MUTEX_STATIC_VFS1
 6663: ** <li>  SQLITE_MUTEX_STATIC_VFS2
 6664: ** <li>  SQLITE_MUTEX_STATIC_VFS3
 6665: ** </ul>
 6666: **
 6667: ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
 6668: ** cause sqlite3_mutex_alloc() to create
 6669: ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
 6670: ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
 6671: ** The mutex implementation does not need to make a distinction
 6672: ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
 6673: ** not want to.  SQLite will only request a recursive mutex in
 6674: ** cases where it really needs one.  If a faster non-recursive mutex
 6675: ** implementation is available on the host platform, the mutex subsystem
 6676: ** might return such a mutex in response to SQLITE_MUTEX_FAST.
 6677: **
 6678: ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
 6679: ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
 6680: ** a pointer to a static preexisting mutex.  ^Nine static mutexes are
 6681: ** used by the current version of SQLite.  Future versions of SQLite
 6682: ** may add additional static mutexes.  Static mutexes are for internal
 6683: ** use by SQLite only.  Applications that use SQLite mutexes should
 6684: ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
 6685: ** SQLITE_MUTEX_RECURSIVE.
 6686: **
 6687: ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
 6688: ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
 6689: ** returns a different mutex on every call.  ^For the static
 6690: ** mutex types, the same mutex is returned on every call that has
 6691: ** the same type number.
 6692: **
 6693: ** ^The sqlite3_mutex_free() routine deallocates a previously
 6694: ** allocated dynamic mutex.  Attempting to deallocate a static
 6695: ** mutex results in undefined behavior.
 6696: **
 6697: ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
 6698: ** to enter a mutex.  ^If another thread is already within the mutex,
 6699: ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
 6700: ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
 6701: ** upon successful entry.  ^(Mutexes created using
 6702: ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
 6703: ** In such cases, the
 6704: ** mutex must be exited an equal number of times before another thread
 6705: ** can enter.)^  If the same thread tries to enter any mutex other
 6706: ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
 6707: **
 6708: ** ^(Some systems (for example, Windows 95) do not support the operation
 6709: ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
 6710: ** will always return SQLITE_BUSY. The SQLite core only ever uses
 6711: ** sqlite3_mutex_try() as an optimization so this is acceptable 
 6712: ** behavior.)^
 6713: **
 6714: ** ^The sqlite3_mutex_leave() routine exits a mutex that was
 6715: ** previously entered by the same thread.   The behavior
 6716: ** is undefined if the mutex is not currently entered by the
 6717: ** calling thread or is not currently allocated.
 6718: **
 6719: ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
 6720: ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
 6721: ** behave as no-ops.
 6722: **
 6723: ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
 6724: */
 6725: SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
 6726: SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
 6727: SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
 6728: SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
 6729: SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
 6730: 
 6731: /*
 6732: ** CAPI3REF: Mutex Methods Object
 6733: **
 6734: ** An instance of this structure defines the low-level routines
 6735: ** used to allocate and use mutexes.
 6736: **
 6737: ** Usually, the default mutex implementations provided by SQLite are
 6738: ** sufficient, however the application has the option of substituting a custom
 6739: ** implementation for specialized deployments or systems for which SQLite
 6740: ** does not provide a suitable implementation. In this case, the application
 6741: ** creates and populates an instance of this structure to pass
 6742: ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
 6743: ** Additionally, an instance of this structure can be used as an
 6744: ** output variable when querying the system for the current mutex
 6745: ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
 6746: **
 6747: ** ^The xMutexInit method defined by this structure is invoked as
 6748: ** part of system initialization by the sqlite3_initialize() function.
 6749: ** ^The xMutexInit routine is called by SQLite exactly once for each
 6750: ** effective call to [sqlite3_initialize()].
 6751: **
 6752: ** ^The xMutexEnd method defined by this structure is invoked as
 6753: ** part of system shutdown by the sqlite3_shutdown() function. The
 6754: ** implementation of this method is expected to release all outstanding
 6755: ** resources obtained by the mutex methods implementation, especially
 6756: ** those obtained by the xMutexInit method.  ^The xMutexEnd()
 6757: ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
 6758: **
 6759: ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
 6760: ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
 6761: ** xMutexNotheld) implement the following interfaces (respectively):
 6762: **
 6763: ** <ul>
 6764: **   <li>  [sqlite3_mutex_alloc()] </li>
 6765: **   <li>  [sqlite3_mutex_free()] </li>
 6766: **   <li>  [sqlite3_mutex_enter()] </li>
 6767: **   <li>  [sqlite3_mutex_try()] </li>
 6768: **   <li>  [sqlite3_mutex_leave()] </li>
 6769: **   <li>  [sqlite3_mutex_held()] </li>
 6770: **   <li>  [sqlite3_mutex_notheld()] </li>
 6771: ** </ul>)^
 6772: **
 6773: ** The only difference is that the public sqlite3_XXX functions enumerated
 6774: ** above silently ignore any invocations that pass a NULL pointer instead
 6775: ** of a valid mutex handle. The implementations of the methods defined
 6776: ** by this structure are not required to handle this case, the results
 6777: ** of passing a NULL pointer instead of a valid mutex handle are undefined
 6778: ** (i.e. it is acceptable to provide an implementation that segfaults if
 6779: ** it is passed a NULL pointer).
 6780: **
 6781: ** The xMutexInit() method must be threadsafe.  It must be harmless to
 6782: ** invoke xMutexInit() multiple times within the same process and without
 6783: ** intervening calls to xMutexEnd().  Second and subsequent calls to
 6784: ** xMutexInit() must be no-ops.
 6785: **
 6786: ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
 6787: ** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
 6788: ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
 6789: ** memory allocation for a fast or recursive mutex.
 6790: **
 6791: ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
 6792: ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
 6793: ** If xMutexInit fails in any way, it is expected to clean up after itself
 6794: ** prior to returning.
 6795: */
 6796: typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
 6797: struct sqlite3_mutex_methods {
 6798:   int (*xMutexInit)(void);
 6799:   int (*xMutexEnd)(void);
 6800:   sqlite3_mutex *(*xMutexAlloc)(int);
 6801:   void (*xMutexFree)(sqlite3_mutex *);
 6802:   void (*xMutexEnter)(sqlite3_mutex *);
 6803:   int (*xMutexTry)(sqlite3_mutex *);
 6804:   void (*xMutexLeave)(sqlite3_mutex *);
 6805:   int (*xMutexHeld)(sqlite3_mutex *);
 6806:   int (*xMutexNotheld)(sqlite3_mutex *);
 6807: };
 6808: 
 6809: /*
 6810: ** CAPI3REF: Mutex Verification Routines
 6811: **
 6812: ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
 6813: ** are intended for use inside assert() statements.  The SQLite core
 6814: ** never uses these routines except inside an assert() and applications
 6815: ** are advised to follow the lead of the core.  The SQLite core only
 6816: ** provides implementations for these routines when it is compiled
 6817: ** with the SQLITE_DEBUG flag.  External mutex implementations
 6818: ** are only required to provide these routines if SQLITE_DEBUG is
 6819: ** defined and if NDEBUG is not defined.
 6820: **
 6821: ** These routines should return true if the mutex in their argument
 6822: ** is held or not held, respectively, by the calling thread.
 6823: **
 6824: ** The implementation is not required to provide versions of these
 6825: ** routines that actually work. If the implementation does not provide working
 6826: ** versions of these routines, it should at least provide stubs that always
 6827: ** return true so that one does not get spurious assertion failures.
 6828: **
 6829: ** If the argument to sqlite3_mutex_held() is a NULL pointer then
 6830: ** the routine should return 1.   This seems counter-intuitive since
 6831: ** clearly the mutex cannot be held if it does not exist.  But
 6832: ** the reason the mutex does not exist is because the build is not
 6833: ** using mutexes.  And we do not want the assert() containing the
 6834: ** call to sqlite3_mutex_held() to fail, so a non-zero return is
 6835: ** the appropriate thing to do.  The sqlite3_mutex_notheld()
 6836: ** interface should also return 1 when given a NULL pointer.
 6837: */
 6838: #ifndef NDEBUG
 6839: SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
 6840: SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
 6841: #endif
 6842: 
 6843: /*
 6844: ** CAPI3REF: Mutex Types
 6845: **
 6846: ** The [sqlite3_mutex_alloc()] interface takes a single argument
 6847: ** which is one of these integer constants.
 6848: **
 6849: ** The set of static mutexes may change from one SQLite release to the
 6850: ** next.  Applications that override the built-in mutex logic must be
 6851: ** prepared to accommodate additional static mutexes.
 6852: */
 6853: #define SQLITE_MUTEX_FAST             0
 6854: #define SQLITE_MUTEX_RECURSIVE        1
 6855: #define SQLITE_MUTEX_STATIC_MASTER    2
 6856: #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
 6857: #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
 6858: #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
 6859: #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
 6860: #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
 6861: #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
 6862: #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
 6863: #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
 6864: #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
 6865: #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
 6866: #define SQLITE_MUTEX_STATIC_VFS1     11  /* For use by built-in VFS */
 6867: #define SQLITE_MUTEX_STATIC_VFS2     12  /* For use by extension VFS */
 6868: #define SQLITE_MUTEX_STATIC_VFS3     13  /* For use by application VFS */
 6869: 
 6870: /*
 6871: ** CAPI3REF: Retrieve the mutex for a database connection
 6872: ** METHOD: sqlite3
 6873: **
 6874: ** ^This interface returns a pointer the [sqlite3_mutex] object that 
 6875: ** serializes access to the [database connection] given in the argument
 6876: ** when the [threading mode] is Serialized.
 6877: ** ^If the [threading mode] is Single-thread or Multi-thread then this
 6878: ** routine returns a NULL pointer.
 6879: */
 6880: SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
 6881: 
 6882: /*
 6883: ** CAPI3REF: Low-Level Control Of Database Files
 6884: ** METHOD: sqlite3
 6885: **
 6886: ** ^The [sqlite3_file_control()] interface makes a direct call to the
 6887: ** xFileControl method for the [sqlite3_io_methods] object associated
 6888: ** with a particular database identified by the second argument. ^The
 6889: ** name of the database is "main" for the main database or "temp" for the
 6890: ** TEMP database, or the name that appears after the AS keyword for
 6891: ** databases that are added using the [ATTACH] SQL command.
 6892: ** ^A NULL pointer can be used in place of "main" to refer to the
 6893: ** main database file.
 6894: ** ^The third and fourth parameters to this routine
 6895: ** are passed directly through to the second and third parameters of
 6896: ** the xFileControl method.  ^The return value of the xFileControl
 6897: ** method becomes the return value of this routine.
 6898: **
 6899: ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
 6900: ** a pointer to the underlying [sqlite3_file] object to be written into
 6901: ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
 6902: ** case is a short-circuit path which does not actually invoke the
 6903: ** underlying sqlite3_io_methods.xFileControl method.
 6904: **
 6905: ** ^If the second parameter (zDbName) does not match the name of any
 6906: ** open database file, then SQLITE_ERROR is returned.  ^This error
 6907: ** code is not remembered and will not be recalled by [sqlite3_errcode()]
 6908: ** or [sqlite3_errmsg()].  The underlying xFileControl method might
 6909: ** also return SQLITE_ERROR.  There is no way to distinguish between
 6910: ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
 6911: ** xFileControl method.
 6912: **
 6913: ** See also: [SQLITE_FCNTL_LOCKSTATE]
 6914: */
 6915: SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
 6916: 
 6917: /*
 6918: ** CAPI3REF: Testing Interface
 6919: **
 6920: ** ^The sqlite3_test_control() interface is used to read out internal
 6921: ** state of SQLite and to inject faults into SQLite for testing
 6922: ** purposes.  ^The first parameter is an operation code that determines
 6923: ** the number, meaning, and operation of all subsequent parameters.
 6924: **
 6925: ** This interface is not for use by applications.  It exists solely
 6926: ** for verifying the correct operation of the SQLite library.  Depending
 6927: ** on how the SQLite library is compiled, this interface might not exist.
 6928: **
 6929: ** The details of the operation codes, their meanings, the parameters
 6930: ** they take, and what they do are all subject to change without notice.
 6931: ** Unlike most of the SQLite API, this function is not guaranteed to
 6932: ** operate consistently from one release to the next.
 6933: */
 6934: SQLITE_API int sqlite3_test_control(int op, ...);
 6935: 
 6936: /*
 6937: ** CAPI3REF: Testing Interface Operation Codes
 6938: **
 6939: ** These constants are the valid operation code parameters used
 6940: ** as the first argument to [sqlite3_test_control()].
 6941: **
 6942: ** These parameters and their meanings are subject to change
 6943: ** without notice.  These values are for testing purposes only.
 6944: ** Applications should not use any of these parameters or the
 6945: ** [sqlite3_test_control()] interface.
 6946: */
 6947: #define SQLITE_TESTCTRL_FIRST                    5
 6948: #define SQLITE_TESTCTRL_PRNG_SAVE                5
 6949: #define SQLITE_TESTCTRL_PRNG_RESTORE             6
 6950: #define SQLITE_TESTCTRL_PRNG_RESET               7
 6951: #define SQLITE_TESTCTRL_BITVEC_TEST              8
 6952: #define SQLITE_TESTCTRL_FAULT_INSTALL            9
 6953: #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
 6954: #define SQLITE_TESTCTRL_PENDING_BYTE            11
 6955: #define SQLITE_TESTCTRL_ASSERT                  12
 6956: #define SQLITE_TESTCTRL_ALWAYS                  13
 6957: #define SQLITE_TESTCTRL_RESERVE                 14
 6958: #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
 6959: #define SQLITE_TESTCTRL_ISKEYWORD               16
 6960: #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
 6961: #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
 6962: #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
 6963: #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
 6964: #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
 6965: #define SQLITE_TESTCTRL_BYTEORDER               22
 6966: #define SQLITE_TESTCTRL_ISINIT                  23
 6967: #define SQLITE_TESTCTRL_SORTER_MMAP             24
 6968: #define SQLITE_TESTCTRL_IMPOSTER                25
 6969: #define SQLITE_TESTCTRL_LAST                    25
 6970: 
 6971: /*
 6972: ** CAPI3REF: SQLite Runtime Status
 6973: **
 6974: ** ^These interfaces are used to retrieve runtime status information
 6975: ** about the performance of SQLite, and optionally to reset various
 6976: ** highwater marks.  ^The first argument is an integer code for
 6977: ** the specific parameter to measure.  ^(Recognized integer codes
 6978: ** are of the form [status parameters | SQLITE_STATUS_...].)^
 6979: ** ^The current value of the parameter is returned into *pCurrent.
 6980: ** ^The highest recorded value is returned in *pHighwater.  ^If the
 6981: ** resetFlag is true, then the highest record value is reset after
 6982: ** *pHighwater is written.  ^(Some parameters do not record the highest
 6983: ** value.  For those parameters
 6984: ** nothing is written into *pHighwater and the resetFlag is ignored.)^
 6985: ** ^(Other parameters record only the highwater mark and not the current
 6986: ** value.  For these latter parameters nothing is written into *pCurrent.)^
 6987: **
 6988: ** ^The sqlite3_status() and sqlite3_status64() routines return
 6989: ** SQLITE_OK on success and a non-zero [error code] on failure.
 6990: **
 6991: ** If either the current value or the highwater mark is too large to
 6992: ** be represented by a 32-bit integer, then the values returned by
 6993: ** sqlite3_status() are undefined.
 6994: **
 6995: ** See also: [sqlite3_db_status()]
 6996: */
 6997: SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
 6998: SQLITE_API int sqlite3_status64(
 6999:   int op,
 7000:   sqlite3_int64 *pCurrent,
 7001:   sqlite3_int64 *pHighwater,
 7002:   int resetFlag
 7003: );
 7004: 
 7005: 
 7006: /*
 7007: ** CAPI3REF: Status Parameters
 7008: ** KEYWORDS: {status parameters}
 7009: **
 7010: ** These integer constants designate various run-time status parameters
 7011: ** that can be returned by [sqlite3_status()].
 7012: **
 7013: ** <dl>
 7014: ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
 7015: ** <dd>This parameter is the current amount of memory checked out
 7016: ** using [sqlite3_malloc()], either directly or indirectly.  The
 7017: ** figure includes calls made to [sqlite3_malloc()] by the application
 7018: ** and internal memory usage by the SQLite library.  Scratch memory
 7019: ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
 7020: ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
 7021: ** this parameter.  The amount returned is the sum of the allocation
 7022: ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
 7023: **
 7024: ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
 7025: ** <dd>This parameter records the largest memory allocation request
 7026: ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
 7027: ** internal equivalents).  Only the value returned in the
 7028: ** *pHighwater parameter to [sqlite3_status()] is of interest.  
 7029: ** The value written into the *pCurrent parameter is undefined.</dd>)^
 7030: **
 7031: ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
 7032: ** <dd>This parameter records the number of separate memory allocations
 7033: ** currently checked out.</dd>)^
 7034: **
 7035: ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
 7036: ** <dd>This parameter returns the number of pages used out of the
 7037: ** [pagecache memory allocator] that was configured using 
 7038: ** [SQLITE_CONFIG_PAGECACHE].  The
 7039: ** value returned is in pages, not in bytes.</dd>)^
 7040: **
 7041: ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
 7042: ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
 7043: ** <dd>This parameter returns the number of bytes of page cache
 7044: ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
 7045: ** buffer and where forced to overflow to [sqlite3_malloc()].  The
 7046: ** returned value includes allocations that overflowed because they
 7047: ** where too large (they were larger than the "sz" parameter to
 7048: ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
 7049: ** no space was left in the page cache.</dd>)^
 7050: **
 7051: ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
 7052: ** <dd>This parameter records the largest memory allocation request
 7053: ** handed to [pagecache memory allocator].  Only the value returned in the
 7054: ** *pHighwater parameter to [sqlite3_status()] is of interest.  
 7055: ** The value written into the *pCurrent parameter is undefined.</dd>)^
 7056: **
 7057: ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
 7058: ** <dd>This parameter returns the number of allocations used out of the
 7059: ** [scratch memory allocator] configured using
 7060: ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
 7061: ** in bytes.  Since a single thread may only have one scratch allocation
 7062: ** outstanding at time, this parameter also reports the number of threads
 7063: ** using scratch memory at the same time.</dd>)^
 7064: **
 7065: ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
 7066: ** <dd>This parameter returns the number of bytes of scratch memory
 7067: ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
 7068: ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
 7069: ** returned include overflows because the requested allocation was too
 7070: ** larger (that is, because the requested allocation was larger than the
 7071: ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
 7072: ** slots were available.
 7073: ** </dd>)^
 7074: **
 7075: ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
 7076: ** <dd>This parameter records the largest memory allocation request
 7077: ** handed to [scratch memory allocator].  Only the value returned in the
 7078: ** *pHighwater parameter to [sqlite3_status()] is of interest.  
 7079: ** The value written into the *pCurrent parameter is undefined.</dd>)^
 7080: **
 7081: ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
 7082: ** <dd>The *pHighwater parameter records the deepest parser stack. 
 7083: ** The *pCurrent value is undefined.  The *pHighwater value is only
 7084: ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
 7085: ** </dl>
 7086: **
 7087: ** New status parameters may be added from time to time.
 7088: */
 7089: #define SQLITE_STATUS_MEMORY_USED          0
 7090: #define SQLITE_STATUS_PAGECACHE_USED       1
 7091: #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
 7092: #define SQLITE_STATUS_SCRATCH_USED         3
 7093: #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
 7094: #define SQLITE_STATUS_MALLOC_SIZE          5
 7095: #define SQLITE_STATUS_PARSER_STACK         6
 7096: #define SQLITE_STATUS_PAGECACHE_SIZE       7
 7097: #define SQLITE_STATUS_SCRATCH_SIZE         8
 7098: #define SQLITE_STATUS_MALLOC_COUNT         9
 7099: 
 7100: /*
 7101: ** CAPI3REF: Database Connection Status
 7102: ** METHOD: sqlite3
 7103: **
 7104: ** ^This interface is used to retrieve runtime status information 
 7105: ** about a single [database connection].  ^The first argument is the
 7106: ** database connection object to be interrogated.  ^The second argument
 7107: ** is an integer constant, taken from the set of
 7108: ** [SQLITE_DBSTATUS options], that
 7109: ** determines the parameter to interrogate.  The set of 
 7110: ** [SQLITE_DBSTATUS options] is likely
 7111: ** to grow in future releases of SQLite.
 7112: **
 7113: ** ^The current value of the requested parameter is written into *pCur
 7114: ** and the highest instantaneous value is written into *pHiwtr.  ^If
 7115: ** the resetFlg is true, then the highest instantaneous value is
 7116: ** reset back down to the current value.
 7117: **
 7118: ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
 7119: ** non-zero [error code] on failure.
 7120: **
 7121: ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
 7122: */
 7123: SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
 7124: 
 7125: /*
 7126: ** CAPI3REF: Status Parameters for database connections
 7127: ** KEYWORDS: {SQLITE_DBSTATUS options}
 7128: **
 7129: ** These constants are the available integer "verbs" that can be passed as
 7130: ** the second argument to the [sqlite3_db_status()] interface.
 7131: **
 7132: ** New verbs may be added in future releases of SQLite. Existing verbs
 7133: ** might be discontinued. Applications should check the return code from
 7134: ** [sqlite3_db_status()] to make sure that the call worked.
 7135: ** The [sqlite3_db_status()] interface will return a non-zero error code
 7136: ** if a discontinued or unsupported verb is invoked.
 7137: **
 7138: ** <dl>
 7139: ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
 7140: ** <dd>This parameter returns the number of lookaside memory slots currently
 7141: ** checked out.</dd>)^
 7142: **
 7143: ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
 7144: ** <dd>This parameter returns the number malloc attempts that were 
 7145: ** satisfied using lookaside memory. Only the high-water value is meaningful;
 7146: ** the current value is always zero.)^
 7147: **
 7148: ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
 7149: ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
 7150: ** <dd>This parameter returns the number malloc attempts that might have
 7151: ** been satisfied using lookaside memory but failed due to the amount of
 7152: ** memory requested being larger than the lookaside slot size.
 7153: ** Only the high-water value is meaningful;
 7154: ** the current value is always zero.)^
 7155: **
 7156: ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
 7157: ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
 7158: ** <dd>This parameter returns the number malloc attempts that might have
 7159: ** been satisfied using lookaside memory but failed due to all lookaside
 7160: ** memory already being in use.
 7161: ** Only the high-water value is meaningful;
 7162: ** the current value is always zero.)^
 7163: **
 7164: ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
 7165: ** <dd>This parameter returns the approximate number of bytes of heap
 7166: ** memory used by all pager caches associated with the database connection.)^
 7167: ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
 7168: **
 7169: ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]] 
 7170: ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
 7171: ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
 7172: ** pager cache is shared between two or more connections the bytes of heap
 7173: ** memory used by that pager cache is divided evenly between the attached
 7174: ** connections.)^  In other words, if none of the pager caches associated
 7175: ** with the database connection are shared, this request returns the same
 7176: ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
 7177: ** shared, the value returned by this call will be smaller than that returned
 7178: ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
 7179: ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
 7180: **
 7181: ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
 7182: ** <dd>This parameter returns the approximate number of bytes of heap
 7183: ** memory used to store the schema for all databases associated
 7184: ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
 7185: ** ^The full amount of memory used by the schemas is reported, even if the
 7186: ** schema memory is shared with other database connections due to
 7187: ** [shared cache mode] being enabled.
 7188: ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
 7189: **
 7190: ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
 7191: ** <dd>This parameter returns the approximate number of bytes of heap
 7192: ** and lookaside memory used by all prepared statements associated with
 7193: ** the database connection.)^
 7194: ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
 7195: ** </dd>
 7196: **
 7197: ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
 7198: ** <dd>This parameter returns the number of pager cache hits that have
 7199: ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
 7200: ** is always 0.
 7201: ** </dd>
 7202: **
 7203: ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
 7204: ** <dd>This parameter returns the number of pager cache misses that have
 7205: ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
 7206: ** is always 0.
 7207: ** </dd>
 7208: **
 7209: ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
 7210: ** <dd>This parameter returns the number of dirty cache entries that have
 7211: ** been written to disk. Specifically, the number of pages written to the
 7212: ** wal file in wal mode databases, or the number of pages written to the
 7213: ** database file in rollback mode databases. Any pages written as part of
 7214: ** transaction rollback or database recovery operations are not included.
 7215: ** If an IO or other error occurs while writing a page to disk, the effect
 7216: ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
 7217: ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
 7218: ** </dd>
 7219: **
 7220: ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
 7221: ** <dd>This parameter returns zero for the current value if and only if
 7222: ** all foreign key constraints (deferred or immediate) have been
 7223: ** resolved.)^  ^The highwater mark is always 0.
 7224: ** </dd>
 7225: ** </dl>
 7226: */
 7227: #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
 7228: #define SQLITE_DBSTATUS_CACHE_USED           1
 7229: #define SQLITE_DBSTATUS_SCHEMA_USED          2
 7230: #define SQLITE_DBSTATUS_STMT_USED            3
 7231: #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
 7232: #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
 7233: #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
 7234: #define SQLITE_DBSTATUS_CACHE_HIT            7
 7235: #define SQLITE_DBSTATUS_CACHE_MISS           8
 7236: #define SQLITE_DBSTATUS_CACHE_WRITE          9
 7237: #define SQLITE_DBSTATUS_DEFERRED_FKS        10
 7238: #define SQLITE_DBSTATUS_CACHE_USED_SHARED   11
 7239: #define SQLITE_DBSTATUS_MAX                 11   /* Largest defined DBSTATUS */
 7240: 
 7241: 
 7242: /*
 7243: ** CAPI3REF: Prepared Statement Status
 7244: ** METHOD: sqlite3_stmt
 7245: **
 7246: ** ^(Each prepared statement maintains various
 7247: ** [SQLITE_STMTSTATUS counters] that measure the number
 7248: ** of times it has performed specific operations.)^  These counters can
 7249: ** be used to monitor the performance characteristics of the prepared
 7250: ** statements.  For example, if the number of table steps greatly exceeds
 7251: ** the number of table searches or result rows, that would tend to indicate
 7252: ** that the prepared statement is using a full table scan rather than
 7253: ** an index.  
 7254: **
 7255: ** ^(This interface is used to retrieve and reset counter values from
 7256: ** a [prepared statement].  The first argument is the prepared statement
 7257: ** object to be interrogated.  The second argument
 7258: ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
 7259: ** to be interrogated.)^
 7260: ** ^The current value of the requested counter is returned.
 7261: ** ^If the resetFlg is true, then the counter is reset to zero after this
 7262: ** interface call returns.
 7263: **
 7264: ** See also: [sqlite3_status()] and [sqlite3_db_status()].
 7265: */
 7266: SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
 7267: 
 7268: /*
 7269: ** CAPI3REF: Status Parameters for prepared statements
 7270: ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
 7271: **
 7272: ** These preprocessor macros define integer codes that name counter
 7273: ** values associated with the [sqlite3_stmt_status()] interface.
 7274: ** The meanings of the various counters are as follows:
 7275: **
 7276: ** <dl>
 7277: ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
 7278: ** <dd>^This is the number of times that SQLite has stepped forward in
 7279: ** a table as part of a full table scan.  Large numbers for this counter
 7280: ** may indicate opportunities for performance improvement through 
 7281: ** careful use of indices.</dd>
 7282: **
 7283: ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
 7284: ** <dd>^This is the number of sort operations that have occurred.
 7285: ** A non-zero value in this counter may indicate an opportunity to
 7286: ** improvement performance through careful use of indices.</dd>
 7287: **
 7288: ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
 7289: ** <dd>^This is the number of rows inserted into transient indices that
 7290: ** were created automatically in order to help joins run faster.
 7291: ** A non-zero value in this counter may indicate an opportunity to
 7292: ** improvement performance by adding permanent indices that do not
 7293: ** need to be reinitialized each time the statement is run.</dd>
 7294: **
 7295: ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
 7296: ** <dd>^This is the number of virtual machine operations executed
 7297: ** by the prepared statement if that number is less than or equal
 7298: ** to 2147483647.  The number of virtual machine operations can be 
 7299: ** used as a proxy for the total work done by the prepared statement.
 7300: ** If the number of virtual machine operations exceeds 2147483647
 7301: ** then the value returned by this statement status code is undefined.
 7302: ** </dd>
 7303: ** </dl>
 7304: */
 7305: #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
 7306: #define SQLITE_STMTSTATUS_SORT              2
 7307: #define SQLITE_STMTSTATUS_AUTOINDEX         3
 7308: #define SQLITE_STMTSTATUS_VM_STEP           4
 7309: 
 7310: /*
 7311: ** CAPI3REF: Custom Page Cache Object
 7312: **
 7313: ** The sqlite3_pcache type is opaque.  It is implemented by
 7314: ** the pluggable module.  The SQLite core has no knowledge of
 7315: ** its size or internal structure and never deals with the
 7316: ** sqlite3_pcache object except by holding and passing pointers
 7317: ** to the object.
 7318: **
 7319: ** See [sqlite3_pcache_methods2] for additional information.
 7320: */
 7321: typedef struct sqlite3_pcache sqlite3_pcache;
 7322: 
 7323: /*
 7324: ** CAPI3REF: Custom Page Cache Object
 7325: **
 7326: ** The sqlite3_pcache_page object represents a single page in the
 7327: ** page cache.  The page cache will allocate instances of this
 7328: ** object.  Various methods of the page cache use pointers to instances
 7329: ** of this object as parameters or as their return value.
 7330: **
 7331: ** See [sqlite3_pcache_methods2] for additional information.
 7332: */
 7333: typedef struct sqlite3_pcache_page sqlite3_pcache_page;
 7334: struct sqlite3_pcache_page {
 7335:   void *pBuf;        /* The content of the page */
 7336:   void *pExtra;      /* Extra information associated with the page */
 7337: };
 7338: 
 7339: /*
 7340: ** CAPI3REF: Application Defined Page Cache.
 7341: ** KEYWORDS: {page cache}
 7342: **
 7343: ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
 7344: ** register an alternative page cache implementation by passing in an 
 7345: ** instance of the sqlite3_pcache_methods2 structure.)^
 7346: ** In many applications, most of the heap memory allocated by 
 7347: ** SQLite is used for the page cache.
 7348: ** By implementing a 
 7349: ** custom page cache using this API, an application can better control
 7350: ** the amount of memory consumed by SQLite, the way in which 
 7351: ** that memory is allocated and released, and the policies used to 
 7352: ** determine exactly which parts of a database file are cached and for 
 7353: ** how long.
 7354: **
 7355: ** The alternative page cache mechanism is an
 7356: ** extreme measure that is only needed by the most demanding applications.
 7357: ** The built-in page cache is recommended for most uses.
 7358: **
 7359: ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
 7360: ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
 7361: ** the application may discard the parameter after the call to
 7362: ** [sqlite3_config()] returns.)^
 7363: **
 7364: ** [[the xInit() page cache method]]
 7365: ** ^(The xInit() method is called once for each effective 
 7366: ** call to [sqlite3_initialize()])^
 7367: ** (usually only once during the lifetime of the process). ^(The xInit()
 7368: ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
 7369: ** The intent of the xInit() method is to set up global data structures 
 7370: ** required by the custom page cache implementation. 
 7371: ** ^(If the xInit() method is NULL, then the 
 7372: ** built-in default page cache is used instead of the application defined
 7373: ** page cache.)^
 7374: **
 7375: ** [[the xShutdown() page cache method]]
 7376: ** ^The xShutdown() method is called by [sqlite3_shutdown()].
 7377: ** It can be used to clean up 
 7378: ** any outstanding resources before process shutdown, if required.
 7379: ** ^The xShutdown() method may be NULL.
 7380: **
 7381: ** ^SQLite automatically serializes calls to the xInit method,
 7382: ** so the xInit method need not be threadsafe.  ^The
 7383: ** xShutdown method is only called from [sqlite3_shutdown()] so it does
 7384: ** not need to be threadsafe either.  All other methods must be threadsafe
 7385: ** in multithreaded applications.
 7386: **
 7387: ** ^SQLite will never invoke xInit() more than once without an intervening
 7388: ** call to xShutdown().
 7389: **
 7390: ** [[the xCreate() page cache methods]]
 7391: ** ^SQLite invokes the xCreate() method to construct a new cache instance.
 7392: ** SQLite will typically create one cache instance for each open database file,
 7393: ** though this is not guaranteed. ^The
 7394: ** first parameter, szPage, is the size in bytes of the pages that must
 7395: ** be allocated by the cache.  ^szPage will always a power of two.  ^The
 7396: ** second parameter szExtra is a number of bytes of extra storage 
 7397: ** associated with each page cache entry.  ^The szExtra parameter will
 7398: ** a number less than 250.  SQLite will use the
 7399: ** extra szExtra bytes on each page to store metadata about the underlying
 7400: ** database page on disk.  The value passed into szExtra depends
 7401: ** on the SQLite version, the target platform, and how SQLite was compiled.
 7402: ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
 7403: ** created will be used to cache database pages of a file stored on disk, or
 7404: ** false if it is used for an in-memory database. The cache implementation
 7405: ** does not have to do anything special based with the value of bPurgeable;
 7406: ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
 7407: ** never invoke xUnpin() except to deliberately delete a page.
 7408: ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
 7409: ** false will always have the "discard" flag set to true.  
 7410: ** ^Hence, a cache created with bPurgeable false will
 7411: ** never contain any unpinned pages.
 7412: **
 7413: ** [[the xCachesize() page cache method]]
 7414: ** ^(The xCachesize() method may be called at any time by SQLite to set the
 7415: ** suggested maximum cache-size (number of pages stored by) the cache
 7416: ** instance passed as the first argument. This is the value configured using
 7417: ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
 7418: ** parameter, the implementation is not required to do anything with this
 7419: ** value; it is advisory only.
 7420: **
 7421: ** [[the xPagecount() page cache methods]]
 7422: ** The xPagecount() method must return the number of pages currently
 7423: ** stored in the cache, both pinned and unpinned.
 7424: ** 
 7425: ** [[the xFetch() page cache methods]]
 7426: ** The xFetch() method locates a page in the cache and returns a pointer to 
 7427: ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
 7428: ** The pBuf element of the returned sqlite3_pcache_page object will be a
 7429: ** pointer to a buffer of szPage bytes used to store the content of a 
 7430: ** single database page.  The pExtra element of sqlite3_pcache_page will be
 7431: ** a pointer to the szExtra bytes of extra storage that SQLite has requested
 7432: ** for each entry in the page cache.
 7433: **
 7434: ** The page to be fetched is determined by the key. ^The minimum key value
 7435: ** is 1.  After it has been retrieved using xFetch, the page is considered
 7436: ** to be "pinned".
 7437: **
 7438: ** If the requested page is already in the page cache, then the page cache
 7439: ** implementation must return a pointer to the page buffer with its content
 7440: ** intact.  If the requested page is not already in the cache, then the
 7441: ** cache implementation should use the value of the createFlag
 7442: ** parameter to help it determined what action to take:
 7443: **
 7444: ** <table border=1 width=85% align=center>
 7445: ** <tr><th> createFlag <th> Behavior when page is not already in cache
 7446: ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
 7447: ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
 7448: **                 Otherwise return NULL.
 7449: ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
 7450: **                 NULL if allocating a new page is effectively impossible.
 7451: ** </table>
 7452: **
 7453: ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
 7454: ** will only use a createFlag of 2 after a prior call with a createFlag of 1
 7455: ** failed.)^  In between the to xFetch() calls, SQLite may
 7456: ** attempt to unpin one or more cache pages by spilling the content of
 7457: ** pinned pages to disk and synching the operating system disk cache.
 7458: **
 7459: ** [[the xUnpin() page cache method]]
 7460: ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
 7461: ** as its second argument.  If the third parameter, discard, is non-zero,
 7462: ** then the page must be evicted from the cache.
 7463: ** ^If the discard parameter is
 7464: ** zero, then the page may be discarded or retained at the discretion of
 7465: ** page cache implementation. ^The page cache implementation
 7466: ** may choose to evict unpinned pages at any time.
 7467: **
 7468: ** The cache must not perform any reference counting. A single 
 7469: ** call to xUnpin() unpins the page regardless of the number of prior calls 
 7470: ** to xFetch().
 7471: **
 7472: ** [[the xRekey() page cache methods]]
 7473: ** The xRekey() method is used to change the key value associated with the
 7474: ** page passed as the second argument. If the cache
 7475: ** previously contains an entry associated with newKey, it must be
 7476: ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
 7477: ** to be pinned.
 7478: **
 7479: ** When SQLite calls the xTruncate() method, the cache must discard all
 7480: ** existing cache entries with page numbers (keys) greater than or equal
 7481: ** to the value of the iLimit parameter passed to xTruncate(). If any
 7482: ** of these pages are pinned, they are implicitly unpinned, meaning that
 7483: ** they can be safely discarded.
 7484: **
 7485: ** [[the xDestroy() page cache method]]
 7486: ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
 7487: ** All resources associated with the specified cache should be freed. ^After
 7488: ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
 7489: ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
 7490: ** functions.
 7491: **
 7492: ** [[the xShrink() page cache method]]
 7493: ** ^SQLite invokes the xShrink() method when it wants the page cache to
 7494: ** free up as much of heap memory as possible.  The page cache implementation
 7495: ** is not obligated to free any memory, but well-behaved implementations should
 7496: ** do their best.
 7497: */
 7498: typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
 7499: struct sqlite3_pcache_methods2 {
 7500:   int iVersion;
 7501:   void *pArg;
 7502:   int (*xInit)(void*);
 7503:   void (*xShutdown)(void*);
 7504:   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
 7505:   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
 7506:   int (*xPagecount)(sqlite3_pcache*);
 7507:   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
 7508:   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
 7509:   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
 7510:       unsigned oldKey, unsigned newKey);
 7511:   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
 7512:   void (*xDestroy)(sqlite3_pcache*);
 7513:   void (*xShrink)(sqlite3_pcache*);
 7514: };
 7515: 
 7516: /*
 7517: ** This is the obsolete pcache_methods object that has now been replaced
 7518: ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
 7519: ** retained in the header file for backwards compatibility only.
 7520: */
 7521: typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
 7522: struct sqlite3_pcache_methods {
 7523:   void *pArg;
 7524:   int (*xInit)(void*);
 7525:   void (*xShutdown)(void*);
 7526:   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
 7527:   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
 7528:   int (*xPagecount)(sqlite3_pcache*);
 7529:   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
 7530:   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
 7531:   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
 7532:   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
 7533:   void (*xDestroy)(sqlite3_pcache*);
 7534: };
 7535: 
 7536: 
 7537: /*
 7538: ** CAPI3REF: Online Backup Object
 7539: **
 7540: ** The sqlite3_backup object records state information about an ongoing
 7541: ** online backup operation.  ^The sqlite3_backup object is created by
 7542: ** a call to [sqlite3_backup_init()] and is destroyed by a call to
 7543: ** [sqlite3_backup_finish()].
 7544: **
 7545: ** See Also: [Using the SQLite Online Backup API]
 7546: */
 7547: typedef struct sqlite3_backup sqlite3_backup;
 7548: 
 7549: /*
 7550: ** CAPI3REF: Online Backup API.
 7551: **
 7552: ** The backup API copies the content of one database into another.
 7553: ** It is useful either for creating backups of databases or
 7554: ** for copying in-memory databases to or from persistent files. 
 7555: **
 7556: ** See Also: [Using the SQLite Online Backup API]
 7557: **
 7558: ** ^SQLite holds a write transaction open on the destination database file
 7559: ** for the duration of the backup operation.
 7560: ** ^The source database is read-locked only while it is being read;
 7561: ** it is not locked continuously for the entire backup operation.
 7562: ** ^Thus, the backup may be performed on a live source database without
 7563: ** preventing other database connections from
 7564: ** reading or writing to the source database while the backup is underway.
 7565: ** 
 7566: ** ^(To perform a backup operation: 
 7567: **   <ol>
 7568: **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
 7569: **         backup, 
 7570: **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
 7571: **         the data between the two databases, and finally
 7572: **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
 7573: **         associated with the backup operation. 
 7574: **   </ol>)^
 7575: ** There should be exactly one call to sqlite3_backup_finish() for each
 7576: ** successful call to sqlite3_backup_init().
 7577: **
 7578: ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
 7579: **
 7580: ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
 7581: ** [database connection] associated with the destination database 
 7582: ** and the database name, respectively.
 7583: ** ^The database name is "main" for the main database, "temp" for the
 7584: ** temporary database, or the name specified after the AS keyword in
 7585: ** an [ATTACH] statement for an attached database.
 7586: ** ^The S and M arguments passed to 
 7587: ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
 7588: ** and database name of the source database, respectively.
 7589: ** ^The source and destination [database connections] (parameters S and D)
 7590: ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
 7591: ** an error.
 7592: **
 7593: ** ^A call to sqlite3_backup_init() will fail, returning NULL, if 
 7594: ** there is already a read or read-write transaction open on the 
 7595: ** destination database.
 7596: **
 7597: ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
 7598: ** returned and an error code and error message are stored in the
 7599: ** destination [database connection] D.
 7600: ** ^The error code and message for the failed call to sqlite3_backup_init()
 7601: ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
 7602: ** [sqlite3_errmsg16()] functions.
 7603: ** ^A successful call to sqlite3_backup_init() returns a pointer to an
 7604: ** [sqlite3_backup] object.
 7605: ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
 7606: ** sqlite3_backup_finish() functions to perform the specified backup 
 7607: ** operation.
 7608: **
 7609: ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
 7610: **
 7611: ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
 7612: ** the source and destination databases specified by [sqlite3_backup] object B.
 7613: ** ^If N is negative, all remaining source pages are copied. 
 7614: ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
 7615: ** are still more pages to be copied, then the function returns [SQLITE_OK].
 7616: ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
 7617: ** from source to destination, then it returns [SQLITE_DONE].
 7618: ** ^If an error occurs while running sqlite3_backup_step(B,N),
 7619: ** then an [error code] is returned. ^As well as [SQLITE_OK] and
 7620: ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
 7621: ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
 7622: ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
 7623: **
 7624: ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
 7625: ** <ol>
 7626: ** <li> the destination database was opened read-only, or
 7627: ** <li> the destination database is using write-ahead-log journaling
 7628: ** and the destination and source page sizes differ, or
 7629: ** <li> the destination database is an in-memory database and the
 7630: ** destination and source page sizes differ.
 7631: ** </ol>)^
 7632: **
 7633: ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
 7634: ** the [sqlite3_busy_handler | busy-handler function]
 7635: ** is invoked (if one is specified). ^If the 
 7636: ** busy-handler returns non-zero before the lock is available, then 
 7637: ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
 7638: ** sqlite3_backup_step() can be retried later. ^If the source
 7639: ** [database connection]
 7640: ** is being used to write to the source database when sqlite3_backup_step()
 7641: ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
 7642: ** case the call to sqlite3_backup_step() can be retried later on. ^(If
 7643: ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
 7644: ** [SQLITE_READONLY] is returned, then 
 7645: ** there is no point in retrying the call to sqlite3_backup_step(). These 
 7646: ** errors are considered fatal.)^  The application must accept 
 7647: ** that the backup operation has failed and pass the backup operation handle 
 7648: ** to the sqlite3_backup_finish() to release associated resources.
 7649: **
 7650: ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
 7651: ** on the destination file. ^The exclusive lock is not released until either 
 7652: ** sqlite3_backup_finish() is called or the backup operation is complete 
 7653: ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
 7654: ** sqlite3_backup_step() obtains a [shared lock] on the source database that
 7655: ** lasts for the duration of the sqlite3_backup_step() call.
 7656: ** ^Because the source database is not locked between calls to
 7657: ** sqlite3_backup_step(), the source database may be modified mid-way
 7658: ** through the backup process.  ^If the source database is modified by an
 7659: ** external process or via a database connection other than the one being
 7660: ** used by the backup operation, then the backup will be automatically
 7661: ** restarted by the next call to sqlite3_backup_step(). ^If the source 
 7662: ** database is modified by the using the same database connection as is used
 7663: ** by the backup operation, then the backup database is automatically
 7664: ** updated at the same time.
 7665: **
 7666: ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
 7667: **
 7668: ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
 7669: ** application wishes to abandon the backup operation, the application
 7670: ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
 7671: ** ^The sqlite3_backup_finish() interfaces releases all
 7672: ** resources associated with the [sqlite3_backup] object. 
 7673: ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
 7674: ** active write-transaction on the destination database is rolled back.
 7675: ** The [sqlite3_backup] object is invalid
 7676: ** and may not be used following a call to sqlite3_backup_finish().
 7677: **
 7678: ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
 7679: ** sqlite3_backup_step() errors occurred, regardless or whether or not
 7680: ** sqlite3_backup_step() completed.
 7681: ** ^If an out-of-memory condition or IO error occurred during any prior
 7682: ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
 7683: ** sqlite3_backup_finish() returns the corresponding [error code].
 7684: **
 7685: ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
 7686: ** is not a permanent error and does not affect the return value of
 7687: ** sqlite3_backup_finish().
 7688: **
 7689: ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
 7690: ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
 7691: **
 7692: ** ^The sqlite3_backup_remaining() routine returns the number of pages still
 7693: ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
 7694: ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
 7695: ** in the source database at the conclusion of the most recent
 7696: ** sqlite3_backup_step().
 7697: ** ^(The values returned by these functions are only updated by
 7698: ** sqlite3_backup_step(). If the source database is modified in a way that
 7699: ** changes the size of the source database or the number of pages remaining,
 7700: ** those changes are not reflected in the output of sqlite3_backup_pagecount()
 7701: ** and sqlite3_backup_remaining() until after the next
 7702: ** sqlite3_backup_step().)^
 7703: **
 7704: ** <b>Concurrent Usage of Database Handles</b>
 7705: **
 7706: ** ^The source [database connection] may be used by the application for other
 7707: ** purposes while a backup operation is underway or being initialized.
 7708: ** ^If SQLite is compiled and configured to support threadsafe database
 7709: ** connections, then the source database connection may be used concurrently
 7710: ** from within other threads.
 7711: **
 7712: ** However, the application must guarantee that the destination 
 7713: ** [database connection] is not passed to any other API (by any thread) after 
 7714: ** sqlite3_backup_init() is called and before the corresponding call to
 7715: ** sqlite3_backup_finish().  SQLite does not currently check to see
 7716: ** if the application incorrectly accesses the destination [database connection]
 7717: ** and so no error code is reported, but the operations may malfunction
 7718: ** nevertheless.  Use of the destination database connection while a
 7719: ** backup is in progress might also also cause a mutex deadlock.
 7720: **
 7721: ** If running in [shared cache mode], the application must
 7722: ** guarantee that the shared cache used by the destination database
 7723: ** is not accessed while the backup is running. In practice this means
 7724: ** that the application must guarantee that the disk file being 
 7725: ** backed up to is not accessed by any connection within the process,
 7726: ** not just the specific connection that was passed to sqlite3_backup_init().
 7727: **
 7728: ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
 7729: ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
 7730: ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
 7731: ** APIs are not strictly speaking threadsafe. If they are invoked at the
 7732: ** same time as another thread is invoking sqlite3_backup_step() it is
 7733: ** possible that they return invalid values.
 7734: */
 7735: SQLITE_API sqlite3_backup *sqlite3_backup_init(
 7736:   sqlite3 *pDest,                        /* Destination database handle */
 7737:   const char *zDestName,                 /* Destination database name */
 7738:   sqlite3 *pSource,                      /* Source database handle */
 7739:   const char *zSourceName                /* Source database name */
 7740: );
 7741: SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
 7742: SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
 7743: SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
 7744: SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
 7745: 
 7746: /*
 7747: ** CAPI3REF: Unlock Notification
 7748: ** METHOD: sqlite3
 7749: **
 7750: ** ^When running in shared-cache mode, a database operation may fail with
 7751: ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
 7752: ** individual tables within the shared-cache cannot be obtained. See
 7753: ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
 7754: ** ^This API may be used to register a callback that SQLite will invoke 
 7755: ** when the connection currently holding the required lock relinquishes it.
 7756: ** ^This API is only available if the library was compiled with the
 7757: ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
 7758: **
 7759: ** See Also: [Using the SQLite Unlock Notification Feature].
 7760: **
 7761: ** ^Shared-cache locks are released when a database connection concludes
 7762: ** its current transaction, either by committing it or rolling it back. 
 7763: **
 7764: ** ^When a connection (known as the blocked connection) fails to obtain a
 7765: ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
 7766: ** identity of the database connection (the blocking connection) that
 7767: ** has locked the required resource is stored internally. ^After an 
 7768: ** application receives an SQLITE_LOCKED error, it may call the
 7769: ** sqlite3_unlock_notify() method with the blocked connection handle as 
 7770: ** the first argument to register for a callback that will be invoked
 7771: ** when the blocking connections current transaction is concluded. ^The
 7772: ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
 7773: ** call that concludes the blocking connections transaction.
 7774: **
 7775: ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
 7776: ** there is a chance that the blocking connection will have already
 7777: ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
 7778: ** If this happens, then the specified callback is invoked immediately,
 7779: ** from within the call to sqlite3_unlock_notify().)^
 7780: **
 7781: ** ^If the blocked connection is attempting to obtain a write-lock on a
 7782: ** shared-cache table, and more than one other connection currently holds
 7783: ** a read-lock on the same table, then SQLite arbitrarily selects one of 
 7784: ** the other connections to use as the blocking connection.
 7785: **
 7786: ** ^(There may be at most one unlock-notify callback registered by a 
 7787: ** blocked connection. If sqlite3_unlock_notify() is called when the
 7788: ** blocked connection already has a registered unlock-notify callback,
 7789: ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
 7790: ** called with a NULL pointer as its second argument, then any existing
 7791: ** unlock-notify callback is canceled. ^The blocked connections 
 7792: ** unlock-notify callback may also be canceled by closing the blocked
 7793: ** connection using [sqlite3_close()].
 7794: **
 7795: ** The unlock-notify callback is not reentrant. If an application invokes
 7796: ** any sqlite3_xxx API functions from within an unlock-notify callback, a
 7797: ** crash or deadlock may be the result.
 7798: **
 7799: ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
 7800: ** returns SQLITE_OK.
 7801: **
 7802: ** <b>Callback Invocation Details</b>
 7803: **
 7804: ** When an unlock-notify callback is registered, the application provides a 
 7805: ** single void* pointer that is passed to the callback when it is invoked.
 7806: ** However, the signature of the callback function allows SQLite to pass
 7807: ** it an array of void* context pointers. The first argument passed to
 7808: ** an unlock-notify callback is a pointer to an array of void* pointers,
 7809: ** and the second is the number of entries in the array.
 7810: **
 7811: ** When a blocking connections transaction is concluded, there may be
 7812: ** more than one blocked connection that has registered for an unlock-notify
 7813: ** callback. ^If two or more such blocked connections have specified the
 7814: ** same callback function, then instead of invoking the callback function
 7815: ** multiple times, it is invoked once with the set of void* context pointers
 7816: ** specified by the blocked connections bundled together into an array.
 7817: ** This gives the application an opportunity to prioritize any actions 
 7818: ** related to the set of unblocked database connections.
 7819: **
 7820: ** <b>Deadlock Detection</b>
 7821: **
 7822: ** Assuming that after registering for an unlock-notify callback a 
 7823: ** database waits for the callback to be issued before taking any further
 7824: ** action (a reasonable assumption), then using this API may cause the
 7825: ** application to deadlock. For example, if connection X is waiting for
 7826: ** connection Y's transaction to be concluded, and similarly connection
 7827: ** Y is waiting on connection X's transaction, then neither connection
 7828: ** will proceed and the system may remain deadlocked indefinitely.
 7829: **
 7830: ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
 7831: ** detection. ^If a given call to sqlite3_unlock_notify() would put the
 7832: ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
 7833: ** unlock-notify callback is registered. The system is said to be in
 7834: ** a deadlocked state if connection A has registered for an unlock-notify
 7835: ** callback on the conclusion of connection B's transaction, and connection
 7836: ** B has itself registered for an unlock-notify callback when connection
 7837: ** A's transaction is concluded. ^Indirect deadlock is also detected, so
 7838: ** the system is also considered to be deadlocked if connection B has
 7839: ** registered for an unlock-notify callback on the conclusion of connection
 7840: ** C's transaction, where connection C is waiting on connection A. ^Any
 7841: ** number of levels of indirection are allowed.
 7842: **
 7843: ** <b>The "DROP TABLE" Exception</b>
 7844: **
 7845: ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
 7846: ** always appropriate to call sqlite3_unlock_notify(). There is however,
 7847: ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
 7848: ** SQLite checks if there are any currently executing SELECT statements
 7849: ** that belong to the same connection. If there are, SQLITE_LOCKED is
 7850: ** returned. In this case there is no "blocking connection", so invoking
 7851: ** sqlite3_unlock_notify() results in the unlock-notify callback being
 7852: ** invoked immediately. If the application then re-attempts the "DROP TABLE"
 7853: ** or "DROP INDEX" query, an infinite loop might be the result.
 7854: **
 7855: ** One way around this problem is to check the extended error code returned
 7856: ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
 7857: ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
 7858: ** the special "DROP TABLE/INDEX" case, the extended error code is just 
 7859: ** SQLITE_LOCKED.)^
 7860: */
 7861: SQLITE_API int sqlite3_unlock_notify(
 7862:   sqlite3 *pBlocked,                          /* Waiting connection */
 7863:   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
 7864:   void *pNotifyArg                            /* Argument to pass to xNotify */
 7865: );
 7866: 
 7867: 
 7868: /*
 7869: ** CAPI3REF: String Comparison
 7870: **
 7871: ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
 7872: ** and extensions to compare the contents of two buffers containing UTF-8
 7873: ** strings in a case-independent fashion, using the same definition of "case
 7874: ** independence" that SQLite uses internally when comparing identifiers.
 7875: */
 7876: SQLITE_API int sqlite3_stricmp(const char *, const char *);
 7877: SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
 7878: 
 7879: /*
 7880: ** CAPI3REF: String Globbing
 7881: *
 7882: ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
 7883: ** string X matches the [GLOB] pattern P.
 7884: ** ^The definition of [GLOB] pattern matching used in
 7885: ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
 7886: ** SQL dialect understood by SQLite.  ^The [sqlite3_strglob(P,X)] function
 7887: ** is case sensitive.
 7888: **
 7889: ** Note that this routine returns zero on a match and non-zero if the strings
 7890: ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
 7891: **
 7892: ** See also: [sqlite3_strlike()].
 7893: */
 7894: SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
 7895: 
 7896: /*
 7897: ** CAPI3REF: String LIKE Matching
 7898: *
 7899: ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
 7900: ** string X matches the [LIKE] pattern P with escape character E.
 7901: ** ^The definition of [LIKE] pattern matching used in
 7902: ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
 7903: ** operator in the SQL dialect understood by SQLite.  ^For "X LIKE P" without
 7904: ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
 7905: ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
 7906: ** insensitive - equivalent upper and lower case ASCII characters match
 7907: ** one another.
 7908: **
 7909: ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
 7910: ** only ASCII characters are case folded.
 7911: **
 7912: ** Note that this routine returns zero on a match and non-zero if the strings
 7913: ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
 7914: **
 7915: ** See also: [sqlite3_strglob()].
 7916: */
 7917: SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
 7918: 
 7919: /*
 7920: ** CAPI3REF: Error Logging Interface
 7921: **
 7922: ** ^The [sqlite3_log()] interface writes a message into the [error log]
 7923: ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
 7924: ** ^If logging is enabled, the zFormat string and subsequent arguments are
 7925: ** used with [sqlite3_snprintf()] to generate the final output string.
 7926: **
 7927: ** The sqlite3_log() interface is intended for use by extensions such as
 7928: ** virtual tables, collating functions, and SQL functions.  While there is
 7929: ** nothing to prevent an application from calling sqlite3_log(), doing so
 7930: ** is considered bad form.
 7931: **
 7932: ** The zFormat string must not be NULL.
 7933: **
 7934: ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
 7935: ** will not use dynamically allocated memory.  The log message is stored in
 7936: ** a fixed-length buffer on the stack.  If the log message is longer than
 7937: ** a few hundred characters, it will be truncated to the length of the
 7938: ** buffer.
 7939: */
 7940: SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
 7941: 
 7942: /*
 7943: ** CAPI3REF: Write-Ahead Log Commit Hook
 7944: ** METHOD: sqlite3
 7945: **
 7946: ** ^The [sqlite3_wal_hook()] function is used to register a callback that
 7947: ** is invoked each time data is committed to a database in wal mode.
 7948: **
 7949: ** ^(The callback is invoked by SQLite after the commit has taken place and 
 7950: ** the associated write-lock on the database released)^, so the implementation 
 7951: ** may read, write or [checkpoint] the database as required.
 7952: **
 7953: ** ^The first parameter passed to the callback function when it is invoked
 7954: ** is a copy of the third parameter passed to sqlite3_wal_hook() when
 7955: ** registering the callback. ^The second is a copy of the database handle.
 7956: ** ^The third parameter is the name of the database that was written to -
 7957: ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
 7958: ** is the number of pages currently in the write-ahead log file,
 7959: ** including those that were just committed.
 7960: **
 7961: ** The callback function should normally return [SQLITE_OK].  ^If an error
 7962: ** code is returned, that error will propagate back up through the
 7963: ** SQLite code base to cause the statement that provoked the callback
 7964: ** to report an error, though the commit will have still occurred. If the
 7965: ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
 7966: ** that does not correspond to any valid SQLite error code, the results
 7967: ** are undefined.
 7968: **
 7969: ** A single database handle may have at most a single write-ahead log callback 
 7970: ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
 7971: ** previously registered write-ahead log callback. ^Note that the
 7972: ** [sqlite3_wal_autocheckpoint()] interface and the
 7973: ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
 7974: ** overwrite any prior [sqlite3_wal_hook()] settings.
 7975: */
 7976: SQLITE_API void *sqlite3_wal_hook(
 7977:   sqlite3*, 
 7978:   int(*)(void *,sqlite3*,const char*,int),
 7979:   void*
 7980: );
 7981: 
 7982: /*
 7983: ** CAPI3REF: Configure an auto-checkpoint
 7984: ** METHOD: sqlite3
 7985: **
 7986: ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
 7987: ** [sqlite3_wal_hook()] that causes any database on [database connection] D
 7988: ** to automatically [checkpoint]
 7989: ** after committing a transaction if there are N or
 7990: ** more frames in the [write-ahead log] file.  ^Passing zero or 
 7991: ** a negative value as the nFrame parameter disables automatic
 7992: ** checkpoints entirely.
 7993: **
 7994: ** ^The callback registered by this function replaces any existing callback
 7995: ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
 7996: ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
 7997: ** configured by this function.
 7998: **
 7999: ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
 8000: ** from SQL.
 8001: **
 8002: ** ^Checkpoints initiated by this mechanism are
 8003: ** [sqlite3_wal_checkpoint_v2|PASSIVE].
 8004: **
 8005: ** ^Every new [database connection] defaults to having the auto-checkpoint
 8006: ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
 8007: ** pages.  The use of this interface
 8008: ** is only necessary if the default setting is found to be suboptimal
 8009: ** for a particular application.
 8010: */
 8011: SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
 8012: 
 8013: /*
 8014: ** CAPI3REF: Checkpoint a database
 8015: ** METHOD: sqlite3
 8016: **
 8017: ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
 8018: ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
 8019: **
 8020: ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the 
 8021: ** [write-ahead log] for database X on [database connection] D to be
 8022: ** transferred into the database file and for the write-ahead log to
 8023: ** be reset.  See the [checkpointing] documentation for addition
 8024: ** information.
 8025: **
 8026: ** This interface used to be the only way to cause a checkpoint to
 8027: ** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
 8028: ** interface was added.  This interface is retained for backwards
 8029: ** compatibility and as a convenience for applications that need to manually
 8030: ** start a callback but which do not need the full power (and corresponding
 8031: ** complication) of [sqlite3_wal_checkpoint_v2()].
 8032: */
 8033: SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
 8034: 
 8035: /*
 8036: ** CAPI3REF: Checkpoint a database
 8037: ** METHOD: sqlite3
 8038: **
 8039: ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
 8040: ** operation on database X of [database connection] D in mode M.  Status
 8041: ** information is written back into integers pointed to by L and C.)^
 8042: ** ^(The M parameter must be a valid [checkpoint mode]:)^
 8043: **
 8044: ** <dl>
 8045: ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
 8046: **   ^Checkpoint as many frames as possible without waiting for any database 
 8047: **   readers or writers to finish, then sync the database file if all frames 
 8048: **   in the log were checkpointed. ^The [busy-handler callback]
 8049: **   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  
 8050: **   ^On the other hand, passive mode might leave the checkpoint unfinished
 8051: **   if there are concurrent readers or writers.
 8052: **
 8053: ** <dt>SQLITE_CHECKPOINT_FULL<dd>
 8054: **   ^This mode blocks (it invokes the
 8055: **   [sqlite3_busy_handler|busy-handler callback]) until there is no
 8056: **   database writer and all readers are reading from the most recent database
 8057: **   snapshot. ^It then checkpoints all frames in the log file and syncs the
 8058: **   database file. ^This mode blocks new database writers while it is pending,
 8059: **   but new database readers are allowed to continue unimpeded.
 8060: **
 8061: ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
 8062: **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
 8063: **   that after checkpointing the log file it blocks (calls the 
 8064: **   [busy-handler callback])
 8065: **   until all readers are reading from the database file only. ^This ensures 
 8066: **   that the next writer will restart the log file from the beginning.
 8067: **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
 8068: **   database writer attempts while it is pending, but does not impede readers.
 8069: **
 8070: ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
 8071: **   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
 8072: **   addition that it also truncates the log file to zero bytes just prior
 8073: **   to a successful return.
 8074: ** </dl>
 8075: **
 8076: ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
 8077: ** the log file or to -1 if the checkpoint could not run because
 8078: ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
 8079: ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
 8080: ** log file (including any that were already checkpointed before the function
 8081: ** was called) or to -1 if the checkpoint could not run due to an error or
 8082: ** because the database is not in WAL mode. ^Note that upon successful
 8083: ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
 8084: ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
 8085: **
 8086: ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
 8087: ** any other process is running a checkpoint operation at the same time, the 
 8088: ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a 
 8089: ** busy-handler configured, it will not be invoked in this case.
 8090: **
 8091: ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the 
 8092: ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
 8093: ** obtained immediately, and a busy-handler is configured, it is invoked and
 8094: ** the writer lock retried until either the busy-handler returns 0 or the lock
 8095: ** is successfully obtained. ^The busy-handler is also invoked while waiting for
 8096: ** database readers as described above. ^If the busy-handler returns 0 before
 8097: ** the writer lock is obtained or while waiting for database readers, the
 8098: ** checkpoint operation proceeds from that point in the same way as 
 8099: ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
 8100: ** without blocking any further. ^SQLITE_BUSY is returned in this case.
 8101: **
 8102: ** ^If parameter zDb is NULL or points to a zero length string, then the
 8103: ** specified operation is attempted on all WAL databases [attached] to 
 8104: ** [database connection] db.  In this case the
 8105: ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If 
 8106: ** an SQLITE_BUSY error is encountered when processing one or more of the 
 8107: ** attached WAL databases, the operation is still attempted on any remaining 
 8108: ** attached databases and SQLITE_BUSY is returned at the end. ^If any other 
 8109: ** error occurs while processing an attached database, processing is abandoned 
 8110: ** and the error code is returned to the caller immediately. ^If no error 
 8111: ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
 8112: ** databases, SQLITE_OK is returned.
 8113: **
 8114: ** ^If database zDb is the name of an attached database that is not in WAL
 8115: ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
 8116: ** zDb is not NULL (or a zero length string) and is not the name of any
 8117: ** attached database, SQLITE_ERROR is returned to the caller.
 8118: **
 8119: ** ^Unless it returns SQLITE_MISUSE,
 8120: ** the sqlite3_wal_checkpoint_v2() interface
 8121: ** sets the error information that is queried by
 8122: ** [sqlite3_errcode()] and [sqlite3_errmsg()].
 8123: **
 8124: ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
 8125: ** from SQL.
 8126: */
 8127: SQLITE_API int sqlite3_wal_checkpoint_v2(
 8128:   sqlite3 *db,                    /* Database handle */
 8129:   const char *zDb,                /* Name of attached database (or NULL) */
 8130:   int eMode,                      /* SQLITE_CHECKPOINT_* value */
 8131:   int *pnLog,                     /* OUT: Size of WAL log in frames */
 8132:   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
 8133: );
 8134: 
 8135: /*
 8136: ** CAPI3REF: Checkpoint Mode Values
 8137: ** KEYWORDS: {checkpoint mode}
 8138: **
 8139: ** These constants define all valid values for the "checkpoint mode" passed
 8140: ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
 8141: ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
 8142: ** meaning of each of these checkpoint modes.
 8143: */
 8144: #define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
 8145: #define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
 8146: #define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
 8147: #define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
 8148: 
 8149: /*
 8150: ** CAPI3REF: Virtual Table Interface Configuration
 8151: **
 8152: ** This function may be called by either the [xConnect] or [xCreate] method
 8153: ** of a [virtual table] implementation to configure
 8154: ** various facets of the virtual table interface.
 8155: **
 8156: ** If this interface is invoked outside the context of an xConnect or
 8157: ** xCreate virtual table method then the behavior is undefined.
 8158: **
 8159: ** At present, there is only one option that may be configured using
 8160: ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
 8161: ** may be added in the future.
 8162: */
 8163: SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
 8164: 
 8165: /*
 8166: ** CAPI3REF: Virtual Table Configuration Options
 8167: **
 8168: ** These macros define the various options to the
 8169: ** [sqlite3_vtab_config()] interface that [virtual table] implementations
 8170: ** can use to customize and optimize their behavior.
 8171: **
 8172: ** <dl>
 8173: ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
 8174: ** <dd>Calls of the form
 8175: ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
 8176: ** where X is an integer.  If X is zero, then the [virtual table] whose
 8177: ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
 8178: ** support constraints.  In this configuration (which is the default) if
 8179: ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
 8180: ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
 8181: ** specified as part of the users SQL statement, regardless of the actual
 8182: ** ON CONFLICT mode specified.
 8183: **
 8184: ** If X is non-zero, then the virtual table implementation guarantees
 8185: ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
 8186: ** any modifications to internal or persistent data structures have been made.
 8187: ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
 8188: ** is able to roll back a statement or database transaction, and abandon
 8189: ** or continue processing the current SQL statement as appropriate. 
 8190: ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
 8191: ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
 8192: ** had been ABORT.
 8193: **
 8194: ** Virtual table implementations that are required to handle OR REPLACE
 8195: ** must do so within the [xUpdate] method. If a call to the 
 8196: ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
 8197: ** CONFLICT policy is REPLACE, the virtual table implementation should 
 8198: ** silently replace the appropriate rows within the xUpdate callback and
 8199: ** return SQLITE_OK. Or, if this is not possible, it may return
 8200: ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
 8201: ** constraint handling.
 8202: ** </dl>
 8203: */
 8204: #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
 8205: 
 8206: /*
 8207: ** CAPI3REF: Determine The Virtual Table Conflict Policy
 8208: **
 8209: ** This function may only be called from within a call to the [xUpdate] method
 8210: ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
 8211: ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
 8212: ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
 8213: ** of the SQL statement that triggered the call to the [xUpdate] method of the
 8214: ** [virtual table].
 8215: */
 8216: SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
 8217: 
 8218: /*
 8219: ** CAPI3REF: Conflict resolution modes
 8220: ** KEYWORDS: {conflict resolution mode}
 8221: **
 8222: ** These constants are returned by [sqlite3_vtab_on_conflict()] to
 8223: ** inform a [virtual table] implementation what the [ON CONFLICT] mode
 8224: ** is for the SQL statement being evaluated.
 8225: **
 8226: ** Note that the [SQLITE_IGNORE] constant is also used as a potential
 8227: ** return value from the [sqlite3_set_authorizer()] callback and that
 8228: ** [SQLITE_ABORT] is also a [result code].
 8229: */
 8230: #define SQLITE_ROLLBACK 1
 8231: /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
 8232: #define SQLITE_FAIL     3
 8233: /* #define SQLITE_ABORT 4  // Also an error code */
 8234: #define SQLITE_REPLACE  5
 8235: 
 8236: /*
 8237: ** CAPI3REF: Prepared Statement Scan Status Opcodes
 8238: ** KEYWORDS: {scanstatus options}
 8239: **
 8240: ** The following constants can be used for the T parameter to the
 8241: ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
 8242: ** different metric for sqlite3_stmt_scanstatus() to return.
 8243: **
 8244: ** When the value returned to V is a string, space to hold that string is
 8245: ** managed by the prepared statement S and will be automatically freed when
 8246: ** S is finalized.
 8247: **
 8248: ** <dl>
 8249: ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
 8250: ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
 8251: ** set to the total number of times that the X-th loop has run.</dd>
 8252: **
 8253: ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
 8254: ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
 8255: ** to the total number of rows examined by all iterations of the X-th loop.</dd>
 8256: **
 8257: ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
 8258: ** <dd>^The "double" variable pointed to by the T parameter will be set to the
 8259: ** query planner's estimate for the average number of rows output from each
 8260: ** iteration of the X-th loop.  If the query planner's estimates was accurate,
 8261: ** then this value will approximate the quotient NVISIT/NLOOP and the
 8262: ** product of this value for all prior loops with the same SELECTID will
 8263: ** be the NLOOP value for the current loop.
 8264: **
 8265: ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
 8266: ** <dd>^The "const char *" variable pointed to by the T parameter will be set
 8267: ** to a zero-terminated UTF-8 string containing the name of the index or table
 8268: ** used for the X-th loop.
 8269: **
 8270: ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
 8271: ** <dd>^The "const char *" variable pointed to by the T parameter will be set
 8272: ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
 8273: ** description for the X-th loop.
 8274: **
 8275: ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
 8276: ** <dd>^The "int" variable pointed to by the T parameter will be set to the
 8277: ** "select-id" for the X-th loop.  The select-id identifies which query or
 8278: ** subquery the loop is part of.  The main query has a select-id of zero.
 8279: ** The select-id is the same value as is output in the first column
 8280: ** of an [EXPLAIN QUERY PLAN] query.
 8281: ** </dl>
 8282: */
 8283: #define SQLITE_SCANSTAT_NLOOP    0
 8284: #define SQLITE_SCANSTAT_NVISIT   1
 8285: #define SQLITE_SCANSTAT_EST      2
 8286: #define SQLITE_SCANSTAT_NAME     3
 8287: #define SQLITE_SCANSTAT_EXPLAIN  4
 8288: #define SQLITE_SCANSTAT_SELECTID 5
 8289: 
 8290: /*
 8291: ** CAPI3REF: Prepared Statement Scan Status
 8292: ** METHOD: sqlite3_stmt
 8293: **
 8294: ** This interface returns information about the predicted and measured
 8295: ** performance for pStmt.  Advanced applications can use this
 8296: ** interface to compare the predicted and the measured performance and
 8297: ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
 8298: **
 8299: ** Since this interface is expected to be rarely used, it is only
 8300: ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
 8301: ** compile-time option.
 8302: **
 8303: ** The "iScanStatusOp" parameter determines which status information to return.
 8304: ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
 8305: ** of this interface is undefined.
 8306: ** ^The requested measurement is written into a variable pointed to by
 8307: ** the "pOut" parameter.
 8308: ** Parameter "idx" identifies the specific loop to retrieve statistics for.
 8309: ** Loops are numbered starting from zero. ^If idx is out of range - less than
 8310: ** zero or greater than or equal to the total number of loops used to implement
 8311: ** the statement - a non-zero value is returned and the variable that pOut
 8312: ** points to is unchanged.
 8313: **
 8314: ** ^Statistics might not be available for all loops in all statements. ^In cases
 8315: ** where there exist loops with no available statistics, this function behaves
 8316: ** as if the loop did not exist - it returns non-zero and leave the variable
 8317: ** that pOut points to unchanged.
 8318: **
 8319: ** See also: [sqlite3_stmt_scanstatus_reset()]
 8320: */
 8321: SQLITE_API int sqlite3_stmt_scanstatus(
 8322:   sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
 8323:   int idx,                  /* Index of loop to report on */
 8324:   int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
 8325:   void *pOut                /* Result written here */
 8326: );     
 8327: 
 8328: /*
 8329: ** CAPI3REF: Zero Scan-Status Counters
 8330: ** METHOD: sqlite3_stmt
 8331: **
 8332: ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
 8333: **
 8334: ** This API is only available if the library is built with pre-processor
 8335: ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
 8336: */
 8337: SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
 8338: 
 8339: /*
 8340: ** CAPI3REF: Flush caches to disk mid-transaction
 8341: **
 8342: ** ^If a write-transaction is open on [database connection] D when the
 8343: ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
 8344: ** pages in the pager-cache that are not currently in use are written out 
 8345: ** to disk. A dirty page may be in use if a database cursor created by an
 8346: ** active SQL statement is reading from it, or if it is page 1 of a database
 8347: ** file (page 1 is always "in use").  ^The [sqlite3_db_cacheflush(D)]
 8348: ** interface flushes caches for all schemas - "main", "temp", and
 8349: ** any [attached] databases.
 8350: **
 8351: ** ^If this function needs to obtain extra database locks before dirty pages 
 8352: ** can be flushed to disk, it does so. ^If those locks cannot be obtained 
 8353: ** immediately and there is a busy-handler callback configured, it is invoked
 8354: ** in the usual manner. ^If the required lock still cannot be obtained, then
 8355: ** the database is skipped and an attempt made to flush any dirty pages
 8356: ** belonging to the next (if any) database. ^If any databases are skipped
 8357: ** because locks cannot be obtained, but no other error occurs, this
 8358: ** function returns SQLITE_BUSY.
 8359: **
 8360: ** ^If any other error occurs while flushing dirty pages to disk (for
 8361: ** example an IO error or out-of-memory condition), then processing is
 8362: ** abandoned and an SQLite [error code] is returned to the caller immediately.
 8363: **
 8364: ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
 8365: **
 8366: ** ^This function does not set the database handle error code or message
 8367: ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
 8368: */
 8369: SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
 8370: 
 8371: /*
 8372: ** CAPI3REF: The pre-update hook.
 8373: **
 8374: ** ^These interfaces are only available if SQLite is compiled using the
 8375: ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
 8376: **
 8377: ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
 8378: ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
 8379: ** on a [rowid table].
 8380: ** ^At most one preupdate hook may be registered at a time on a single
 8381: ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
 8382: ** the previous setting.
 8383: ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
 8384: ** with a NULL pointer as the second parameter.
 8385: ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
 8386: ** the first parameter to callbacks.
 8387: **
 8388: ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
 8389: ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
 8390: ** tables.
 8391: **
 8392: ** ^The second parameter to the preupdate callback is a pointer to
 8393: ** the [database connection] that registered the preupdate hook.
 8394: ** ^The third parameter to the preupdate callback is one of the constants
 8395: ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
 8396: ** kind of update operation that is about to occur.
 8397: ** ^(The fourth parameter to the preupdate callback is the name of the
 8398: ** database within the database connection that is being modified.  This
 8399: ** will be "main" for the main database or "temp" for TEMP tables or 
 8400: ** the name given after the AS keyword in the [ATTACH] statement for attached
 8401: ** databases.)^
 8402: ** ^The fifth parameter to the preupdate callback is the name of the
 8403: ** table that is being modified.
 8404: ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
 8405: ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
 8406: ** undefined for SQLITE_INSERT changes.
 8407: ** ^The seventh parameter to the preupdate callback is the final [rowid] of
 8408: ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
 8409: ** undefined for SQLITE_DELETE changes.
 8410: **
 8411: ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
 8412: ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
 8413: ** provide additional information about a preupdate event. These routines
 8414: ** may only be called from within a preupdate callback.  Invoking any of
 8415: ** these routines from outside of a preupdate callback or with a
 8416: ** [database connection] pointer that is different from the one supplied
 8417: ** to the preupdate callback results in undefined and probably undesirable
 8418: ** behavior.
 8419: **
 8420: ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
 8421: ** in the row that is being inserted, updated, or deleted.
 8422: **
 8423: ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
 8424: ** a [protected sqlite3_value] that contains the value of the Nth column of
 8425: ** the table row before it is updated.  The N parameter must be between 0
 8426: ** and one less than the number of columns or the behavior will be
 8427: ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
 8428: ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
 8429: ** behavior is undefined.  The [sqlite3_value] that P points to
 8430: ** will be destroyed when the preupdate callback returns.
 8431: **
 8432: ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
 8433: ** a [protected sqlite3_value] that contains the value of the Nth column of
 8434: ** the table row after it is updated.  The N parameter must be between 0
 8435: ** and one less than the number of columns or the behavior will be
 8436: ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
 8437: ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
 8438: ** behavior is undefined.  The [sqlite3_value] that P points to
 8439: ** will be destroyed when the preupdate callback returns.
 8440: **
 8441: ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
 8442: ** callback was invoked as a result of a direct insert, update, or delete
 8443: ** operation; or 1 for inserts, updates, or deletes invoked by top-level 
 8444: ** triggers; or 2 for changes resulting from triggers called by top-level
 8445: ** triggers; and so forth.
 8446: **
 8447: ** See also:  [sqlite3_update_hook()]
 8448: */
 8449: SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_preupdate_hook(
 8450:   sqlite3 *db,
 8451:   void(*xPreUpdate)(
 8452:     void *pCtx,                   /* Copy of third arg to preupdate_hook() */
 8453:     sqlite3 *db,                  /* Database handle */
 8454:     int op,                       /* SQLITE_UPDATE, DELETE or INSERT */
 8455:     char const *zDb,              /* Database name */
 8456:     char const *zName,            /* Table name */
 8457:     sqlite3_int64 iKey1,          /* Rowid of row about to be deleted/updated */
 8458:     sqlite3_int64 iKey2           /* New rowid value (for a rowid UPDATE) */
 8459:   ),
 8460:   void*
 8461: );
 8462: SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
 8463: SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_count(sqlite3 *);
 8464: SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_depth(sqlite3 *);
 8465: SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
 8466: 
 8467: /*
 8468: ** CAPI3REF: Low-level system error code
 8469: **
 8470: ** ^Attempt to return the underlying operating system error code or error
 8471: ** number that caused the most recent I/O error or failure to open a file.
 8472: ** The return value is OS-dependent.  For example, on unix systems, after
 8473: ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
 8474: ** called to get back the underlying "errno" that caused the problem, such
 8475: ** as ENOSPC, EAUTH, EISDIR, and so forth.  
 8476: */
 8477: SQLITE_API int sqlite3_system_errno(sqlite3*);
 8478: 
 8479: /*
 8480: ** CAPI3REF: Database Snapshot
 8481: ** KEYWORDS: {snapshot}
 8482: ** EXPERIMENTAL
 8483: **
 8484: ** An instance of the snapshot object records the state of a [WAL mode]
 8485: ** database for some specific point in history.
 8486: **
 8487: ** In [WAL mode], multiple [database connections] that are open on the
 8488: ** same database file can each be reading a different historical version
 8489: ** of the database file.  When a [database connection] begins a read
 8490: ** transaction, that connection sees an unchanging copy of the database
 8491: ** as it existed for the point in time when the transaction first started.
 8492: ** Subsequent changes to the database from other connections are not seen
 8493: ** by the reader until a new read transaction is started.
 8494: **
 8495: ** The sqlite3_snapshot object records state information about an historical
 8496: ** version of the database file so that it is possible to later open a new read
 8497: ** transaction that sees that historical version of the database rather than
 8498: ** the most recent version.
 8499: **
 8500: ** The constructor for this object is [sqlite3_snapshot_get()].  The
 8501: ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
 8502: ** to an historical snapshot (if possible).  The destructor for 
 8503: ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
 8504: */
 8505: typedef struct sqlite3_snapshot sqlite3_snapshot;
 8506: 
 8507: /*
 8508: ** CAPI3REF: Record A Database Snapshot
 8509: ** EXPERIMENTAL
 8510: **
 8511: ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
 8512: ** new [sqlite3_snapshot] object that records the current state of
 8513: ** schema S in database connection D.  ^On success, the
 8514: ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
 8515: ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
 8516: ** ^If schema S of [database connection] D is not a [WAL mode] database
 8517: ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
 8518: ** leaves the *P value unchanged and returns an appropriate [error code].
 8519: **
 8520: ** The [sqlite3_snapshot] object returned from a successful call to
 8521: ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
 8522: ** to avoid a memory leak.
 8523: **
 8524: ** The [sqlite3_snapshot_get()] interface is only available when the
 8525: ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
 8526: */
 8527: SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
 8528:   sqlite3 *db,
 8529:   const char *zSchema,
 8530:   sqlite3_snapshot **ppSnapshot
 8531: );
 8532: 
 8533: /*
 8534: ** CAPI3REF: Start a read transaction on an historical snapshot
 8535: ** EXPERIMENTAL
 8536: **
 8537: ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
 8538: ** read transaction for schema S of
 8539: ** [database connection] D such that the read transaction
 8540: ** refers to historical [snapshot] P, rather than the most
 8541: ** recent change to the database.
 8542: ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
 8543: ** or an appropriate [error code] if it fails.
 8544: **
 8545: ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
 8546: ** the first operation following the [BEGIN] that takes the schema S
 8547: ** out of [autocommit mode].
 8548: ** ^In other words, schema S must not currently be in
 8549: ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
 8550: ** database connection D must be out of [autocommit mode].
 8551: ** ^A [snapshot] will fail to open if it has been overwritten by a
 8552: ** [checkpoint].
 8553: ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
 8554: ** database connection D does not know that the database file for
 8555: ** schema S is in [WAL mode].  A database connection might not know
 8556: ** that the database file is in [WAL mode] if there has been no prior
 8557: ** I/O on that database connection, or if the database entered [WAL mode] 
 8558: ** after the most recent I/O on the database connection.)^
 8559: ** (Hint: Run "[PRAGMA application_id]" against a newly opened
 8560: ** database connection in order to make it ready to use snapshots.)
 8561: **
 8562: ** The [sqlite3_snapshot_open()] interface is only available when the
 8563: ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
 8564: */
 8565: SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
 8566:   sqlite3 *db,
 8567:   const char *zSchema,
 8568:   sqlite3_snapshot *pSnapshot
 8569: );
 8570: 
 8571: /*
 8572: ** CAPI3REF: Destroy a snapshot
 8573: ** EXPERIMENTAL
 8574: **
 8575: ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
 8576: ** The application must eventually free every [sqlite3_snapshot] object
 8577: ** using this routine to avoid a memory leak.
 8578: **
 8579: ** The [sqlite3_snapshot_free()] interface is only available when the
 8580: ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
 8581: */
 8582: SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
 8583: 
 8584: /*
 8585: ** CAPI3REF: Compare the ages of two snapshot handles.
 8586: ** EXPERIMENTAL
 8587: **
 8588: ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
 8589: ** of two valid snapshot handles. 
 8590: **
 8591: ** If the two snapshot handles are not associated with the same database 
 8592: ** file, the result of the comparison is undefined. 
 8593: **
 8594: ** Additionally, the result of the comparison is only valid if both of the
 8595: ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
 8596: ** last time the wal file was deleted. The wal file is deleted when the
 8597: ** database is changed back to rollback mode or when the number of database
 8598: ** clients drops to zero. If either snapshot handle was obtained before the 
 8599: ** wal file was last deleted, the value returned by this function 
 8600: ** is undefined.
 8601: **
 8602: ** Otherwise, this API returns a negative value if P1 refers to an older
 8603: ** snapshot than P2, zero if the two handles refer to the same database
 8604: ** snapshot, and a positive value if P1 is a newer snapshot than P2.
 8605: */
 8606: SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
 8607:   sqlite3_snapshot *p1,
 8608:   sqlite3_snapshot *p2
 8609: );
 8610: 
 8611: /*
 8612: ** Undo the hack that converts floating point types to integer for
 8613: ** builds on processors without floating point support.
 8614: */
 8615: #ifdef SQLITE_OMIT_FLOATING_POINT
 8616: # undef double
 8617: #endif
 8618: 
 8619: #if 0
 8620: }  /* End of the 'extern "C"' block */
 8621: #endif
 8622: #endif /* SQLITE3_H */
 8623: 
 8624: /******** Begin file sqlite3rtree.h *********/
 8625: /*
 8626: ** 2010 August 30
 8627: **
 8628: ** The author disclaims copyright to this source code.  In place of
 8629: ** a legal notice, here is a blessing:
 8630: **
 8631: **    May you do good and not evil.
 8632: **    May you find forgiveness for yourself and forgive others.
 8633: **    May you share freely, never taking more than you give.
 8634: **
 8635: *************************************************************************
 8636: */
 8637: 
 8638: #ifndef _SQLITE3RTREE_H_
 8639: #define _SQLITE3RTREE_H_
 8640: 
 8641: 
 8642: #if 0
 8643: extern "C" {
 8644: #endif
 8645: 
 8646: typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
 8647: typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
 8648: 
 8649: /* The double-precision datatype used by RTree depends on the
 8650: ** SQLITE_RTREE_INT_ONLY compile-time option.
 8651: */
 8652: #ifdef SQLITE_RTREE_INT_ONLY
 8653:   typedef sqlite3_int64 sqlite3_rtree_dbl;
 8654: #else
 8655:   typedef double sqlite3_rtree_dbl;
 8656: #endif
 8657: 
 8658: /*
 8659: ** Register a geometry callback named zGeom that can be used as part of an
 8660: ** R-Tree geometry query as follows:
 8661: **
 8662: **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
 8663: */
 8664: SQLITE_API int sqlite3_rtree_geometry_callback(
 8665:   sqlite3 *db,
 8666:   const char *zGeom,
 8667:   int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
 8668:   void *pContext
 8669: );
 8670: 
 8671: 
 8672: /*
 8673: ** A pointer to a structure of the following type is passed as the first
 8674: ** argument to callbacks registered using rtree_geometry_callback().
 8675: */
 8676: struct sqlite3_rtree_geometry {
 8677:   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
 8678:   int nParam;                     /* Size of array aParam[] */
 8679:   sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
 8680:   void *pUser;                    /* Callback implementation user data */
 8681:   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
 8682: };
 8683: 
 8684: /*
 8685: ** Register a 2nd-generation geometry callback named zScore that can be 
 8686: ** used as part of an R-Tree geometry query as follows:
 8687: **
 8688: **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
 8689: */
 8690: SQLITE_API int sqlite3_rtree_query_callback(
 8691:   sqlite3 *db,
 8692:   const char *zQueryFunc,
 8693:   int (*xQueryFunc)(sqlite3_rtree_query_info*),
 8694:   void *pContext,
 8695:   void (*xDestructor)(void*)
 8696: );
 8697: 
 8698: 
 8699: /*
 8700: ** A pointer to a structure of the following type is passed as the 
 8701: ** argument to scored geometry callback registered using
 8702: ** sqlite3_rtree_query_callback().
 8703: **
 8704: ** Note that the first 5 fields of this structure are identical to
 8705: ** sqlite3_rtree_geometry.  This structure is a subclass of
 8706: ** sqlite3_rtree_geometry.
 8707: */
 8708: struct sqlite3_rtree_query_info {
 8709:   void *pContext;                   /* pContext from when function registered */
 8710:   int nParam;                       /* Number of function parameters */
 8711:   sqlite3_rtree_dbl *aParam;        /* value of function parameters */
 8712:   void *pUser;                      /* callback can use this, if desired */
 8713:   void (*xDelUser)(void*);          /* function to free pUser */
 8714:   sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
 8715:   unsigned int *anQueue;            /* Number of pending entries in the queue */
 8716:   int nCoord;                       /* Number of coordinates */
 8717:   int iLevel;                       /* Level of current node or entry */
 8718:   int mxLevel;                      /* The largest iLevel value in the tree */
 8719:   sqlite3_int64 iRowid;             /* Rowid for current entry */
 8720:   sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
 8721:   int eParentWithin;                /* Visibility of parent node */
 8722:   int eWithin;                      /* OUT: Visiblity */
 8723:   sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
 8724:   /* The following fields are only available in 3.8.11 and later */
 8725:   sqlite3_value **apSqlParam;       /* Original SQL values of parameters */
 8726: };
 8727: 
 8728: /*
 8729: ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
 8730: */
 8731: #define NOT_WITHIN       0   /* Object completely outside of query region */
 8732: #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
 8733: #define FULLY_WITHIN     2   /* Object fully contained within query region */
 8734: 
 8735: 
 8736: #if 0
 8737: }  /* end of the 'extern "C"' block */
 8738: #endif
 8739: 
 8740: #endif  /* ifndef _SQLITE3RTREE_H_ */
 8741: 
 8742: /******** End of sqlite3rtree.h *********/
 8743: /******** Begin file sqlite3session.h *********/
 8744: 
 8745: #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
 8746: #define __SQLITESESSION_H_ 1
 8747: 
 8748: /*
 8749: ** Make sure we can call this stuff from C++.
 8750: */
 8751: #if 0
 8752: extern "C" {
 8753: #endif
 8754: 
 8755: 
 8756: /*
 8757: ** CAPI3REF: Session Object Handle
 8758: */
 8759: typedef struct sqlite3_session sqlite3_session;
 8760: 
 8761: /*
 8762: ** CAPI3REF: Changeset Iterator Handle
 8763: */
 8764: typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
 8765: 
 8766: /*
 8767: ** CAPI3REF: Create A New Session Object
 8768: **
 8769: ** Create a new session object attached to database handle db. If successful,
 8770: ** a pointer to the new object is written to *ppSession and SQLITE_OK is
 8771: ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
 8772: ** error code (e.g. SQLITE_NOMEM) is returned.
 8773: **
 8774: ** It is possible to create multiple session objects attached to a single
 8775: ** database handle.
 8776: **
 8777: ** Session objects created using this function should be deleted using the
 8778: ** [sqlite3session_delete()] function before the database handle that they
 8779: ** are attached to is itself closed. If the database handle is closed before
 8780: ** the session object is deleted, then the results of calling any session
 8781: ** module function, including [sqlite3session_delete()] on the session object
 8782: ** are undefined.
 8783: **
 8784: ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
 8785: ** is not possible for an application to register a pre-update hook on a
 8786: ** database handle that has one or more session objects attached. Nor is
 8787: ** it possible to create a session object attached to a database handle for
 8788: ** which a pre-update hook is already defined. The results of attempting 
 8789: ** either of these things are undefined.
 8790: **
 8791: ** The session object will be used to create changesets for tables in
 8792: ** database zDb, where zDb is either "main", or "temp", or the name of an
 8793: ** attached database. It is not an error if database zDb is not attached
 8794: ** to the database when the session object is created.
 8795: */
 8796: int sqlite3session_create(
 8797:   sqlite3 *db,                    /* Database handle */
 8798:   const char *zDb,                /* Name of db (e.g. "main") */
 8799:   sqlite3_session **ppSession     /* OUT: New session object */
 8800: );
 8801: 
 8802: /*
 8803: ** CAPI3REF: Delete A Session Object
 8804: **
 8805: ** Delete a session object previously allocated using 
 8806: ** [sqlite3session_create()]. Once a session object has been deleted, the
 8807: ** results of attempting to use pSession with any other session module
 8808: ** function are undefined.
 8809: **
 8810: ** Session objects must be deleted before the database handle to which they
 8811: ** are attached is closed. Refer to the documentation for 
 8812: ** [sqlite3session_create()] for details.
 8813: */
 8814: void sqlite3session_delete(sqlite3_session *pSession);
 8815: 
 8816: 
 8817: /*
 8818: ** CAPI3REF: Enable Or Disable A Session Object
 8819: **
 8820: ** Enable or disable the recording of changes by a session object. When
 8821: ** enabled, a session object records changes made to the database. When
 8822: ** disabled - it does not. A newly created session object is enabled.
 8823: ** Refer to the documentation for [sqlite3session_changeset()] for further
 8824: ** details regarding how enabling and disabling a session object affects
 8825: ** the eventual changesets.
 8826: **
 8827: ** Passing zero to this function disables the session. Passing a value
 8828: ** greater than zero enables it. Passing a value less than zero is a 
 8829: ** no-op, and may be used to query the current state of the session.
 8830: **
 8831: ** The return value indicates the final state of the session object: 0 if 
 8832: ** the session is disabled, or 1 if it is enabled.
 8833: */
 8834: int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
 8835: 
 8836: /*
 8837: ** CAPI3REF: Set Or Clear the Indirect Change Flag
 8838: **
 8839: ** Each change recorded by a session object is marked as either direct or
 8840: ** indirect. A change is marked as indirect if either:
 8841: **
 8842: ** <ul>
 8843: **   <li> The session object "indirect" flag is set when the change is
 8844: **        made, or
 8845: **   <li> The change is made by an SQL trigger or foreign key action 
 8846: **        instead of directly as a result of a users SQL statement.
 8847: ** </ul>
 8848: **
 8849: ** If a single row is affected by more than one operation within a session,
 8850: ** then the change is considered indirect if all operations meet the criteria
 8851: ** for an indirect change above, or direct otherwise.
 8852: **
 8853: ** This function is used to set, clear or query the session object indirect
 8854: ** flag.  If the second argument passed to this function is zero, then the
 8855: ** indirect flag is cleared. If it is greater than zero, the indirect flag
 8856: ** is set. Passing a value less than zero does not modify the current value
 8857: ** of the indirect flag, and may be used to query the current state of the 
 8858: ** indirect flag for the specified session object.
 8859: **
 8860: ** The return value indicates the final state of the indirect flag: 0 if 
 8861: ** it is clear, or 1 if it is set.
 8862: */
 8863: int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
 8864: 
 8865: /*
 8866: ** CAPI3REF: Attach A Table To A Session Object
 8867: **
 8868: ** If argument zTab is not NULL, then it is the name of a table to attach
 8869: ** to the session object passed as the first argument. All subsequent changes 
 8870: ** made to the table while the session object is enabled will be recorded. See 
 8871: ** documentation for [sqlite3session_changeset()] for further details.
 8872: **
 8873: ** Or, if argument zTab is NULL, then changes are recorded for all tables
 8874: ** in the database. If additional tables are added to the database (by 
 8875: ** executing "CREATE TABLE" statements) after this call is made, changes for 
 8876: ** the new tables are also recorded.
 8877: **
 8878: ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
 8879: ** defined as part of their CREATE TABLE statement. It does not matter if the 
 8880: ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
 8881: ** KEY may consist of a single column, or may be a composite key.
 8882: ** 
 8883: ** It is not an error if the named table does not exist in the database. Nor
 8884: ** is it an error if the named table does not have a PRIMARY KEY. However,
 8885: ** no changes will be recorded in either of these scenarios.
 8886: **
 8887: ** Changes are not recorded for individual rows that have NULL values stored
 8888: ** in one or more of their PRIMARY KEY columns.
 8889: **
 8890: ** SQLITE_OK is returned if the call completes without error. Or, if an error 
 8891: ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
 8892: */
 8893: int sqlite3session_attach(
 8894:   sqlite3_session *pSession,      /* Session object */
 8895:   const char *zTab                /* Table name */
 8896: );
 8897: 
 8898: /*
 8899: ** CAPI3REF: Set a table filter on a Session Object.
 8900: **
 8901: ** The second argument (xFilter) is the "filter callback". For changes to rows 
 8902: ** in tables that are not attached to the Session oject, the filter is called
 8903: ** to determine whether changes to the table's rows should be tracked or not. 
 8904: ** If xFilter returns 0, changes is not tracked. Note that once a table is 
 8905: ** attached, xFilter will not be called again.
 8906: */
 8907: void sqlite3session_table_filter(
 8908:   sqlite3_session *pSession,      /* Session object */
 8909:   int(*xFilter)(
 8910:     void *pCtx,                   /* Copy of third arg to _filter_table() */
 8911:     const char *zTab              /* Table name */
 8912:   ),
 8913:   void *pCtx                      /* First argument passed to xFilter */
 8914: );
 8915: 
 8916: /*
 8917: ** CAPI3REF: Generate A Changeset From A Session Object
 8918: **
 8919: ** Obtain a changeset containing changes to the tables attached to the 
 8920: ** session object passed as the first argument. If successful, 
 8921: ** set *ppChangeset to point to a buffer containing the changeset 
 8922: ** and *pnChangeset to the size of the changeset in bytes before returning
 8923: ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
 8924: ** zero and return an SQLite error code.
 8925: **
 8926: ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
 8927: ** each representing a change to a single row of an attached table. An INSERT
 8928: ** change contains the values of each field of a new database row. A DELETE
 8929: ** contains the original values of each field of a deleted database row. An
 8930: ** UPDATE change contains the original values of each field of an updated
 8931: ** database row along with the updated values for each updated non-primary-key
 8932: ** column. It is not possible for an UPDATE change to represent a change that
 8933: ** modifies the values of primary key columns. If such a change is made, it
 8934: ** is represented in a changeset as a DELETE followed by an INSERT.
 8935: **
 8936: ** Changes are not recorded for rows that have NULL values stored in one or 
 8937: ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
 8938: ** no corresponding change is present in the changesets returned by this
 8939: ** function. If an existing row with one or more NULL values stored in
 8940: ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
 8941: ** only an INSERT is appears in the changeset. Similarly, if an existing row
 8942: ** with non-NULL PRIMARY KEY values is updated so that one or more of its
 8943: ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
 8944: ** DELETE change only.
 8945: **
 8946: ** The contents of a changeset may be traversed using an iterator created
 8947: ** using the [sqlite3changeset_start()] API. A changeset may be applied to
 8948: ** a database with a compatible schema using the [sqlite3changeset_apply()]
 8949: ** API.
 8950: **
 8951: ** Within a changeset generated by this function, all changes related to a
 8952: ** single table are grouped together. In other words, when iterating through
 8953: ** a changeset or when applying a changeset to a database, all changes related
 8954: ** to a single table are processed before moving on to the next table. Tables
 8955: ** are sorted in the same order in which they were attached (or auto-attached)
 8956: ** to the sqlite3_session object. The order in which the changes related to
 8957: ** a single table are stored is undefined.
 8958: **
 8959: ** Following a successful call to this function, it is the responsibility of
 8960: ** the caller to eventually free the buffer that *ppChangeset points to using
 8961: ** [sqlite3_free()].
 8962: **
 8963: ** <h3>Changeset Generation</h3>
 8964: **
 8965: ** Once a table has been attached to a session object, the session object
 8966: ** records the primary key values of all new rows inserted into the table.
 8967: ** It also records the original primary key and other column values of any
 8968: ** deleted or updated rows. For each unique primary key value, data is only
 8969: ** recorded once - the first time a row with said primary key is inserted,
 8970: ** updated or deleted in the lifetime of the session.
 8971: **
 8972: ** There is one exception to the previous paragraph: when a row is inserted,
 8973: ** updated or deleted, if one or more of its primary key columns contain a
 8974: ** NULL value, no record of the change is made.
 8975: **
 8976: ** The session object therefore accumulates two types of records - those
 8977: ** that consist of primary key values only (created when the user inserts
 8978: ** a new record) and those that consist of the primary key values and the
 8979: ** original values of other table columns (created when the users deletes
 8980: ** or updates a record).
 8981: **
 8982: ** When this function is called, the requested changeset is created using
 8983: ** both the accumulated records and the current contents of the database
 8984: ** file. Specifically:
 8985: **
 8986: ** <ul>
 8987: **   <li> For each record generated by an insert, the database is queried
 8988: **        for a row with a matching primary key. If one is found, an INSERT
 8989: **        change is added to the changeset. If no such row is found, no change 
 8990: **        is added to the changeset.
 8991: **
 8992: **   <li> For each record generated by an update or delete, the database is 
 8993: **        queried for a row with a matching primary key. If such a row is
 8994: **        found and one or more of the non-primary key fields have been
 8995: **        modified from their original values, an UPDATE change is added to 
 8996: **        the changeset. Or, if no such row is found in the table, a DELETE 
 8997: **        change is added to the changeset. If there is a row with a matching
 8998: **        primary key in the database, but all fields contain their original
 8999: **        values, no change is added to the changeset.
 9000: ** </ul>
 9001: **
 9002: ** This means, amongst other things, that if a row is inserted and then later
 9003: ** deleted while a session object is active, neither the insert nor the delete
 9004: ** will be present in the changeset. Or if a row is deleted and then later a 
 9005: ** row with the same primary key values inserted while a session object is
 9006: ** active, the resulting changeset will contain an UPDATE change instead of
 9007: ** a DELETE and an INSERT.
 9008: **
 9009: ** When a session object is disabled (see the [sqlite3session_enable()] API),
 9010: ** it does not accumulate records when rows are inserted, updated or deleted.
 9011: ** This may appear to have some counter-intuitive effects if a single row
 9012: ** is written to more than once during a session. For example, if a row
 9013: ** is inserted while a session object is enabled, then later deleted while 
 9014: ** the same session object is disabled, no INSERT record will appear in the
 9015: ** changeset, even though the delete took place while the session was disabled.
 9016: ** Or, if one field of a row is updated while a session is disabled, and 
 9017: ** another field of the same row is updated while the session is enabled, the
 9018: ** resulting changeset will contain an UPDATE change that updates both fields.
 9019: */
 9020: int sqlite3session_changeset(
 9021:   sqlite3_session *pSession,      /* Session object */
 9022:   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
 9023:   void **ppChangeset              /* OUT: Buffer containing changeset */
 9024: );
 9025: 
 9026: /*
 9027: ** CAPI3REF: Load The Difference Between Tables Into A Session 
 9028: **
 9029: ** If it is not already attached to the session object passed as the first
 9030: ** argument, this function attaches table zTbl in the same manner as the
 9031: ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
 9032: ** does not have a primary key, this function is a no-op (but does not return
 9033: ** an error).
 9034: **
 9035: ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
 9036: ** attached to the same database handle as the session object that contains 
 9037: ** a table compatible with the table attached to the session by this function.
 9038: ** A table is considered compatible if it:
 9039: **
 9040: ** <ul>
 9041: **   <li> Has the same name,
 9042: **   <li> Has the same set of columns declared in the same order, and
 9043: **   <li> Has the same PRIMARY KEY definition.
 9044: ** </ul>
 9045: **
 9046: ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
 9047: ** are compatible but do not have any PRIMARY KEY columns, it is not an error
 9048: ** but no changes are added to the session object. As with other session
 9049: ** APIs, tables without PRIMARY KEYs are simply ignored.
 9050: **
 9051: ** This function adds a set of changes to the session object that could be
 9052: ** used to update the table in database zFrom (call this the "from-table") 
 9053: ** so that its content is the same as the table attached to the session 
 9054: ** object (call this the "to-table"). Specifically:
 9055: **
 9056: ** <ul>
 9057: **   <li> For each row (primary key) that exists in the to-table but not in 
 9058: **     the from-table, an INSERT record is added to the session object.
 9059: **
 9060: **   <li> For each row (primary key) that exists in the to-table but not in 
 9061: **     the from-table, a DELETE record is added to the session object.
 9062: **
 9063: **   <li> For each row (primary key) that exists in both tables, but features 
 9064: **     different in each, an UPDATE record is added to the session.
 9065: ** </ul>
 9066: **
 9067: ** To clarify, if this function is called and then a changeset constructed
 9068: ** using [sqlite3session_changeset()], then after applying that changeset to 
 9069: ** database zFrom the contents of the two compatible tables would be 
 9070: ** identical.
 9071: **
 9072: ** It an error if database zFrom does not exist or does not contain the
 9073: ** required compatible table.
 9074: **
 9075: ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
 9076: ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
 9077: ** may be set to point to a buffer containing an English language error 
 9078: ** message. It is the responsibility of the caller to free this buffer using
 9079: ** sqlite3_free().
 9080: */
 9081: int sqlite3session_diff(
 9082:   sqlite3_session *pSession,
 9083:   const char *zFromDb,
 9084:   const char *zTbl,
 9085:   char **pzErrMsg
 9086: );
 9087: 
 9088: 
 9089: /*
 9090: ** CAPI3REF: Generate A Patchset From A Session Object
 9091: **
 9092: ** The differences between a patchset and a changeset are that:
 9093: **
 9094: ** <ul>
 9095: **   <li> DELETE records consist of the primary key fields only. The 
 9096: **        original values of other fields are omitted.
 9097: **   <li> The original values of any modified fields are omitted from 
 9098: **        UPDATE records.
 9099: ** </ul>
 9100: **
 9101: ** A patchset blob may be used with up to date versions of all 
 9102: ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(), 
 9103: ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
 9104: ** attempting to use a patchset blob with old versions of the
 9105: ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error. 
 9106: **
 9107: ** Because the non-primary key "old.*" fields are omitted, no 
 9108: ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
 9109: ** is passed to the sqlite3changeset_apply() API. Other conflict types work
 9110: ** in the same way as for changesets.
 9111: **
 9112: ** Changes within a patchset are ordered in the same way as for changesets
 9113: ** generated by the sqlite3session_changeset() function (i.e. all changes for
 9114: ** a single table are grouped together, tables appear in the order in which
 9115: ** they were attached to the session object).
 9116: */
 9117: int sqlite3session_patchset(
 9118:   sqlite3_session *pSession,      /* Session object */
 9119:   int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
 9120:   void **ppPatchset               /* OUT: Buffer containing changeset */
 9121: );
 9122: 
 9123: /*
 9124: ** CAPI3REF: Test if a changeset has recorded any changes.
 9125: **
 9126: ** Return non-zero if no changes to attached tables have been recorded by 
 9127: ** the session object passed as the first argument. Otherwise, if one or 
 9128: ** more changes have been recorded, return zero.
 9129: **
 9130: ** Even if this function returns zero, it is possible that calling
 9131: ** [sqlite3session_changeset()] on the session handle may still return a
 9132: ** changeset that contains no changes. This can happen when a row in 
 9133: ** an attached table is modified and then later on the original values 
 9134: ** are restored. However, if this function returns non-zero, then it is
 9135: ** guaranteed that a call to sqlite3session_changeset() will return a 
 9136: ** changeset containing zero changes.
 9137: */
 9138: int sqlite3session_isempty(sqlite3_session *pSession);
 9139: 
 9140: /*
 9141: ** CAPI3REF: Create An Iterator To Traverse A Changeset 
 9142: **
 9143: ** Create an iterator used to iterate through the contents of a changeset.
 9144: ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
 9145: ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
 9146: ** SQLite error code is returned.
 9147: **
 9148: ** The following functions can be used to advance and query a changeset 
 9149: ** iterator created by this function:
 9150: **
 9151: ** <ul>
 9152: **   <li> [sqlite3changeset_next()]
 9153: **   <li> [sqlite3changeset_op()]
 9154: **   <li> [sqlite3changeset_new()]
 9155: **   <li> [sqlite3changeset_old()]
 9156: ** </ul>
 9157: **
 9158: ** It is the responsibility of the caller to eventually destroy the iterator
 9159: ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
 9160: ** changeset (pChangeset) must remain valid until after the iterator is
 9161: ** destroyed.
 9162: **
 9163: ** Assuming the changeset blob was created by one of the
 9164: ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
 9165: ** [sqlite3changeset_invert()] functions, all changes within the changeset 
 9166: ** that apply to a single table are grouped together. This means that when 
 9167: ** an application iterates through a changeset using an iterator created by 
 9168: ** this function, all changes that relate to a single table are visted 
 9169: ** consecutively. There is no chance that the iterator will visit a change 
 9170: ** the applies to table X, then one for table Y, and then later on visit 
 9171: ** another change for table X.
 9172: */
 9173: int sqlite3changeset_start(
 9174:   sqlite3_changeset_iter **pp,    /* OUT: New changeset iterator handle */
 9175:   int nChangeset,                 /* Size of changeset blob in bytes */
 9176:   void *pChangeset                /* Pointer to blob containing changeset */
 9177: );
 9178: 
 9179: 
 9180: /*
 9181: ** CAPI3REF: Advance A Changeset Iterator
 9182: **
 9183: ** This function may only be used with iterators created by function
 9184: ** [sqlite3changeset_start()]. If it is called on an iterator passed to
 9185: ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
 9186: ** is returned and the call has no effect.
 9187: **
 9188: ** Immediately after an iterator is created by sqlite3changeset_start(), it
 9189: ** does not point to any change in the changeset. Assuming the changeset
 9190: ** is not empty, the first call to this function advances the iterator to
 9191: ** point to the first change in the changeset. Each subsequent call advances
 9192: ** the iterator to point to the next change in the changeset (if any). If
 9193: ** no error occurs and the iterator points to a valid change after a call
 9194: ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned. 
 9195: ** Otherwise, if all changes in the changeset have already been visited,
 9196: ** SQLITE_DONE is returned.
 9197: **
 9198: ** If an error occurs, an SQLite error code is returned. Possible error 
 9199: ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or 
 9200: ** SQLITE_NOMEM.
 9201: */
 9202: int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
 9203: 
 9204: /*
 9205: ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
 9206: **
 9207: ** The pIter argument passed to this function may either be an iterator
 9208: ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 9209: ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 9210: ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
 9211: ** is not the case, this function returns [SQLITE_MISUSE].
 9212: **
 9213: ** If argument pzTab is not NULL, then *pzTab is set to point to a
 9214: ** nul-terminated utf-8 encoded string containing the name of the table
 9215: ** affected by the current change. The buffer remains valid until either
 9216: ** sqlite3changeset_next() is called on the iterator or until the 
 9217: ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is 
 9218: ** set to the number of columns in the table affected by the change. If
 9219: ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
 9220: ** is an indirect change, or false (0) otherwise. See the documentation for
 9221: ** [sqlite3session_indirect()] for a description of direct and indirect
 9222: ** changes. Finally, if pOp is not NULL, then *pOp is set to one of 
 9223: ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the 
 9224: ** type of change that the iterator currently points to.
 9225: **
 9226: ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
 9227: ** SQLite error code is returned. The values of the output variables may not
 9228: ** be trusted in this case.
 9229: */
 9230: int sqlite3changeset_op(
 9231:   sqlite3_changeset_iter *pIter,  /* Iterator object */
 9232:   const char **pzTab,             /* OUT: Pointer to table name */
 9233:   int *pnCol,                     /* OUT: Number of columns in table */
 9234:   int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
 9235:   int *pbIndirect                 /* OUT: True for an 'indirect' change */
 9236: );
 9237: 
 9238: /*
 9239: ** CAPI3REF: Obtain The Primary Key Definition Of A Table
 9240: **
 9241: ** For each modified table, a changeset includes the following:
 9242: **
 9243: ** <ul>
 9244: **   <li> The number of columns in the table, and
 9245: **   <li> Which of those columns make up the tables PRIMARY KEY.
 9246: ** </ul>
 9247: **
 9248: ** This function is used to find which columns comprise the PRIMARY KEY of
 9249: ** the table modified by the change that iterator pIter currently points to.
 9250: ** If successful, *pabPK is set to point to an array of nCol entries, where
 9251: ** nCol is the number of columns in the table. Elements of *pabPK are set to
 9252: ** 0x01 if the corresponding column is part of the tables primary key, or
 9253: ** 0x00 if it is not.
 9254: **
 9255: ** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
 9256: ** in the table.
 9257: **
 9258: ** If this function is called when the iterator does not point to a valid
 9259: ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
 9260: ** SQLITE_OK is returned and the output variables populated as described
 9261: ** above.
 9262: */
 9263: int sqlite3changeset_pk(
 9264:   sqlite3_changeset_iter *pIter,  /* Iterator object */
 9265:   unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
 9266:   int *pnCol                      /* OUT: Number of entries in output array */
 9267: );
 9268: 
 9269: /*
 9270: ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
 9271: **
 9272: ** The pIter argument passed to this function may either be an iterator
 9273: ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 9274: ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 9275: ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
 9276: ** Furthermore, it may only be called if the type of change that the iterator
 9277: ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
 9278: ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
 9279: **
 9280: ** Argument iVal must be greater than or equal to 0, and less than the number
 9281: ** of columns in the table affected by the current change. Otherwise,
 9282: ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 9283: **
 9284: ** If successful, this function sets *ppValue to point to a protected
 9285: ** sqlite3_value object containing the iVal'th value from the vector of 
 9286: ** original row values stored as part of the UPDATE or DELETE change and
 9287: ** returns SQLITE_OK. The name of the function comes from the fact that this 
 9288: ** is similar to the "old.*" columns available to update or delete triggers.
 9289: **
 9290: ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 9291: ** is returned and *ppValue is set to NULL.
 9292: */
 9293: int sqlite3changeset_old(
 9294:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 9295:   int iVal,                       /* Column number */
 9296:   sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
 9297: );
 9298: 
 9299: /*
 9300: ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
 9301: **
 9302: ** The pIter argument passed to this function may either be an iterator
 9303: ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
 9304: ** created by [sqlite3changeset_start()]. In the latter case, the most recent
 9305: ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW. 
 9306: ** Furthermore, it may only be called if the type of change that the iterator
 9307: ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
 9308: ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
 9309: **
 9310: ** Argument iVal must be greater than or equal to 0, and less than the number
 9311: ** of columns in the table affected by the current change. Otherwise,
 9312: ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 9313: **
 9314: ** If successful, this function sets *ppValue to point to a protected
 9315: ** sqlite3_value object containing the iVal'th value from the vector of 
 9316: ** new row values stored as part of the UPDATE or INSERT change and
 9317: ** returns SQLITE_OK. If the change is an UPDATE and does not include
 9318: ** a new value for the requested column, *ppValue is set to NULL and 
 9319: ** SQLITE_OK returned. The name of the function comes from the fact that 
 9320: ** this is similar to the "new.*" columns available to update or delete 
 9321: ** triggers.
 9322: **
 9323: ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 9324: ** is returned and *ppValue is set to NULL.
 9325: */
 9326: int sqlite3changeset_new(
 9327:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 9328:   int iVal,                       /* Column number */
 9329:   sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
 9330: );
 9331: 
 9332: /*
 9333: ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
 9334: **
 9335: ** This function should only be used with iterator objects passed to a
 9336: ** conflict-handler callback by [sqlite3changeset_apply()] with either
 9337: ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
 9338: ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
 9339: ** is set to NULL.
 9340: **
 9341: ** Argument iVal must be greater than or equal to 0, and less than the number
 9342: ** of columns in the table affected by the current change. Otherwise,
 9343: ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
 9344: **
 9345: ** If successful, this function sets *ppValue to point to a protected
 9346: ** sqlite3_value object containing the iVal'th value from the 
 9347: ** "conflicting row" associated with the current conflict-handler callback
 9348: ** and returns SQLITE_OK.
 9349: **
 9350: ** If some other error occurs (e.g. an OOM condition), an SQLite error code
 9351: ** is returned and *ppValue is set to NULL.
 9352: */
 9353: int sqlite3changeset_conflict(
 9354:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 9355:   int iVal,                       /* Column number */
 9356:   sqlite3_value **ppValue         /* OUT: Value from conflicting row */
 9357: );
 9358: 
 9359: /*
 9360: ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
 9361: **
 9362: ** This function may only be called with an iterator passed to an
 9363: ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
 9364: ** it sets the output variable to the total number of known foreign key
 9365: ** violations in the destination database and returns SQLITE_OK.
 9366: **
 9367: ** In all other cases this function returns SQLITE_MISUSE.
 9368: */
 9369: int sqlite3changeset_fk_conflicts(
 9370:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
 9371:   int *pnOut                      /* OUT: Number of FK violations */
 9372: );
 9373: 
 9374: 
 9375: /*
 9376: ** CAPI3REF: Finalize A Changeset Iterator
 9377: **
 9378: ** This function is used to finalize an iterator allocated with
 9379: ** [sqlite3changeset_start()].
 9380: **
 9381: ** This function should only be called on iterators created using the
 9382: ** [sqlite3changeset_start()] function. If an application calls this
 9383: ** function with an iterator passed to a conflict-handler by
 9384: ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
 9385: ** call has no effect.
 9386: **
 9387: ** If an error was encountered within a call to an sqlite3changeset_xxx()
 9388: ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an 
 9389: ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
 9390: ** to that error is returned by this function. Otherwise, SQLITE_OK is
 9391: ** returned. This is to allow the following pattern (pseudo-code):
 9392: **
 9393: **   sqlite3changeset_start();
 9394: **   while( SQLITE_ROW==sqlite3changeset_next() ){
 9395: **     // Do something with change.
 9396: **   }
 9397: **   rc = sqlite3changeset_finalize();
 9398: **   if( rc!=SQLITE_OK ){
 9399: **     // An error has occurred 
 9400: **   }
 9401: */
 9402: int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
 9403: 
 9404: /*
 9405: ** CAPI3REF: Invert A Changeset
 9406: **
 9407: ** This function is used to "invert" a changeset object. Applying an inverted
 9408: ** changeset to a database reverses the effects of applying the uninverted
 9409: ** changeset. Specifically:
 9410: **
 9411: ** <ul>
 9412: **   <li> Each DELETE change is changed to an INSERT, and
 9413: **   <li> Each INSERT change is changed to a DELETE, and
 9414: **   <li> For each UPDATE change, the old.* and new.* values are exchanged.
 9415: ** </ul>
 9416: **
 9417: ** This function does not change the order in which changes appear within
 9418: ** the changeset. It merely reverses the sense of each individual change.
 9419: **
 9420: ** If successful, a pointer to a buffer containing the inverted changeset
 9421: ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
 9422: ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
 9423: ** zeroed and an SQLite error code returned.
 9424: **
 9425: ** It is the responsibility of the caller to eventually call sqlite3_free()
 9426: ** on the *ppOut pointer to free the buffer allocation following a successful 
 9427: ** call to this function.
 9428: **
 9429: ** WARNING/TODO: This function currently assumes that the input is a valid
 9430: ** changeset. If it is not, the results are undefined.
 9431: */
 9432: int sqlite3changeset_invert(
 9433:   int nIn, const void *pIn,       /* Input changeset */
 9434:   int *pnOut, void **ppOut        /* OUT: Inverse of input */
 9435: );
 9436: 
 9437: /*
 9438: ** CAPI3REF: Concatenate Two Changeset Objects
 9439: **
 9440: ** This function is used to concatenate two changesets, A and B, into a 
 9441: ** single changeset. The result is a changeset equivalent to applying
 9442: ** changeset A followed by changeset B. 
 9443: **
 9444: ** This function combines the two input changesets using an 
 9445: ** sqlite3_changegroup object. Calling it produces similar results as the
 9446: ** following code fragment:
 9447: **
 9448: **   sqlite3_changegroup *pGrp;
 9449: **   rc = sqlite3_changegroup_new(&pGrp);
 9450: **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
 9451: **   if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
 9452: **   if( rc==SQLITE_OK ){
 9453: **     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
 9454: **   }else{
 9455: **     *ppOut = 0;
 9456: **     *pnOut = 0;
 9457: **   }
 9458: **
 9459: ** Refer to the sqlite3_changegroup documentation below for details.
 9460: */
 9461: int sqlite3changeset_concat(
 9462:   int nA,                         /* Number of bytes in buffer pA */
 9463:   void *pA,                       /* Pointer to buffer containing changeset A */
 9464:   int nB,                         /* Number of bytes in buffer pB */
 9465:   void *pB,                       /* Pointer to buffer containing changeset B */
 9466:   int *pnOut,                     /* OUT: Number of bytes in output changeset */
 9467:   void **ppOut                    /* OUT: Buffer containing output changeset */
 9468: );
 9469: 
 9470: 
 9471: /*
 9472: ** Changegroup handle.
 9473: */
 9474: typedef struct sqlite3_changegroup sqlite3_changegroup;
 9475: 
 9476: /*
 9477: ** CAPI3REF: Combine two or more changesets into a single changeset.
 9478: **
 9479: ** An sqlite3_changegroup object is used to combine two or more changesets
 9480: ** (or patchsets) into a single changeset (or patchset). A single changegroup
 9481: ** object may combine changesets or patchsets, but not both. The output is
 9482: ** always in the same format as the input.
 9483: **
 9484: ** If successful, this function returns SQLITE_OK and populates (*pp) with
 9485: ** a pointer to a new sqlite3_changegroup object before returning. The caller
 9486: ** should eventually free the returned object using a call to 
 9487: ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
 9488: ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
 9489: **
 9490: ** The usual usage pattern for an sqlite3_changegroup object is as follows:
 9491: **
 9492: ** <ul>
 9493: **   <li> It is created using a call to sqlite3changegroup_new().
 9494: **
 9495: **   <li> Zero or more changesets (or patchsets) are added to the object
 9496: **        by calling sqlite3changegroup_add().
 9497: **
 9498: **   <li> The result of combining all input changesets together is obtained 
 9499: **        by the application via a call to sqlite3changegroup_output().
 9500: **
 9501: **   <li> The object is deleted using a call to sqlite3changegroup_delete().
 9502: ** </ul>
 9503: **
 9504: ** Any number of calls to add() and output() may be made between the calls to
 9505: ** new() and delete(), and in any order.
 9506: **
 9507: ** As well as the regular sqlite3changegroup_add() and 
 9508: ** sqlite3changegroup_output() functions, also available are the streaming
 9509: ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
 9510: */
 9511: int sqlite3changegroup_new(sqlite3_changegroup **pp);
 9512: 
 9513: /*
 9514: ** Add all changes within the changeset (or patchset) in buffer pData (size
 9515: ** nData bytes) to the changegroup. 
 9516: **
 9517: ** If the buffer contains a patchset, then all prior calls to this function
 9518: ** on the same changegroup object must also have specified patchsets. Or, if
 9519: ** the buffer contains a changeset, so must have the earlier calls to this
 9520: ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
 9521: ** to the changegroup.
 9522: **
 9523: ** Rows within the changeset and changegroup are identified by the values in
 9524: ** their PRIMARY KEY columns. A change in the changeset is considered to
 9525: ** apply to the same row as a change already present in the changegroup if
 9526: ** the two rows have the same primary key.
 9527: **
 9528: ** Changes to rows that that do not already appear in the changegroup are
 9529: ** simply copied into it. Or, if both the new changeset and the changegroup
 9530: ** contain changes that apply to a single row, the final contents of the
 9531: ** changegroup depends on the type of each change, as follows:
 9532: **
 9533: ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 9534: **   <tr><th style="white-space:pre">Existing Change  </th>
 9535: **       <th style="white-space:pre">New Change       </th>
 9536: **       <th>Output Change
 9537: **   <tr><td>INSERT <td>INSERT <td>
 9538: **       The new change is ignored. This case does not occur if the new
 9539: **       changeset was recorded immediately after the changesets already
 9540: **       added to the changegroup.
 9541: **   <tr><td>INSERT <td>UPDATE <td>
 9542: **       The INSERT change remains in the changegroup. The values in the 
 9543: **       INSERT change are modified as if the row was inserted by the
 9544: **       existing change and then updated according to the new change.
 9545: **   <tr><td>INSERT <td>DELETE <td>
 9546: **       The existing INSERT is removed from the changegroup. The DELETE is
 9547: **       not added.
 9548: **   <tr><td>UPDATE <td>INSERT <td>
 9549: **       The new change is ignored. This case does not occur if the new
 9550: **       changeset was recorded immediately after the changesets already
 9551: **       added to the changegroup.
 9552: **   <tr><td>UPDATE <td>UPDATE <td>
 9553: **       The existing UPDATE remains within the changegroup. It is amended 
 9554: **       so that the accompanying values are as if the row was updated once 
 9555: **       by the existing change and then again by the new change.
 9556: **   <tr><td>UPDATE <td>DELETE <td>
 9557: **       The existing UPDATE is replaced by the new DELETE within the
 9558: **       changegroup.
 9559: **   <tr><td>DELETE <td>INSERT <td>
 9560: **       If one or more of the column values in the row inserted by the
 9561: **       new change differ from those in the row deleted by the existing 
 9562: **       change, the existing DELETE is replaced by an UPDATE within the
 9563: **       changegroup. Otherwise, if the inserted row is exactly the same 
 9564: **       as the deleted row, the existing DELETE is simply discarded.
 9565: **   <tr><td>DELETE <td>UPDATE <td>
 9566: **       The new change is ignored. This case does not occur if the new
 9567: **       changeset was recorded immediately after the changesets already
 9568: **       added to the changegroup.
 9569: **   <tr><td>DELETE <td>DELETE <td>
 9570: **       The new change is ignored. This case does not occur if the new
 9571: **       changeset was recorded immediately after the changesets already
 9572: **       added to the changegroup.
 9573: ** </table>
 9574: **
 9575: ** If the new changeset contains changes to a table that is already present
 9576: ** in the changegroup, then the number of columns and the position of the
 9577: ** primary key columns for the table must be consistent. If this is not the
 9578: ** case, this function fails with SQLITE_SCHEMA. If the input changeset
 9579: ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
 9580: ** returned. Or, if an out-of-memory condition occurs during processing, this
 9581: ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
 9582: ** final contents of the changegroup is undefined.
 9583: **
 9584: ** If no error occurs, SQLITE_OK is returned.
 9585: */
 9586: int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
 9587: 
 9588: /*
 9589: ** Obtain a buffer containing a changeset (or patchset) representing the
 9590: ** current contents of the changegroup. If the inputs to the changegroup
 9591: ** were themselves changesets, the output is a changeset. Or, if the
 9592: ** inputs were patchsets, the output is also a patchset.
 9593: **
 9594: ** As with the output of the sqlite3session_changeset() and
 9595: ** sqlite3session_patchset() functions, all changes related to a single
 9596: ** table are grouped together in the output of this function. Tables appear
 9597: ** in the same order as for the very first changeset added to the changegroup.
 9598: ** If the second or subsequent changesets added to the changegroup contain
 9599: ** changes for tables that do not appear in the first changeset, they are
 9600: ** appended onto the end of the output changeset, again in the order in
 9601: ** which they are first encountered.
 9602: **
 9603: ** If an error occurs, an SQLite error code is returned and the output
 9604: ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
 9605: ** is returned and the output variables are set to the size of and a 
 9606: ** pointer to the output buffer, respectively. In this case it is the
 9607: ** responsibility of the caller to eventually free the buffer using a
 9608: ** call to sqlite3_free().
 9609: */
 9610: int sqlite3changegroup_output(
 9611:   sqlite3_changegroup*,
 9612:   int *pnData,                    /* OUT: Size of output buffer in bytes */
 9613:   void **ppData                   /* OUT: Pointer to output buffer */
 9614: );
 9615: 
 9616: /*
 9617: ** Delete a changegroup object.
 9618: */
 9619: void sqlite3changegroup_delete(sqlite3_changegroup*);
 9620: 
 9621: /*
 9622: ** CAPI3REF: Apply A Changeset To A Database
 9623: **
 9624: ** Apply a changeset to a database. This function attempts to update the
 9625: ** "main" database attached to handle db with the changes found in the
 9626: ** changeset passed via the second and third arguments.
 9627: **
 9628: ** The fourth argument (xFilter) passed to this function is the "filter
 9629: ** callback". If it is not NULL, then for each table affected by at least one
 9630: ** change in the changeset, the filter callback is invoked with
 9631: ** the table name as the second argument, and a copy of the context pointer
 9632: ** passed as the sixth argument to this function as the first. If the "filter
 9633: ** callback" returns zero, then no attempt is made to apply any changes to 
 9634: ** the table. Otherwise, if the return value is non-zero or the xFilter
 9635: ** argument to this function is NULL, all changes related to the table are
 9636: ** attempted.
 9637: **
 9638: ** For each table that is not excluded by the filter callback, this function 
 9639: ** tests that the target database contains a compatible table. A table is 
 9640: ** considered compatible if all of the following are true:
 9641: **
 9642: ** <ul>
 9643: **   <li> The table has the same name as the name recorded in the 
 9644: **        changeset, and
 9645: **   <li> The table has the same number of columns as recorded in the 
 9646: **        changeset, and
 9647: **   <li> The table has primary key columns in the same position as 
 9648: **        recorded in the changeset.
 9649: ** </ul>
 9650: **
 9651: ** If there is no compatible table, it is not an error, but none of the
 9652: ** changes associated with the table are applied. A warning message is issued
 9653: ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
 9654: ** one such warning is issued for each table in the changeset.
 9655: **
 9656: ** For each change for which there is a compatible table, an attempt is made 
 9657: ** to modify the table contents according to the UPDATE, INSERT or DELETE 
 9658: ** change. If a change cannot be applied cleanly, the conflict handler 
 9659: ** function passed as the fifth argument to sqlite3changeset_apply() may be 
 9660: ** invoked. A description of exactly when the conflict handler is invoked for 
 9661: ** each type of change is below.
 9662: **
 9663: ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
 9664: ** of passing anything other than a valid function pointer as the xConflict
 9665: ** argument are undefined.
 9666: **
 9667: ** Each time the conflict handler function is invoked, it must return one
 9668: ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or 
 9669: ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
 9670: ** if the second argument passed to the conflict handler is either
 9671: ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
 9672: ** returns an illegal value, any changes already made are rolled back and
 9673: ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different 
 9674: ** actions are taken by sqlite3changeset_apply() depending on the value
 9675: ** returned by each invocation of the conflict-handler function. Refer to
 9676: ** the documentation for the three 
 9677: ** [SQLITE_CHANGESET_OMIT|available return values] for details.
 9678: **
 9679: ** <dl>
 9680: ** <dt>DELETE Changes<dd>
 9681: **   For each DELETE change, this function checks if the target database 
 9682: **   contains a row with the same primary key value (or values) as the 
 9683: **   original row values stored in the changeset. If it does, and the values 
 9684: **   stored in all non-primary key columns also match the values stored in 
 9685: **   the changeset the row is deleted from the target database.
 9686: **
 9687: **   If a row with matching primary key values is found, but one or more of
 9688: **   the non-primary key fields contains a value different from the original
 9689: **   row value stored in the changeset, the conflict-handler function is
 9690: **   invoked with [SQLITE_CHANGESET_DATA] as the second argument.
 9691: **
 9692: **   If no row with matching primary key values is found in the database,
 9693: **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 9694: **   passed as the second argument.
 9695: **
 9696: **   If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
 9697: **   (which can only happen if a foreign key constraint is violated), the
 9698: **   conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
 9699: **   passed as the second argument. This includes the case where the DELETE
 9700: **   operation is attempted because an earlier call to the conflict handler
 9701: **   function returned [SQLITE_CHANGESET_REPLACE].
 9702: **
 9703: ** <dt>INSERT Changes<dd>
 9704: **   For each INSERT change, an attempt is made to insert the new row into
 9705: **   the database.
 9706: **
 9707: **   If the attempt to insert the row fails because the database already 
 9708: **   contains a row with the same primary key values, the conflict handler
 9709: **   function is invoked with the second argument set to 
 9710: **   [SQLITE_CHANGESET_CONFLICT].
 9711: **
 9712: **   If the attempt to insert the row fails because of some other constraint
 9713: **   violation (e.g. NOT NULL or UNIQUE), the conflict handler function is 
 9714: **   invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
 9715: **   This includes the case where the INSERT operation is re-attempted because 
 9716: **   an earlier call to the conflict handler function returned 
 9717: **   [SQLITE_CHANGESET_REPLACE].
 9718: **
 9719: ** <dt>UPDATE Changes<dd>
 9720: **   For each UPDATE change, this function checks if the target database 
 9721: **   contains a row with the same primary key value (or values) as the 
 9722: **   original row values stored in the changeset. If it does, and the values 
 9723: **   stored in all non-primary key columns also match the values stored in 
 9724: **   the changeset the row is updated within the target database.
 9725: **
 9726: **   If a row with matching primary key values is found, but one or more of
 9727: **   the non-primary key fields contains a value different from an original
 9728: **   row value stored in the changeset, the conflict-handler function is
 9729: **   invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
 9730: **   UPDATE changes only contain values for non-primary key fields that are
 9731: **   to be modified, only those fields need to match the original values to
 9732: **   avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
 9733: **
 9734: **   If no row with matching primary key values is found in the database,
 9735: **   the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
 9736: **   passed as the second argument.
 9737: **
 9738: **   If the UPDATE operation is attempted, but SQLite returns 
 9739: **   SQLITE_CONSTRAINT, the conflict-handler function is invoked with 
 9740: **   [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
 9741: **   This includes the case where the UPDATE operation is attempted after 
 9742: **   an earlier call to the conflict handler function returned
 9743: **   [SQLITE_CHANGESET_REPLACE].  
 9744: ** </dl>
 9745: **
 9746: ** It is safe to execute SQL statements, including those that write to the
 9747: ** table that the callback related to, from within the xConflict callback.
 9748: ** This can be used to further customize the applications conflict
 9749: ** resolution strategy.
 9750: **
 9751: ** All changes made by this function are enclosed in a savepoint transaction.
 9752: ** If any other error (aside from a constraint failure when attempting to
 9753: ** write to the target database) occurs, then the savepoint transaction is
 9754: ** rolled back, restoring the target database to its original state, and an 
 9755: ** SQLite error code returned.
 9756: */
 9757: int sqlite3changeset_apply(
 9758:   sqlite3 *db,                    /* Apply change to "main" db of this handle */
 9759:   int nChangeset,                 /* Size of changeset in bytes */
 9760:   void *pChangeset,               /* Changeset blob */
 9761:   int(*xFilter)(
 9762:     void *pCtx,                   /* Copy of sixth arg to _apply() */
 9763:     const char *zTab              /* Table name */
 9764:   ),
 9765:   int(*xConflict)(
 9766:     void *pCtx,                   /* Copy of sixth arg to _apply() */
 9767:     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 9768:     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 9769:   ),
 9770:   void *pCtx                      /* First argument passed to xConflict */
 9771: );
 9772: 
 9773: /* 
 9774: ** CAPI3REF: Constants Passed To The Conflict Handler
 9775: **
 9776: ** Values that may be passed as the second argument to a conflict-handler.
 9777: **
 9778: ** <dl>
 9779: ** <dt>SQLITE_CHANGESET_DATA<dd>
 9780: **   The conflict handler is invoked with CHANGESET_DATA as the second argument
 9781: **   when processing a DELETE or UPDATE change if a row with the required
 9782: **   PRIMARY KEY fields is present in the database, but one or more other 
 9783: **   (non primary-key) fields modified by the update do not contain the 
 9784: **   expected "before" values.
 9785: ** 
 9786: **   The conflicting row, in this case, is the database row with the matching
 9787: **   primary key.
 9788: ** 
 9789: ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
 9790: **   The conflict handler is invoked with CHANGESET_NOTFOUND as the second
 9791: **   argument when processing a DELETE or UPDATE change if a row with the
 9792: **   required PRIMARY KEY fields is not present in the database.
 9793: ** 
 9794: **   There is no conflicting row in this case. The results of invoking the
 9795: **   sqlite3changeset_conflict() API are undefined.
 9796: ** 
 9797: ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
 9798: **   CHANGESET_CONFLICT is passed as the second argument to the conflict
 9799: **   handler while processing an INSERT change if the operation would result 
 9800: **   in duplicate primary key values.
 9801: ** 
 9802: **   The conflicting row in this case is the database row with the matching
 9803: **   primary key.
 9804: **
 9805: ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
 9806: **   If foreign key handling is enabled, and applying a changeset leaves the
 9807: **   database in a state containing foreign key violations, the conflict 
 9808: **   handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
 9809: **   exactly once before the changeset is committed. If the conflict handler
 9810: **   returns CHANGESET_OMIT, the changes, including those that caused the
 9811: **   foreign key constraint violation, are committed. Or, if it returns
 9812: **   CHANGESET_ABORT, the changeset is rolled back.
 9813: **
 9814: **   No current or conflicting row information is provided. The only function
 9815: **   it is possible to call on the supplied sqlite3_changeset_iter handle
 9816: **   is sqlite3changeset_fk_conflicts().
 9817: ** 
 9818: ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
 9819: **   If any other constraint violation occurs while applying a change (i.e. 
 9820: **   a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is 
 9821: **   invoked with CHANGESET_CONSTRAINT as the second argument.
 9822: ** 
 9823: **   There is no conflicting row in this case. The results of invoking the
 9824: **   sqlite3changeset_conflict() API are undefined.
 9825: **
 9826: ** </dl>
 9827: */
 9828: #define SQLITE_CHANGESET_DATA        1
 9829: #define SQLITE_CHANGESET_NOTFOUND    2
 9830: #define SQLITE_CHANGESET_CONFLICT    3
 9831: #define SQLITE_CHANGESET_CONSTRAINT  4
 9832: #define SQLITE_CHANGESET_FOREIGN_KEY 5
 9833: 
 9834: /* 
 9835: ** CAPI3REF: Constants Returned By The Conflict Handler
 9836: **
 9837: ** A conflict handler callback must return one of the following three values.
 9838: **
 9839: ** <dl>
 9840: ** <dt>SQLITE_CHANGESET_OMIT<dd>
 9841: **   If a conflict handler returns this value no special action is taken. The
 9842: **   change that caused the conflict is not applied. The session module 
 9843: **   continues to the next change in the changeset.
 9844: **
 9845: ** <dt>SQLITE_CHANGESET_REPLACE<dd>
 9846: **   This value may only be returned if the second argument to the conflict
 9847: **   handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
 9848: **   is not the case, any changes applied so far are rolled back and the 
 9849: **   call to sqlite3changeset_apply() returns SQLITE_MISUSE.
 9850: **
 9851: **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
 9852: **   handler, then the conflicting row is either updated or deleted, depending
 9853: **   on the type of change.
 9854: **
 9855: **   If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
 9856: **   handler, then the conflicting row is removed from the database and a
 9857: **   second attempt to apply the change is made. If this second attempt fails,
 9858: **   the original row is restored to the database before continuing.
 9859: **
 9860: ** <dt>SQLITE_CHANGESET_ABORT<dd>
 9861: **   If this value is returned, any changes applied so far are rolled back 
 9862: **   and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
 9863: ** </dl>
 9864: */
 9865: #define SQLITE_CHANGESET_OMIT       0
 9866: #define SQLITE_CHANGESET_REPLACE    1
 9867: #define SQLITE_CHANGESET_ABORT      2
 9868: 
 9869: /*
 9870: ** CAPI3REF: Streaming Versions of API functions.
 9871: **
 9872: ** The six streaming API xxx_strm() functions serve similar purposes to the 
 9873: ** corresponding non-streaming API functions:
 9874: **
 9875: ** <table border=1 style="margin-left:8ex;margin-right:8ex">
 9876: **   <tr><th>Streaming function<th>Non-streaming equivalent</th>
 9877: **   <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply] 
 9878: **   <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat] 
 9879: **   <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert] 
 9880: **   <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start] 
 9881: **   <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset] 
 9882: **   <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset] 
 9883: ** </table>
 9884: **
 9885: ** Non-streaming functions that accept changesets (or patchsets) as input
 9886: ** require that the entire changeset be stored in a single buffer in memory. 
 9887: ** Similarly, those that return a changeset or patchset do so by returning 
 9888: ** a pointer to a single large buffer allocated using sqlite3_malloc(). 
 9889: ** Normally this is convenient. However, if an application running in a 
 9890: ** low-memory environment is required to handle very large changesets, the
 9891: ** large contiguous memory allocations required can become onerous.
 9892: **
 9893: ** In order to avoid this problem, instead of a single large buffer, input
 9894: ** is passed to a streaming API functions by way of a callback function that
 9895: ** the sessions module invokes to incrementally request input data as it is
 9896: ** required. In all cases, a pair of API function parameters such as
 9897: **
 9898: **  <pre>
 9899: **  &nbsp;     int nChangeset,
 9900: **  &nbsp;     void *pChangeset,
 9901: **  </pre>
 9902: **
 9903: ** Is replaced by:
 9904: **
 9905: **  <pre>
 9906: **  &nbsp;     int (*xInput)(void *pIn, void *pData, int *pnData),
 9907: **  &nbsp;     void *pIn,
 9908: **  </pre>
 9909: **
 9910: ** Each time the xInput callback is invoked by the sessions module, the first
 9911: ** argument passed is a copy of the supplied pIn context pointer. The second 
 9912: ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no 
 9913: ** error occurs the xInput method should copy up to (*pnData) bytes of data 
 9914: ** into the buffer and set (*pnData) to the actual number of bytes copied 
 9915: ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData) 
 9916: ** should be set to zero to indicate this. Or, if an error occurs, an SQLite 
 9917: ** error code should be returned. In all cases, if an xInput callback returns
 9918: ** an error, all processing is abandoned and the streaming API function
 9919: ** returns a copy of the error code to the caller.
 9920: **
 9921: ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
 9922: ** invoked by the sessions module at any point during the lifetime of the
 9923: ** iterator. If such an xInput callback returns an error, the iterator enters
 9924: ** an error state, whereby all subsequent calls to iterator functions 
 9925: ** immediately fail with the same error code as returned by xInput.
 9926: **
 9927: ** Similarly, streaming API functions that return changesets (or patchsets)
 9928: ** return them in chunks by way of a callback function instead of via a
 9929: ** pointer to a single large buffer. In this case, a pair of parameters such
 9930: ** as:
 9931: **
 9932: **  <pre>
 9933: **  &nbsp;     int *pnChangeset,
 9934: **  &nbsp;     void **ppChangeset,
 9935: **  </pre>
 9936: **
 9937: ** Is replaced by:
 9938: **
 9939: **  <pre>
 9940: **  &nbsp;     int (*xOutput)(void *pOut, const void *pData, int nData),
 9941: **  &nbsp;     void *pOut
 9942: **  </pre>
 9943: **
 9944: ** The xOutput callback is invoked zero or more times to return data to
 9945: ** the application. The first parameter passed to each call is a copy of the
 9946: ** pOut pointer supplied by the application. The second parameter, pData,
 9947: ** points to a buffer nData bytes in size containing the chunk of output
 9948: ** data being returned. If the xOutput callback successfully processes the
 9949: ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
 9950: ** it should return some other SQLite error code. In this case processing
 9951: ** is immediately abandoned and the streaming API function returns a copy
 9952: ** of the xOutput error code to the application.
 9953: **
 9954: ** The sessions module never invokes an xOutput callback with the third 
 9955: ** parameter set to a value less than or equal to zero. Other than this,
 9956: ** no guarantees are made as to the size of the chunks of data returned.
 9957: */
 9958: int sqlite3changeset_apply_strm(
 9959:   sqlite3 *db,                    /* Apply change to "main" db of this handle */
 9960:   int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
 9961:   void *pIn,                                          /* First arg for xInput */
 9962:   int(*xFilter)(
 9963:     void *pCtx,                   /* Copy of sixth arg to _apply() */
 9964:     const char *zTab              /* Table name */
 9965:   ),
 9966:   int(*xConflict)(
 9967:     void *pCtx,                   /* Copy of sixth arg to _apply() */
 9968:     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
 9969:     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
 9970:   ),
 9971:   void *pCtx                      /* First argument passed to xConflict */
 9972: );
 9973: int sqlite3changeset_concat_strm(
 9974:   int (*xInputA)(void *pIn, void *pData, int *pnData),
 9975:   void *pInA,
 9976:   int (*xInputB)(void *pIn, void *pData, int *pnData),
 9977:   void *pInB,
 9978:   int (*xOutput)(void *pOut, const void *pData, int nData),
 9979:   void *pOut
 9980: );
 9981: int sqlite3changeset_invert_strm(
 9982:   int (*xInput)(void *pIn, void *pData, int *pnData),
 9983:   void *pIn,
 9984:   int (*xOutput)(void *pOut, const void *pData, int nData),
 9985:   void *pOut
 9986: );
 9987: int sqlite3changeset_start_strm(
 9988:   sqlite3_changeset_iter **pp,
 9989:   int (*xInput)(void *pIn, void *pData, int *pnData),
 9990:   void *pIn
 9991: );
 9992: int sqlite3session_changeset_strm(
 9993:   sqlite3_session *pSession,
 9994:   int (*xOutput)(void *pOut, const void *pData, int nData),
 9995:   void *pOut
 9996: );
 9997: int sqlite3session_patchset_strm(
 9998:   sqlite3_session *pSession,
 9999:   int (*xOutput)(void *pOut, const void *pData, int nData),
10000:   void *pOut
10001: );
10002: int sqlite3changegroup_add_strm(sqlite3_changegroup*, 
10003:     int (*xInput)(void *pIn, void *pData, int *pnData),
10004:     void *pIn
10005: );
10006: int sqlite3changegroup_output_strm(sqlite3_changegroup*,
10007:     int (*xOutput)(void *pOut, const void *pData, int nData), 
10008:     void *pOut
10009: );
10010: 
10011: 
10012: /*
10013: ** Make sure we can call this stuff from C++.
10014: */
10015: #if 0
10016: }
10017: #endif
10018: 
10019: #endif  /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
10020: 
10021: /******** End of sqlite3session.h *********/
10022: /******** Begin file fts5.h *********/
10023: /*
10024: ** 2014 May 31
10025: **
10026: ** The author disclaims copyright to this source code.  In place of
10027: ** a legal notice, here is a blessing:
10028: **
10029: **    May you do good and not evil.
10030: **    May you find forgiveness for yourself and forgive others.
10031: **    May you share freely, never taking more than you give.
10032: **
10033: ******************************************************************************
10034: **
10035: ** Interfaces to extend FTS5. Using the interfaces defined in this file, 
10036: ** FTS5 may be extended with:
10037: **
10038: **     * custom tokenizers, and
10039: **     * custom auxiliary functions.
10040: */
10041: 
10042: 
10043: #ifndef _FTS5_H
10044: #define _FTS5_H
10045: 
10046: 
10047: #if 0
10048: extern "C" {
10049: #endif
10050: 
10051: /*************************************************************************
10052: ** CUSTOM AUXILIARY FUNCTIONS
10053: **
10054: ** Virtual table implementations may overload SQL functions by implementing
10055: ** the sqlite3_module.xFindFunction() method.
10056: */
10057: 
10058: typedef struct Fts5ExtensionApi Fts5ExtensionApi;
10059: typedef struct Fts5Context Fts5Context;
10060: typedef struct Fts5PhraseIter Fts5PhraseIter;
10061: 
10062: typedef void (*fts5_extension_function)(
10063:   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
10064:   Fts5Context *pFts,              /* First arg to pass to pApi functions */
10065:   sqlite3_context *pCtx,          /* Context for returning result/error */
10066:   int nVal,                       /* Number of values in apVal[] array */
10067:   sqlite3_value **apVal           /* Array of trailing arguments */
10068: );
10069: 
10070: struct Fts5PhraseIter {
10071:   const unsigned char *a;
10072:   const unsigned char *b;
10073: };
10074: 
10075: /*
10076: ** EXTENSION API FUNCTIONS
10077: **
10078: ** xUserData(pFts):
10079: **   Return a copy of the context pointer the extension function was 
10080: **   registered with.
10081: **
10082: ** xColumnTotalSize(pFts, iCol, pnToken):
10083: **   If parameter iCol is less than zero, set output variable *pnToken
10084: **   to the total number of tokens in the FTS5 table. Or, if iCol is
10085: **   non-negative but less than the number of columns in the table, return
10086: **   the total number of tokens in column iCol, considering all rows in 
10087: **   the FTS5 table.
10088: **
10089: **   If parameter iCol is greater than or equal to the number of columns
10090: **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10091: **   an OOM condition or IO error), an appropriate SQLite error code is 
10092: **   returned.
10093: **
10094: ** xColumnCount(pFts):
10095: **   Return the number of columns in the table.
10096: **
10097: ** xColumnSize(pFts, iCol, pnToken):
10098: **   If parameter iCol is less than zero, set output variable *pnToken
10099: **   to the total number of tokens in the current row. Or, if iCol is
10100: **   non-negative but less than the number of columns in the table, set
10101: **   *pnToken to the number of tokens in column iCol of the current row.
10102: **
10103: **   If parameter iCol is greater than or equal to the number of columns
10104: **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
10105: **   an OOM condition or IO error), an appropriate SQLite error code is 
10106: **   returned.
10107: **
10108: **   This function may be quite inefficient if used with an FTS5 table
10109: **   created with the "columnsize=0" option.
10110: **
10111: ** xColumnText:
10112: **   This function attempts to retrieve the text of column iCol of the
10113: **   current document. If successful, (*pz) is set to point to a buffer
10114: **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
10115: **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
10116: **   if an error occurs, an SQLite error code is returned and the final values
10117: **   of (*pz) and (*pn) are undefined.
10118: **
10119: ** xPhraseCount:
10120: **   Returns the number of phrases in the current query expression.
10121: **
10122: ** xPhraseSize:
10123: **   Returns the number of tokens in phrase iPhrase of the query. Phrases
10124: **   are numbered starting from zero.
10125: **
10126: ** xInstCount:
10127: **   Set *pnInst to the total number of occurrences of all phrases within
10128: **   the query within the current row. Return SQLITE_OK if successful, or
10129: **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
10130: **
10131: **   This API can be quite slow if used with an FTS5 table created with the
10132: **   "detail=none" or "detail=column" option. If the FTS5 table is created 
10133: **   with either "detail=none" or "detail=column" and "content=" option 
10134: **   (i.e. if it is a contentless table), then this API always returns 0.
10135: **
10136: ** xInst:
10137: **   Query for the details of phrase match iIdx within the current row.
10138: **   Phrase matches are numbered starting from zero, so the iIdx argument
10139: **   should be greater than or equal to zero and smaller than the value
10140: **   output by xInstCount().
10141: **
10142: **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
10143: **   to the column in which it occurs and *piOff the token offset of the
10144: **   first token of the phrase. The exception is if the table was created
10145: **   with the offsets=0 option specified. In this case *piOff is always
10146: **   set to -1.
10147: **
10148: **   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) 
10149: **   if an error occurs.
10150: **
10151: **   This API can be quite slow if used with an FTS5 table created with the
10152: **   "detail=none" or "detail=column" option. 
10153: **
10154: ** xRowid:
10155: **   Returns the rowid of the current row.
10156: **
10157: ** xTokenize:
10158: **   Tokenize text using the tokenizer belonging to the FTS5 table.
10159: **
10160: ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
10161: **   This API function is used to query the FTS table for phrase iPhrase
10162: **   of the current query. Specifically, a query equivalent to:
10163: **
10164: **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10165: **
10166: **   with $p set to a phrase equivalent to the phrase iPhrase of the
10167: **   current query is executed. Any column filter that applies to
10168: **   phrase iPhrase of the current query is included in $p. For each 
10169: **   row visited, the callback function passed as the fourth argument 
10170: **   is invoked. The context and API objects passed to the callback 
10171: **   function may be used to access the properties of each matched row.
10172: **   Invoking Api.xUserData() returns a copy of the pointer passed as 
10173: **   the third argument to pUserData.
10174: **
10175: **   If the callback function returns any value other than SQLITE_OK, the
10176: **   query is abandoned and the xQueryPhrase function returns immediately.
10177: **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10178: **   Otherwise, the error code is propagated upwards.
10179: **
10180: **   If the query runs to completion without incident, SQLITE_OK is returned.
10181: **   Or, if some error occurs before the query completes or is aborted by
10182: **   the callback, an SQLite error code is returned.
10183: **
10184: **
10185: ** xSetAuxdata(pFts5, pAux, xDelete)
10186: **
10187: **   Save the pointer passed as the second argument as the extension functions 
10188: **   "auxiliary data". The pointer may then be retrieved by the current or any
10189: **   future invocation of the same fts5 extension function made as part of
10190: **   of the same MATCH query using the xGetAuxdata() API.
10191: **
10192: **   Each extension function is allocated a single auxiliary data slot for
10193: **   each FTS query (MATCH expression). If the extension function is invoked 
10194: **   more than once for a single FTS query, then all invocations share a 
10195: **   single auxiliary data context.
10196: **
10197: **   If there is already an auxiliary data pointer when this function is
10198: **   invoked, then it is replaced by the new pointer. If an xDelete callback
10199: **   was specified along with the original pointer, it is invoked at this
10200: **   point.
10201: **
10202: **   The xDelete callback, if one is specified, is also invoked on the
10203: **   auxiliary data pointer after the FTS5 query has finished.
10204: **
10205: **   If an error (e.g. an OOM condition) occurs within this function, an
10206: **   the auxiliary data is set to NULL and an error code returned. If the
10207: **   xDelete parameter was not NULL, it is invoked on the auxiliary data
10208: **   pointer before returning.
10209: **
10210: **
10211: ** xGetAuxdata(pFts5, bClear)
10212: **
10213: **   Returns the current auxiliary data pointer for the fts5 extension 
10214: **   function. See the xSetAuxdata() method for details.
10215: **
10216: **   If the bClear argument is non-zero, then the auxiliary data is cleared
10217: **   (set to NULL) before this function returns. In this case the xDelete,
10218: **   if any, is not invoked.
10219: **
10220: **
10221: ** xRowCount(pFts5, pnRow)
10222: **
10223: **   This function is used to retrieve the total number of rows in the table.
10224: **   In other words, the same value that would be returned by:
10225: **
10226: **        SELECT count(*) FROM ftstable;
10227: **
10228: ** xPhraseFirst()
10229: **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
10230: **   method, to iterate through all instances of a single query phrase within
10231: **   the current row. This is the same information as is accessible via the
10232: **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
10233: **   to use, this API may be faster under some circumstances. To iterate 
10234: **   through instances of phrase iPhrase, use the following code:
10235: **
10236: **       Fts5PhraseIter iter;
10237: **       int iCol, iOff;
10238: **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
10239: **           iCol>=0;
10240: **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
10241: **       ){
10242: **         // An instance of phrase iPhrase at offset iOff of column iCol
10243: **       }
10244: **
10245: **   The Fts5PhraseIter structure is defined above. Applications should not
10246: **   modify this structure directly - it should only be used as shown above
10247: **   with the xPhraseFirst() and xPhraseNext() API methods (and by
10248: **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
10249: **
10250: **   This API can be quite slow if used with an FTS5 table created with the
10251: **   "detail=none" or "detail=column" option. If the FTS5 table is created 
10252: **   with either "detail=none" or "detail=column" and "content=" option 
10253: **   (i.e. if it is a contentless table), then this API always iterates
10254: **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
10255: **
10256: ** xPhraseNext()
10257: **   See xPhraseFirst above.
10258: **
10259: ** xPhraseFirstColumn()
10260: **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
10261: **   and xPhraseNext() APIs described above. The difference is that instead
10262: **   of iterating through all instances of a phrase in the current row, these
10263: **   APIs are used to iterate through the set of columns in the current row
10264: **   that contain one or more instances of a specified phrase. For example:
10265: **
10266: **       Fts5PhraseIter iter;
10267: **       int iCol;
10268: **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
10269: **           iCol>=0;
10270: **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
10271: **       ){
10272: **         // Column iCol contains at least one instance of phrase iPhrase
10273: **       }
10274: **
10275: **   This API can be quite slow if used with an FTS5 table created with the
10276: **   "detail=none" option. If the FTS5 table is created with either 
10277: **   "detail=none" "content=" option (i.e. if it is a contentless table), 
10278: **   then this API always iterates through an empty set (all calls to 
10279: **   xPhraseFirstColumn() set iCol to -1).
10280: **
10281: **   The information accessed using this API and its companion
10282: **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
10283: **   (or xInst/xInstCount). The chief advantage of this API is that it is
10284: **   significantly more efficient than those alternatives when used with
10285: **   "detail=column" tables.  
10286: **
10287: ** xPhraseNextColumn()
10288: **   See xPhraseFirstColumn above.
10289: */
10290: struct Fts5ExtensionApi {
10291:   int iVersion;                   /* Currently always set to 3 */
10292: 
10293:   void *(*xUserData)(Fts5Context*);
10294: 
10295:   int (*xColumnCount)(Fts5Context*);
10296:   int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
10297:   int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
10298: 
10299:   int (*xTokenize)(Fts5Context*, 
10300:     const char *pText, int nText, /* Text to tokenize */
10301:     void *pCtx,                   /* Context passed to xToken() */
10302:     int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
10303:   );
10304: 
10305:   int (*xPhraseCount)(Fts5Context*);
10306:   int (*xPhraseSize)(Fts5Context*, int iPhrase);
10307: 
10308:   int (*xInstCount)(Fts5Context*, int *pnInst);
10309:   int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
10310: 
10311:   sqlite3_int64 (*xRowid)(Fts5Context*);
10312:   int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
10313:   int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
10314: 
10315:   int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
10316:     int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
10317:   );
10318:   int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
10319:   void *(*xGetAuxdata)(Fts5Context*, int bClear);
10320: 
10321:   int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
10322:   void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
10323: 
10324:   int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
10325:   void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
10326: };
10327: 
10328: /* 
10329: ** CUSTOM AUXILIARY FUNCTIONS
10330: *************************************************************************/
10331: 
10332: /*************************************************************************
10333: ** CUSTOM TOKENIZERS
10334: **
10335: ** Applications may also register custom tokenizer types. A tokenizer 
10336: ** is registered by providing fts5 with a populated instance of the 
10337: ** following structure. All structure methods must be defined, setting
10338: ** any member of the fts5_tokenizer struct to NULL leads to undefined
10339: ** behaviour. The structure methods are expected to function as follows:
10340: **
10341: ** xCreate:
10342: **   This function is used to allocate and initialize a tokenizer instance.
10343: **   A tokenizer instance is required to actually tokenize text.
10344: **
10345: **   The first argument passed to this function is a copy of the (void*)
10346: **   pointer provided by the application when the fts5_tokenizer object
10347: **   was registered with FTS5 (the third argument to xCreateTokenizer()). 
10348: **   The second and third arguments are an array of nul-terminated strings
10349: **   containing the tokenizer arguments, if any, specified following the
10350: **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
10351: **   to create the FTS5 table.
10352: **
10353: **   The final argument is an output variable. If successful, (*ppOut) 
10354: **   should be set to point to the new tokenizer handle and SQLITE_OK
10355: **   returned. If an error occurs, some value other than SQLITE_OK should
10356: **   be returned. In this case, fts5 assumes that the final value of *ppOut 
10357: **   is undefined.
10358: **
10359: ** xDelete:
10360: **   This function is invoked to delete a tokenizer handle previously
10361: **   allocated using xCreate(). Fts5 guarantees that this function will
10362: **   be invoked exactly once for each successful call to xCreate().
10363: **
10364: ** xTokenize:
10365: **   This function is expected to tokenize the nText byte string indicated 
10366: **   by argument pText. pText may or may not be nul-terminated. The first
10367: **   argument passed to this function is a pointer to an Fts5Tokenizer object
10368: **   returned by an earlier call to xCreate().
10369: **
10370: **   The second argument indicates the reason that FTS5 is requesting
10371: **   tokenization of the supplied text. This is always one of the following
10372: **   four values:
10373: **
10374: **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
10375: **            or removed from the FTS table. The tokenizer is being invoked to
10376: **            determine the set of tokens to add to (or delete from) the
10377: **            FTS index.
10378: **
10379: **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
10380: **            against the FTS index. The tokenizer is being called to tokenize 
10381: **            a bareword or quoted string specified as part of the query.
10382: **
10383: **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
10384: **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
10385: **            followed by a "*" character, indicating that the last token
10386: **            returned by the tokenizer will be treated as a token prefix.
10387: **
10388: **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
10389: **            satisfy an fts5_api.xTokenize() request made by an auxiliary
10390: **            function. Or an fts5_api.xColumnSize() request made by the same
10391: **            on a columnsize=0 database.  
10392: **   </ul>
10393: **
10394: **   For each token in the input string, the supplied callback xToken() must
10395: **   be invoked. The first argument to it should be a copy of the pointer
10396: **   passed as the second argument to xTokenize(). The third and fourth
10397: **   arguments are a pointer to a buffer containing the token text, and the
10398: **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
10399: **   of the first byte of and first byte immediately following the text from
10400: **   which the token is derived within the input.
10401: **
10402: **   The second argument passed to the xToken() callback ("tflags") should
10403: **   normally be set to 0. The exception is if the tokenizer supports 
10404: **   synonyms. In this case see the discussion below for details.
10405: **
10406: **   FTS5 assumes the xToken() callback is invoked for each token in the 
10407: **   order that they occur within the input text.
10408: **
10409: **   If an xToken() callback returns any value other than SQLITE_OK, then
10410: **   the tokenization should be abandoned and the xTokenize() method should
10411: **   immediately return a copy of the xToken() return value. Or, if the
10412: **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
10413: **   if an error occurs with the xTokenize() implementation itself, it
10414: **   may abandon the tokenization and return any error code other than
10415: **   SQLITE_OK or SQLITE_DONE.
10416: **
10417: ** SYNONYM SUPPORT
10418: **
10419: **   Custom tokenizers may also support synonyms. Consider a case in which a
10420: **   user wishes to query for a phrase such as "first place". Using the 
10421: **   built-in tokenizers, the FTS5 query 'first + place' will match instances
10422: **   of "first place" within the document set, but not alternative forms
10423: **   such as "1st place". In some applications, it would be better to match
10424: **   all instances of "first place" or "1st place" regardless of which form
10425: **   the user specified in the MATCH query text.
10426: **
10427: **   There are several ways to approach this in FTS5:
10428: **
10429: **   <ol><li> By mapping all synonyms to a single token. In this case, the 
10430: **            In the above example, this means that the tokenizer returns the
10431: **            same token for inputs "first" and "1st". Say that token is in
10432: **            fact "first", so that when the user inserts the document "I won
10433: **            1st place" entries are added to the index for tokens "i", "won",
10434: **            "first" and "place". If the user then queries for '1st + place',
10435: **            the tokenizer substitutes "first" for "1st" and the query works
10436: **            as expected.
10437: **
10438: **       <li> By adding multiple synonyms for a single term to the FTS index.
10439: **            In this case, when tokenizing query text, the tokenizer may 
10440: **            provide multiple synonyms for a single term within the document.
10441: **            FTS5 then queries the index for each synonym individually. For
10442: **            example, faced with the query:
10443: **
10444: **   <codeblock>
10445: **     ... MATCH 'first place'</codeblock>
10446: **
10447: **            the tokenizer offers both "1st" and "first" as synonyms for the
10448: **            first token in the MATCH query and FTS5 effectively runs a query 
10449: **            similar to:
10450: **
10451: **   <codeblock>
10452: **     ... MATCH '(first OR 1st) place'</codeblock>
10453: **
10454: **            except that, for the purposes of auxiliary functions, the query
10455: **            still appears to contain just two phrases - "(first OR 1st)" 
10456: **            being treated as a single phrase.
10457: **
10458: **       <li> By adding multiple synonyms for a single term to the FTS index.
10459: **            Using this method, when tokenizing document text, the tokenizer
10460: **            provides multiple synonyms for each token. So that when a 
10461: **            document such as "I won first place" is tokenized, entries are
10462: **            added to the FTS index for "i", "won", "first", "1st" and
10463: **            "place".
10464: **
10465: **            This way, even if the tokenizer does not provide synonyms
10466: **            when tokenizing query text (it should not - to do would be
10467: **            inefficient), it doesn't matter if the user queries for 
10468: **            'first + place' or '1st + place', as there are entires in the
10469: **            FTS index corresponding to both forms of the first token.
10470: **   </ol>
10471: **
10472: **   Whether it is parsing document or query text, any call to xToken that
10473: **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
10474: **   is considered to supply a synonym for the previous token. For example,
10475: **   when parsing the document "I won first place", a tokenizer that supports
10476: **   synonyms would call xToken() 5 times, as follows:
10477: **
10478: **   <codeblock>
10479: **       xToken(pCtx, 0, "i",                      1,  0,  1);
10480: **       xToken(pCtx, 0, "won",                    3,  2,  5);
10481: **       xToken(pCtx, 0, "first",                  5,  6, 11);
10482: **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
10483: **       xToken(pCtx, 0, "place",                  5, 12, 17);
10484: **</codeblock>
10485: **
10486: **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
10487: **   xToken() is called. Multiple synonyms may be specified for a single token
10488: **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
10489: **   There is no limit to the number of synonyms that may be provided for a
10490: **   single token.
10491: **
10492: **   In many cases, method (1) above is the best approach. It does not add 
10493: **   extra data to the FTS index or require FTS5 to query for multiple terms,
10494: **   so it is efficient in terms of disk space and query speed. However, it
10495: **   does not support prefix queries very well. If, as suggested above, the
10496: **   token "first" is subsituted for "1st" by the tokenizer, then the query:
10497: **
10498: **   <codeblock>
10499: **     ... MATCH '1s*'</codeblock>
10500: **
10501: **   will not match documents that contain the token "1st" (as the tokenizer
10502: **   will probably not map "1s" to any prefix of "first").
10503: **
10504: **   For full prefix support, method (3) may be preferred. In this case, 
10505: **   because the index contains entries for both "first" and "1st", prefix
10506: **   queries such as 'fi*' or '1s*' will match correctly. However, because
10507: **   extra entries are added to the FTS index, this method uses more space
10508: **   within the database.
10509: **
10510: **   Method (2) offers a midpoint between (1) and (3). Using this method,
10511: **   a query such as '1s*' will match documents that contain the literal 
10512: **   token "1st", but not "first" (assuming the tokenizer is not able to
10513: **   provide synonyms for prefixes). However, a non-prefix query like '1st'
10514: **   will match against "1st" and "first". This method does not require
10515: **   extra disk space, as no extra entries are added to the FTS index. 
10516: **   On the other hand, it may require more CPU cycles to run MATCH queries,
10517: **   as separate queries of the FTS index are required for each synonym.
10518: **
10519: **   When using methods (2) or (3), it is important that the tokenizer only
10520: **   provide synonyms when tokenizing document text (method (2)) or query
10521: **   text (method (3)), not both. Doing so will not cause any errors, but is
10522: **   inefficient.
10523: */
10524: typedef struct Fts5Tokenizer Fts5Tokenizer;
10525: typedef struct fts5_tokenizer fts5_tokenizer;
10526: struct fts5_tokenizer {
10527:   int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
10528:   void (*xDelete)(Fts5Tokenizer*);
10529:   int (*xTokenize)(Fts5Tokenizer*, 
10530:       void *pCtx,
10531:       int flags,            /* Mask of FTS5_TOKENIZE_* flags */
10532:       const char *pText, int nText, 
10533:       int (*xToken)(
10534:         void *pCtx,         /* Copy of 2nd argument to xTokenize() */
10535:         int tflags,         /* Mask of FTS5_TOKEN_* flags */
10536:         const char *pToken, /* Pointer to buffer containing token */
10537:         int nToken,         /* Size of token in bytes */
10538:         int iStart,         /* Byte offset of token within input text */
10539:         int iEnd            /* Byte offset of end of token within input text */
10540:       )
10541:   );
10542: };
10543: 
10544: /* Flags that may be passed as the third argument to xTokenize() */
10545: #define FTS5_TOKENIZE_QUERY     0x0001
10546: #define FTS5_TOKENIZE_PREFIX    0x0002
10547: #define FTS5_TOKENIZE_DOCUMENT  0x0004
10548: #define FTS5_TOKENIZE_AUX       0x0008
10549: 
10550: /* Flags that may be passed by the tokenizer implementation back to FTS5
10551: ** as the third argument to the supplied xToken callback. */
10552: #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
10553: 
10554: /*
10555: ** END OF CUSTOM TOKENIZERS
10556: *************************************************************************/
10557: 
10558: /*************************************************************************
10559: ** FTS5 EXTENSION REGISTRATION API
10560: */
10561: typedef struct fts5_api fts5_api;
10562: struct fts5_api {
10563:   int iVersion;                   /* Currently always set to 2 */
10564: 
10565:   /* Create a new tokenizer */
10566:   int (*xCreateTokenizer)(
10567:     fts5_api *pApi,
10568:     const char *zName,
10569:     void *pContext,
10570:     fts5_tokenizer *pTokenizer,
10571:     void (*xDestroy)(void*)
10572:   );
10573: 
10574:   /* Find an existing tokenizer */
10575:   int (*xFindTokenizer)(
10576:     fts5_api *pApi,
10577:     const char *zName,
10578:     void **ppContext,
10579:     fts5_tokenizer *pTokenizer
10580:   );
10581: 
10582:   /* Create a new auxiliary function */
10583:   int (*xCreateFunction)(
10584:     fts5_api *pApi,
10585:     const char *zName,
10586:     void *pContext,
10587:     fts5_extension_function xFunction,
10588:     void (*xDestroy)(void*)
10589:   );
10590: };
10591: 
10592: /*
10593: ** END OF REGISTRATION API
10594: *************************************************************************/
10595: 
10596: #if 0
10597: }  /* end of the 'extern "C"' block */
10598: #endif
10599: 
10600: #endif /* _FTS5_H */
10601: 
10602: /******** End of fts5.h *********/
10603: 
10604: /************** End of sqlite3.h *********************************************/
10605: /************** Continuing where we left off in sqliteInt.h ******************/
10606: 
10607: /*
10608: ** Include the configuration header output by 'configure' if we're using the
10609: ** autoconf-based build
10610: */
10611: #ifdef _HAVE_SQLITE_CONFIG_H
10612: #include "config.h"
10613: #endif
10614: 
10615: /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
10616: /************** Begin file sqliteLimit.h *************************************/
10617: /*
10618: ** 2007 May 7
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 defines various limits of what SQLite can process.
10630: */
10631: 
10632: /*
10633: ** The maximum length of a TEXT or BLOB in bytes.   This also
10634: ** limits the size of a row in a table or index.
10635: **
10636: ** The hard limit is the ability of a 32-bit signed integer
10637: ** to count the size: 2^31-1 or 2147483647.
10638: */
10639: #ifndef SQLITE_MAX_LENGTH
10640: # define SQLITE_MAX_LENGTH 1000000000
10641: #endif
10642: 
10643: /*
10644: ** This is the maximum number of
10645: **
10646: **    * Columns in a table
10647: **    * Columns in an index
10648: **    * Columns in a view
10649: **    * Terms in the SET clause of an UPDATE statement
10650: **    * Terms in the result set of a SELECT statement
10651: **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
10652: **    * Terms in the VALUES clause of an INSERT statement
10653: **
10654: ** The hard upper limit here is 32676.  Most database people will
10655: ** tell you that in a well-normalized database, you usually should
10656: ** not have more than a dozen or so columns in any table.  And if
10657: ** that is the case, there is no point in having more than a few
10658: ** dozen values in any of the other situations described above.
10659: */
10660: #ifndef SQLITE_MAX_COLUMN
10661: # define SQLITE_MAX_COLUMN 2000
10662: #endif
10663: 
10664: /*
10665: ** The maximum length of a single SQL statement in bytes.
10666: **
10667: ** It used to be the case that setting this value to zero would
10668: ** turn the limit off.  That is no longer true.  It is not possible
10669: ** to turn this limit off.
10670: */
10671: #ifndef SQLITE_MAX_SQL_LENGTH
10672: # define SQLITE_MAX_SQL_LENGTH 1000000000
10673: #endif
10674: 
10675: /*
10676: ** The maximum depth of an expression tree. This is limited to 
10677: ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
10678: ** want to place more severe limits on the complexity of an 
10679: ** expression.
10680: **
10681: ** A value of 0 used to mean that the limit was not enforced.
10682: ** But that is no longer true.  The limit is now strictly enforced
10683: ** at all times.
10684: */
10685: #ifndef SQLITE_MAX_EXPR_DEPTH
10686: # define SQLITE_MAX_EXPR_DEPTH 1000
10687: #endif
10688: 
10689: /*
10690: ** The maximum number of terms in a compound SELECT statement.
10691: ** The code generator for compound SELECT statements does one
10692: ** level of recursion for each term.  A stack overflow can result
10693: ** if the number of terms is too large.  In practice, most SQL
10694: ** never has more than 3 or 4 terms.  Use a value of 0 to disable
10695: ** any limit on the number of terms in a compount SELECT.
10696: */
10697: #ifndef SQLITE_MAX_COMPOUND_SELECT
10698: # define SQLITE_MAX_COMPOUND_SELECT 500
10699: #endif
10700: 
10701: /*
10702: ** The maximum number of opcodes in a VDBE program.
10703: ** Not currently enforced.
10704: */
10705: #ifndef SQLITE_MAX_VDBE_OP
10706: # define SQLITE_MAX_VDBE_OP 25000
10707: #endif
10708: 
10709: /*
10710: ** The maximum number of arguments to an SQL function.
10711: */
10712: #ifndef SQLITE_MAX_FUNCTION_ARG
10713: # define SQLITE_MAX_FUNCTION_ARG 127
10714: #endif
10715: 
10716: /*
10717: ** The suggested maximum number of in-memory pages to use for
10718: ** the main database table and for temporary tables.
10719: **
10720: ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
10721: ** which means the cache size is limited to 2048000 bytes of memory.
10722: ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
10723: ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
10724: */
10725: #ifndef SQLITE_DEFAULT_CACHE_SIZE
10726: # define SQLITE_DEFAULT_CACHE_SIZE  -2000
10727: #endif
10728: 
10729: /*
10730: ** The default number of frames to accumulate in the log file before
10731: ** checkpointing the database in WAL mode.
10732: */
10733: #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
10734: # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
10735: #endif
10736: 
10737: /*
10738: ** The maximum number of attached databases.  This must be between 0
10739: ** and 125.  The upper bound of 125 is because the attached databases are
10740: ** counted using a signed 8-bit integer which has a maximum value of 127
10741: ** and we have to allow 2 extra counts for the "main" and "temp" databases.
10742: */
10743: #ifndef SQLITE_MAX_ATTACHED
10744: # define SQLITE_MAX_ATTACHED 10
10745: #endif
10746: 
10747: 
10748: /*
10749: ** The maximum value of a ?nnn wildcard that the parser will accept.
10750: */
10751: #ifndef SQLITE_MAX_VARIABLE_NUMBER
10752: # define SQLITE_MAX_VARIABLE_NUMBER 999
10753: #endif
10754: 
10755: /* Maximum page size.  The upper bound on this value is 65536.  This a limit
10756: ** imposed by the use of 16-bit offsets within each page.
10757: **
10758: ** Earlier versions of SQLite allowed the user to change this value at
10759: ** compile time. This is no longer permitted, on the grounds that it creates
10760: ** a library that is technically incompatible with an SQLite library 
10761: ** compiled with a different limit. If a process operating on a database 
10762: ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
10763: ** compiled with the default page-size limit will not be able to rollback 
10764: ** the aborted transaction. This could lead to database corruption.
10765: */
10766: #ifdef SQLITE_MAX_PAGE_SIZE
10767: # undef SQLITE_MAX_PAGE_SIZE
10768: #endif
10769: #define SQLITE_MAX_PAGE_SIZE 65536
10770: 
10771: 
10772: /*
10773: ** The default size of a database page.
10774: */
10775: #ifndef SQLITE_DEFAULT_PAGE_SIZE
10776: # define SQLITE_DEFAULT_PAGE_SIZE 4096
10777: #endif
10778: #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10779: # undef SQLITE_DEFAULT_PAGE_SIZE
10780: # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10781: #endif
10782: 
10783: /*
10784: ** Ordinarily, if no value is explicitly provided, SQLite creates databases
10785: ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
10786: ** device characteristics (sector-size and atomic write() support),
10787: ** SQLite may choose a larger value. This constant is the maximum value
10788: ** SQLite will choose on its own.
10789: */
10790: #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
10791: # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
10792: #endif
10793: #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10794: # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
10795: # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10796: #endif
10797: 
10798: 
10799: /*
10800: ** Maximum number of pages in one database file.
10801: **
10802: ** This is really just the default value for the max_page_count pragma.
10803: ** This value can be lowered (or raised) at run-time using that the
10804: ** max_page_count macro.
10805: */
10806: #ifndef SQLITE_MAX_PAGE_COUNT
10807: # define SQLITE_MAX_PAGE_COUNT 1073741823
10808: #endif
10809: 
10810: /*
10811: ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
10812: ** operator.
10813: */
10814: #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
10815: # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
10816: #endif
10817: 
10818: /*
10819: ** Maximum depth of recursion for triggers.
10820: **
10821: ** A value of 1 means that a trigger program will not be able to itself
10822: ** fire any triggers. A value of 0 means that no trigger programs at all 
10823: ** may be executed.
10824: */
10825: #ifndef SQLITE_MAX_TRIGGER_DEPTH
10826: # define SQLITE_MAX_TRIGGER_DEPTH 1000
10827: #endif
10828: 
10829: /************** End of sqliteLimit.h *****************************************/
10830: /************** Continuing where we left off in sqliteInt.h ******************/
10831: 
10832: /* Disable nuisance warnings on Borland compilers */
10833: #if defined(__BORLANDC__)
10834: #pragma warn -rch /* unreachable code */
10835: #pragma warn -ccc /* Condition is always true or false */
10836: #pragma warn -aus /* Assigned value is never used */
10837: #pragma warn -csu /* Comparing signed and unsigned */
10838: #pragma warn -spa /* Suspicious pointer arithmetic */
10839: #endif
10840: 
10841: /*
10842: ** Include standard header files as necessary
10843: */
10844: #ifdef HAVE_STDINT_H
10845: #include <stdint.h>
10846: #endif
10847: #ifdef HAVE_INTTYPES_H
10848: #include <inttypes.h>
10849: #endif
10850: 
10851: /*
10852: ** The following macros are used to cast pointers to integers and
10853: ** integers to pointers.  The way you do this varies from one compiler
10854: ** to the next, so we have developed the following set of #if statements
10855: ** to generate appropriate macros for a wide range of compilers.
10856: **
10857: ** The correct "ANSI" way to do this is to use the intptr_t type.
10858: ** Unfortunately, that typedef is not available on all compilers, or
10859: ** if it is available, it requires an #include of specific headers
10860: ** that vary from one machine to the next.
10861: **
10862: ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
10863: ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
10864: ** So we have to define the macros in different ways depending on the
10865: ** compiler.
10866: */
10867: #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
10868: # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
10869: # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
10870: #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
10871: # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
10872: # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
10873: #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
10874: # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
10875: # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
10876: #else                          /* Generates a warning - but it always works */
10877: # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
10878: # define SQLITE_PTR_TO_INT(X)  ((int)(X))
10879: #endif
10880: 
10881: /*
10882: ** A macro to hint to the compiler that a function should not be
10883: ** inlined.
10884: */
10885: #if defined(__GNUC__)
10886: #  define SQLITE_NOINLINE  __attribute__((noinline))
10887: #elif defined(_MSC_VER) && _MSC_VER>=1310
10888: #  define SQLITE_NOINLINE  __declspec(noinline)
10889: #else
10890: #  define SQLITE_NOINLINE
10891: #endif
10892: 
10893: /*
10894: ** Make sure that the compiler intrinsics we desire are enabled when
10895: ** compiling with an appropriate version of MSVC unless prevented by
10896: ** the SQLITE_DISABLE_INTRINSIC define.
10897: */
10898: #if !defined(SQLITE_DISABLE_INTRINSIC)
10899: #  if defined(_MSC_VER) && _MSC_VER>=1400
10900: #    if !defined(_WIN32_WCE)
10901: #      include <intrin.h>
10902: #      pragma intrinsic(_byteswap_ushort)
10903: #      pragma intrinsic(_byteswap_ulong)
10904: #      pragma intrinsic(_ReadWriteBarrier)
10905: #    else
10906: #      include <cmnintrin.h>
10907: #    endif
10908: #  endif
10909: #endif
10910: 
10911: /*
10912: ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
10913: ** 0 means mutexes are permanently disable and the library is never
10914: ** threadsafe.  1 means the library is serialized which is the highest
10915: ** level of threadsafety.  2 means the library is multithreaded - multiple
10916: ** threads can use SQLite as long as no two threads try to use the same
10917: ** database connection at the same time.
10918: **
10919: ** Older versions of SQLite used an optional THREADSAFE macro.
10920: ** We support that for legacy.
10921: */
10922: #if !defined(SQLITE_THREADSAFE)
10923: # if defined(THREADSAFE)
10924: #   define SQLITE_THREADSAFE THREADSAFE
10925: # else
10926: #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
10927: # endif
10928: #endif
10929: 
10930: /*
10931: ** Powersafe overwrite is on by default.  But can be turned off using
10932: ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
10933: */
10934: #ifndef SQLITE_POWERSAFE_OVERWRITE
10935: # define SQLITE_POWERSAFE_OVERWRITE 1
10936: #endif
10937: 
10938: /*
10939: ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
10940: ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
10941: ** which case memory allocation statistics are disabled by default.
10942: */
10943: #if !defined(SQLITE_DEFAULT_MEMSTATUS)
10944: # define SQLITE_DEFAULT_MEMSTATUS 1
10945: #endif
10946: 
10947: /*
10948: ** Exactly one of the following macros must be defined in order to
10949: ** specify which memory allocation subsystem to use.
10950: **
10951: **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
10952: **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
10953: **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
10954: **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
10955: **
10956: ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
10957: ** assert() macro is enabled, each call into the Win32 native heap subsystem
10958: ** will cause HeapValidate to be called.  If heap validation should fail, an
10959: ** assertion will be triggered.
10960: **
10961: ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
10962: ** the default.
10963: */
10964: #if defined(SQLITE_SYSTEM_MALLOC) \
10965:   + defined(SQLITE_WIN32_MALLOC) \
10966:   + defined(SQLITE_ZERO_MALLOC) \
10967:   + defined(SQLITE_MEMDEBUG)>1
10968: # error "Two or more of the following compile-time configuration options\
10969:  are defined but at most one is allowed:\
10970:  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
10971:  SQLITE_ZERO_MALLOC"
10972: #endif
10973: #if defined(SQLITE_SYSTEM_MALLOC) \
10974:   + defined(SQLITE_WIN32_MALLOC) \
10975:   + defined(SQLITE_ZERO_MALLOC) \
10976:   + defined(SQLITE_MEMDEBUG)==0
10977: # define SQLITE_SYSTEM_MALLOC 1
10978: #endif
10979: 
10980: /*
10981: ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
10982: ** sizes of memory allocations below this value where possible.
10983: */
10984: #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
10985: # define SQLITE_MALLOC_SOFT_LIMIT 1024
10986: #endif
10987: 
10988: /*
10989: ** We need to define _XOPEN_SOURCE as follows in order to enable
10990: ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
10991: ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
10992: ** it.
10993: */
10994: #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
10995: #  define _XOPEN_SOURCE 600
10996: #endif
10997: 
10998: /*
10999: ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
11000: ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
11001: ** make it true by defining or undefining NDEBUG.
11002: **
11003: ** Setting NDEBUG makes the code smaller and faster by disabling the
11004: ** assert() statements in the code.  So we want the default action
11005: ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
11006: ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
11007: ** feature.
11008: */
11009: #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
11010: # define NDEBUG 1
11011: #endif
11012: #if defined(NDEBUG) && defined(SQLITE_DEBUG)
11013: # undef NDEBUG
11014: #endif
11015: 
11016: /*
11017: ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
11018: */
11019: #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
11020: # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
11021: #endif
11022: 
11023: /*
11024: ** The testcase() macro is used to aid in coverage testing.  When
11025: ** doing coverage testing, the condition inside the argument to
11026: ** testcase() must be evaluated both true and false in order to
11027: ** get full branch coverage.  The testcase() macro is inserted
11028: ** to help ensure adequate test coverage in places where simple
11029: ** condition/decision coverage is inadequate.  For example, testcase()
11030: ** can be used to make sure boundary values are tested.  For
11031: ** bitmask tests, testcase() can be used to make sure each bit
11032: ** is significant and used at least once.  On switch statements
11033: ** where multiple cases go to the same block of code, testcase()
11034: ** can insure that all cases are evaluated.
11035: **
11036: */
11037: #ifdef SQLITE_COVERAGE_TEST
11038: SQLITE_PRIVATE   void sqlite3Coverage(int);
11039: # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
11040: #else
11041: # define testcase(X)
11042: #endif
11043: 
11044: /*
11045: ** The TESTONLY macro is used to enclose variable declarations or
11046: ** other bits of code that are needed to support the arguments
11047: ** within testcase() and assert() macros.
11048: */
11049: #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
11050: # define TESTONLY(X)  X
11051: #else
11052: # define TESTONLY(X)
11053: #endif
11054: 
11055: /*
11056: ** Sometimes we need a small amount of code such as a variable initialization
11057: ** to setup for a later assert() statement.  We do not want this code to
11058: ** appear when assert() is disabled.  The following macro is therefore
11059: ** used to contain that setup code.  The "VVA" acronym stands for
11060: ** "Verification, Validation, and Accreditation".  In other words, the
11061: ** code within VVA_ONLY() will only run during verification processes.
11062: */
11063: #ifndef NDEBUG
11064: # define VVA_ONLY(X)  X
11065: #else
11066: # define VVA_ONLY(X)
11067: #endif
11068: 
11069: /*
11070: ** The ALWAYS and NEVER macros surround boolean expressions which
11071: ** are intended to always be true or false, respectively.  Such
11072: ** expressions could be omitted from the code completely.  But they
11073: ** are included in a few cases in order to enhance the resilience
11074: ** of SQLite to unexpected behavior - to make the code "self-healing"
11075: ** or "ductile" rather than being "brittle" and crashing at the first
11076: ** hint of unplanned behavior.
11077: **
11078: ** In other words, ALWAYS and NEVER are added for defensive code.
11079: **
11080: ** When doing coverage testing ALWAYS and NEVER are hard-coded to
11081: ** be true and false so that the unreachable code they specify will
11082: ** not be counted as untested code.
11083: */
11084: #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
11085: # define ALWAYS(X)      (1)
11086: # define NEVER(X)       (0)
11087: #elif !defined(NDEBUG)
11088: # define ALWAYS(X)      ((X)?1:(assert(0),0))
11089: # define NEVER(X)       ((X)?(assert(0),1):0)
11090: #else
11091: # define ALWAYS(X)      (X)
11092: # define NEVER(X)       (X)
11093: #endif
11094: 
11095: /*
11096: ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
11097: ** defined.  We need to defend against those failures when testing with
11098: ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
11099: ** during a normal build.  The following macro can be used to disable tests
11100: ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
11101: */
11102: #if defined(SQLITE_TEST_REALLOC_STRESS)
11103: # define ONLY_IF_REALLOC_STRESS(X)  (X)
11104: #elif !defined(NDEBUG)
11105: # define ONLY_IF_REALLOC_STRESS(X)  ((X)?(assert(0),1):0)
11106: #else
11107: # define ONLY_IF_REALLOC_STRESS(X)  (0)
11108: #endif
11109: 
11110: /*
11111: ** Declarations used for tracing the operating system interfaces.
11112: */
11113: #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
11114:     (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11115:   extern int sqlite3OSTrace;
11116: # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
11117: # define SQLITE_HAVE_OS_TRACE
11118: #else
11119: # define OSTRACE(X)
11120: # undef  SQLITE_HAVE_OS_TRACE
11121: #endif
11122: 
11123: /*
11124: ** Is the sqlite3ErrName() function needed in the build?  Currently,
11125: ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
11126: ** OSTRACE is enabled), and by several "test*.c" files (which are
11127: ** compiled using SQLITE_TEST).
11128: */
11129: #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
11130:     (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
11131: # define SQLITE_NEED_ERR_NAME
11132: #else
11133: # undef  SQLITE_NEED_ERR_NAME
11134: #endif
11135: 
11136: /*
11137: ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
11138: */
11139: #ifdef SQLITE_OMIT_EXPLAIN
11140: # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
11141: #endif
11142: 
11143: /*
11144: ** Return true (non-zero) if the input is an integer that is too large
11145: ** to fit in 32-bits.  This macro is used inside of various testcase()
11146: ** macros to verify that we have tested SQLite for large-file support.
11147: */
11148: #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
11149: 
11150: /*
11151: ** The macro unlikely() is a hint that surrounds a boolean
11152: ** expression that is usually false.  Macro likely() surrounds
11153: ** a boolean expression that is usually true.  These hints could,
11154: ** in theory, be used by the compiler to generate better code, but
11155: ** currently they are just comments for human readers.
11156: */
11157: #define likely(X)    (X)
11158: #define unlikely(X)  (X)
11159: 
11160: /************** Include hash.h in the middle of sqliteInt.h ******************/
11161: /************** Begin file hash.h ********************************************/
11162: /*
11163: ** 2001 September 22
11164: **
11165: ** The author disclaims copyright to this source code.  In place of
11166: ** a legal notice, here is a blessing:
11167: **
11168: **    May you do good and not evil.
11169: **    May you find forgiveness for yourself and forgive others.
11170: **    May you share freely, never taking more than you give.
11171: **
11172: *************************************************************************
11173: ** This is the header file for the generic hash-table implementation
11174: ** used in SQLite.
11175: */
11176: #ifndef SQLITE_HASH_H
11177: #define SQLITE_HASH_H
11178: 
11179: /* Forward declarations of structures. */
11180: typedef struct Hash Hash;
11181: typedef struct HashElem HashElem;
11182: 
11183: /* A complete hash table is an instance of the following structure.
11184: ** The internals of this structure are intended to be opaque -- client
11185: ** code should not attempt to access or modify the fields of this structure
11186: ** directly.  Change this structure only by using the routines below.
11187: ** However, some of the "procedures" and "functions" for modifying and
11188: ** accessing this structure are really macros, so we can't really make
11189: ** this structure opaque.
11190: **
11191: ** All elements of the hash table are on a single doubly-linked list.
11192: ** Hash.first points to the head of this list.
11193: **
11194: ** There are Hash.htsize buckets.  Each bucket points to a spot in
11195: ** the global doubly-linked list.  The contents of the bucket are the
11196: ** element pointed to plus the next _ht.count-1 elements in the list.
11197: **
11198: ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
11199: ** by a linear search of the global list.  For small tables, the 
11200: ** Hash.ht table is never allocated because if there are few elements
11201: ** in the table, it is faster to do a linear search than to manage
11202: ** the hash table.
11203: */
11204: struct Hash {
11205:   unsigned int htsize;      /* Number of buckets in the hash table */
11206:   unsigned int count;       /* Number of entries in this table */
11207:   HashElem *first;          /* The first element of the array */
11208:   struct _ht {              /* the hash table */
11209:     int count;                 /* Number of entries with this hash */
11210:     HashElem *chain;           /* Pointer to first entry with this hash */
11211:   } *ht;
11212: };
11213: 
11214: /* Each element in the hash table is an instance of the following 
11215: ** structure.  All elements are stored on a single doubly-linked list.
11216: **
11217: ** Again, this structure is intended to be opaque, but it can't really
11218: ** be opaque because it is used by macros.
11219: */
11220: struct HashElem {
11221:   HashElem *next, *prev;       /* Next and previous elements in the table */
11222:   void *data;                  /* Data associated with this element */
11223:   const char *pKey;            /* Key associated with this element */
11224: };
11225: 
11226: /*
11227: ** Access routines.  To delete, insert a NULL pointer.
11228: */
11229: SQLITE_PRIVATE void sqlite3HashInit(Hash*);
11230: SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
11231: SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
11232: SQLITE_PRIVATE void sqlite3HashClear(Hash*);
11233: 
11234: /*
11235: ** Macros for looping over all elements of a hash table.  The idiom is
11236: ** like this:
11237: **
11238: **   Hash h;
11239: **   HashElem *p;
11240: **   ...
11241: **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
11242: **     SomeStructure *pData = sqliteHashData(p);
11243: **     // do something with pData
11244: **   }
11245: */
11246: #define sqliteHashFirst(H)  ((H)->first)
11247: #define sqliteHashNext(E)   ((E)->next)
11248: #define sqliteHashData(E)   ((E)->data)
11249: /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
11250: /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
11251: 
11252: /*
11253: ** Number of entries in a hash table
11254: */
11255: /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
11256: 
11257: #endif /* SQLITE_HASH_H */
11258: 
11259: /************** End of hash.h ************************************************/
11260: /************** Continuing where we left off in sqliteInt.h ******************/
11261: /************** Include parse.h in the middle of sqliteInt.h *****************/
11262: /************** Begin file parse.h *******************************************/
11263: #define TK_SEMI                             1
11264: #define TK_EXPLAIN                          2
11265: #define TK_QUERY                            3
11266: #define TK_PLAN                             4
11267: #define TK_BEGIN                            5
11268: #define TK_TRANSACTION                      6
11269: #define TK_DEFERRED                         7
11270: #define TK_IMMEDIATE                        8
11271: #define TK_EXCLUSIVE                        9
11272: #define TK_COMMIT                          10
11273: #define TK_END                             11
11274: #define TK_ROLLBACK                        12
11275: #define TK_SAVEPOINT                       13
11276: #define TK_RELEASE                         14
11277: #define TK_TO                              15
11278: #define TK_TABLE                           16
11279: #define TK_CREATE                          17
11280: #define TK_IF                              18
11281: #define TK_NOT                             19
11282: #define TK_EXISTS                          20
11283: #define TK_TEMP                            21
11284: #define TK_LP                              22
11285: #define TK_RP                              23
11286: #define TK_AS                              24
11287: #define TK_WITHOUT                         25
11288: #define TK_COMMA                           26
11289: #define TK_OR                              27
11290: #define TK_AND                             28
11291: #define TK_IS                              29
11292: #define TK_MATCH                           30
11293: #define TK_LIKE_KW                         31
11294: #define TK_BETWEEN                         32
11295: #define TK_IN                              33
11296: #define TK_ISNULL                          34
11297: #define TK_NOTNULL                         35
11298: #define TK_NE                              36
11299: #define TK_EQ                              37
11300: #define TK_GT                              38
11301: #define TK_LE                              39
11302: #define TK_LT                              40
11303: #define TK_GE                              41
11304: #define TK_ESCAPE                          42
11305: #define TK_BITAND                          43
11306: #define TK_BITOR                           44
11307: #define TK_LSHIFT                          45
11308: #define TK_RSHIFT                          46
11309: #define TK_PLUS                            47
11310: #define TK_MINUS                           48
11311: #define TK_STAR                            49
11312: #define TK_SLASH                           50
11313: #define TK_REM                             51
11314: #define TK_CONCAT                          52
11315: #define TK_COLLATE                         53
11316: #define TK_BITNOT                          54
11317: #define TK_ID                              55
11318: #define TK_INDEXED                         56
11319: #define TK_ABORT                           57
11320: #define TK_ACTION                          58
11321: #define TK_AFTER                           59
11322: #define TK_ANALYZE                         60
11323: #define TK_ASC                             61
11324: #define TK_ATTACH                          62
11325: #define TK_BEFORE                          63
11326: #define TK_BY                              64
11327: #define TK_CASCADE                         65
11328: #define TK_CAST                            66
11329: #define TK_COLUMNKW                        67
11330: #define TK_CONFLICT                        68
11331: #define TK_DATABASE                        69
11332: #define TK_DESC                            70
11333: #define TK_DETACH                          71
11334: #define TK_EACH                            72
11335: #define TK_FAIL                            73
11336: #define TK_FOR                             74
11337: #define TK_IGNORE                          75
11338: #define TK_INITIALLY                       76
11339: #define TK_INSTEAD                         77
11340: #define TK_NO                              78
11341: #define TK_KEY                             79
11342: #define TK_OF                              80
11343: #define TK_OFFSET                          81
11344: #define TK_PRAGMA                          82
11345: #define TK_RAISE                           83
11346: #define TK_RECURSIVE                       84
11347: #define TK_REPLACE                         85
11348: #define TK_RESTRICT                        86
11349: #define TK_ROW                             87
11350: #define TK_TRIGGER                         88
11351: #define TK_VACUUM                          89
11352: #define TK_VIEW                            90
11353: #define TK_VIRTUAL                         91
11354: #define TK_WITH                            92
11355: #define TK_REINDEX                         93
11356: #define TK_RENAME                          94
11357: #define TK_CTIME_KW                        95
11358: #define TK_ANY                             96
11359: #define TK_STRING                          97
11360: #define TK_JOIN_KW                         98
11361: #define TK_CONSTRAINT                      99
11362: #define TK_DEFAULT                        100
11363: #define TK_NULL                           101
11364: #define TK_PRIMARY                        102
11365: #define TK_UNIQUE                         103
11366: #define TK_CHECK                          104
11367: #define TK_REFERENCES                     105
11368: #define TK_AUTOINCR                       106
11369: #define TK_ON                             107
11370: #define TK_INSERT                         108
11371: #define TK_DELETE                         109
11372: #define TK_UPDATE                         110
11373: #define TK_SET                            111
11374: #define TK_DEFERRABLE                     112
11375: #define TK_FOREIGN                        113
11376: #define TK_DROP                           114
11377: #define TK_UNION                          115
11378: #define TK_ALL                            116
11379: #define TK_EXCEPT                         117
11380: #define TK_INTERSECT                      118
11381: #define TK_SELECT                         119
11382: #define TK_VALUES                         120
11383: #define TK_DISTINCT                       121
11384: #define TK_DOT                            122
11385: #define TK_FROM                           123
11386: #define TK_JOIN                           124
11387: #define TK_USING                          125
11388: #define TK_ORDER                          126
11389: #define TK_GROUP                          127
11390: #define TK_HAVING                         128
11391: #define TK_LIMIT                          129
11392: #define TK_WHERE                          130
11393: #define TK_INTO                           131
11394: #define TK_INTEGER                        132
11395: #define TK_FLOAT                          133
11396: #define TK_BLOB                           134
11397: #define TK_VARIABLE                       135
11398: #define TK_CASE                           136
11399: #define TK_WHEN                           137
11400: #define TK_THEN                           138
11401: #define TK_ELSE                           139
11402: #define TK_INDEX                          140
11403: #define TK_ALTER                          141
11404: #define TK_ADD                            142
11405: #define TK_TO_TEXT                        143
11406: #define TK_TO_BLOB                        144
11407: #define TK_TO_NUMERIC                     145
11408: #define TK_TO_INT                         146
11409: #define TK_TO_REAL                        147
11410: #define TK_ISNOT                          148
11411: #define TK_END_OF_FILE                    149
11412: #define TK_UNCLOSED_STRING                150
11413: #define TK_FUNCTION                       151
11414: #define TK_COLUMN                         152
11415: #define TK_AGG_FUNCTION                   153
11416: #define TK_AGG_COLUMN                     154
11417: #define TK_UMINUS                         155
11418: #define TK_UPLUS                          156
11419: #define TK_REGISTER                       157
11420: #define TK_ASTERISK                       158
11421: #define TK_SPAN                           159
11422: #define TK_SPACE                          160
11423: #define TK_ILLEGAL                        161
11424: 
11425: /* The token codes above must all fit in 8 bits */
11426: #define TKFLG_MASK           0xff  
11427: 
11428: /* Flags that can be added to a token code when it is not
11429: ** being stored in a u8: */
11430: #define TKFLG_DONTFOLD       0x100  /* Omit constant folding optimizations */
11431: 
11432: /************** End of parse.h ***********************************************/
11433: /************** Continuing where we left off in sqliteInt.h ******************/
11434: #include <stdio.h>
11435: #include <stdlib.h>
11436: #include <string.h>
11437: #include <assert.h>
11438: #include <stddef.h>
11439: 
11440: /*
11441: ** If compiling for a processor that lacks floating point support,
11442: ** substitute integer for floating-point
11443: */
11444: #ifdef SQLITE_OMIT_FLOATING_POINT
11445: # define double sqlite_int64
11446: # define float sqlite_int64
11447: # define LONGDOUBLE_TYPE sqlite_int64
11448: # ifndef SQLITE_BIG_DBL
11449: #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
11450: # endif
11451: # define SQLITE_OMIT_DATETIME_FUNCS 1
11452: # define SQLITE_OMIT_TRACE 1
11453: # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11454: # undef SQLITE_HAVE_ISNAN
11455: #endif
11456: #ifndef SQLITE_BIG_DBL
11457: # define SQLITE_BIG_DBL (1e99)
11458: #endif
11459: 
11460: /*
11461: ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
11462: ** afterward. Having this macro allows us to cause the C compiler
11463: ** to omit code used by TEMP tables without messy #ifndef statements.
11464: */
11465: #ifdef SQLITE_OMIT_TEMPDB
11466: #define OMIT_TEMPDB 1
11467: #else
11468: #define OMIT_TEMPDB 0
11469: #endif
11470: 
11471: /*
11472: ** The "file format" number is an integer that is incremented whenever
11473: ** the VDBE-level file format changes.  The following macros define the
11474: ** the default file format for new databases and the maximum file format
11475: ** that the library can read.
11476: */
11477: #define SQLITE_MAX_FILE_FORMAT 4
11478: #ifndef SQLITE_DEFAULT_FILE_FORMAT
11479: # define SQLITE_DEFAULT_FILE_FORMAT 4
11480: #endif
11481: 
11482: /*
11483: ** Determine whether triggers are recursive by default.  This can be
11484: ** changed at run-time using a pragma.
11485: */
11486: #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
11487: # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
11488: #endif
11489: 
11490: /*
11491: ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
11492: ** on the command-line
11493: */
11494: #ifndef SQLITE_TEMP_STORE
11495: # define SQLITE_TEMP_STORE 1
11496: # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
11497: #endif
11498: 
11499: /*
11500: ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
11501: ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
11502: ** to zero.
11503: */
11504: #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
11505: # undef SQLITE_MAX_WORKER_THREADS
11506: # define SQLITE_MAX_WORKER_THREADS 0
11507: #endif
11508: #ifndef SQLITE_MAX_WORKER_THREADS
11509: # define SQLITE_MAX_WORKER_THREADS 8
11510: #endif
11511: #ifndef SQLITE_DEFAULT_WORKER_THREADS
11512: # define SQLITE_DEFAULT_WORKER_THREADS 0
11513: #endif
11514: #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
11515: # undef SQLITE_MAX_WORKER_THREADS
11516: # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
11517: #endif
11518: 
11519: /*
11520: ** The default initial allocation for the pagecache when using separate
11521: ** pagecaches for each database connection.  A positive number is the
11522: ** number of pages.  A negative number N translations means that a buffer
11523: ** of -1024*N bytes is allocated and used for as many pages as it will hold.
11524: */
11525: #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
11526: # define SQLITE_DEFAULT_PCACHE_INITSZ 100
11527: #endif
11528: 
11529: /*
11530: ** GCC does not define the offsetof() macro so we'll have to do it
11531: ** ourselves.
11532: */
11533: #ifndef offsetof
11534: #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
11535: #endif
11536: 
11537: /*
11538: ** Macros to compute minimum and maximum of two numbers.
11539: */
11540: #ifndef MIN
11541: # define MIN(A,B) ((A)<(B)?(A):(B))
11542: #endif
11543: #ifndef MAX
11544: # define MAX(A,B) ((A)>(B)?(A):(B))
11545: #endif
11546: 
11547: /*
11548: ** Swap two objects of type TYPE.
11549: */
11550: #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
11551: 
11552: /*
11553: ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
11554: ** not, there are still machines out there that use EBCDIC.)
11555: */
11556: #if 'A' == '\301'
11557: # define SQLITE_EBCDIC 1
11558: #else
11559: # define SQLITE_ASCII 1
11560: #endif
11561: 
11562: /*
11563: ** Integers of known sizes.  These typedefs might change for architectures
11564: ** where the sizes very.  Preprocessor macros are available so that the
11565: ** types can be conveniently redefined at compile-type.  Like this:
11566: **
11567: **         cc '-DUINTPTR_TYPE=long long int' ...
11568: */
11569: #ifndef UINT32_TYPE
11570: # ifdef HAVE_UINT32_T
11571: #  define UINT32_TYPE uint32_t
11572: # else
11573: #  define UINT32_TYPE unsigned int
11574: # endif
11575: #endif
11576: #ifndef UINT16_TYPE
11577: # ifdef HAVE_UINT16_T
11578: #  define UINT16_TYPE uint16_t
11579: # else
11580: #  define UINT16_TYPE unsigned short int
11581: # endif
11582: #endif
11583: #ifndef INT16_TYPE
11584: # ifdef HAVE_INT16_T
11585: #  define INT16_TYPE int16_t
11586: # else
11587: #  define INT16_TYPE short int
11588: # endif
11589: #endif
11590: #ifndef UINT8_TYPE
11591: # ifdef HAVE_UINT8_T
11592: #  define UINT8_TYPE uint8_t
11593: # else
11594: #  define UINT8_TYPE unsigned char
11595: # endif
11596: #endif
11597: #ifndef INT8_TYPE
11598: # ifdef HAVE_INT8_T
11599: #  define INT8_TYPE int8_t
11600: # else
11601: #  define INT8_TYPE signed char
11602: # endif
11603: #endif
11604: #ifndef LONGDOUBLE_TYPE
11605: # define LONGDOUBLE_TYPE long double
11606: #endif
11607: typedef sqlite_int64 i64;          /* 8-byte signed integer */
11608: typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
11609: typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
11610: typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
11611: typedef INT16_TYPE i16;            /* 2-byte signed integer */
11612: typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
11613: typedef INT8_TYPE i8;              /* 1-byte signed integer */
11614: 
11615: /*
11616: ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
11617: ** that can be stored in a u32 without loss of data.  The value
11618: ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
11619: ** have to specify the value in the less intuitive manner shown:
11620: */
11621: #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
11622: 
11623: /*
11624: ** The datatype used to store estimates of the number of rows in a
11625: ** table or index.  This is an unsigned integer type.  For 99.9% of
11626: ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
11627: ** can be used at compile-time if desired.
11628: */
11629: #ifdef SQLITE_64BIT_STATS
11630:  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
11631: #else
11632:  typedef u32 tRowcnt;    /* 32-bit is the default */
11633: #endif
11634: 
11635: /*
11636: ** Estimated quantities used for query planning are stored as 16-bit
11637: ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
11638: ** gives a possible range of values of approximately 1.0e986 to 1e-986.
11639: ** But the allowed values are "grainy".  Not every value is representable.
11640: ** For example, quantities 16 and 17 are both represented by a LogEst
11641: ** of 40.  However, since LogEst quantities are suppose to be estimates,
11642: ** not exact values, this imprecision is not a problem.
11643: **
11644: ** "LogEst" is short for "Logarithmic Estimate".
11645: **
11646: ** Examples:
11647: **      1 -> 0              20 -> 43          10000 -> 132
11648: **      2 -> 10             25 -> 46          25000 -> 146
11649: **      3 -> 16            100 -> 66        1000000 -> 199
11650: **      4 -> 20           1000 -> 99        1048576 -> 200
11651: **     10 -> 33           1024 -> 100    4294967296 -> 320
11652: **
11653: ** The LogEst can be negative to indicate fractional values.
11654: ** Examples:
11655: **
11656: **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
11657: */
11658: typedef INT16_TYPE LogEst;
11659: 
11660: /*
11661: ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
11662: */
11663: #ifndef SQLITE_PTRSIZE
11664: # if defined(__SIZEOF_POINTER__)
11665: #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
11666: # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
11667:        defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
11668: #   define SQLITE_PTRSIZE 4
11669: # else
11670: #   define SQLITE_PTRSIZE 8
11671: # endif
11672: #endif
11673: 
11674: /* The uptr type is an unsigned integer large enough to hold a pointer
11675: */
11676: #if defined(HAVE_STDINT_H)
11677:   typedef uintptr_t uptr;
11678: #elif SQLITE_PTRSIZE==4
11679:   typedef u32 uptr;
11680: #else
11681:   typedef u64 uptr;
11682: #endif
11683: 
11684: /*
11685: ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
11686: ** something between S (inclusive) and E (exclusive).
11687: **
11688: ** In other words, S is a buffer and E is a pointer to the first byte after
11689: ** the end of buffer S.  This macro returns true if P points to something
11690: ** contained within the buffer S.
11691: */
11692: #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
11693: 
11694: 
11695: /*
11696: ** Macros to determine whether the machine is big or little endian,
11697: ** and whether or not that determination is run-time or compile-time.
11698: **
11699: ** For best performance, an attempt is made to guess at the byte-order
11700: ** using C-preprocessor macros.  If that is unsuccessful, or if
11701: ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
11702: ** at run-time.
11703: */
11704: #if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
11705:      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
11706:      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
11707:      defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
11708: # define SQLITE_BYTEORDER    1234
11709: # define SQLITE_BIGENDIAN    0
11710: # define SQLITE_LITTLEENDIAN 1
11711: # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
11712: #endif
11713: #if (defined(sparc)    || defined(__ppc__))  \
11714:     && !defined(SQLITE_RUNTIME_BYTEORDER)
11715: # define SQLITE_BYTEORDER    4321
11716: # define SQLITE_BIGENDIAN    1
11717: # define SQLITE_LITTLEENDIAN 0
11718: # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
11719: #endif
11720: #if !defined(SQLITE_BYTEORDER)
11721: # ifdef SQLITE_AMALGAMATION
11722:   const int sqlite3one = 1;
11723: # else
11724:   extern const int sqlite3one;
11725: # endif
11726: # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
11727: # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
11728: # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
11729: # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
11730: #endif
11731: 
11732: /*
11733: ** Constants for the largest and smallest possible 64-bit signed integers.
11734: ** These macros are designed to work correctly on both 32-bit and 64-bit
11735: ** compilers.
11736: */
11737: #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
11738: #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
11739: 
11740: /*
11741: ** Round up a number to the next larger multiple of 8.  This is used
11742: ** to force 8-byte alignment on 64-bit architectures.
11743: */
11744: #define ROUND8(x)     (((x)+7)&~7)
11745: 
11746: /*
11747: ** Round down to the nearest multiple of 8
11748: */
11749: #define ROUNDDOWN8(x) ((x)&~7)
11750: 
11751: /*
11752: ** Assert that the pointer X is aligned to an 8-byte boundary.  This
11753: ** macro is used only within assert() to verify that the code gets
11754: ** all alignment restrictions correct.
11755: **
11756: ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
11757: ** underlying malloc() implementation might return us 4-byte aligned
11758: ** pointers.  In that case, only verify 4-byte alignment.
11759: */
11760: #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11761: # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
11762: #else
11763: # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
11764: #endif
11765: 
11766: /*
11767: ** Disable MMAP on platforms where it is known to not work
11768: */
11769: #if defined(__OpenBSD__) || defined(__QNXNTO__)
11770: # undef SQLITE_MAX_MMAP_SIZE
11771: # define SQLITE_MAX_MMAP_SIZE 0
11772: #endif
11773: 
11774: /*
11775: ** Default maximum size of memory used by memory-mapped I/O in the VFS
11776: */
11777: #ifdef __APPLE__
11778: # include <TargetConditionals.h>
11779: #endif
11780: #ifndef SQLITE_MAX_MMAP_SIZE
11781: # if defined(__linux__) \
11782:   || defined(_WIN32) \
11783:   || (defined(__APPLE__) && defined(__MACH__)) \
11784:   || defined(__sun) \
11785:   || defined(__FreeBSD__) \
11786:   || defined(__DragonFly__)
11787: #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
11788: # else
11789: #   define SQLITE_MAX_MMAP_SIZE 0
11790: # endif
11791: # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
11792: #endif
11793: 
11794: /*
11795: ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
11796: ** default MMAP_SIZE is specified at compile-time, make sure that it does
11797: ** not exceed the maximum mmap size.
11798: */
11799: #ifndef SQLITE_DEFAULT_MMAP_SIZE
11800: # define SQLITE_DEFAULT_MMAP_SIZE 0
11801: # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
11802: #endif
11803: #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
11804: # undef SQLITE_DEFAULT_MMAP_SIZE
11805: # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
11806: #endif
11807: 
11808: /*
11809: ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
11810: ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
11811: ** define SQLITE_ENABLE_STAT3_OR_STAT4
11812: */
11813: #ifdef SQLITE_ENABLE_STAT4
11814: # undef SQLITE_ENABLE_STAT3
11815: # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11816: #elif SQLITE_ENABLE_STAT3
11817: # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11818: #elif SQLITE_ENABLE_STAT3_OR_STAT4
11819: # undef SQLITE_ENABLE_STAT3_OR_STAT4
11820: #endif
11821: 
11822: /*
11823: ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
11824: ** the Select query generator tracing logic is turned on.
11825: */
11826: #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
11827: # define SELECTTRACE_ENABLED 1
11828: #else
11829: # define SELECTTRACE_ENABLED 0
11830: #endif
11831: 
11832: /*
11833: ** An instance of the following structure is used to store the busy-handler
11834: ** callback for a given sqlite handle.
11835: **
11836: ** The sqlite.busyHandler member of the sqlite struct contains the busy
11837: ** callback for the database handle. Each pager opened via the sqlite
11838: ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
11839: ** callback is currently invoked only from within pager.c.
11840: */
11841: typedef struct BusyHandler BusyHandler;
11842: struct BusyHandler {
11843:   int (*xFunc)(void *,int);  /* The busy callback */
11844:   void *pArg;                /* First arg to busy callback */
11845:   int nBusy;                 /* Incremented with each busy call */
11846: };
11847: 
11848: /*
11849: ** Name of the master database table.  The master database table
11850: ** is a special table that holds the names and attributes of all
11851: ** user tables and indices.
11852: */
11853: #define MASTER_NAME       "sqlite_master"
11854: #define TEMP_MASTER_NAME  "sqlite_temp_master"
11855: 
11856: /*
11857: ** The root-page of the master database table.
11858: */
11859: #define MASTER_ROOT       1
11860: 
11861: /*
11862: ** The name of the schema table.
11863: */
11864: #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
11865: 
11866: /*
11867: ** A convenience macro that returns the number of elements in
11868: ** an array.
11869: */
11870: #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
11871: 
11872: /*
11873: ** Determine if the argument is a power of two
11874: */
11875: #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
11876: 
11877: /*
11878: ** The following value as a destructor means to use sqlite3DbFree().
11879: ** The sqlite3DbFree() routine requires two parameters instead of the
11880: ** one parameter that destructors normally want.  So we have to introduce
11881: ** this magic value that the code knows to handle differently.  Any
11882: ** pointer will work here as long as it is distinct from SQLITE_STATIC
11883: ** and SQLITE_TRANSIENT.
11884: */
11885: #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
11886: 
11887: /*
11888: ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
11889: ** not support Writable Static Data (WSD) such as global and static variables.
11890: ** All variables must either be on the stack or dynamically allocated from
11891: ** the heap.  When WSD is unsupported, the variable declarations scattered
11892: ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
11893: ** macro is used for this purpose.  And instead of referencing the variable
11894: ** directly, we use its constant as a key to lookup the run-time allocated
11895: ** buffer that holds real variable.  The constant is also the initializer
11896: ** for the run-time allocated buffer.
11897: **
11898: ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
11899: ** macros become no-ops and have zero performance impact.
11900: */
11901: #ifdef SQLITE_OMIT_WSD
11902:   #define SQLITE_WSD const
11903:   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
11904:   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
11905: SQLITE_API int sqlite3_wsd_init(int N, int J);
11906: SQLITE_API void *sqlite3_wsd_find(void *K, int L);
11907: #else
11908:   #define SQLITE_WSD
11909:   #define GLOBAL(t,v) v
11910:   #define sqlite3GlobalConfig sqlite3Config
11911: #endif
11912: 
11913: /*
11914: ** The following macros are used to suppress compiler warnings and to
11915: ** make it clear to human readers when a function parameter is deliberately
11916: ** left unused within the body of a function. This usually happens when
11917: ** a function is called via a function pointer. For example the
11918: ** implementation of an SQL aggregate step callback may not use the
11919: ** parameter indicating the number of arguments passed to the aggregate,
11920: ** if it knows that this is enforced elsewhere.
11921: **
11922: ** When a function parameter is not used at all within the body of a function,
11923: ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
11924: ** However, these macros may also be used to suppress warnings related to
11925: ** parameters that may or may not be used depending on compilation options.
11926: ** For example those parameters only used in assert() statements. In these
11927: ** cases the parameters are named as per the usual conventions.
11928: */
11929: #define UNUSED_PARAMETER(x) (void)(x)
11930: #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
11931: 
11932: /*
11933: ** Forward references to structures
11934: */
11935: typedef struct AggInfo AggInfo;
11936: typedef struct AuthContext AuthContext;
11937: typedef struct AutoincInfo AutoincInfo;
11938: typedef struct Bitvec Bitvec;
11939: typedef struct CollSeq CollSeq;
11940: typedef struct Column Column;
11941: typedef struct Db Db;
11942: typedef struct Schema Schema;
11943: typedef struct Expr Expr;
11944: typedef struct ExprList ExprList;
11945: typedef struct ExprSpan ExprSpan;
11946: typedef struct FKey FKey;
11947: typedef struct FuncDestructor FuncDestructor;
11948: typedef struct FuncDef FuncDef;
11949: typedef struct FuncDefHash FuncDefHash;
11950: typedef struct IdList IdList;
11951: typedef struct Index Index;
11952: typedef struct IndexSample IndexSample;
11953: typedef struct KeyClass KeyClass;
11954: typedef struct KeyInfo KeyInfo;
11955: typedef struct Lookaside Lookaside;
11956: typedef struct LookasideSlot LookasideSlot;
11957: typedef struct Module Module;
11958: typedef struct NameContext NameContext;
11959: typedef struct Parse Parse;
11960: typedef struct PreUpdate PreUpdate;
11961: typedef struct PrintfArguments PrintfArguments;
11962: typedef struct RowSet RowSet;
11963: typedef struct Savepoint Savepoint;
11964: typedef struct Select Select;
11965: typedef struct SQLiteThread SQLiteThread;
11966: typedef struct SelectDest SelectDest;
11967: typedef struct SrcList SrcList;
11968: typedef struct StrAccum StrAccum;
11969: typedef struct Table Table;
11970: typedef struct TableLock TableLock;
11971: typedef struct Token Token;
11972: typedef struct TreeView TreeView;
11973: typedef struct Trigger Trigger;
11974: typedef struct TriggerPrg TriggerPrg;
11975: typedef struct TriggerStep TriggerStep;
11976: typedef struct UnpackedRecord UnpackedRecord;
11977: typedef struct VTable VTable;
11978: typedef struct VtabCtx VtabCtx;
11979: typedef struct Walker Walker;
11980: typedef struct WhereInfo WhereInfo;
11981: typedef struct With With;
11982: 
11983: /*
11984: ** Defer sourcing vdbe.h and btree.h until after the "u8" and
11985: ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
11986: ** pointer types (i.e. FuncDef) defined above.
11987: */
11988: /************** Include btree.h in the middle of sqliteInt.h *****************/
11989: /************** Begin file btree.h *******************************************/
11990: /*
11991: ** 2001 September 15
11992: **
11993: ** The author disclaims copyright to this source code.  In place of
11994: ** a legal notice, here is a blessing:
11995: **
11996: **    May you do good and not evil.
11997: **    May you find forgiveness for yourself and forgive others.
11998: **    May you share freely, never taking more than you give.
11999: **
12000: *************************************************************************
12001: ** This header file defines the interface that the sqlite B-Tree file
12002: ** subsystem.  See comments in the source code for a detailed description
12003: ** of what each interface routine does.
12004: */
12005: #ifndef SQLITE_BTREE_H
12006: #define SQLITE_BTREE_H
12007: 
12008: /* TODO: This definition is just included so other modules compile. It
12009: ** needs to be revisited.
12010: */
12011: #define SQLITE_N_BTREE_META 16
12012: 
12013: /*
12014: ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
12015: ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
12016: */
12017: #ifndef SQLITE_DEFAULT_AUTOVACUUM
12018:   #define SQLITE_DEFAULT_AUTOVACUUM 0
12019: #endif
12020: 
12021: #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
12022: #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
12023: #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
12024: 
12025: /*
12026: ** Forward declarations of structure
12027: */
12028: typedef struct Btree Btree;
12029: typedef struct BtCursor BtCursor;
12030: typedef struct BtShared BtShared;
12031: typedef struct BtreePayload BtreePayload;
12032: 
12033: 
12034: SQLITE_PRIVATE int sqlite3BtreeOpen(
12035:   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
12036:   const char *zFilename,   /* Name of database file to open */
12037:   sqlite3 *db,             /* Associated database connection */
12038:   Btree **ppBtree,         /* Return open Btree* here */
12039:   int flags,               /* Flags */
12040:   int vfsFlags             /* Flags passed through to VFS open */
12041: );
12042: 
12043: /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
12044: ** following values.
12045: **
12046: ** NOTE:  These values must match the corresponding PAGER_ values in
12047: ** pager.h.
12048: */
12049: #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
12050: #define BTREE_MEMORY        2  /* This is an in-memory DB */
12051: #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
12052: #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
12053: 
12054: SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
12055: SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
12056: SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
12057: #if SQLITE_MAX_MMAP_SIZE>0
12058: SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
12059: #endif
12060: SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
12061: SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
12062: SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
12063: SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
12064: SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
12065: SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
12066: SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
12067: SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
12068: SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
12069: SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
12070: SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
12071: SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
12072: SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
12073: SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
12074: SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
12075: SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
12076: SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
12077: SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
12078: SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
12079: SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
12080: SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
12081: SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
12082: SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
12083: SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
12084: 
12085: SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
12086: SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
12087: SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
12088: 
12089: SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
12090: 
12091: /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
12092: ** of the flags shown below.
12093: **
12094: ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
12095: ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
12096: ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
12097: ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
12098: ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
12099: ** indices.)
12100: */
12101: #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
12102: #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
12103: 
12104: SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
12105: SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
12106: SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
12107: SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
12108: 
12109: SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
12110: SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
12111: 
12112: SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
12113: 
12114: /*
12115: ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
12116: ** should be one of the following values. The integer values are assigned 
12117: ** to constants so that the offset of the corresponding field in an
12118: ** SQLite database header may be found using the following formula:
12119: **
12120: **   offset = 36 + (idx * 4)
12121: **
12122: ** For example, the free-page-count field is located at byte offset 36 of
12123: ** the database file header. The incr-vacuum-flag field is located at
12124: ** byte offset 64 (== 36+4*7).
12125: **
12126: ** The BTREE_DATA_VERSION value is not really a value stored in the header.
12127: ** It is a read-only number computed by the pager.  But we merge it with
12128: ** the header value access routines since its access pattern is the same.
12129: ** Call it a "virtual meta value".
12130: */
12131: #define BTREE_FREE_PAGE_COUNT     0
12132: #define BTREE_SCHEMA_VERSION      1
12133: #define BTREE_FILE_FORMAT         2
12134: #define BTREE_DEFAULT_CACHE_SIZE  3
12135: #define BTREE_LARGEST_ROOT_PAGE   4
12136: #define BTREE_TEXT_ENCODING       5
12137: #define BTREE_USER_VERSION        6
12138: #define BTREE_INCR_VACUUM         7
12139: #define BTREE_APPLICATION_ID      8
12140: #define BTREE_DATA_VERSION        15  /* A virtual meta-value */
12141: 
12142: /*
12143: ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
12144: ** interface.
12145: **
12146: ** BTREE_HINT_RANGE  (arguments: Expr*, Mem*)
12147: **
12148: **     The first argument is an Expr* (which is guaranteed to be constant for
12149: **     the lifetime of the cursor) that defines constraints on which rows
12150: **     might be fetched with this cursor.  The Expr* tree may contain
12151: **     TK_REGISTER nodes that refer to values stored in the array of registers
12152: **     passed as the second parameter.  In other words, if Expr.op==TK_REGISTER
12153: **     then the value of the node is the value in Mem[pExpr.iTable].  Any
12154: **     TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
12155: **     column of the b-tree of the cursor.  The Expr tree will not contain
12156: **     any function calls nor subqueries nor references to b-trees other than
12157: **     the cursor being hinted.
12158: **
12159: **     The design of the _RANGE hint is aid b-tree implementations that try
12160: **     to prefetch content from remote machines - to provide those
12161: **     implementations with limits on what needs to be prefetched and thereby
12162: **     reduce network bandwidth.
12163: **
12164: ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
12165: ** standard SQLite.  The other hints are provided for extentions that use
12166: ** the SQLite parser and code generator but substitute their own storage
12167: ** engine.
12168: */
12169: #define BTREE_HINT_RANGE 0       /* Range constraints on queries */
12170: 
12171: /*
12172: ** Values that may be OR'd together to form the argument to the
12173: ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
12174: **
12175: ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
12176: ** to be filled with content that is already in sorted order.
12177: **
12178: ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
12179: ** OP_SeekLE opcodes for a range search, but where the range of entries
12180: ** selected will all have the same key.  In other words, the cursor will
12181: ** be used only for equality key searches.
12182: **
12183: */
12184: #define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
12185: #define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
12186: 
12187: /* 
12188: ** Flags passed as the third argument to sqlite3BtreeCursor().
12189: **
12190: ** For read-only cursors the wrFlag argument is always zero. For read-write
12191: ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
12192: ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
12193: ** only be used by SQLite for the following:
12194: **
12195: **   * to seek to and then delete specific entries, and/or
12196: **
12197: **   * to read values that will be used to create keys that other
12198: **     BTREE_FORDELETE cursors will seek to and delete.
12199: **
12200: ** The BTREE_FORDELETE flag is an optimization hint.  It is not used by
12201: ** by this, the native b-tree engine of SQLite, but it is available to
12202: ** alternative storage engines that might be substituted in place of this
12203: ** b-tree system.  For alternative storage engines in which a delete of
12204: ** the main table row automatically deletes corresponding index rows,
12205: ** the FORDELETE flag hint allows those alternative storage engines to
12206: ** skip a lot of work.  Namely:  FORDELETE cursors may treat all SEEK
12207: ** and DELETE operations as no-ops, and any READ operation against a
12208: ** FORDELETE cursor may return a null row: 0x01 0x00.
12209: */
12210: #define BTREE_WRCSR     0x00000004     /* read-write cursor */
12211: #define BTREE_FORDELETE 0x00000008     /* Cursor is for seek/delete only */
12212: 
12213: SQLITE_PRIVATE int sqlite3BtreeCursor(
12214:   Btree*,                              /* BTree containing table to open */
12215:   int iTable,                          /* Index of root page */
12216:   int wrFlag,                          /* 1 for writing.  0 for read-only */
12217:   struct KeyInfo*,                     /* First argument to compare function */
12218:   BtCursor *pCursor                    /* Space to write cursor structure */
12219: );
12220: SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
12221: SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
12222: SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
12223: #ifdef SQLITE_ENABLE_CURSOR_HINTS
12224: SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
12225: #endif
12226: 
12227: SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
12228: SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
12229:   BtCursor*,
12230:   UnpackedRecord *pUnKey,
12231:   i64 intKey,
12232:   int bias,
12233:   int *pRes
12234: );
12235: SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
12236: SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
12237: SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
12238: 
12239: /* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */
12240: #define BTREE_SAVEPOSITION 0x02  /* Leave cursor pointing at NEXT or PREV */
12241: #define BTREE_AUXDELETE    0x04  /* not the primary delete operation */
12242: 
12243: /* An instance of the BtreePayload object describes the content of a single
12244: ** entry in either an index or table btree.
12245: **
12246: ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
12247: ** an arbitrary key and no data.  These btrees have pKey,nKey set to their
12248: ** key and pData,nData,nZero set to zero.
12249: **
12250: ** Table btrees (used for rowid tables) contain an integer rowid used as
12251: ** the key and passed in the nKey field.  The pKey field is zero.  
12252: ** pData,nData hold the content of the new entry.  nZero extra zero bytes
12253: ** are appended to the end of the content when constructing the entry.
12254: **
12255: ** This object is used to pass information into sqlite3BtreeInsert().  The
12256: ** same information used to be passed as five separate parameters.  But placing
12257: ** the information into this object helps to keep the interface more 
12258: ** organized and understandable, and it also helps the resulting code to
12259: ** run a little faster by using fewer registers for parameter passing.
12260: */
12261: struct BtreePayload {
12262:   const void *pKey;       /* Key content for indexes.  NULL for tables */
12263:   sqlite3_int64 nKey;     /* Size of pKey for indexes.  PRIMARY KEY for tabs */
12264:   const void *pData;      /* Data for tables.  NULL for indexes */
12265:   int nData;              /* Size of pData.  0 if none. */
12266:   int nZero;              /* Extra zero data appended after pData,nData */
12267: };
12268: 
12269: SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
12270:                        int bias, int seekResult);
12271: SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
12272: SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
12273: SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
12274: SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
12275: SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
12276: SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
12277: SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
12278: SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
12279: SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
12280: SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
12281: 
12282: SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
12283: SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
12284: 
12285: SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
12286: SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
12287: SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
12288: SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
12289: SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
12290: SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
12291: SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
12292: 
12293: #ifndef NDEBUG
12294: SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
12295: #endif
12296: 
12297: #ifndef SQLITE_OMIT_BTREECOUNT
12298: SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
12299: #endif
12300: 
12301: #ifdef SQLITE_TEST
12302: SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
12303: SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
12304: #endif
12305: 
12306: #ifndef SQLITE_OMIT_WAL
12307: SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
12308: #endif
12309: 
12310: /*
12311: ** If we are not using shared cache, then there is no need to
12312: ** use mutexes to access the BtShared structures.  So make the
12313: ** Enter and Leave procedures no-ops.
12314: */
12315: #ifndef SQLITE_OMIT_SHARED_CACHE
12316: SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
12317: SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
12318: SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
12319: SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
12320: SQLITE_PRIVATE   int sqlite3BtreeConnectionCount(Btree*);
12321: #else
12322: # define sqlite3BtreeEnter(X) 
12323: # define sqlite3BtreeEnterAll(X)
12324: # define sqlite3BtreeSharable(X) 0
12325: # define sqlite3BtreeEnterCursor(X)
12326: # define sqlite3BtreeConnectionCount(X) 1
12327: #endif
12328: 
12329: #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
12330: SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
12331: SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
12332: SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
12333: #ifndef NDEBUG
12334:   /* These routines are used inside assert() statements only. */
12335: SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
12336: SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
12337: SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
12338: #endif
12339: #else
12340: 
12341: # define sqlite3BtreeLeave(X)
12342: # define sqlite3BtreeLeaveCursor(X)
12343: # define sqlite3BtreeLeaveAll(X)
12344: 
12345: # define sqlite3BtreeHoldsMutex(X) 1
12346: # define sqlite3BtreeHoldsAllMutexes(X) 1
12347: # define sqlite3SchemaMutexHeld(X,Y,Z) 1
12348: #endif
12349: 
12350: 
12351: #endif /* SQLITE_BTREE_H */
12352: 
12353: /************** End of btree.h ***********************************************/
12354: /************** Continuing where we left off in sqliteInt.h ******************/
12355: /************** Include vdbe.h in the middle of sqliteInt.h ******************/
12356: /************** Begin file vdbe.h ********************************************/
12357: /*
12358: ** 2001 September 15
12359: **
12360: ** The author disclaims copyright to this source code.  In place of
12361: ** a legal notice, here is a blessing:
12362: **
12363: **    May you do good and not evil.
12364: **    May you find forgiveness for yourself and forgive others.
12365: **    May you share freely, never taking more than you give.
12366: **
12367: *************************************************************************
12368: ** Header file for the Virtual DataBase Engine (VDBE)
12369: **
12370: ** This header defines the interface to the virtual database engine
12371: ** or VDBE.  The VDBE implements an abstract machine that runs a
12372: ** simple program to access and modify the underlying database.
12373: */
12374: #ifndef SQLITE_VDBE_H
12375: #define SQLITE_VDBE_H
12376: /* #include <stdio.h> */
12377: 
12378: /*
12379: ** A single VDBE is an opaque structure named "Vdbe".  Only routines
12380: ** in the source file sqliteVdbe.c are allowed to see the insides
12381: ** of this structure.
12382: */
12383: typedef struct Vdbe Vdbe;
12384: 
12385: /*
12386: ** The names of the following types declared in vdbeInt.h are required
12387: ** for the VdbeOp definition.
12388: */
12389: typedef struct Mem Mem;
12390: typedef struct SubProgram SubProgram;
12391: 
12392: /*
12393: ** A single instruction of the virtual machine has an opcode
12394: ** and as many as three operands.  The instruction is recorded
12395: ** as an instance of the following structure:
12396: */
12397: struct VdbeOp {
12398:   u8 opcode;          /* What operation to perform */
12399:   signed char p4type; /* One of the P4_xxx constants for p4 */
12400:   u8 notUsed1;
12401:   u8 p5;              /* Fifth parameter is an unsigned character */
12402:   int p1;             /* First operand */
12403:   int p2;             /* Second parameter (often the jump destination) */
12404:   int p3;             /* The third parameter */
12405:   union p4union {     /* fourth parameter */
12406:     int i;                 /* Integer value if p4type==P4_INT32 */
12407:     void *p;               /* Generic pointer */
12408:     char *z;               /* Pointer to data for string (char array) types */
12409:     i64 *pI64;             /* Used when p4type is P4_INT64 */
12410:     double *pReal;         /* Used when p4type is P4_REAL */
12411:     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
12412:     sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
12413:     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
12414:     Mem *pMem;             /* Used when p4type is P4_MEM */
12415:     VTable *pVtab;         /* Used when p4type is P4_VTAB */
12416:     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
12417:     int *ai;               /* Used when p4type is P4_INTARRAY */
12418:     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
12419:     Table *pTab;           /* Used when p4type is P4_TABLE */
12420: #ifdef SQLITE_ENABLE_CURSOR_HINTS
12421:     Expr *pExpr;           /* Used when p4type is P4_EXPR */
12422: #endif
12423:     int (*xAdvance)(BtCursor *, int *);
12424:   } p4;
12425: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12426:   char *zComment;          /* Comment to improve readability */
12427: #endif
12428: #ifdef VDBE_PROFILE
12429:   u32 cnt;                 /* Number of times this instruction was executed */
12430:   u64 cycles;              /* Total time spent executing this instruction */
12431: #endif
12432: #ifdef SQLITE_VDBE_COVERAGE
12433:   int iSrcLine;            /* Source-code line that generated this opcode */
12434: #endif
12435: };
12436: typedef struct VdbeOp VdbeOp;
12437: 
12438: 
12439: /*
12440: ** A sub-routine used to implement a trigger program.
12441: */
12442: struct SubProgram {
12443:   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
12444:   int nOp;                      /* Elements in aOp[] */
12445:   int nMem;                     /* Number of memory cells required */
12446:   int nCsr;                     /* Number of cursors required */
12447:   int nOnce;                    /* Number of OP_Once instructions */
12448:   void *token;                  /* id that may be used to recursive triggers */
12449:   SubProgram *pNext;            /* Next sub-program already visited */
12450: };
12451: 
12452: /*
12453: ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
12454: ** it takes up less space.
12455: */
12456: struct VdbeOpList {
12457:   u8 opcode;          /* What operation to perform */
12458:   signed char p1;     /* First operand */
12459:   signed char p2;     /* Second parameter (often the jump destination) */
12460:   signed char p3;     /* Third parameter */
12461: };
12462: typedef struct VdbeOpList VdbeOpList;
12463: 
12464: /*
12465: ** Allowed values of VdbeOp.p4type
12466: */
12467: #define P4_NOTUSED    0   /* The P4 parameter is not used */
12468: #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
12469: #define P4_STATIC   (-2)  /* Pointer to a static string */
12470: #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
12471: #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
12472: #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
12473: #define P4_EXPR     (-7)  /* P4 is a pointer to an Expr tree */
12474: #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
12475: #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
12476: #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
12477: #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
12478: #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
12479: #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
12480: #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
12481: #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
12482: #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
12483: #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12484: #define P4_TABLE    (-20) /* P4 is a pointer to a Table structure */
12485: #define P4_FUNCCTX  (-21) /* P4 is a pointer to an sqlite3_context object */
12486: 
12487: /* Error message codes for OP_Halt */
12488: #define P5_ConstraintNotNull 1
12489: #define P5_ConstraintUnique  2
12490: #define P5_ConstraintCheck   3
12491: #define P5_ConstraintFK      4
12492: 
12493: /*
12494: ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
12495: ** number of columns of data returned by the statement.
12496: */
12497: #define COLNAME_NAME     0
12498: #define COLNAME_DECLTYPE 1
12499: #define COLNAME_DATABASE 2
12500: #define COLNAME_TABLE    3
12501: #define COLNAME_COLUMN   4
12502: #ifdef SQLITE_ENABLE_COLUMN_METADATA
12503: # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
12504: #else
12505: # ifdef SQLITE_OMIT_DECLTYPE
12506: #   define COLNAME_N      1      /* Store only the name */
12507: # else
12508: #   define COLNAME_N      2      /* Store the name and decltype */
12509: # endif
12510: #endif
12511: 
12512: /*
12513: ** The following macro converts a relative address in the p2 field
12514: ** of a VdbeOp structure into a negative number so that 
12515: ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
12516: ** the macro again restores the address.
12517: */
12518: #define ADDR(X)  (-1-(X))
12519: 
12520: /*
12521: ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
12522: ** header file that defines a number for each opcode used by the VDBE.
12523: */
12524: /************** Include opcodes.h in the middle of vdbe.h ********************/
12525: /************** Begin file opcodes.h *****************************************/
12526: /* Automatically generated.  Do not edit */
12527: /* See the tool/mkopcodeh.tcl script for details */
12528: #define OP_Savepoint       0
12529: #define OP_AutoCommit      1
12530: #define OP_Transaction     2
12531: #define OP_SorterNext      3
12532: #define OP_PrevIfOpen      4
12533: #define OP_NextIfOpen      5
12534: #define OP_Prev            6
12535: #define OP_Next            7
12536: #define OP_Checkpoint      8
12537: #define OP_JournalMode     9
12538: #define OP_Vacuum         10
12539: #define OP_VFilter        11 /* synopsis: iplan=r[P3] zplan='P4'           */
12540: #define OP_VUpdate        12 /* synopsis: data=r[P3@P2]                    */
12541: #define OP_Goto           13
12542: #define OP_Gosub          14
12543: #define OP_InitCoroutine  15
12544: #define OP_Yield          16
12545: #define OP_MustBeInt      17
12546: #define OP_Jump           18
12547: #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
12548: #define OP_Once           20
12549: #define OP_If             21
12550: #define OP_IfNot          22
12551: #define OP_SeekLT         23 /* synopsis: key=r[P3@P4]                     */
12552: #define OP_SeekLE         24 /* synopsis: key=r[P3@P4]                     */
12553: #define OP_SeekGE         25 /* synopsis: key=r[P3@P4]                     */
12554: #define OP_SeekGT         26 /* synopsis: key=r[P3@P4]                     */
12555: #define OP_Or             27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12556: #define OP_And            28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12557: #define OP_NoConflict     29 /* synopsis: key=r[P3@P4]                     */
12558: #define OP_NotFound       30 /* synopsis: key=r[P3@P4]                     */
12559: #define OP_Found          31 /* synopsis: key=r[P3@P4]                     */
12560: #define OP_SeekRowid      32 /* synopsis: intkey=r[P3]                     */
12561: #define OP_NotExists      33 /* synopsis: intkey=r[P3]                     */
12562: #define OP_IsNull         34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12563: #define OP_NotNull        35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12564: #define OP_Ne             36 /* same as TK_NE, synopsis: IF r[P3]!=r[P1]   */
12565: #define OP_Eq             37 /* same as TK_EQ, synopsis: IF r[P3]==r[P1]   */
12566: #define OP_Gt             38 /* same as TK_GT, synopsis: IF r[P3]>r[P1]    */
12567: #define OP_Le             39 /* same as TK_LE, synopsis: IF r[P3]<=r[P1]   */
12568: #define OP_Lt             40 /* same as TK_LT, synopsis: IF r[P3]<r[P1]    */
12569: #define OP_Ge             41 /* same as TK_GE, synopsis: IF r[P3]>=r[P1]   */
12570: #define OP_Last           42
12571: #define OP_BitAnd         43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12572: #define OP_BitOr          44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12573: #define OP_ShiftLeft      45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12574: #define OP_ShiftRight     46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12575: #define OP_Add            47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12576: #define OP_Subtract       48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12577: #define OP_Multiply       49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12578: #define OP_Divide         50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12579: #define OP_Remainder      51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12580: #define OP_Concat         52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12581: #define OP_SorterSort     53
12582: #define OP_BitNot         54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12583: #define OP_Sort           55
12584: #define OP_Rewind         56
12585: #define OP_IdxLE          57 /* synopsis: key=r[P3@P4]                     */
12586: #define OP_IdxGT          58 /* synopsis: key=r[P3@P4]                     */
12587: #define OP_IdxLT          59 /* synopsis: key=r[P3@P4]                     */
12588: #define OP_IdxGE          60 /* synopsis: key=r[P3@P4]                     */
12589: #define OP_RowSetRead     61 /* synopsis: r[P3]=rowset(P1)                 */
12590: #define OP_RowSetTest     62 /* synopsis: if r[P3] in rowset(P1) goto P2   */
12591: #define OP_Program        63
12592: #define OP_FkIfZero       64 /* synopsis: if fkctr[P1]==0 goto P2          */
12593: #define OP_IfPos          65 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12594: #define OP_IfNotZero      66 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12595: #define OP_DecrJumpZero   67 /* synopsis: if (--r[P1])==0 goto P2          */
12596: #define OP_IncrVacuum     68
12597: #define OP_VNext          69
12598: #define OP_Init           70 /* synopsis: Start at P2                      */
12599: #define OP_Return         71
12600: #define OP_EndCoroutine   72
12601: #define OP_HaltIfNull     73 /* synopsis: if r[P3]=null halt               */
12602: #define OP_Halt           74
12603: #define OP_Integer        75 /* synopsis: r[P2]=P1                         */
12604: #define OP_Int64          76 /* synopsis: r[P2]=P4                         */
12605: #define OP_String         77 /* synopsis: r[P2]='P4' (len=P1)              */
12606: #define OP_Null           78 /* synopsis: r[P2..P3]=NULL                   */
12607: #define OP_SoftNull       79 /* synopsis: r[P1]=NULL                       */
12608: #define OP_Blob           80 /* synopsis: r[P2]=P4 (len=P1)                */
12609: #define OP_Variable       81 /* synopsis: r[P2]=parameter(P1,P4)           */
12610: #define OP_Move           82 /* synopsis: r[P2@P3]=r[P1@P3]                */
12611: #define OP_Copy           83 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
12612: #define OP_SCopy          84 /* synopsis: r[P2]=r[P1]                      */
12613: #define OP_IntCopy        85 /* synopsis: r[P2]=r[P1]                      */
12614: #define OP_ResultRow      86 /* synopsis: output=r[P1@P2]                  */
12615: #define OP_CollSeq        87
12616: #define OP_Function0      88 /* synopsis: r[P3]=func(r[P2@P5])             */
12617: #define OP_Function       89 /* synopsis: r[P3]=func(r[P2@P5])             */
12618: #define OP_AddImm         90 /* synopsis: r[P1]=r[P1]+P2                   */
12619: #define OP_RealAffinity   91
12620: #define OP_Cast           92 /* synopsis: affinity(r[P1])                  */
12621: #define OP_Permutation    93
12622: #define OP_Compare        94 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
12623: #define OP_Column         95 /* synopsis: r[P3]=PX                         */
12624: #define OP_Affinity       96 /* synopsis: affinity(r[P1@P2])               */
12625: #define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
12626: #define OP_MakeRecord     98 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
12627: #define OP_Count          99 /* synopsis: r[P2]=count()                    */
12628: #define OP_ReadCookie    100
12629: #define OP_SetCookie     101
12630: #define OP_ReopenIdx     102 /* synopsis: root=P2 iDb=P3                   */
12631: #define OP_OpenRead      103 /* synopsis: root=P2 iDb=P3                   */
12632: #define OP_OpenWrite     104 /* synopsis: root=P2 iDb=P3                   */
12633: #define OP_OpenAutoindex 105 /* synopsis: nColumn=P2                       */
12634: #define OP_OpenEphemeral 106 /* synopsis: nColumn=P2                       */
12635: #define OP_SorterOpen    107
12636: #define OP_SequenceTest  108 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
12637: #define OP_OpenPseudo    109 /* synopsis: P3 columns in r[P2]              */
12638: #define OP_Close         110
12639: #define OP_ColumnsUsed   111
12640: #define OP_Sequence      112 /* synopsis: r[P2]=cursor[P1].ctr++           */
12641: #define OP_NewRowid      113 /* synopsis: r[P2]=rowid                      */
12642: #define OP_Insert        114 /* synopsis: intkey=r[P3] data=r[P2]          */
12643: #define OP_InsertInt     115 /* synopsis: intkey=P3 data=r[P2]             */
12644: #define OP_Delete        116
12645: #define OP_ResetCount    117
12646: #define OP_SorterCompare 118 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12647: #define OP_SorterData    119 /* synopsis: r[P2]=data                       */
12648: #define OP_RowKey        120 /* synopsis: r[P2]=key                        */
12649: #define OP_RowData       121 /* synopsis: r[P2]=data                       */
12650: #define OP_Rowid         122 /* synopsis: r[P2]=rowid                      */
12651: #define OP_NullRow       123
12652: #define OP_SorterInsert  124
12653: #define OP_IdxInsert     125 /* synopsis: key=r[P2]                        */
12654: #define OP_IdxDelete     126 /* synopsis: key=r[P2@P3]                     */
12655: #define OP_Seek          127 /* synopsis: Move P3 to P1.rowid              */
12656: #define OP_IdxRowid      128 /* synopsis: r[P2]=rowid                      */
12657: #define OP_Destroy       129
12658: #define OP_Clear         130
12659: #define OP_ResetSorter   131
12660: #define OP_CreateIndex   132 /* synopsis: r[P2]=root iDb=P1                */
12661: #define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
12662: #define OP_CreateTable   134 /* synopsis: r[P2]=root iDb=P1                */
12663: #define OP_ParseSchema   135
12664: #define OP_LoadAnalysis  136
12665: #define OP_DropTable     137
12666: #define OP_DropIndex     138
12667: #define OP_DropTrigger   139
12668: #define OP_IntegrityCk   140
12669: #define OP_RowSetAdd     141 /* synopsis: rowset(P1)=r[P2]                 */
12670: #define OP_Param         142
12671: #define OP_FkCounter     143 /* synopsis: fkctr[P1]+=P2                    */
12672: #define OP_MemMax        144 /* synopsis: r[P1]=max(r[P1],r[P2])           */
12673: #define OP_OffsetLimit   145 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12674: #define OP_AggStep0      146 /* synopsis: accum=r[P3] step(r[P2@P5])       */
12675: #define OP_AggStep       147 /* synopsis: accum=r[P3] step(r[P2@P5])       */
12676: #define OP_AggFinal      148 /* synopsis: accum=r[P1] N=P2                 */
12677: #define OP_Expire        149
12678: #define OP_TableLock     150 /* synopsis: iDb=P1 root=P2 write=P3          */
12679: #define OP_VBegin        151
12680: #define OP_VCreate       152
12681: #define OP_VDestroy      153
12682: #define OP_VOpen         154
12683: #define OP_VColumn       155 /* synopsis: r[P3]=vcolumn(P2)                */
12684: #define OP_VRename       156
12685: #define OP_Pagecount     157
12686: #define OP_MaxPgcnt      158
12687: #define OP_CursorHint    159
12688: #define OP_Noop          160
12689: #define OP_Explain       161
12690: 
12691: /* Properties such as "out2" or "jump" that are specified in
12692: ** comments following the "case" for each opcode in the vdbe.c
12693: ** are encoded into bitvectors as follows:
12694: */
12695: #define OPFLG_JUMP        0x01  /* jump:  P2 holds jmp target */
12696: #define OPFLG_IN1         0x02  /* in1:   P1 is an input */
12697: #define OPFLG_IN2         0x04  /* in2:   P2 is an input */
12698: #define OPFLG_IN3         0x08  /* in3:   P3 is an input */
12699: #define OPFLG_OUT2        0x10  /* out2:  P2 is an output */
12700: #define OPFLG_OUT3        0x20  /* out3:  P3 is an output */
12701: #define OPFLG_INITIALIZER {\
12702: /*   0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12703: /*   8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12704: /*  16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12705: /*  24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12706: /*  32 */ 0x09, 0x09, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12707: /*  40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12708: /*  48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12709: /*  56 */ 0x01, 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b, 0x01,\
12710: /*  64 */ 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x01, 0x02,\
12711: /*  72 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
12712: /*  80 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12713: /*  88 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00,\
12714: /*  96 */ 0x00, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
12715: /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12716: /* 112 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12717: /* 120 */ 0x00, 0x00, 0x10, 0x00, 0x04, 0x04, 0x00, 0x00,\
12718: /* 128 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00,\
12719: /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00,\
12720: /* 144 */ 0x04, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12721: /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00,\
12722: /* 160 */ 0x00, 0x00,}
12723: 
12724: /* The sqlite3P2Values() routine is able to run faster if it knows
12725: ** the value of the largest JUMP opcode.  The smaller the maximum
12726: ** JUMP opcode the better, so the mkopcodeh.tcl script that
12727: ** generated this include file strives to group all JUMP opcodes
12728: ** together near the beginning of the list.
12729: */
12730: #define SQLITE_MX_JUMP_OPCODE  70  /* Maximum JUMP opcode */
12731: 
12732: /************** End of opcodes.h *********************************************/
12733: /************** Continuing where we left off in vdbe.h ***********************/
12734: 
12735: /*
12736: ** Prototypes for the VDBE interface.  See comments on the implementation
12737: ** for a description of what each of these routines does.
12738: */
12739: SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
12740: SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
12741: SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
12742: SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
12743: SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
12744: SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
12745: SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
12746: SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
12747: SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
12748: SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
12749: SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
12750: SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
12751: #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
12752: SQLITE_PRIVATE   void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
12753: #else
12754: # define sqlite3VdbeVerifyNoMallocRequired(A,B)
12755: #endif
12756: SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
12757: SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
12758: SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
12759: SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
12760: SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
12761: SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
12762: SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
12763: SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
12764: SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
12765: SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
12766: SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
12767: SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
12768: SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
12769: SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
12770: SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
12771: SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
12772: SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
12773: SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
12774: SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
12775: SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
12776: SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
12777: SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
12778: SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
12779: #ifdef SQLITE_DEBUG
12780: SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
12781: #endif
12782: SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
12783: SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
12784: SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
12785: SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
12786: SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
12787: SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
12788: SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
12789: SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
12790: SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
12791: SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
12792: SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
12793: SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
12794: #ifndef SQLITE_OMIT_TRACE
12795: SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
12796: #endif
12797: SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12798: 
12799: SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
12800: SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
12801: SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
12802: SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
12803: 
12804: typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
12805: SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
12806: 
12807: #ifndef SQLITE_OMIT_TRIGGER
12808: SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
12809: #endif
12810: 
12811: /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
12812: ** each VDBE opcode.
12813: **
12814: ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
12815: ** comments in VDBE programs that show key decision points in the code
12816: ** generator.
12817: */
12818: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12819: SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
12820: # define VdbeComment(X)  sqlite3VdbeComment X
12821: SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
12822: # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
12823: # ifdef SQLITE_ENABLE_MODULE_COMMENTS
12824: #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
12825: # else
12826: #   define VdbeModuleComment(X)
12827: # endif
12828: #else
12829: # define VdbeComment(X)
12830: # define VdbeNoopComment(X)
12831: # define VdbeModuleComment(X)
12832: #endif
12833: 
12834: /*
12835: ** The VdbeCoverage macros are used to set a coverage testing point
12836: ** for VDBE branch instructions.  The coverage testing points are line
12837: ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
12838: ** only works with an amalagmation build.  That's ok since a VDBE branch
12839: ** coverage build designed for testing the test suite only.  No application
12840: ** should ever ship with VDBE branch coverage measuring turned on.
12841: **
12842: **    VdbeCoverage(v)                  // Mark the previously coded instruction
12843: **                                     // as a branch
12844: **
12845: **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
12846: **
12847: **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
12848: **
12849: **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
12850: **
12851: ** Every VDBE branch operation must be tagged with one of the macros above.
12852: ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
12853: ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
12854: ** routine in vdbe.c, alerting the developer to the missed tag.
12855: */
12856: #ifdef SQLITE_VDBE_COVERAGE
12857: SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
12858: # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
12859: # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
12860: # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
12861: # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
12862: # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
12863: #else
12864: # define VdbeCoverage(v)
12865: # define VdbeCoverageIf(v,x)
12866: # define VdbeCoverageAlwaysTaken(v)
12867: # define VdbeCoverageNeverTaken(v)
12868: # define VDBE_OFFSET_LINENO(x) 0
12869: #endif
12870: 
12871: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
12872: SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
12873: #else
12874: # define sqlite3VdbeScanStatus(a,b,c,d,e)
12875: #endif
12876: 
12877: #endif /* SQLITE_VDBE_H */
12878: 
12879: /************** End of vdbe.h ************************************************/
12880: /************** Continuing where we left off in sqliteInt.h ******************/
12881: /************** Include pager.h in the middle of sqliteInt.h *****************/
12882: /************** Begin file pager.h *******************************************/
12883: /*
12884: ** 2001 September 15
12885: **
12886: ** The author disclaims copyright to this source code.  In place of
12887: ** a legal notice, here is a blessing:
12888: **
12889: **    May you do good and not evil.
12890: **    May you find forgiveness for yourself and forgive others.
12891: **    May you share freely, never taking more than you give.
12892: **
12893: *************************************************************************
12894: ** This header file defines the interface that the sqlite page cache
12895: ** subsystem.  The page cache subsystem reads and writes a file a page
12896: ** at a time and provides a journal for rollback.
12897: */
12898: 
12899: #ifndef SQLITE_PAGER_H
12900: #define SQLITE_PAGER_H
12901: 
12902: /*
12903: ** Default maximum size for persistent journal files. A negative 
12904: ** value means no limit. This value may be overridden using the 
12905: ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
12906: */
12907: #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
12908:   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
12909: #endif
12910: 
12911: /*
12912: ** The type used to represent a page number.  The first page in a file
12913: ** is called page 1.  0 is used to represent "not a page".
12914: */
12915: typedef u32 Pgno;
12916: 
12917: /*
12918: ** Each open file is managed by a separate instance of the "Pager" structure.
12919: */
12920: typedef struct Pager Pager;
12921: 
12922: /*
12923: ** Handle type for pages.
12924: */
12925: typedef struct PgHdr DbPage;
12926: 
12927: /*
12928: ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
12929: ** reserved for working around a windows/posix incompatibility). It is
12930: ** used in the journal to signify that the remainder of the journal file 
12931: ** is devoted to storing a master journal name - there are no more pages to
12932: ** roll back. See comments for function writeMasterJournal() in pager.c 
12933: ** for details.
12934: */
12935: #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
12936: 
12937: /*
12938: ** Allowed values for the flags parameter to sqlite3PagerOpen().
12939: **
12940: ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
12941: */
12942: #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
12943: #define PAGER_MEMORY        0x0002    /* In-memory database */
12944: 
12945: /*
12946: ** Valid values for the second argument to sqlite3PagerLockingMode().
12947: */
12948: #define PAGER_LOCKINGMODE_QUERY      -1
12949: #define PAGER_LOCKINGMODE_NORMAL      0
12950: #define PAGER_LOCKINGMODE_EXCLUSIVE   1
12951: 
12952: /*
12953: ** Numeric constants that encode the journalmode.
12954: **
12955: ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
12956: ** are exposed in the API via the "PRAGMA journal_mode" command and
12957: ** therefore cannot be changed without a compatibility break.
12958: */
12959: #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
12960: #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
12961: #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
12962: #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
12963: #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
12964: #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
12965: #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
12966: 
12967: /*
12968: ** Flags that make up the mask passed to sqlite3PagerGet().
12969: */
12970: #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
12971: #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
12972: 
12973: /*
12974: ** Flags for sqlite3PagerSetFlags()
12975: **
12976: ** Value constraints (enforced via assert()):
12977: **    PAGER_FULLFSYNC      == SQLITE_FullFSync
12978: **    PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
12979: **    PAGER_CACHE_SPILL    == SQLITE_CacheSpill
12980: */
12981: #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
12982: #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
12983: #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
12984: #define PAGER_SYNCHRONOUS_EXTRA     0x04  /* PRAGMA synchronous=EXTRA */
12985: #define PAGER_SYNCHRONOUS_MASK      0x07  /* Mask for four values above */
12986: #define PAGER_FULLFSYNC             0x08  /* PRAGMA fullfsync=ON */
12987: #define PAGER_CKPT_FULLFSYNC        0x10  /* PRAGMA checkpoint_fullfsync=ON */
12988: #define PAGER_CACHESPILL            0x20  /* PRAGMA cache_spill=ON */
12989: #define PAGER_FLAGS_MASK            0x38  /* All above except SYNCHRONOUS */
12990: 
12991: /*
12992: ** The remainder of this file contains the declarations of the functions
12993: ** that make up the Pager sub-system API. See source code comments for 
12994: ** a detailed description of each routine.
12995: */
12996: 
12997: /* Open and close a Pager connection. */ 
12998: SQLITE_PRIVATE int sqlite3PagerOpen(
12999:   sqlite3_vfs*,
13000:   Pager **ppPager,
13001:   const char*,
13002:   int,
13003:   int,
13004:   int,
13005:   void(*)(DbPage*)
13006: );
13007: SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
13008: SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
13009: 
13010: /* Functions used to configure a Pager object. */
13011: SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
13012: SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
13013: #ifdef SQLITE_HAS_CODEC
13014: SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
13015: #endif
13016: SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
13017: SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
13018: SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
13019: SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
13020: SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
13021: SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
13022: SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
13023: SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
13024: SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
13025: SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
13026: SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
13027: SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
13028: SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
13029: 
13030: /* Functions used to obtain and release page references. */ 
13031: SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
13032: SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
13033: SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
13034: SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
13035: SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
13036: 
13037: /* Operations on page references. */
13038: SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
13039: SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
13040: SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
13041: SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
13042: SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
13043: SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
13044: 
13045: /* Functions used to manage pager transactions and savepoints. */
13046: SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
13047: SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
13048: SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
13049: SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
13050: SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
13051: SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
13052: SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
13053: SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
13054: SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
13055: SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
13056: 
13057: #ifndef SQLITE_OMIT_WAL
13058: SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
13059: SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
13060: SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
13061: SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
13062: SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
13063: # ifdef SQLITE_ENABLE_SNAPSHOT
13064: SQLITE_PRIVATE   int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
13065: SQLITE_PRIVATE   int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
13066: # endif
13067: #endif
13068: 
13069: #ifdef SQLITE_ENABLE_ZIPVFS
13070: SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
13071: #endif
13072: 
13073: /* Functions used to query pager state and configuration. */
13074: SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
13075: SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
13076: #ifdef SQLITE_DEBUG
13077: SQLITE_PRIVATE   int sqlite3PagerRefcount(Pager*);
13078: #endif
13079: SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
13080: SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
13081: SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
13082: SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
13083: SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
13084: SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
13085: SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
13086: SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
13087: SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
13088: SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
13089: SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
13090: 
13091: /* Functions used to truncate the database file. */
13092: SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
13093: 
13094: SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
13095: 
13096: #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
13097: SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
13098: #endif
13099: 
13100: /* Functions to support testing and debugging. */
13101: #if !defined(NDEBUG) || defined(SQLITE_TEST)
13102: SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
13103: SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
13104: #endif
13105: #ifdef SQLITE_TEST
13106: SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
13107: SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
13108:   void disable_simulated_io_errors(void);
13109:   void enable_simulated_io_errors(void);
13110: #else
13111: # define disable_simulated_io_errors()
13112: # define enable_simulated_io_errors()
13113: #endif
13114: 
13115: #endif /* SQLITE_PAGER_H */
13116: 
13117: /************** End of pager.h ***********************************************/
13118: /************** Continuing where we left off in sqliteInt.h ******************/
13119: /************** Include pcache.h in the middle of sqliteInt.h ****************/
13120: /************** Begin file pcache.h ******************************************/
13121: /*
13122: ** 2008 August 05
13123: **
13124: ** The author disclaims copyright to this source code.  In place of
13125: ** a legal notice, here is a blessing:
13126: **
13127: **    May you do good and not evil.
13128: **    May you find forgiveness for yourself and forgive others.
13129: **    May you share freely, never taking more than you give.
13130: **
13131: *************************************************************************
13132: ** This header file defines the interface that the sqlite page cache
13133: ** subsystem. 
13134: */
13135: 
13136: #ifndef _PCACHE_H_
13137: 
13138: typedef struct PgHdr PgHdr;
13139: typedef struct PCache PCache;
13140: 
13141: /*
13142: ** Every page in the cache is controlled by an instance of the following
13143: ** structure.
13144: */
13145: struct PgHdr {
13146:   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
13147:   void *pData;                   /* Page data */
13148:   void *pExtra;                  /* Extra content */
13149:   PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
13150:   Pager *pPager;                 /* The pager this page is part of */
13151:   Pgno pgno;                     /* Page number for this page */
13152: #ifdef SQLITE_CHECK_PAGES
13153:   u32 pageHash;                  /* Hash of page content */
13154: #endif
13155:   u16 flags;                     /* PGHDR flags defined below */
13156: 
13157:   /**********************************************************************
13158:   ** Elements above are public.  All that follows is private to pcache.c
13159:   ** and should not be accessed by other modules.
13160:   */
13161:   i16 nRef;                      /* Number of users of this page */
13162:   PCache *pCache;                /* Cache that owns this page */
13163: 
13164:   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
13165:   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
13166: };
13167: 
13168: /* Bit values for PgHdr.flags */
13169: #define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
13170: #define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
13171: #define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
13172: #define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
13173:                                      ** writing this page to the database */
13174: #define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
13175: #define PGHDR_MMAP            0x020  /* This is an mmap page object */
13176: 
13177: #define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */
13178: 
13179: /* Initialize and shutdown the page cache subsystem */
13180: SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
13181: SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
13182: 
13183: /* Page cache buffer management:
13184: ** These routines implement SQLITE_CONFIG_PAGECACHE.
13185: */
13186: SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
13187: 
13188: /* Create a new pager cache.
13189: ** Under memory stress, invoke xStress to try to make pages clean.
13190: ** Only clean and unpinned pages can be reclaimed.
13191: */
13192: SQLITE_PRIVATE int sqlite3PcacheOpen(
13193:   int szPage,                    /* Size of every page */
13194:   int szExtra,                   /* Extra space associated with each page */
13195:   int bPurgeable,                /* True if pages are on backing store */
13196:   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
13197:   void *pStress,                 /* Argument to xStress */
13198:   PCache *pToInit                /* Preallocated space for the PCache */
13199: );
13200: 
13201: /* Modify the page-size after the cache has been created. */
13202: SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
13203: 
13204: /* Return the size in bytes of a PCache object.  Used to preallocate
13205: ** storage space.
13206: */
13207: SQLITE_PRIVATE int sqlite3PcacheSize(void);
13208: 
13209: /* One release per successful fetch.  Page is pinned until released.
13210: ** Reference counted. 
13211: */
13212: SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
13213: SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
13214: SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
13215: SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
13216: 
13217: SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
13218: SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
13219: SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
13220: SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
13221: SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
13222: 
13223: /* Change a page number.  Used by incr-vacuum. */
13224: SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
13225: 
13226: /* Remove all pages with pgno>x.  Reset the cache if x==0 */
13227: SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
13228: 
13229: /* Get a list of all dirty pages in the cache, sorted by page number */
13230: SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
13231: 
13232: /* Reset and close the cache object */
13233: SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
13234: 
13235: /* Clear flags from pages of the page cache */
13236: SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
13237: 
13238: /* Discard the contents of the cache */
13239: SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
13240: 
13241: /* Return the total number of outstanding page references */
13242: SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
13243: 
13244: /* Increment the reference count of an existing page */
13245: SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
13246: 
13247: SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
13248: 
13249: /* Return the total number of pages stored in the cache */
13250: SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
13251: 
13252: #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
13253: /* Iterate through all dirty pages currently stored in the cache. This
13254: ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
13255: ** library is built.
13256: */
13257: SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13258: #endif
13259: 
13260: #if defined(SQLITE_DEBUG)
13261: /* Check invariants on a PgHdr object */
13262: SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13263: #endif
13264: 
13265: /* Set and get the suggested cache-size for the specified pager-cache.
13266: **
13267: ** If no global maximum is configured, then the system attempts to limit
13268: ** the total number of pages cached by purgeable pager-caches to the sum
13269: ** of the suggested cache-sizes.
13270: */
13271: SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
13272: #ifdef SQLITE_TEST
13273: SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
13274: #endif
13275: 
13276: /* Set or get the suggested spill-size for the specified pager-cache.
13277: **
13278: ** The spill-size is the minimum number of pages in cache before the cache
13279: ** will attempt to spill dirty pages by calling xStress.
13280: */
13281: SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
13282: 
13283: /* Free up as much memory as possible from the page cache */
13284: SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
13285: 
13286: #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13287: /* Try to return memory used by the pcache module to the main memory heap */
13288: SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
13289: #endif
13290: 
13291: #ifdef SQLITE_TEST
13292: SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
13293: #endif
13294: 
13295: SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
13296: 
13297: /* Return the header size */
13298: SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
13299: SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
13300: 
13301: /* Number of dirty pages as a percentage of the configured cache size */
13302: SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
13303: 
13304: #endif /* _PCACHE_H_ */
13305: 
13306: /************** End of pcache.h **********************************************/
13307: /************** Continuing where we left off in sqliteInt.h ******************/
13308: /************** Include os.h in the middle of sqliteInt.h ********************/
13309: /************** Begin file os.h **********************************************/
13310: /*
13311: ** 2001 September 16
13312: **
13313: ** The author disclaims copyright to this source code.  In place of
13314: ** a legal notice, here is a blessing:
13315: **
13316: **    May you do good and not evil.
13317: **    May you find forgiveness for yourself and forgive others.
13318: **    May you share freely, never taking more than you give.
13319: **
13320: ******************************************************************************
13321: **
13322: ** This header file (together with is companion C source-code file
13323: ** "os.c") attempt to abstract the underlying operating system so that
13324: ** the SQLite library will work on both POSIX and windows systems.
13325: **
13326: ** This header file is #include-ed by sqliteInt.h and thus ends up
13327: ** being included by every source file.
13328: */
13329: #ifndef _SQLITE_OS_H_
13330: #define _SQLITE_OS_H_
13331: 
13332: /*
13333: ** Attempt to automatically detect the operating system and setup the
13334: ** necessary pre-processor macros for it.
13335: */
13336: /************** Include os_setup.h in the middle of os.h *********************/
13337: /************** Begin file os_setup.h ****************************************/
13338: /*
13339: ** 2013 November 25
13340: **
13341: ** The author disclaims copyright to this source code.  In place of
13342: ** a legal notice, here is a blessing:
13343: **
13344: **    May you do good and not evil.
13345: **    May you find forgiveness for yourself and forgive others.
13346: **    May you share freely, never taking more than you give.
13347: **
13348: ******************************************************************************
13349: **
13350: ** This file contains pre-processor directives related to operating system
13351: ** detection and/or setup.
13352: */
13353: #ifndef SQLITE_OS_SETUP_H
13354: #define SQLITE_OS_SETUP_H
13355: 
13356: /*
13357: ** Figure out if we are dealing with Unix, Windows, or some other operating
13358: ** system.
13359: **
13360: ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
13361: ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
13362: ** the three will be 1.  The other two will be 0.
13363: */
13364: #if defined(SQLITE_OS_OTHER)
13365: #  if SQLITE_OS_OTHER==1
13366: #    undef SQLITE_OS_UNIX
13367: #    define SQLITE_OS_UNIX 0
13368: #    undef SQLITE_OS_WIN
13369: #    define SQLITE_OS_WIN 0
13370: #  else
13371: #    undef SQLITE_OS_OTHER
13372: #  endif
13373: #endif
13374: #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
13375: #  define SQLITE_OS_OTHER 0
13376: #  ifndef SQLITE_OS_WIN
13377: #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
13378:         defined(__MINGW32__) || defined(__BORLANDC__)
13379: #      define SQLITE_OS_WIN 1
13380: #      define SQLITE_OS_UNIX 0
13381: #    else
13382: #      define SQLITE_OS_WIN 0
13383: #      define SQLITE_OS_UNIX 1
13384: #    endif
13385: #  else
13386: #    define SQLITE_OS_UNIX 0
13387: #  endif
13388: #else
13389: #  ifndef SQLITE_OS_WIN
13390: #    define SQLITE_OS_WIN 0
13391: #  endif
13392: #endif
13393: 
13394: #endif /* SQLITE_OS_SETUP_H */
13395: 
13396: /************** End of os_setup.h ********************************************/
13397: /************** Continuing where we left off in os.h *************************/
13398: 
13399: /* If the SET_FULLSYNC macro is not defined above, then make it
13400: ** a no-op
13401: */
13402: #ifndef SET_FULLSYNC
13403: # define SET_FULLSYNC(x,y)
13404: #endif
13405: 
13406: /*
13407: ** The default size of a disk sector
13408: */
13409: #ifndef SQLITE_DEFAULT_SECTOR_SIZE
13410: # define SQLITE_DEFAULT_SECTOR_SIZE 4096
13411: #endif
13412: 
13413: /*
13414: ** Temporary files are named starting with this prefix followed by 16 random
13415: ** alphanumeric characters, and no file extension. They are stored in the
13416: ** OS's standard temporary file directory, and are deleted prior to exit.
13417: ** If sqlite is being embedded in another program, you may wish to change the
13418: ** prefix to reflect your program's name, so that if your program exits
13419: ** prematurely, old temporary files can be easily identified. This can be done
13420: ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
13421: **
13422: ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
13423: ** Mcafee started using SQLite in their anti-virus product and it
13424: ** started putting files with the "sqlite" name in the c:/temp folder.
13425: ** This annoyed many windows users.  Those users would then do a 
13426: ** Google search for "sqlite", find the telephone numbers of the
13427: ** developers and call to wake them up at night and complain.
13428: ** For this reason, the default name prefix is changed to be "sqlite" 
13429: ** spelled backwards.  So the temp files are still identified, but
13430: ** anybody smart enough to figure out the code is also likely smart
13431: ** enough to know that calling the developer will not help get rid
13432: ** of the file.
13433: */
13434: #ifndef SQLITE_TEMP_FILE_PREFIX
13435: # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
13436: #endif
13437: 
13438: /*
13439: ** The following values may be passed as the second argument to
13440: ** sqlite3OsLock(). The various locks exhibit the following semantics:
13441: **
13442: ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
13443: ** RESERVED:  A single process may hold a RESERVED lock on a file at
13444: **            any time. Other processes may hold and obtain new SHARED locks.
13445: ** PENDING:   A single process may hold a PENDING lock on a file at
13446: **            any one time. Existing SHARED locks may persist, but no new
13447: **            SHARED locks may be obtained by other processes.
13448: ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
13449: **
13450: ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
13451: ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
13452: ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
13453: ** sqlite3OsLock().
13454: */
13455: #define NO_LOCK         0
13456: #define SHARED_LOCK     1
13457: #define RESERVED_LOCK   2
13458: #define PENDING_LOCK    3
13459: #define EXCLUSIVE_LOCK  4
13460: 
13461: /*
13462: ** File Locking Notes:  (Mostly about windows but also some info for Unix)
13463: **
13464: ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
13465: ** those functions are not available.  So we use only LockFile() and
13466: ** UnlockFile().
13467: **
13468: ** LockFile() prevents not just writing but also reading by other processes.
13469: ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
13470: ** byte out of a specific range of bytes. The lock byte is obtained at 
13471: ** random so two separate readers can probably access the file at the 
13472: ** same time, unless they are unlucky and choose the same lock byte.
13473: ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
13474: ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
13475: ** a single byte of the file that is designated as the reserved lock byte.
13476: ** A PENDING_LOCK is obtained by locking a designated byte different from
13477: ** the RESERVED_LOCK byte.
13478: **
13479: ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
13480: ** which means we can use reader/writer locks.  When reader/writer locks
13481: ** are used, the lock is placed on the same range of bytes that is used
13482: ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
13483: ** will support two or more Win95 readers or two or more WinNT readers.
13484: ** But a single Win95 reader will lock out all WinNT readers and a single
13485: ** WinNT reader will lock out all other Win95 readers.
13486: **
13487: ** The following #defines specify the range of bytes used for locking.
13488: ** SHARED_SIZE is the number of bytes available in the pool from which
13489: ** a random byte is selected for a shared lock.  The pool of bytes for
13490: ** shared locks begins at SHARED_FIRST. 
13491: **
13492: ** The same locking strategy and
13493: ** byte ranges are used for Unix.  This leaves open the possibility of having
13494: ** clients on win95, winNT, and unix all talking to the same shared file
13495: ** and all locking correctly.  To do so would require that samba (or whatever
13496: ** tool is being used for file sharing) implements locks correctly between
13497: ** windows and unix.  I'm guessing that isn't likely to happen, but by
13498: ** using the same locking range we are at least open to the possibility.
13499: **
13500: ** Locking in windows is manditory.  For this reason, we cannot store
13501: ** actual data in the bytes used for locking.  The pager never allocates
13502: ** the pages involved in locking therefore.  SHARED_SIZE is selected so
13503: ** that all locks will fit on a single page even at the minimum page size.
13504: ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
13505: ** is set high so that we don't have to allocate an unused page except
13506: ** for very large databases.  But one should test the page skipping logic 
13507: ** by setting PENDING_BYTE low and running the entire regression suite.
13508: **
13509: ** Changing the value of PENDING_BYTE results in a subtly incompatible
13510: ** file format.  Depending on how it is changed, you might not notice
13511: ** the incompatibility right away, even running a full regression test.
13512: ** The default location of PENDING_BYTE is the first byte past the
13513: ** 1GB boundary.
13514: **
13515: */
13516: #ifdef SQLITE_OMIT_WSD
13517: # define PENDING_BYTE     (0x40000000)
13518: #else
13519: # define PENDING_BYTE      sqlite3PendingByte
13520: #endif
13521: #define RESERVED_BYTE     (PENDING_BYTE+1)
13522: #define SHARED_FIRST      (PENDING_BYTE+2)
13523: #define SHARED_SIZE       510
13524: 
13525: /*
13526: ** Wrapper around OS specific sqlite3_os_init() function.
13527: */
13528: SQLITE_PRIVATE int sqlite3OsInit(void);
13529: 
13530: /* 
13531: ** Functions for accessing sqlite3_file methods 
13532: */
13533: SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13534: SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13535: SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13536: SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13537: SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13538: SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
13539: SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
13540: SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
13541: SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
13542: SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
13543: SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
13544: #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
13545: SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
13546: SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
13547: SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
13548: SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
13549: SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
13550: SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
13551: SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
13552: SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
13553: 
13554: 
13555: /* 
13556: ** Functions for accessing sqlite3_vfs methods 
13557: */
13558: SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
13559: SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
13560: SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
13561: SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
13562: #ifndef SQLITE_OMIT_LOAD_EXTENSION
13563: SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
13564: SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
13565: SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
13566: SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
13567: #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13568: SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
13569: SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
13570: SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
13571: SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
13572: 
13573: /*
13574: ** Convenience functions for opening and closing files using 
13575: ** sqlite3_malloc() to obtain space for the file-handle structure.
13576: */
13577: SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13578: SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13579: 
13580: #endif /* _SQLITE_OS_H_ */
13581: 
13582: /************** End of os.h **************************************************/
13583: /************** Continuing where we left off in sqliteInt.h ******************/
13584: /************** Include mutex.h in the middle of sqliteInt.h *****************/
13585: /************** Begin file mutex.h *******************************************/
13586: /*
13587: ** 2007 August 28
13588: **
13589: ** The author disclaims copyright to this source code.  In place of
13590: ** a legal notice, here is a blessing:
13591: **
13592: **    May you do good and not evil.
13593: **    May you find forgiveness for yourself and forgive others.
13594: **    May you share freely, never taking more than you give.
13595: **
13596: *************************************************************************
13597: **
13598: ** This file contains the common header for all mutex implementations.
13599: ** The sqliteInt.h header #includes this file so that it is available
13600: ** to all source files.  We break it out in an effort to keep the code
13601: ** better organized.
13602: **
13603: ** NOTE:  source files should *not* #include this header file directly.
13604: ** Source files should #include the sqliteInt.h file and let that file
13605: ** include this one indirectly.
13606: */
13607: 
13608: 
13609: /*
13610: ** Figure out what version of the code to use.  The choices are
13611: **
13612: **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
13613: **                             mutexes implementation cannot be overridden
13614: **                             at start-time.
13615: **
13616: **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
13617: **                             mutual exclusion is provided.  But this
13618: **                             implementation can be overridden at
13619: **                             start-time.
13620: **
13621: **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
13622: **
13623: **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
13624: */
13625: #if !SQLITE_THREADSAFE
13626: # define SQLITE_MUTEX_OMIT
13627: #endif
13628: #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
13629: #  if SQLITE_OS_UNIX
13630: #    define SQLITE_MUTEX_PTHREADS
13631: #  elif SQLITE_OS_WIN
13632: #    define SQLITE_MUTEX_W32
13633: #  else
13634: #    define SQLITE_MUTEX_NOOP
13635: #  endif
13636: #endif
13637: 
13638: #ifdef SQLITE_MUTEX_OMIT
13639: /*
13640: ** If this is a no-op implementation, implement everything as macros.
13641: */
13642: #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
13643: #define sqlite3_mutex_free(X)
13644: #define sqlite3_mutex_enter(X)    
13645: #define sqlite3_mutex_try(X)      SQLITE_OK
13646: #define sqlite3_mutex_leave(X)    
13647: #define sqlite3_mutex_held(X)     ((void)(X),1)
13648: #define sqlite3_mutex_notheld(X)  ((void)(X),1)
13649: #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
13650: #define sqlite3MutexInit()        SQLITE_OK
13651: #define sqlite3MutexEnd()
13652: #define MUTEX_LOGIC(X)
13653: #else
13654: #define MUTEX_LOGIC(X)            X
13655: #endif /* defined(SQLITE_MUTEX_OMIT) */
13656: 
13657: /************** End of mutex.h ***********************************************/
13658: /************** Continuing where we left off in sqliteInt.h ******************/
13659: 
13660: /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
13661: ** synchronous setting to EXTRA.  It is no longer supported.
13662: */
13663: #ifdef SQLITE_EXTRA_DURABLE
13664: # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
13665: # define SQLITE_DEFAULT_SYNCHRONOUS 3
13666: #endif
13667: 
13668: /*
13669: ** Default synchronous levels.
13670: **
13671: ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
13672: ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
13673: **
13674: **           PAGER_SYNCHRONOUS       DEFAULT_SYNCHRONOUS
13675: **   OFF           1                         0
13676: **   NORMAL        2                         1
13677: **   FULL          3                         2
13678: **   EXTRA         4                         3
13679: **
13680: ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
13681: ** In other words, the zero-based numbers are used for all external interfaces
13682: ** and the one-based values are used internally.
13683: */
13684: #ifndef SQLITE_DEFAULT_SYNCHRONOUS
13685: # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
13686: #endif
13687: #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
13688: # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
13689: #endif
13690: 
13691: /*
13692: ** Each database file to be accessed by the system is an instance
13693: ** of the following structure.  There are normally two of these structures
13694: ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
13695: ** aDb[1] is the database file used to hold temporary tables.  Additional
13696: ** databases may be attached.
13697: */
13698: struct Db {
13699:   char *zName;         /* Name of this database */
13700:   Btree *pBt;          /* The B*Tree structure for this database file */
13701:   u8 safety_level;     /* How aggressive at syncing data to disk */
13702:   u8 bSyncSet;         /* True if "PRAGMA synchronous=N" has been run */
13703:   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
13704: };
13705: 
13706: /*
13707: ** An instance of the following structure stores a database schema.
13708: **
13709: ** Most Schema objects are associated with a Btree.  The exception is
13710: ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
13711: ** In shared cache mode, a single Schema object can be shared by multiple
13712: ** Btrees that refer to the same underlying BtShared object.
13713: **
13714: ** Schema objects are automatically deallocated when the last Btree that
13715: ** references them is destroyed.   The TEMP Schema is manually freed by
13716: ** sqlite3_close().
13717: *
13718: ** A thread must be holding a mutex on the corresponding Btree in order
13719: ** to access Schema content.  This implies that the thread must also be
13720: ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
13721: ** For a TEMP Schema, only the connection mutex is required.
13722: */
13723: struct Schema {
13724:   int schema_cookie;   /* Database schema version number for this file */
13725:   int iGeneration;     /* Generation counter.  Incremented with each change */
13726:   Hash tblHash;        /* All tables indexed by name */
13727:   Hash idxHash;        /* All (named) indices indexed by name */
13728:   Hash trigHash;       /* All triggers indexed by name */
13729:   Hash fkeyHash;       /* All foreign keys by referenced table name */
13730:   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
13731:   u8 file_format;      /* Schema format version for this file */
13732:   u8 enc;              /* Text encoding used by this database */
13733:   u16 schemaFlags;     /* Flags associated with this schema */
13734:   int cache_size;      /* Number of pages to use in the cache */
13735: };
13736: 
13737: /*
13738: ** These macros can be used to test, set, or clear bits in the
13739: ** Db.pSchema->flags field.
13740: */
13741: #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
13742: #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
13743: #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
13744: #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
13745: 
13746: /*
13747: ** Allowed values for the DB.pSchema->flags field.
13748: **
13749: ** The DB_SchemaLoaded flag is set after the database schema has been
13750: ** read into internal hash tables.
13751: **
13752: ** DB_UnresetViews means that one or more views have column names that
13753: ** have been filled out.  If the schema changes, these column names might
13754: ** changes and so the view will need to be reset.
13755: */
13756: #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
13757: #define DB_UnresetViews    0x0002  /* Some views have defined column names */
13758: #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
13759: 
13760: /*
13761: ** The number of different kinds of things that can be limited
13762: ** using the sqlite3_limit() interface.
13763: */
13764: #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
13765: 
13766: /*
13767: ** Lookaside malloc is a set of fixed-size buffers that can be used
13768: ** to satisfy small transient memory allocation requests for objects
13769: ** associated with a particular database connection.  The use of
13770: ** lookaside malloc provides a significant performance enhancement
13771: ** (approx 10%) by avoiding numerous malloc/free requests while parsing
13772: ** SQL statements.
13773: **
13774: ** The Lookaside structure holds configuration information about the
13775: ** lookaside malloc subsystem.  Each available memory allocation in
13776: ** the lookaside subsystem is stored on a linked list of LookasideSlot
13777: ** objects.
13778: **
13779: ** Lookaside allocations are only allowed for objects that are associated
13780: ** with a particular database connection.  Hence, schema information cannot
13781: ** be stored in lookaside because in shared cache mode the schema information
13782: ** is shared by multiple database connections.  Therefore, while parsing
13783: ** schema information, the Lookaside.bEnabled flag is cleared so that
13784: ** lookaside allocations are not used to construct the schema objects.
13785: */
13786: struct Lookaside {
13787:   u32 bDisable;           /* Only operate the lookaside when zero */
13788:   u16 sz;                 /* Size of each buffer in bytes */
13789:   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
13790:   int nOut;               /* Number of buffers currently checked out */
13791:   int mxOut;              /* Highwater mark for nOut */
13792:   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
13793:   LookasideSlot *pFree;   /* List of available buffers */
13794:   void *pStart;           /* First byte of available memory space */
13795:   void *pEnd;             /* First byte past end of available space */
13796: };
13797: struct LookasideSlot {
13798:   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
13799: };
13800: 
13801: /*
13802: ** A hash table for built-in function definitions.  (Application-defined
13803: ** functions use a regular table table from hash.h.)
13804: **
13805: ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
13806: ** Collisions are on the FuncDef.u.pHash chain.
13807: */
13808: #define SQLITE_FUNC_HASH_SZ 23
13809: struct FuncDefHash {
13810:   FuncDef *a[SQLITE_FUNC_HASH_SZ];       /* Hash table for functions */
13811: };
13812: 
13813: #ifdef SQLITE_USER_AUTHENTICATION
13814: /*
13815: ** Information held in the "sqlite3" database connection object and used
13816: ** to manage user authentication.
13817: */
13818: typedef struct sqlite3_userauth sqlite3_userauth;
13819: struct sqlite3_userauth {
13820:   u8 authLevel;                 /* Current authentication level */
13821:   int nAuthPW;                  /* Size of the zAuthPW in bytes */
13822:   char *zAuthPW;                /* Password used to authenticate */
13823:   char *zAuthUser;              /* User name used to authenticate */
13824: };
13825: 
13826: /* Allowed values for sqlite3_userauth.authLevel */
13827: #define UAUTH_Unknown     0     /* Authentication not yet checked */
13828: #define UAUTH_Fail        1     /* User authentication failed */
13829: #define UAUTH_User        2     /* Authenticated as a normal user */
13830: #define UAUTH_Admin       3     /* Authenticated as an administrator */
13831: 
13832: /* Functions used only by user authorization logic */
13833: SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
13834: SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
13835: SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
13836: SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
13837: 
13838: #endif /* SQLITE_USER_AUTHENTICATION */
13839: 
13840: /*
13841: ** typedef for the authorization callback function.
13842: */
13843: #ifdef SQLITE_USER_AUTHENTICATION
13844:   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13845:                                const char*, const char*);
13846: #else
13847:   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13848:                                const char*);
13849: #endif
13850: 
13851: #ifndef SQLITE_OMIT_DEPRECATED
13852: /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
13853: ** in the style of sqlite3_trace()
13854: */
13855: #define SQLITE_TRACE_LEGACY  0x80
13856: #else
13857: #define SQLITE_TRACE_LEGACY  0
13858: #endif /* SQLITE_OMIT_DEPRECATED */
13859: 
13860: 
13861: /*
13862: ** Each database connection is an instance of the following structure.
13863: */
13864: struct sqlite3 {
13865:   sqlite3_vfs *pVfs;            /* OS Interface */
13866:   struct Vdbe *pVdbe;           /* List of active virtual machines */
13867:   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
13868:   sqlite3_mutex *mutex;         /* Connection mutex */
13869:   Db *aDb;                      /* All backends */
13870:   int nDb;                      /* Number of backends currently in use */
13871:   int flags;                    /* Miscellaneous flags. See below */
13872:   i64 lastRowid;                /* ROWID of most recent insert (see above) */
13873:   i64 szMmap;                   /* Default mmap_size setting */
13874:   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
13875:   int errCode;                  /* Most recent error code (SQLITE_*) */
13876:   int errMask;                  /* & result codes with this before returning */
13877:   int iSysErrno;                /* Errno value from last system error */
13878:   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
13879:   u8 enc;                       /* Text encoding */
13880:   u8 autoCommit;                /* The auto-commit flag. */
13881:   u8 temp_store;                /* 1: file 2: memory 0: default */
13882:   u8 mallocFailed;              /* True if we have seen a malloc failure */
13883:   u8 bBenignMalloc;             /* Do not require OOMs if true */
13884:   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
13885:   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
13886:   u8 suppressErr;               /* Do not issue error messages if true */
13887:   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
13888:   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
13889:   u8 mTrace;                    /* zero or more SQLITE_TRACE flags */
13890:   int nextPagesize;             /* Pagesize after VACUUM if >0 */
13891:   u32 magic;                    /* Magic number for detect library misuse */
13892:   int nChange;                  /* Value returned by sqlite3_changes() */
13893:   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
13894:   int aLimit[SQLITE_N_LIMIT];   /* Limits */
13895:   int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
13896:   struct sqlite3InitInfo {      /* Information used during initialization */
13897:     int newTnum;                /* Rootpage of table being initialized */
13898:     u8 iDb;                     /* Which db file is being initialized */
13899:     u8 busy;                    /* TRUE if currently initializing */
13900:     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
13901:     u8 imposterTable;           /* Building an imposter table */
13902:   } init;
13903:   int nVdbeActive;              /* Number of VDBEs currently running */
13904:   int nVdbeRead;                /* Number of active VDBEs that read or write */
13905:   int nVdbeWrite;               /* Number of active VDBEs that read and write */
13906:   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
13907:   int nVDestroy;                /* Number of active OP_VDestroy operations */
13908:   int nExtension;               /* Number of loaded extensions */
13909:   void **aExtension;            /* Array of shared library handles */
13910:   int (*xTrace)(u32,void*,void*,void*);     /* Trace function */
13911:   void *pTraceArg;                          /* Argument to the trace function */
13912:   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
13913:   void *pProfileArg;                        /* Argument to profile function */
13914:   void *pCommitArg;                 /* Argument to xCommitCallback() */
13915:   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
13916:   void *pRollbackArg;               /* Argument to xRollbackCallback() */
13917:   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
13918:   void *pUpdateArg;
13919:   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13920: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13921:   void *pPreUpdateArg;          /* First argument to xPreUpdateCallback */
13922:   void (*xPreUpdateCallback)(   /* Registered using sqlite3_preupdate_hook() */
13923:     void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13924:   );
13925:   PreUpdate *pPreUpdate;        /* Context for active pre-update callback */
13926: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
13927: #ifndef SQLITE_OMIT_WAL
13928:   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
13929:   void *pWalArg;
13930: #endif
13931:   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
13932:   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
13933:   void *pCollNeededArg;
13934:   sqlite3_value *pErr;          /* Most recent error message */
13935:   union {
13936:     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
13937:     double notUsed1;            /* Spacer */
13938:   } u1;
13939:   Lookaside lookaside;          /* Lookaside malloc configuration */
13940: #ifndef SQLITE_OMIT_AUTHORIZATION
13941:   sqlite3_xauth xAuth;          /* Access authorization function */
13942:   void *pAuthArg;               /* 1st argument to the access auth function */
13943: #endif
13944: #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
13945:   int (*xProgress)(void *);     /* The progress callback */
13946:   void *pProgressArg;           /* Argument to the progress callback */
13947:   unsigned nProgressOps;        /* Number of opcodes for progress callback */
13948: #endif
13949: #ifndef SQLITE_OMIT_VIRTUALTABLE
13950:   int nVTrans;                  /* Allocated size of aVTrans */
13951:   Hash aModule;                 /* populated by sqlite3_create_module() */
13952:   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
13953:   VTable **aVTrans;             /* Virtual tables with open transactions */
13954:   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
13955: #endif
13956:   Hash aFunc;                   /* Hash table of connection functions */
13957:   Hash aCollSeq;                /* All collating sequences */
13958:   BusyHandler busyHandler;      /* Busy callback */
13959:   Db aDbStatic[2];              /* Static space for the 2 default backends */
13960:   Savepoint *pSavepoint;        /* List of active savepoints */
13961:   int busyTimeout;              /* Busy handler timeout, in msec */
13962:   int nSavepoint;               /* Number of non-transaction savepoints */
13963:   int nStatement;               /* Number of nested statement-transactions  */
13964:   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
13965:   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
13966:   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
13967: #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13968:   /* The following variables are all protected by the STATIC_MASTER
13969:   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
13970:   **
13971:   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
13972:   ** unlock so that it can proceed.
13973:   **
13974:   ** When X.pBlockingConnection==Y, that means that something that X tried
13975:   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
13976:   ** held by Y.
13977:   */
13978:   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
13979:   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
13980:   void *pUnlockArg;                     /* Argument to xUnlockNotify */
13981:   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
13982:   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
13983: #endif
13984: #ifdef SQLITE_USER_AUTHENTICATION
13985:   sqlite3_userauth auth;        /* User authentication information */
13986: #endif
13987: };
13988: 
13989: /*
13990: ** A macro to discover the encoding of a database.
13991: */
13992: #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
13993: #define ENC(db)        ((db)->enc)
13994: 
13995: /*
13996: ** Possible values for the sqlite3.flags.
13997: **
13998: ** Value constraints (enforced via assert()):
13999: **      SQLITE_FullFSync     == PAGER_FULLFSYNC
14000: **      SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
14001: **      SQLITE_CacheSpill    == PAGER_CACHE_SPILL
14002: */
14003: #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
14004: #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
14005: #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
14006: #define SQLITE_FullFSync      0x00000008  /* Use full fsync on the backend */
14007: #define SQLITE_CkptFullFSync  0x00000010  /* Use full fsync for checkpoint */
14008: #define SQLITE_CacheSpill     0x00000020  /* OK to spill pager cache */
14009: #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
14010: #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
14011:                                           /*   DELETE, or UPDATE and return */
14012:                                           /*   the count using a callback. */
14013: #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
14014:                                           /*   result set is empty */
14015: #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
14016: #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
14017: #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
14018: #define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
14019: #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
14020: #define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
14021: #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
14022: #define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
14023: #define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
14024: #define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
14025: #define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
14026: #define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
14027: #define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
14028: #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
14029: #define SQLITE_LoadExtFunc    0x00800000  /* Enable load_extension() SQL func */
14030: #define SQLITE_EnableTrigger  0x01000000  /* True to enable triggers */
14031: #define SQLITE_DeferFKs       0x02000000  /* Defer all FK constraints */
14032: #define SQLITE_QueryOnly      0x04000000  /* Disable database changes */
14033: #define SQLITE_VdbeEQP        0x08000000  /* Debug EXPLAIN QUERY PLAN */
14034: #define SQLITE_Vacuum         0x10000000  /* Currently in a VACUUM */
14035: #define SQLITE_CellSizeCk     0x20000000  /* Check btree cell sizes on load */
14036: #define SQLITE_Fts3Tokenizer  0x40000000  /* Enable fts3_tokenizer(2) */
14037: 
14038: 
14039: /*
14040: ** Bits of the sqlite3.dbOptFlags field that are used by the
14041: ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
14042: ** selectively disable various optimizations.
14043: */
14044: #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
14045: #define SQLITE_ColumnCache    0x0002   /* Column cache */
14046: #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
14047: #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
14048: /*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
14049: #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
14050: #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
14051: #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
14052: #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
14053: #define SQLITE_Transitive     0x0200   /* Transitive constraints */
14054: #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
14055: #define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
14056: #define SQLITE_CursorHints    0x2000   /* Add OP_CursorHint opcodes */
14057: #define SQLITE_AllOpts        0xffff   /* All optimizations */
14058: 
14059: /*
14060: ** Macros for testing whether or not optimizations are enabled or disabled.
14061: */
14062: #ifndef SQLITE_OMIT_BUILTIN_TEST
14063: #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
14064: #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
14065: #else
14066: #define OptimizationDisabled(db, mask)  0
14067: #define OptimizationEnabled(db, mask)   1
14068: #endif
14069: 
14070: /*
14071: ** Return true if it OK to factor constant expressions into the initialization
14072: ** code. The argument is a Parse object for the code generator.
14073: */
14074: #define ConstFactorOk(P) ((P)->okConstFactor)
14075: 
14076: /*
14077: ** Possible values for the sqlite.magic field.
14078: ** The numbers are obtained at random and have no special meaning, other
14079: ** than being distinct from one another.
14080: */
14081: #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
14082: #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
14083: #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
14084: #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
14085: #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
14086: #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
14087: 
14088: /*
14089: ** Each SQL function is defined by an instance of the following
14090: ** structure.  For global built-in functions (ex: substr(), max(), count())
14091: ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
14092: ** For per-connection application-defined functions, a pointer to this
14093: ** structure is held in the db->aHash hash table.
14094: **
14095: ** The u.pHash field is used by the global built-ins.  The u.pDestructor
14096: ** field is used by per-connection app-def functions.
14097: */
14098: struct FuncDef {
14099:   i8 nArg;             /* Number of arguments.  -1 means unlimited */
14100:   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
14101:   void *pUserData;     /* User data parameter */
14102:   FuncDef *pNext;      /* Next function with same name */
14103:   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
14104:   void (*xFinalize)(sqlite3_context*);                  /* Agg finalizer */
14105:   const char *zName;   /* SQL name of the function. */
14106:   union {
14107:     FuncDef *pHash;      /* Next with a different name but the same hash */
14108:     FuncDestructor *pDestructor;   /* Reference counted destructor function */
14109:   } u;
14110: };
14111: 
14112: /*
14113: ** This structure encapsulates a user-function destructor callback (as
14114: ** configured using create_function_v2()) and a reference counter. When
14115: ** create_function_v2() is called to create a function with a destructor,
14116: ** a single object of this type is allocated. FuncDestructor.nRef is set to
14117: ** the number of FuncDef objects created (either 1 or 3, depending on whether
14118: ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
14119: ** member of each of the new FuncDef objects is set to point to the allocated
14120: ** FuncDestructor.
14121: **
14122: ** Thereafter, when one of the FuncDef objects is deleted, the reference
14123: ** count on this object is decremented. When it reaches 0, the destructor
14124: ** is invoked and the FuncDestructor structure freed.
14125: */
14126: struct FuncDestructor {
14127:   int nRef;
14128:   void (*xDestroy)(void *);
14129:   void *pUserData;
14130: };
14131: 
14132: /*
14133: ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
14134: ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  And
14135: ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC.  There
14136: ** are assert() statements in the code to verify this.
14137: **
14138: ** Value constraints (enforced via assert()):
14139: **     SQLITE_FUNC_MINMAX    ==  NC_MinMaxAgg      == SF_MinMaxAgg
14140: **     SQLITE_FUNC_LENGTH    ==  OPFLAG_LENGTHARG
14141: **     SQLITE_FUNC_TYPEOF    ==  OPFLAG_TYPEOFARG
14142: **     SQLITE_FUNC_CONSTANT  ==  SQLITE_DETERMINISTIC from the API
14143: **     SQLITE_FUNC_ENCMASK   depends on SQLITE_UTF* macros in the API
14144: */
14145: #define SQLITE_FUNC_ENCMASK  0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
14146: #define SQLITE_FUNC_LIKE     0x0004 /* Candidate for the LIKE optimization */
14147: #define SQLITE_FUNC_CASE     0x0008 /* Case-sensitive LIKE-type function */
14148: #define SQLITE_FUNC_EPHEM    0x0010 /* Ephemeral.  Delete with VDBE */
14149: #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
14150: #define SQLITE_FUNC_LENGTH   0x0040 /* Built-in length() function */
14151: #define SQLITE_FUNC_TYPEOF   0x0080 /* Built-in typeof() function */
14152: #define SQLITE_FUNC_COUNT    0x0100 /* Built-in count(*) aggregate */
14153: #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
14154: #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
14155: #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
14156: #define SQLITE_FUNC_MINMAX   0x1000 /* True for min() and max() aggregates */
14157: #define SQLITE_FUNC_SLOCHNG  0x2000 /* "Slow Change". Value constant during a
14158:                                     ** single query - might change over time */
14159: 
14160: /*
14161: ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
14162: ** used to create the initializers for the FuncDef structures.
14163: **
14164: **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
14165: **     Used to create a scalar function definition of a function zName
14166: **     implemented by C function xFunc that accepts nArg arguments. The
14167: **     value passed as iArg is cast to a (void*) and made available
14168: **     as the user-data (sqlite3_user_data()) for the function. If
14169: **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
14170: **
14171: **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
14172: **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
14173: **
14174: **   DFUNCTION(zName, nArg, iArg, bNC, xFunc)
14175: **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
14176: **     adds the SQLITE_FUNC_SLOCHNG flag.  Used for date & time functions
14177: **     and functions like sqlite_version() that can change, but not during
14178: **     a single query.
14179: **
14180: **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
14181: **     Used to create an aggregate function definition implemented by
14182: **     the C functions xStep and xFinal. The first four parameters
14183: **     are interpreted in the same way as the first 4 parameters to
14184: **     FUNCTION().
14185: **
14186: **   LIKEFUNC(zName, nArg, pArg, flags)
14187: **     Used to create a scalar function definition of a function zName
14188: **     that accepts nArg arguments and is implemented by a call to C
14189: **     function likeFunc. Argument pArg is cast to a (void *) and made
14190: **     available as the function user-data (sqlite3_user_data()). The
14191: **     FuncDef.flags variable is set to the value passed as the flags
14192: **     parameter.
14193: */
14194: #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
14195:   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14196:    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14197: #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14198:   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14199:    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14200: #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14201:   {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14202:    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14203: #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
14204:   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
14205:    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14206: #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
14207:   {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14208:    pArg, 0, xFunc, 0, #zName, }
14209: #define LIKEFUNC(zName, nArg, arg, flags) \
14210:   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
14211:    (void *)arg, 0, likeFunc, 0, #zName, {0} }
14212: #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
14213:   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
14214:    SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14215: #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
14216:   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
14217:    SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14218: 
14219: /*
14220: ** All current savepoints are stored in a linked list starting at
14221: ** sqlite3.pSavepoint. The first element in the list is the most recently
14222: ** opened savepoint. Savepoints are added to the list by the vdbe
14223: ** OP_Savepoint instruction.
14224: */
14225: struct Savepoint {
14226:   char *zName;                        /* Savepoint name (nul-terminated) */
14227:   i64 nDeferredCons;                  /* Number of deferred fk violations */
14228:   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
14229:   Savepoint *pNext;                   /* Parent savepoint (if any) */
14230: };
14231: 
14232: /*
14233: ** The following are used as the second parameter to sqlite3Savepoint(),
14234: ** and as the P1 argument to the OP_Savepoint instruction.
14235: */
14236: #define SAVEPOINT_BEGIN      0
14237: #define SAVEPOINT_RELEASE    1
14238: #define SAVEPOINT_ROLLBACK   2
14239: 
14240: 
14241: /*
14242: ** Each SQLite module (virtual table definition) is defined by an
14243: ** instance of the following structure, stored in the sqlite3.aModule
14244: ** hash table.
14245: */
14246: struct Module {
14247:   const sqlite3_module *pModule;       /* Callback pointers */
14248:   const char *zName;                   /* Name passed to create_module() */
14249:   void *pAux;                          /* pAux passed to create_module() */
14250:   void (*xDestroy)(void *);            /* Module destructor function */
14251:   Table *pEpoTab;                      /* Eponymous table for this module */
14252: };
14253: 
14254: /*
14255: ** information about each column of an SQL table is held in an instance
14256: ** of this structure.
14257: */
14258: struct Column {
14259:   char *zName;     /* Name of this column, \000, then the type */
14260:   Expr *pDflt;     /* Default value of this column */
14261:   char *zColl;     /* Collating sequence.  If NULL, use the default */
14262:   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
14263:   char affinity;   /* One of the SQLITE_AFF_... values */
14264:   u8 szEst;        /* Estimated size of value in this column. sizeof(INT)==1 */
14265:   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
14266: };
14267: 
14268: /* Allowed values for Column.colFlags:
14269: */
14270: #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
14271: #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
14272: #define COLFLAG_HASTYPE  0x0004    /* Type name follows column name */
14273: 
14274: /*
14275: ** A "Collating Sequence" is defined by an instance of the following
14276: ** structure. Conceptually, a collating sequence consists of a name and
14277: ** a comparison routine that defines the order of that sequence.
14278: **
14279: ** If CollSeq.xCmp is NULL, it means that the
14280: ** collating sequence is undefined.  Indices built on an undefined
14281: ** collating sequence may not be read or written.
14282: */
14283: struct CollSeq {
14284:   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
14285:   u8 enc;               /* Text encoding handled by xCmp() */
14286:   void *pUser;          /* First argument to xCmp() */
14287:   int (*xCmp)(void*,int, const void*, int, const void*);
14288:   void (*xDel)(void*);  /* Destructor for pUser */
14289: };
14290: 
14291: /*
14292: ** A sort order can be either ASC or DESC.
14293: */
14294: #define SQLITE_SO_ASC       0  /* Sort in ascending order */
14295: #define SQLITE_SO_DESC      1  /* Sort in ascending order */
14296: #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
14297: 
14298: /*
14299: ** Column affinity types.
14300: **
14301: ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
14302: ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
14303: ** the speed a little by numbering the values consecutively.
14304: **
14305: ** But rather than start with 0 or 1, we begin with 'A'.  That way,
14306: ** when multiple affinity types are concatenated into a string and
14307: ** used as the P4 operand, they will be more readable.
14308: **
14309: ** Note also that the numeric types are grouped together so that testing
14310: ** for a numeric type is a single comparison.  And the BLOB type is first.
14311: */
14312: #define SQLITE_AFF_BLOB     'A'
14313: #define SQLITE_AFF_TEXT     'B'
14314: #define SQLITE_AFF_NUMERIC  'C'
14315: #define SQLITE_AFF_INTEGER  'D'
14316: #define SQLITE_AFF_REAL     'E'
14317: 
14318: #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
14319: 
14320: /*
14321: ** The SQLITE_AFF_MASK values masks off the significant bits of an
14322: ** affinity value.
14323: */
14324: #define SQLITE_AFF_MASK     0x47
14325: 
14326: /*
14327: ** Additional bit values that can be ORed with an affinity without
14328: ** changing the affinity.
14329: **
14330: ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
14331: ** It causes an assert() to fire if either operand to a comparison
14332: ** operator is NULL.  It is added to certain comparison operators to
14333: ** prove that the operands are always NOT NULL.
14334: */
14335: #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
14336: #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
14337: #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
14338: #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
14339: 
14340: /*
14341: ** An object of this type is created for each virtual table present in
14342: ** the database schema.
14343: **
14344: ** If the database schema is shared, then there is one instance of this
14345: ** structure for each database connection (sqlite3*) that uses the shared
14346: ** schema. This is because each database connection requires its own unique
14347: ** instance of the sqlite3_vtab* handle used to access the virtual table
14348: ** implementation. sqlite3_vtab* handles can not be shared between
14349: ** database connections, even when the rest of the in-memory database
14350: ** schema is shared, as the implementation often stores the database
14351: ** connection handle passed to it via the xConnect() or xCreate() method
14352: ** during initialization internally. This database connection handle may
14353: ** then be used by the virtual table implementation to access real tables
14354: ** within the database. So that they appear as part of the callers
14355: ** transaction, these accesses need to be made via the same database
14356: ** connection as that used to execute SQL operations on the virtual table.
14357: **
14358: ** All VTable objects that correspond to a single table in a shared
14359: ** database schema are initially stored in a linked-list pointed to by
14360: ** the Table.pVTable member variable of the corresponding Table object.
14361: ** When an sqlite3_prepare() operation is required to access the virtual
14362: ** table, it searches the list for the VTable that corresponds to the
14363: ** database connection doing the preparing so as to use the correct
14364: ** sqlite3_vtab* handle in the compiled query.
14365: **
14366: ** When an in-memory Table object is deleted (for example when the
14367: ** schema is being reloaded for some reason), the VTable objects are not
14368: ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
14369: ** immediately. Instead, they are moved from the Table.pVTable list to
14370: ** another linked list headed by the sqlite3.pDisconnect member of the
14371: ** corresponding sqlite3 structure. They are then deleted/xDisconnected
14372: ** next time a statement is prepared using said sqlite3*. This is done
14373: ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
14374: ** Refer to comments above function sqlite3VtabUnlockList() for an
14375: ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
14376: ** list without holding the corresponding sqlite3.mutex mutex.
14377: **
14378: ** The memory for objects of this type is always allocated by
14379: ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
14380: ** the first argument.
14381: */
14382: struct VTable {
14383:   sqlite3 *db;              /* Database connection associated with this table */
14384:   Module *pMod;             /* Pointer to module implementation */
14385:   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
14386:   int nRef;                 /* Number of pointers to this structure */
14387:   u8 bConstraint;           /* True if constraints are supported */
14388:   int iSavepoint;           /* Depth of the SAVEPOINT stack */
14389:   VTable *pNext;            /* Next in linked list (see above) */
14390: };
14391: 
14392: /*
14393: ** The schema for each SQL table and view is represented in memory
14394: ** by an instance of the following structure.
14395: */
14396: struct Table {
14397:   char *zName;         /* Name of the table or view */
14398:   Column *aCol;        /* Information about each column */
14399:   Index *pIndex;       /* List of SQL indexes on this table. */
14400:   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
14401:   FKey *pFKey;         /* Linked list of all foreign keys in this table */
14402:   char *zColAff;       /* String defining the affinity of each column */
14403:   ExprList *pCheck;    /* All CHECK constraints */
14404:                        /*   ... also used as column name list in a VIEW */
14405:   int tnum;            /* Root BTree page for this table */
14406:   i16 iPKey;           /* If not negative, use aCol[iPKey] as the rowid */
14407:   i16 nCol;            /* Number of columns in this table */
14408:   u16 nRef;            /* Number of pointers to this Table */
14409:   LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
14410:   LogEst szTabRow;     /* Estimated size of each table row in bytes */
14411: #ifdef SQLITE_ENABLE_COSTMULT
14412:   LogEst costMult;     /* Cost multiplier for using this table */
14413: #endif
14414:   u8 tabFlags;         /* Mask of TF_* values */
14415:   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
14416: #ifndef SQLITE_OMIT_ALTERTABLE
14417:   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
14418: #endif
14419: #ifndef SQLITE_OMIT_VIRTUALTABLE
14420:   int nModuleArg;      /* Number of arguments to the module */
14421:   char **azModuleArg;  /* 0: module 1: schema 2: vtab name 3...: args */
14422:   VTable *pVTable;     /* List of VTable objects. */
14423: #endif
14424:   Trigger *pTrigger;   /* List of triggers stored in pSchema */
14425:   Schema *pSchema;     /* Schema that contains this table */
14426:   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
14427: };
14428: 
14429: /*
14430: ** Allowed values for Table.tabFlags.
14431: **
14432: ** TF_OOOHidden applies to tables or view that have hidden columns that are
14433: ** followed by non-hidden columns.  Example:  "CREATE VIRTUAL TABLE x USING
14434: ** vtab1(a HIDDEN, b);".  Since "b" is a non-hidden column but "a" is hidden,
14435: ** the TF_OOOHidden attribute would apply in this case.  Such tables require
14436: ** special handling during INSERT processing.
14437: */
14438: #define TF_Readonly        0x01    /* Read-only system table */
14439: #define TF_Ephemeral       0x02    /* An ephemeral table */
14440: #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
14441: #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
14442: #define TF_Virtual         0x10    /* Is a virtual table */
14443: #define TF_WithoutRowid    0x20    /* No rowid.  PRIMARY KEY is the key */
14444: #define TF_NoVisibleRowid  0x40    /* No user-visible "rowid" column */
14445: #define TF_OOOHidden       0x80    /* Out-of-Order hidden columns */
14446: 
14447: 
14448: /*
14449: ** Test to see whether or not a table is a virtual table.  This is
14450: ** done as a macro so that it will be optimized out when virtual
14451: ** table support is omitted from the build.
14452: */
14453: #ifndef SQLITE_OMIT_VIRTUALTABLE
14454: #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
14455: #else
14456: #  define IsVirtual(X)      0
14457: #endif
14458: 
14459: /*
14460: ** Macros to determine if a column is hidden.  IsOrdinaryHiddenColumn()
14461: ** only works for non-virtual tables (ordinary tables and views) and is
14462: ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined.  The
14463: ** IsHiddenColumn() macro is general purpose.
14464: */
14465: #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
14466: #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14467: #  define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14468: #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
14469: #  define IsHiddenColumn(X)         (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14470: #  define IsOrdinaryHiddenColumn(X) 0
14471: #else
14472: #  define IsHiddenColumn(X)         0
14473: #  define IsOrdinaryHiddenColumn(X) 0
14474: #endif
14475: 
14476: 
14477: /* Does the table have a rowid */
14478: #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
14479: #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
14480: 
14481: /*
14482: ** Each foreign key constraint is an instance of the following structure.
14483: **
14484: ** A foreign key is associated with two tables.  The "from" table is
14485: ** the table that contains the REFERENCES clause that creates the foreign
14486: ** key.  The "to" table is the table that is named in the REFERENCES clause.
14487: ** Consider this example:
14488: **
14489: **     CREATE TABLE ex1(
14490: **       a INTEGER PRIMARY KEY,
14491: **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
14492: **     );
14493: **
14494: ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
14495: ** Equivalent names:
14496: **
14497: **     from-table == child-table
14498: **       to-table == parent-table
14499: **
14500: ** Each REFERENCES clause generates an instance of the following structure
14501: ** which is attached to the from-table.  The to-table need not exist when
14502: ** the from-table is created.  The existence of the to-table is not checked.
14503: **
14504: ** The list of all parents for child Table X is held at X.pFKey.
14505: **
14506: ** A list of all children for a table named Z (which might not even exist)
14507: ** is held in Schema.fkeyHash with a hash key of Z.
14508: */
14509: struct FKey {
14510:   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
14511:   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
14512:   char *zTo;        /* Name of table that the key points to (aka: Parent) */
14513:   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
14514:   FKey *pPrevTo;    /* Previous with the same zTo */
14515:   int nCol;         /* Number of columns in this key */
14516:   /* EV: R-30323-21917 */
14517:   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
14518:   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
14519:   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
14520:   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
14521:     int iFrom;            /* Index of column in pFrom */
14522:     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
14523:   } aCol[1];            /* One entry for each of nCol columns */
14524: };
14525: 
14526: /*
14527: ** SQLite supports many different ways to resolve a constraint
14528: ** error.  ROLLBACK processing means that a constraint violation
14529: ** causes the operation in process to fail and for the current transaction
14530: ** to be rolled back.  ABORT processing means the operation in process
14531: ** fails and any prior changes from that one operation are backed out,
14532: ** but the transaction is not rolled back.  FAIL processing means that
14533: ** the operation in progress stops and returns an error code.  But prior
14534: ** changes due to the same operation are not backed out and no rollback
14535: ** occurs.  IGNORE means that the particular row that caused the constraint
14536: ** error is not inserted or updated.  Processing continues and no error
14537: ** is returned.  REPLACE means that preexisting database rows that caused
14538: ** a UNIQUE constraint violation are removed so that the new insert or
14539: ** update can proceed.  Processing continues and no error is reported.
14540: **
14541: ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
14542: ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
14543: ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
14544: ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
14545: ** referenced table row is propagated into the row that holds the
14546: ** foreign key.
14547: **
14548: ** The following symbolic values are used to record which type
14549: ** of action to take.
14550: */
14551: #define OE_None     0   /* There is no constraint to check */
14552: #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
14553: #define OE_Abort    2   /* Back out changes but do no rollback transaction */
14554: #define OE_Fail     3   /* Stop the operation but leave all prior changes */
14555: #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
14556: #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
14557: 
14558: #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
14559: #define OE_SetNull  7   /* Set the foreign key value to NULL */
14560: #define OE_SetDflt  8   /* Set the foreign key value to its default */
14561: #define OE_Cascade  9   /* Cascade the changes */
14562: 
14563: #define OE_Default  10  /* Do whatever the default action is */
14564: 
14565: 
14566: /*
14567: ** An instance of the following structure is passed as the first
14568: ** argument to sqlite3VdbeKeyCompare and is used to control the
14569: ** comparison of the two index keys.
14570: **
14571: ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
14572: ** are nField slots for the columns of an index then one extra slot
14573: ** for the rowid at the end.
14574: */
14575: struct KeyInfo {
14576:   u32 nRef;           /* Number of references to this KeyInfo object */
14577:   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
14578:   u16 nField;         /* Number of key columns in the index */
14579:   u16 nXField;        /* Number of columns beyond the key columns */
14580:   sqlite3 *db;        /* The database connection */
14581:   u8 *aSortOrder;     /* Sort order for each column. */
14582:   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
14583: };
14584: 
14585: /*
14586: ** This object holds a record which has been parsed out into individual
14587: ** fields, for the purposes of doing a comparison.
14588: **
14589: ** A record is an object that contains one or more fields of data.
14590: ** Records are used to store the content of a table row and to store
14591: ** the key of an index.  A blob encoding of a record is created by
14592: ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
14593: ** OP_Column opcode.
14594: **
14595: ** An instance of this object serves as a "key" for doing a search on
14596: ** an index b+tree. The goal of the search is to find the entry that
14597: ** is closed to the key described by this object.  This object might hold
14598: ** just a prefix of the key.  The number of fields is given by
14599: ** pKeyInfo->nField.
14600: **
14601: ** The r1 and r2 fields are the values to return if this key is less than
14602: ** or greater than a key in the btree, respectively.  These are normally
14603: ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
14604: ** is in DESC order.
14605: **
14606: ** The key comparison functions actually return default_rc when they find
14607: ** an equals comparison.  default_rc can be -1, 0, or +1.  If there are
14608: ** multiple entries in the b-tree with the same key (when only looking
14609: ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
14610: ** cause the search to find the last match, or +1 to cause the search to
14611: ** find the first match.
14612: **
14613: ** The key comparison functions will set eqSeen to true if they ever
14614: ** get and equal results when comparing this structure to a b-tree record.
14615: ** When default_rc!=0, the search might end up on the record immediately
14616: ** before the first match or immediately after the last match.  The
14617: ** eqSeen field will indicate whether or not an exact match exists in the
14618: ** b-tree.
14619: */
14620: struct UnpackedRecord {
14621:   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
14622:   Mem *aMem;          /* Values */
14623:   u16 nField;         /* Number of entries in apMem[] */
14624:   i8 default_rc;      /* Comparison result if keys are equal */
14625:   u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
14626:   i8 r1;              /* Value to return if (lhs > rhs) */
14627:   i8 r2;              /* Value to return if (rhs < lhs) */
14628:   u8 eqSeen;          /* True if an equality comparison has been seen */
14629: };
14630: 
14631: 
14632: /*
14633: ** Each SQL index is represented in memory by an
14634: ** instance of the following structure.
14635: **
14636: ** The columns of the table that are to be indexed are described
14637: ** by the aiColumn[] field of this structure.  For example, suppose
14638: ** we have the following table and index:
14639: **
14640: **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
14641: **     CREATE INDEX Ex2 ON Ex1(c3,c1);
14642: **
14643: ** In the Table structure describing Ex1, nCol==3 because there are
14644: ** three columns in the table.  In the Index structure describing
14645: ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
14646: ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
14647: ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
14648: ** The second column to be indexed (c1) has an index of 0 in
14649: ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
14650: **
14651: ** The Index.onError field determines whether or not the indexed columns
14652: ** must be unique and what to do if they are not.  When Index.onError=OE_None,
14653: ** it means this is not a unique index.  Otherwise it is a unique index
14654: ** and the value of Index.onError indicate the which conflict resolution
14655: ** algorithm to employ whenever an attempt is made to insert a non-unique
14656: ** element.
14657: **
14658: ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
14659: ** generate VDBE code (as opposed to parsing one read from an sqlite_master
14660: ** table as part of parsing an existing database schema), transient instances
14661: ** of this structure may be created. In this case the Index.tnum variable is
14662: ** used to store the address of a VDBE instruction, not a database page
14663: ** number (it cannot - the database page is not allocated until the VDBE
14664: ** program is executed). See convertToWithoutRowidTable() for details.
14665: */
14666: struct Index {
14667:   char *zName;             /* Name of this index */
14668:   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
14669:   LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
14670:   Table *pTable;           /* The SQL table being indexed */
14671:   char *zColAff;           /* String defining the affinity of each column */
14672:   Index *pNext;            /* The next index associated with the same table */
14673:   Schema *pSchema;         /* Schema containing this index */
14674:   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
14675:   const char **azColl;     /* Array of collation sequence names for index */
14676:   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
14677:   ExprList *aColExpr;      /* Column expressions */
14678:   int tnum;                /* DB Page containing root of this index */
14679:   LogEst szIdxRow;         /* Estimated average row size in bytes */
14680:   u16 nKeyCol;             /* Number of columns forming the key */
14681:   u16 nColumn;             /* Number of columns stored in the index */
14682:   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
14683:   unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
14684:   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
14685:   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
14686:   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
14687:   unsigned isCovering:1;   /* True if this is a covering index */
14688:   unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
14689: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14690:   int nSample;             /* Number of elements in aSample[] */
14691:   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
14692:   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
14693:   IndexSample *aSample;    /* Samples of the left-most key */
14694:   tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
14695:   tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
14696: #endif
14697: };
14698: 
14699: /*
14700: ** Allowed values for Index.idxType
14701: */
14702: #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
14703: #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
14704: #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
14705: 
14706: /* Return true if index X is a PRIMARY KEY index */
14707: #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
14708: 
14709: /* Return true if index X is a UNIQUE index */
14710: #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
14711: 
14712: /* The Index.aiColumn[] values are normally positive integer.  But
14713: ** there are some negative values that have special meaning:
14714: */
14715: #define XN_ROWID     (-1)     /* Indexed column is the rowid */
14716: #define XN_EXPR      (-2)     /* Indexed column is an expression */
14717: 
14718: /*
14719: ** Each sample stored in the sqlite_stat3 table is represented in memory
14720: ** using a structure of this type.  See documentation at the top of the
14721: ** analyze.c source file for additional information.
14722: */
14723: struct IndexSample {
14724:   void *p;          /* Pointer to sampled record */
14725:   int n;            /* Size of record in bytes */
14726:   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
14727:   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
14728:   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
14729: };
14730: 
14731: /*
14732: ** Each token coming out of the lexer is an instance of
14733: ** this structure.  Tokens are also used as part of an expression.
14734: **
14735: ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
14736: ** may contain random values.  Do not make any assumptions about Token.dyn
14737: ** and Token.n when Token.z==0.
14738: */
14739: struct Token {
14740:   const char *z;     /* Text of the token.  Not NULL-terminated! */
14741:   unsigned int n;    /* Number of characters in this token */
14742: };
14743: 
14744: /*
14745: ** An instance of this structure contains information needed to generate
14746: ** code for a SELECT that contains aggregate functions.
14747: **
14748: ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
14749: ** pointer to this structure.  The Expr.iColumn field is the index in
14750: ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
14751: ** code for that node.
14752: **
14753: ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
14754: ** original Select structure that describes the SELECT statement.  These
14755: ** fields do not need to be freed when deallocating the AggInfo structure.
14756: */
14757: struct AggInfo {
14758:   u8 directMode;          /* Direct rendering mode means take data directly
14759:                           ** from source tables rather than from accumulators */
14760:   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
14761:                           ** than the source table */
14762:   int sortingIdx;         /* Cursor number of the sorting index */
14763:   int sortingIdxPTab;     /* Cursor number of pseudo-table */
14764:   int nSortingColumn;     /* Number of columns in the sorting index */
14765:   int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
14766:   ExprList *pGroupBy;     /* The group by clause */
14767:   struct AggInfo_col {    /* For each column used in source tables */
14768:     Table *pTab;             /* Source table */
14769:     int iTable;              /* Cursor number of the source table */
14770:     int iColumn;             /* Column number within the source table */
14771:     int iSorterColumn;       /* Column number in the sorting index */
14772:     int iMem;                /* Memory location that acts as accumulator */
14773:     Expr *pExpr;             /* The original expression */
14774:   } *aCol;
14775:   int nColumn;            /* Number of used entries in aCol[] */
14776:   int nAccumulator;       /* Number of columns that show through to the output.
14777:                           ** Additional columns are used only as parameters to
14778:                           ** aggregate functions */
14779:   struct AggInfo_func {   /* For each aggregate function */
14780:     Expr *pExpr;             /* Expression encoding the function */
14781:     FuncDef *pFunc;          /* The aggregate function implementation */
14782:     int iMem;                /* Memory location that acts as accumulator */
14783:     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
14784:   } *aFunc;
14785:   int nFunc;              /* Number of entries in aFunc[] */
14786: };
14787: 
14788: /*
14789: ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
14790: ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
14791: ** than 32767 we have to make it 32-bit.  16-bit is preferred because
14792: ** it uses less memory in the Expr object, which is a big memory user
14793: ** in systems with lots of prepared statements.  And few applications
14794: ** need more than about 10 or 20 variables.  But some extreme users want
14795: ** to have prepared statements with over 32767 variables, and for them
14796: ** the option is available (at compile-time).
14797: */
14798: #if SQLITE_MAX_VARIABLE_NUMBER<=32767
14799: typedef i16 ynVar;
14800: #else
14801: typedef int ynVar;
14802: #endif
14803: 
14804: /*
14805: ** Each node of an expression in the parse tree is an instance
14806: ** of this structure.
14807: **
14808: ** Expr.op is the opcode. The integer parser token codes are reused
14809: ** as opcodes here. For example, the parser defines TK_GE to be an integer
14810: ** code representing the ">=" operator. This same integer code is reused
14811: ** to represent the greater-than-or-equal-to operator in the expression
14812: ** tree.
14813: **
14814: ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
14815: ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
14816: ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
14817: ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
14818: ** then Expr.token contains the name of the function.
14819: **
14820: ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
14821: ** binary operator. Either or both may be NULL.
14822: **
14823: ** Expr.x.pList is a list of arguments if the expression is an SQL function,
14824: ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
14825: ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
14826: ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
14827: ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
14828: ** valid.
14829: **
14830: ** An expression of the form ID or ID.ID refers to a column in a table.
14831: ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
14832: ** the integer cursor number of a VDBE cursor pointing to that table and
14833: ** Expr.iColumn is the column number for the specific column.  If the
14834: ** expression is used as a result in an aggregate SELECT, then the
14835: ** value is also stored in the Expr.iAgg column in the aggregate so that
14836: ** it can be accessed after all aggregates are computed.
14837: **
14838: ** If the expression is an unbound variable marker (a question mark
14839: ** character '?' in the original SQL) then the Expr.iTable holds the index
14840: ** number for that variable.
14841: **
14842: ** If the expression is a subquery then Expr.iColumn holds an integer
14843: ** register number containing the result of the subquery.  If the
14844: ** subquery gives a constant result, then iTable is -1.  If the subquery
14845: ** gives a different answer at different times during statement processing
14846: ** then iTable is the address of a subroutine that computes the subquery.
14847: **
14848: ** If the Expr is of type OP_Column, and the table it is selecting from
14849: ** is a disk table or the "old.*" pseudo-table, then pTab points to the
14850: ** corresponding table definition.
14851: **
14852: ** ALLOCATION NOTES:
14853: **
14854: ** Expr objects can use a lot of memory space in database schema.  To
14855: ** help reduce memory requirements, sometimes an Expr object will be
14856: ** truncated.  And to reduce the number of memory allocations, sometimes
14857: ** two or more Expr objects will be stored in a single memory allocation,
14858: ** together with Expr.zToken strings.
14859: **
14860: ** If the EP_Reduced and EP_TokenOnly flags are set when
14861: ** an Expr object is truncated.  When EP_Reduced is set, then all
14862: ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
14863: ** are contained within the same memory allocation.  Note, however, that
14864: ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
14865: ** allocated, regardless of whether or not EP_Reduced is set.
14866: */
14867: struct Expr {
14868:   u8 op;                 /* Operation performed by this node */
14869:   char affinity;         /* The affinity of the column or 0 if not a column */
14870:   u32 flags;             /* Various flags.  EP_* See below */
14871:   union {
14872:     char *zToken;          /* Token value. Zero terminated and dequoted */
14873:     int iValue;            /* Non-negative integer value if EP_IntValue */
14874:   } u;
14875: 
14876:   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
14877:   ** space is allocated for the fields below this point. An attempt to
14878:   ** access them will result in a segfault or malfunction.
14879:   *********************************************************************/
14880: 
14881:   Expr *pLeft;           /* Left subnode */
14882:   Expr *pRight;          /* Right subnode */
14883:   union {
14884:     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
14885:     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
14886:   } x;
14887: 
14888:   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
14889:   ** space is allocated for the fields below this point. An attempt to
14890:   ** access them will result in a segfault or malfunction.
14891:   *********************************************************************/
14892: 
14893: #if SQLITE_MAX_EXPR_DEPTH>0
14894:   int nHeight;           /* Height of the tree headed by this node */
14895: #endif
14896:   int iTable;            /* TK_COLUMN: cursor number of table holding column
14897:                          ** TK_REGISTER: register number
14898:                          ** TK_TRIGGER: 1 -> new, 0 -> old
14899:                          ** EP_Unlikely:  134217728 times likelihood */
14900:   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
14901:                          ** TK_VARIABLE: variable number (always >= 1). */
14902:   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
14903:   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
14904:   u8 op2;                /* TK_REGISTER: original value of Expr.op
14905:                          ** TK_COLUMN: the value of p5 for OP_Column
14906:                          ** TK_AGG_FUNCTION: nesting depth */
14907:   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
14908:   Table *pTab;           /* Table for TK_COLUMN expressions. */
14909: };
14910: 
14911: /*
14912: ** The following are the meanings of bits in the Expr.flags field.
14913: */
14914: #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
14915: #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
14916: #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
14917: #define EP_Error     0x000008 /* Expression contains one or more errors */
14918: #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
14919: #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
14920: #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
14921: #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
14922: #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
14923: #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
14924: #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
14925: #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
14926: #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
14927: #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
14928: #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
14929: #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
14930: #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
14931: #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
14932: #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
14933: #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
14934: #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
14935: #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
14936: #define EP_Alias     0x400000 /* Is an alias for a result set column */
14937: 
14938: /*
14939: ** Combinations of two or more EP_* flags
14940: */
14941: #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
14942: 
14943: /*
14944: ** These macros can be used to test, set, or clear bits in the
14945: ** Expr.flags field.
14946: */
14947: #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
14948: #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
14949: #define ExprSetProperty(E,P)     (E)->flags|=(P)
14950: #define ExprClearProperty(E,P)   (E)->flags&=~(P)
14951: 
14952: /* The ExprSetVVAProperty() macro is used for Verification, Validation,
14953: ** and Accreditation only.  It works like ExprSetProperty() during VVA
14954: ** processes but is a no-op for delivery.
14955: */
14956: #ifdef SQLITE_DEBUG
14957: # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
14958: #else
14959: # define ExprSetVVAProperty(E,P)
14960: #endif
14961: 
14962: /*
14963: ** Macros to determine the number of bytes required by a normal Expr
14964: ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
14965: ** and an Expr struct with the EP_TokenOnly flag set.
14966: */
14967: #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
14968: #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
14969: #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
14970: 
14971: /*
14972: ** Flags passed to the sqlite3ExprDup() function. See the header comment
14973: ** above sqlite3ExprDup() for details.
14974: */
14975: #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
14976: 
14977: /*
14978: ** A list of expressions.  Each expression may optionally have a
14979: ** name.  An expr/name combination can be used in several ways, such
14980: ** as the list of "expr AS ID" fields following a "SELECT" or in the
14981: ** list of "ID = expr" items in an UPDATE.  A list of expressions can
14982: ** also be used as the argument to a function, in which case the a.zName
14983: ** field is not used.
14984: **
14985: ** By default the Expr.zSpan field holds a human-readable description of
14986: ** the expression that is used in the generation of error messages and
14987: ** column labels.  In this case, Expr.zSpan is typically the text of a
14988: ** column expression as it exists in a SELECT statement.  However, if
14989: ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
14990: ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
14991: ** form is used for name resolution with nested FROM clauses.
14992: */
14993: struct ExprList {
14994:   int nExpr;             /* Number of expressions on the list */
14995:   struct ExprList_item { /* For each expression in the list */
14996:     Expr *pExpr;            /* The list of expressions */
14997:     char *zName;            /* Token associated with this expression */
14998:     char *zSpan;            /* Original text of the expression */
14999:     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
15000:     unsigned done :1;       /* A flag to indicate when processing is finished */
15001:     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
15002:     unsigned reusable :1;   /* Constant expression is reusable */
15003:     union {
15004:       struct {
15005:         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
15006:         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
15007:       } x;
15008:       int iConstExprReg;      /* Register in which Expr value is cached */
15009:     } u;
15010:   } *a;                  /* Alloc a power of two greater or equal to nExpr */
15011: };
15012: 
15013: /*
15014: ** An instance of this structure is used by the parser to record both
15015: ** the parse tree for an expression and the span of input text for an
15016: ** expression.
15017: */
15018: struct ExprSpan {
15019:   Expr *pExpr;          /* The expression parse tree */
15020:   const char *zStart;   /* First character of input text */
15021:   const char *zEnd;     /* One character past the end of input text */
15022: };
15023: 
15024: /*
15025: ** An instance of this structure can hold a simple list of identifiers,
15026: ** such as the list "a,b,c" in the following statements:
15027: **
15028: **      INSERT INTO t(a,b,c) VALUES ...;
15029: **      CREATE INDEX idx ON t(a,b,c);
15030: **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
15031: **
15032: ** The IdList.a.idx field is used when the IdList represents the list of
15033: ** column names after a table name in an INSERT statement.  In the statement
15034: **
15035: **     INSERT INTO t(a,b,c) ...
15036: **
15037: ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
15038: */
15039: struct IdList {
15040:   struct IdList_item {
15041:     char *zName;      /* Name of the identifier */
15042:     int idx;          /* Index in some Table.aCol[] of a column named zName */
15043:   } *a;
15044:   int nId;         /* Number of identifiers on the list */
15045: };
15046: 
15047: /*
15048: ** The bitmask datatype defined below is used for various optimizations.
15049: **
15050: ** Changing this from a 64-bit to a 32-bit type limits the number of
15051: ** tables in a join to 32 instead of 64.  But it also reduces the size
15052: ** of the library by 738 bytes on ix86.
15053: */
15054: #ifdef SQLITE_BITMASK_TYPE
15055:   typedef SQLITE_BITMASK_TYPE Bitmask;
15056: #else
15057:   typedef u64 Bitmask;
15058: #endif
15059: 
15060: /*
15061: ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
15062: */
15063: #define BMS  ((int)(sizeof(Bitmask)*8))
15064: 
15065: /*
15066: ** A bit in a Bitmask
15067: */
15068: #define MASKBIT(n)   (((Bitmask)1)<<(n))
15069: #define MASKBIT32(n) (((unsigned int)1)<<(n))
15070: #define ALLBITS      ((Bitmask)-1)
15071: 
15072: /*
15073: ** The following structure describes the FROM clause of a SELECT statement.
15074: ** Each table or subquery in the FROM clause is a separate element of
15075: ** the SrcList.a[] array.
15076: **
15077: ** With the addition of multiple database support, the following structure
15078: ** can also be used to describe a particular table such as the table that
15079: ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
15080: ** such a table must be a simple name: ID.  But in SQLite, the table can
15081: ** now be identified by a database name, a dot, then the table name: ID.ID.
15082: **
15083: ** The jointype starts out showing the join type between the current table
15084: ** and the next table on the list.  The parser builds the list this way.
15085: ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
15086: ** jointype expresses the join between the table and the previous table.
15087: **
15088: ** In the colUsed field, the high-order bit (bit 63) is set if the table
15089: ** contains more than 63 columns and the 64-th or later column is used.
15090: */
15091: struct SrcList {
15092:   int nSrc;        /* Number of tables or subqueries in the FROM clause */
15093:   u32 nAlloc;      /* Number of entries allocated in a[] below */
15094:   struct SrcList_item {
15095:     Schema *pSchema;  /* Schema to which this item is fixed */
15096:     char *zDatabase;  /* Name of database holding this table */
15097:     char *zName;      /* Name of the table */
15098:     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
15099:     Table *pTab;      /* An SQL table corresponding to zName */
15100:     Select *pSelect;  /* A SELECT statement used in place of a table name */
15101:     int addrFillSub;  /* Address of subroutine to manifest a subquery */
15102:     int regReturn;    /* Register holding return address of addrFillSub */
15103:     int regResult;    /* Registers holding results of a co-routine */
15104:     struct {
15105:       u8 jointype;      /* Type of join between this table and the previous */
15106:       unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
15107:       unsigned isIndexedBy :1;   /* True if there is an INDEXED BY clause */
15108:       unsigned isTabFunc :1;     /* True if table-valued-function syntax */
15109:       unsigned isCorrelated :1;  /* True if sub-query is correlated */
15110:       unsigned viaCoroutine :1;  /* Implemented as a co-routine */
15111:       unsigned isRecursive :1;   /* True for recursive reference in WITH */
15112:     } fg;
15113: #ifndef SQLITE_OMIT_EXPLAIN
15114:     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
15115: #endif
15116:     int iCursor;      /* The VDBE cursor number used to access this table */
15117:     Expr *pOn;        /* The ON clause of a join */
15118:     IdList *pUsing;   /* The USING clause of a join */
15119:     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
15120:     union {
15121:       char *zIndexedBy;    /* Identifier from "INDEXED BY <zIndex>" clause */
15122:       ExprList *pFuncArg;  /* Arguments to table-valued-function */
15123:     } u1;
15124:     Index *pIBIndex;  /* Index structure corresponding to u1.zIndexedBy */
15125:   } a[1];             /* One entry for each identifier on the list */
15126: };
15127: 
15128: /*
15129: ** Permitted values of the SrcList.a.jointype field
15130: */
15131: #define JT_INNER     0x0001    /* Any kind of inner or cross join */
15132: #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
15133: #define JT_NATURAL   0x0004    /* True for a "natural" join */
15134: #define JT_LEFT      0x0008    /* Left outer join */
15135: #define JT_RIGHT     0x0010    /* Right outer join */
15136: #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
15137: #define JT_ERROR     0x0040    /* unknown or unsupported join type */
15138: 
15139: 
15140: /*
15141: ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
15142: ** and the WhereInfo.wctrlFlags member.
15143: **
15144: ** Value constraints (enforced via assert()):
15145: **     WHERE_USE_LIMIT  == SF_FixedLimit
15146: */
15147: #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
15148: #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
15149: #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
15150: #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
15151: #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
15152: #define WHERE_DUPLICATES_OK    0x0010 /* Ok to return a row more than once */
15153: #define WHERE_OR_SUBCLAUSE     0x0020 /* Processing a sub-WHERE as part of
15154:                                       ** the OR optimization  */
15155: #define WHERE_GROUPBY          0x0040 /* pOrderBy is really a GROUP BY */
15156: #define WHERE_DISTINCTBY       0x0080 /* pOrderby is really a DISTINCT clause */
15157: #define WHERE_WANT_DISTINCT    0x0100 /* All output needs to be distinct */
15158: #define WHERE_SORTBYGROUP      0x0200 /* Support sqlite3WhereIsSorted() */
15159: #define WHERE_SEEK_TABLE       0x0400 /* Do not defer seeks on main table */
15160: #define WHERE_ORDERBY_LIMIT    0x0800 /* ORDERBY+LIMIT on the inner loop */
15161:                         /*     0x1000    not currently used */
15162:                         /*     0x2000    not currently used */
15163: #define WHERE_USE_LIMIT        0x4000 /* Use the LIMIT in cost estimates */
15164:                         /*     0x8000    not currently used */
15165: 
15166: /* Allowed return values from sqlite3WhereIsDistinct()
15167: */
15168: #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
15169: #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
15170: #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
15171: #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
15172: 
15173: /*
15174: ** A NameContext defines a context in which to resolve table and column
15175: ** names.  The context consists of a list of tables (the pSrcList) field and
15176: ** a list of named expression (pEList).  The named expression list may
15177: ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
15178: ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
15179: ** pEList corresponds to the result set of a SELECT and is NULL for
15180: ** other statements.
15181: **
15182: ** NameContexts can be nested.  When resolving names, the inner-most
15183: ** context is searched first.  If no match is found, the next outer
15184: ** context is checked.  If there is still no match, the next context
15185: ** is checked.  This process continues until either a match is found
15186: ** or all contexts are check.  When a match is found, the nRef member of
15187: ** the context containing the match is incremented.
15188: **
15189: ** Each subquery gets a new NameContext.  The pNext field points to the
15190: ** NameContext in the parent query.  Thus the process of scanning the
15191: ** NameContext list corresponds to searching through successively outer
15192: ** subqueries looking for a match.
15193: */
15194: struct NameContext {
15195:   Parse *pParse;       /* The parser */
15196:   SrcList *pSrcList;   /* One or more tables used to resolve names */
15197:   ExprList *pEList;    /* Optional list of result-set columns */
15198:   AggInfo *pAggInfo;   /* Information about aggregates at this level */
15199:   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
15200:   int nRef;            /* Number of names resolved by this context */
15201:   int nErr;            /* Number of errors encountered while resolving names */
15202:   u16 ncFlags;         /* Zero or more NC_* flags defined below */
15203: };
15204: 
15205: /*
15206: ** Allowed values for the NameContext, ncFlags field.
15207: **
15208: ** Value constraints (all checked via assert()):
15209: **    NC_HasAgg    == SF_HasAgg
15210: **    NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15211: **
15212: */
15213: #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
15214: #define NC_PartIdx   0x0002  /* True if resolving a partial index WHERE */
15215: #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
15216: #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
15217: #define NC_HasAgg    0x0010  /* One or more aggregate functions seen */
15218: #define NC_IdxExpr   0x0020  /* True if resolving columns of CREATE INDEX */
15219: #define NC_VarSelect 0x0040  /* A correlated subquery has been seen */
15220: #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
15221: 
15222: /*
15223: ** An instance of the following structure contains all information
15224: ** needed to generate code for a single SELECT statement.
15225: **
15226: ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
15227: ** If there is a LIMIT clause, the parser sets nLimit to the value of the
15228: ** limit and nOffset to the value of the offset (or 0 if there is not
15229: ** offset).  But later on, nLimit and nOffset become the memory locations
15230: ** in the VDBE that record the limit and offset counters.
15231: **
15232: ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
15233: ** These addresses must be stored so that we can go back and fill in
15234: ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
15235: ** the number of columns in P2 can be computed at the same time
15236: ** as the OP_OpenEphm instruction is coded because not
15237: ** enough information about the compound query is known at that point.
15238: ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
15239: ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
15240: ** sequences for the ORDER BY clause.
15241: */
15242: struct Select {
15243:   ExprList *pEList;      /* The fields of the result */
15244:   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
15245:   LogEst nSelectRow;     /* Estimated number of result rows */
15246:   u32 selFlags;          /* Various SF_* values */
15247:   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
15248: #if SELECTTRACE_ENABLED
15249:   char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
15250: #endif
15251:   int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
15252:   SrcList *pSrc;         /* The FROM clause */
15253:   Expr *pWhere;          /* The WHERE clause */
15254:   ExprList *pGroupBy;    /* The GROUP BY clause */
15255:   Expr *pHaving;         /* The HAVING clause */
15256:   ExprList *pOrderBy;    /* The ORDER BY clause */
15257:   Select *pPrior;        /* Prior select in a compound select statement */
15258:   Select *pNext;         /* Next select to the left in a compound */
15259:   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
15260:   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
15261:   With *pWith;           /* WITH clause attached to this select. Or NULL. */
15262: };
15263: 
15264: /*
15265: ** Allowed values for Select.selFlags.  The "SF" prefix stands for
15266: ** "Select Flag".
15267: **
15268: ** Value constraints (all checked via assert())
15269: **     SF_HasAgg     == NC_HasAgg
15270: **     SF_MinMaxAgg  == NC_MinMaxAgg     == SQLITE_FUNC_MINMAX
15271: **     SF_FixedLimit == WHERE_USE_LIMIT
15272: */
15273: #define SF_Distinct       0x00001  /* Output should be DISTINCT */
15274: #define SF_All            0x00002  /* Includes the ALL keyword */
15275: #define SF_Resolved       0x00004  /* Identifiers have been resolved */
15276: #define SF_Aggregate      0x00008  /* Contains agg functions or a GROUP BY */
15277: #define SF_HasAgg         0x00010  /* Contains aggregate functions */
15278: #define SF_UsesEphemeral  0x00020  /* Uses the OpenEphemeral opcode */
15279: #define SF_Expanded       0x00040  /* sqlite3SelectExpand() called on this */
15280: #define SF_HasTypeInfo    0x00080  /* FROM subqueries have Table metadata */
15281: #define SF_Compound       0x00100  /* Part of a compound query */
15282: #define SF_Values         0x00200  /* Synthesized from VALUES clause */
15283: #define SF_MultiValue     0x00400  /* Single VALUES term with multiple rows */
15284: #define SF_NestedFrom     0x00800  /* Part of a parenthesized FROM clause */
15285: #define SF_MinMaxAgg      0x01000  /* Aggregate containing min() or max() */
15286: #define SF_Recursive      0x02000  /* The recursive part of a recursive CTE */
15287: #define SF_FixedLimit     0x04000  /* nSelectRow set by a constant LIMIT */
15288: #define SF_MaybeConvert   0x08000  /* Need convertCompoundSelectToSubquery() */
15289: #define SF_Converted      0x10000  /* By convertCompoundSelectToSubquery() */
15290: #define SF_IncludeHidden  0x20000  /* Include hidden columns in output */
15291: 
15292: 
15293: /*
15294: ** The results of a SELECT can be distributed in several ways, as defined
15295: ** by one of the following macros.  The "SRT" prefix means "SELECT Result
15296: ** Type".
15297: **
15298: **     SRT_Union       Store results as a key in a temporary index
15299: **                     identified by pDest->iSDParm.
15300: **
15301: **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
15302: **
15303: **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
15304: **                     set is not empty.
15305: **
15306: **     SRT_Discard     Throw the results away.  This is used by SELECT
15307: **                     statements within triggers whose only purpose is
15308: **                     the side-effects of functions.
15309: **
15310: ** All of the above are free to ignore their ORDER BY clause. Those that
15311: ** follow must honor the ORDER BY clause.
15312: **
15313: **     SRT_Output      Generate a row of output (using the OP_ResultRow
15314: **                     opcode) for each row in the result set.
15315: **
15316: **     SRT_Mem         Only valid if the result is a single column.
15317: **                     Store the first column of the first result row
15318: **                     in register pDest->iSDParm then abandon the rest
15319: **                     of the query.  This destination implies "LIMIT 1".
15320: **
15321: **     SRT_Set         The result must be a single column.  Store each
15322: **                     row of result as the key in table pDest->iSDParm.
15323: **                     Apply the affinity pDest->affSdst before storing
15324: **                     results.  Used to implement "IN (SELECT ...)".
15325: **
15326: **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
15327: **                     the result there. The cursor is left open after
15328: **                     returning.  This is like SRT_Table except that
15329: **                     this destination uses OP_OpenEphemeral to create
15330: **                     the table first.
15331: **
15332: **     SRT_Coroutine   Generate a co-routine that returns a new row of
15333: **                     results each time it is invoked.  The entry point
15334: **                     of the co-routine is stored in register pDest->iSDParm
15335: **                     and the result row is stored in pDest->nDest registers
15336: **                     starting with pDest->iSdst.
15337: **
15338: **     SRT_Table       Store results in temporary table pDest->iSDParm.
15339: **     SRT_Fifo        This is like SRT_EphemTab except that the table
15340: **                     is assumed to already be open.  SRT_Fifo has
15341: **                     the additional property of being able to ignore
15342: **                     the ORDER BY clause.
15343: **
15344: **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
15345: **                     But also use temporary table pDest->iSDParm+1 as
15346: **                     a record of all prior results and ignore any duplicate
15347: **                     rows.  Name means:  "Distinct Fifo".
15348: **
15349: **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
15350: **                     an index).  Append a sequence number so that all entries
15351: **                     are distinct.
15352: **
15353: **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
15354: **                     the same record has never been stored before.  The
15355: **                     index at pDest->iSDParm+1 hold all prior stores.
15356: */
15357: #define SRT_Union        1  /* Store result as keys in an index */
15358: #define SRT_Except       2  /* Remove result from a UNION index */
15359: #define SRT_Exists       3  /* Store 1 if the result is not empty */
15360: #define SRT_Discard      4  /* Do not save the results anywhere */
15361: #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
15362: #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
15363: #define SRT_Queue        7  /* Store result in an queue */
15364: #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
15365: 
15366: /* The ORDER BY clause is ignored for all of the above */
15367: #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
15368: 
15369: #define SRT_Output       9  /* Output each row of result */
15370: #define SRT_Mem         10  /* Store result in a memory cell */
15371: #define SRT_Set         11  /* Store results as keys in an index */
15372: #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
15373: #define SRT_Coroutine   13  /* Generate a single row of result */
15374: #define SRT_Table       14  /* Store result as data with an automatic rowid */
15375: 
15376: /*
15377: ** An instance of this object describes where to put of the results of
15378: ** a SELECT statement.
15379: */
15380: struct SelectDest {
15381:   u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
15382:   char affSdst;        /* Affinity used when eDest==SRT_Set */
15383:   int iSDParm;         /* A parameter used by the eDest disposal method */
15384:   int iSdst;           /* Base register where results are written */
15385:   int nSdst;           /* Number of registers allocated */
15386:   ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
15387: };
15388: 
15389: /*
15390: ** During code generation of statements that do inserts into AUTOINCREMENT
15391: ** tables, the following information is attached to the Table.u.autoInc.p
15392: ** pointer of each autoincrement table to record some side information that
15393: ** the code generator needs.  We have to keep per-table autoincrement
15394: ** information in case inserts are done within triggers.  Triggers do not
15395: ** normally coordinate their activities, but we do need to coordinate the
15396: ** loading and saving of autoincrement information.
15397: */
15398: struct AutoincInfo {
15399:   AutoincInfo *pNext;   /* Next info block in a list of them all */
15400:   Table *pTab;          /* Table this info block refers to */
15401:   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
15402:   int regCtr;           /* Memory register holding the rowid counter */
15403: };
15404: 
15405: /*
15406: ** Size of the column cache
15407: */
15408: #ifndef SQLITE_N_COLCACHE
15409: # define SQLITE_N_COLCACHE 10
15410: #endif
15411: 
15412: /*
15413: ** At least one instance of the following structure is created for each
15414: ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
15415: ** statement. All such objects are stored in the linked list headed at
15416: ** Parse.pTriggerPrg and deleted once statement compilation has been
15417: ** completed.
15418: **
15419: ** A Vdbe sub-program that implements the body and WHEN clause of trigger
15420: ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
15421: ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
15422: ** The Parse.pTriggerPrg list never contains two entries with the same
15423: ** values for both pTrigger and orconf.
15424: **
15425: ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
15426: ** accessed (or set to 0 for triggers fired as a result of INSERT
15427: ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
15428: ** a mask of new.* columns used by the program.
15429: */
15430: struct TriggerPrg {
15431:   Trigger *pTrigger;      /* Trigger this program was coded from */
15432:   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
15433:   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
15434:   int orconf;             /* Default ON CONFLICT policy */
15435:   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
15436: };
15437: 
15438: /*
15439: ** The yDbMask datatype for the bitmask of all attached databases.
15440: */
15441: #if SQLITE_MAX_ATTACHED>30
15442:   typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
15443: # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
15444: # define DbMaskZero(M)      memset((M),0,sizeof(M))
15445: # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
15446: # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
15447: # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
15448: #else
15449:   typedef unsigned int yDbMask;
15450: # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
15451: # define DbMaskZero(M)      (M)=0
15452: # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
15453: # define DbMaskAllZero(M)   (M)==0
15454: # define DbMaskNonZero(M)   (M)!=0
15455: #endif
15456: 
15457: /*
15458: ** An SQL parser context.  A copy of this structure is passed through
15459: ** the parser and down into all the parser action routine in order to
15460: ** carry around information that is global to the entire parse.
15461: **
15462: ** The structure is divided into two parts.  When the parser and code
15463: ** generate call themselves recursively, the first part of the structure
15464: ** is constant but the second part is reset at the beginning and end of
15465: ** each recursion.
15466: **
15467: ** The nTableLock and aTableLock variables are only used if the shared-cache
15468: ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
15469: ** used to store the set of table-locks required by the statement being
15470: ** compiled. Function sqlite3TableLock() is used to add entries to the
15471: ** list.
15472: */
15473: struct Parse {
15474:   sqlite3 *db;         /* The main database structure */
15475:   char *zErrMsg;       /* An error message */
15476:   Vdbe *pVdbe;         /* An engine for executing database bytecode */
15477:   int rc;              /* Return code from execution */
15478:   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
15479:   u8 checkSchema;      /* Causes schema cookie check after an error */
15480:   u8 nested;           /* Number of nested calls to the parser/code generator */
15481:   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
15482:   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
15483:   u8 mayAbort;         /* True if statement may throw an ABORT exception */
15484:   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
15485:   u8 okConstFactor;    /* OK to factor out constants */
15486:   u8 disableLookaside; /* Number of times lookaside has been disabled */
15487:   u8 nColCache;        /* Number of entries in aColCache[] */
15488:   int aTempReg[8];     /* Holding area for temporary registers */
15489:   int nRangeReg;       /* Size of the temporary register block */
15490:   int iRangeReg;       /* First register in temporary register block */
15491:   int nErr;            /* Number of errors seen */
15492:   int nTab;            /* Number of previously allocated VDBE cursors */
15493:   int nMem;            /* Number of memory cells used so far */
15494:   int nSet;            /* Number of sets used so far */
15495:   int nOnce;           /* Number of OP_Once instructions so far */
15496:   int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
15497:   int szOpAlloc;       /* Bytes of memory space allocated for Vdbe.aOp[] */
15498:   int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
15499:   int ckBase;          /* Base register of data during check constraints */
15500:   int iSelfTab;        /* Table of an index whose exprs are being coded */
15501:   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
15502:   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
15503:   int nLabel;          /* Number of labels used */
15504:   int *aLabel;         /* Space to hold the labels */
15505:   struct yColCache {
15506:     int iTable;           /* Table cursor number */
15507:     i16 iColumn;          /* Table column number */
15508:     u8 tempReg;           /* iReg is a temp register that needs to be freed */
15509:     int iLevel;           /* Nesting level */
15510:     int iReg;             /* Reg with value of this column. 0 means none. */
15511:     int lru;              /* Least recently used entry has the smallest value */
15512:   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
15513:   ExprList *pConstExpr;/* Constant expressions */
15514:   Token constraintName;/* Name of the constraint currently being parsed */
15515:   yDbMask writeMask;   /* Start a write transaction on these databases */
15516:   yDbMask cookieMask;  /* Bitmask of schema verified databases */
15517:   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
15518:   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
15519:   int regRoot;         /* Register holding root page number for new objects */
15520:   int nMaxArg;         /* Max args passed to user function by sub-program */
15521: #if SELECTTRACE_ENABLED
15522:   int nSelect;         /* Number of SELECT statements seen */
15523:   int nSelectIndent;   /* How far to indent SELECTTRACE() output */
15524: #endif
15525: #ifndef SQLITE_OMIT_SHARED_CACHE
15526:   int nTableLock;        /* Number of locks in aTableLock */
15527:   TableLock *aTableLock; /* Required table locks for shared-cache mode */
15528: #endif
15529:   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
15530: 
15531:   /* Information used while coding trigger programs. */
15532:   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
15533:   Table *pTriggerTab;  /* Table triggers are being coded for */
15534:   int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
15535:   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
15536:   u32 oldmask;         /* Mask of old.* columns referenced */
15537:   u32 newmask;         /* Mask of new.* columns referenced */
15538:   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
15539:   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
15540:   u8 disableTriggers;  /* True to disable triggers */
15541: 
15542:   /************************************************************************
15543:   ** Above is constant between recursions.  Below is reset before and after
15544:   ** each recursion.  The boundary between these two regions is determined
15545:   ** using offsetof(Parse,nVar) so the nVar field must be the first field
15546:   ** in the recursive region.
15547:   ************************************************************************/
15548: 
15549:   ynVar nVar;               /* Number of '?' variables seen in the SQL so far */
15550:   int nzVar;                /* Number of available slots in azVar[] */
15551:   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
15552:   u8 explain;               /* True if the EXPLAIN flag is found on the query */
15553: #ifndef SQLITE_OMIT_VIRTUALTABLE
15554:   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
15555:   int nVtabLock;            /* Number of virtual tables to lock */
15556: #endif
15557:   int nAlias;               /* Number of aliased result set columns */
15558:   int nHeight;              /* Expression tree height of current sub-select */
15559: #ifndef SQLITE_OMIT_EXPLAIN
15560:   int iSelectId;            /* ID of current select for EXPLAIN output */
15561:   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
15562: #endif
15563:   char **azVar;             /* Pointers to names of parameters */
15564:   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
15565:   const char *zTail;        /* All SQL text past the last semicolon parsed */
15566:   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
15567:   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
15568:   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
15569:   Token sNameToken;         /* Token with unqualified schema object name */
15570:   Token sLastToken;         /* The last token parsed */
15571: #ifndef SQLITE_OMIT_VIRTUALTABLE
15572:   Token sArg;               /* Complete text of a module argument */
15573:   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
15574: #endif
15575:   Table *pZombieTab;        /* List of Table objects to delete after code gen */
15576:   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
15577:   With *pWith;              /* Current WITH clause, or NULL */
15578:   With *pWithToFree;        /* Free this WITH object at the end of the parse */
15579: };
15580: 
15581: /*
15582: ** Return true if currently inside an sqlite3_declare_vtab() call.
15583: */
15584: #ifdef SQLITE_OMIT_VIRTUALTABLE
15585:   #define IN_DECLARE_VTAB 0
15586: #else
15587:   #define IN_DECLARE_VTAB (pParse->declareVtab)
15588: #endif
15589: 
15590: /*
15591: ** An instance of the following structure can be declared on a stack and used
15592: ** to save the Parse.zAuthContext value so that it can be restored later.
15593: */
15594: struct AuthContext {
15595:   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
15596:   Parse *pParse;              /* The Parse structure */
15597: };
15598: 
15599: /*
15600: ** Bitfield flags for P5 value in various opcodes.
15601: **
15602: ** Value constraints (enforced via assert()):
15603: **    OPFLAG_LENGTHARG    == SQLITE_FUNC_LENGTH
15604: **    OPFLAG_TYPEOFARG    == SQLITE_FUNC_TYPEOF
15605: **    OPFLAG_BULKCSR      == BTREE_BULKLOAD
15606: **    OPFLAG_SEEKEQ       == BTREE_SEEK_EQ
15607: **    OPFLAG_FORDELETE    == BTREE_FORDELETE
15608: **    OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15609: **    OPFLAG_AUXDELETE    == BTREE_AUXDELETE
15610: */
15611: #define OPFLAG_NCHANGE       0x01    /* OP_Insert: Set to update db->nChange */
15612:                                      /* Also used in P2 (not P5) of OP_Delete */
15613: #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
15614: #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
15615: #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
15616: #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
15617: #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
15618: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15619: #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
15620: #endif
15621: #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
15622: #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
15623: #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
15624: #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
15625: #define OPFLAG_FORDELETE     0x08    /* OP_Open should use BTREE_FORDELETE */
15626: #define OPFLAG_P2ISREG       0x10    /* P2 to OP_Open** is a register number */
15627: #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
15628: #define OPFLAG_SAVEPOSITION  0x02    /* OP_Delete: keep cursor position */
15629: #define OPFLAG_AUXDELETE     0x04    /* OP_Delete: index in a DELETE op */
15630: 
15631: /*
15632:  * Each trigger present in the database schema is stored as an instance of
15633:  * struct Trigger.
15634:  *
15635:  * Pointers to instances of struct Trigger are stored in two ways.
15636:  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
15637:  *    database). This allows Trigger structures to be retrieved by name.
15638:  * 2. All triggers associated with a single table form a linked list, using the
15639:  *    pNext member of struct Trigger. A pointer to the first element of the
15640:  *    linked list is stored as the "pTrigger" member of the associated
15641:  *    struct Table.
15642:  *
15643:  * The "step_list" member points to the first element of a linked list
15644:  * containing the SQL statements specified as the trigger program.
15645:  */
15646: struct Trigger {
15647:   char *zName;            /* The name of the trigger                        */
15648:   char *table;            /* The table or view to which the trigger applies */
15649:   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
15650:   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
15651:   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
15652:   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
15653:                              the <column-list> is stored here */
15654:   Schema *pSchema;        /* Schema containing the trigger */
15655:   Schema *pTabSchema;     /* Schema containing the table */
15656:   TriggerStep *step_list; /* Link list of trigger program steps             */
15657:   Trigger *pNext;         /* Next trigger associated with the table */
15658: };
15659: 
15660: /*
15661: ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
15662: ** determine which.
15663: **
15664: ** If there are multiple triggers, you might of some BEFORE and some AFTER.
15665: ** In that cases, the constants below can be ORed together.
15666: */
15667: #define TRIGGER_BEFORE  1
15668: #define TRIGGER_AFTER   2
15669: 
15670: /*
15671:  * An instance of struct TriggerStep is used to store a single SQL statement
15672:  * that is a part of a trigger-program.
15673:  *
15674:  * Instances of struct TriggerStep are stored in a singly linked list (linked
15675:  * using the "pNext" member) referenced by the "step_list" member of the
15676:  * associated struct Trigger instance. The first element of the linked list is
15677:  * the first step of the trigger-program.
15678:  *
15679:  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
15680:  * "SELECT" statement. The meanings of the other members is determined by the
15681:  * value of "op" as follows:
15682:  *
15683:  * (op == TK_INSERT)
15684:  * orconf    -> stores the ON CONFLICT algorithm
15685:  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
15686:  *              this stores a pointer to the SELECT statement. Otherwise NULL.
15687:  * zTarget   -> Dequoted name of the table to insert into.
15688:  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
15689:  *              this stores values to be inserted. Otherwise NULL.
15690:  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
15691:  *              statement, then this stores the column-names to be
15692:  *              inserted into.
15693:  *
15694:  * (op == TK_DELETE)
15695:  * zTarget   -> Dequoted name of the table to delete from.
15696:  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
15697:  *              Otherwise NULL.
15698:  *
15699:  * (op == TK_UPDATE)
15700:  * zTarget   -> Dequoted name of the table to update.
15701:  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
15702:  *              Otherwise NULL.
15703:  * pExprList -> A list of the columns to update and the expressions to update
15704:  *              them to. See sqlite3Update() documentation of "pChanges"
15705:  *              argument.
15706:  *
15707:  */
15708: struct TriggerStep {
15709:   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
15710:   u8 orconf;           /* OE_Rollback etc. */
15711:   Trigger *pTrig;      /* The trigger that this step is a part of */
15712:   Select *pSelect;     /* SELECT statement or RHS of INSERT INTO SELECT ... */
15713:   char *zTarget;       /* Target table for DELETE, UPDATE, INSERT */
15714:   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
15715:   ExprList *pExprList; /* SET clause for UPDATE. */
15716:   IdList *pIdList;     /* Column names for INSERT */
15717:   TriggerStep *pNext;  /* Next in the link-list */
15718:   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
15719: };
15720: 
15721: /*
15722: ** The following structure contains information used by the sqliteFix...
15723: ** routines as they walk the parse tree to make database references
15724: ** explicit.
15725: */
15726: typedef struct DbFixer DbFixer;
15727: struct DbFixer {
15728:   Parse *pParse;      /* The parsing context.  Error messages written here */
15729:   Schema *pSchema;    /* Fix items to this schema */
15730:   int bVarOnly;       /* Check for variable references only */
15731:   const char *zDb;    /* Make sure all objects are contained in this database */
15732:   const char *zType;  /* Type of the container - used for error messages */
15733:   const Token *pName; /* Name of the container - used for error messages */
15734: };
15735: 
15736: /*
15737: ** An objected used to accumulate the text of a string where we
15738: ** do not necessarily know how big the string will be in the end.
15739: */
15740: struct StrAccum {
15741:   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
15742:   char *zBase;         /* A base allocation.  Not from malloc. */
15743:   char *zText;         /* The string collected so far */
15744:   u32  nChar;          /* Length of the string so far */
15745:   u32  nAlloc;         /* Amount of space allocated in zText */
15746:   u32  mxAlloc;        /* Maximum allowed allocation.  0 for no malloc usage */
15747:   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
15748:   u8   printfFlags;    /* SQLITE_PRINTF flags below */
15749: };
15750: #define STRACCUM_NOMEM   1
15751: #define STRACCUM_TOOBIG  2
15752: #define SQLITE_PRINTF_INTERNAL 0x01  /* Internal-use-only converters allowed */
15753: #define SQLITE_PRINTF_SQLFUNC  0x02  /* SQL function arguments to VXPrintf */
15754: #define SQLITE_PRINTF_MALLOCED 0x04  /* True if xText is allocated space */
15755: 
15756: #define isMalloced(X)  (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
15757: 
15758: 
15759: /*
15760: ** A pointer to this structure is used to communicate information
15761: ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
15762: */
15763: typedef struct {
15764:   sqlite3 *db;        /* The database being initialized */
15765:   char **pzErrMsg;    /* Error message stored here */
15766:   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
15767:   int rc;             /* Result code stored here */
15768: } InitData;
15769: 
15770: /*
15771: ** Structure containing global configuration data for the SQLite library.
15772: **
15773: ** This structure also contains some state information.
15774: */
15775: struct Sqlite3Config {
15776:   int bMemstat;                     /* True to enable memory status */
15777:   int bCoreMutex;                   /* True to enable core mutexing */
15778:   int bFullMutex;                   /* True to enable full mutexing */
15779:   int bOpenUri;                     /* True to interpret filenames as URIs */
15780:   int bUseCis;                      /* Use covering indices for full-scans */
15781:   int mxStrlen;                     /* Maximum string length */
15782:   int neverCorrupt;                 /* Database is always well-formed */
15783:   int szLookaside;                  /* Default lookaside buffer size */
15784:   int nLookaside;                   /* Default lookaside buffer count */
15785:   int nStmtSpill;                   /* Stmt-journal spill-to-disk threshold */
15786:   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
15787:   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
15788:   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
15789:   void *pHeap;                      /* Heap storage space */
15790:   int nHeap;                        /* Size of pHeap[] */
15791:   int mnReq, mxReq;                 /* Min and max heap requests sizes */
15792:   sqlite3_int64 szMmap;             /* mmap() space per open file */
15793:   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
15794:   void *pScratch;                   /* Scratch memory */
15795:   int szScratch;                    /* Size of each scratch buffer */
15796:   int nScratch;                     /* Number of scratch buffers */
15797:   void *pPage;                      /* Page cache memory */
15798:   int szPage;                       /* Size of each page in pPage[] */
15799:   int nPage;                        /* Number of pages in pPage[] */
15800:   int mxParserStack;                /* maximum depth of the parser stack */
15801:   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
15802:   u32 szPma;                        /* Maximum Sorter PMA size */
15803:   /* The above might be initialized to non-zero.  The following need to always
15804:   ** initially be zero, however. */
15805:   int isInit;                       /* True after initialization has finished */
15806:   int inProgress;                   /* True while initialization in progress */
15807:   int isMutexInit;                  /* True after mutexes are initialized */
15808:   int isMallocInit;                 /* True after malloc is initialized */
15809:   int isPCacheInit;                 /* True after malloc is initialized */
15810:   int nRefInitMutex;                /* Number of users of pInitMutex */
15811:   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
15812:   void (*xLog)(void*,int,const char*); /* Function for logging */
15813:   void *pLogArg;                       /* First argument to xLog() */
15814: #ifdef SQLITE_ENABLE_SQLLOG
15815:   void(*xSqllog)(void*,sqlite3*,const char*, int);
15816:   void *pSqllogArg;
15817: #endif
15818: #ifdef SQLITE_VDBE_COVERAGE
15819:   /* The following callback (if not NULL) is invoked on every VDBE branch
15820:   ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
15821:   */
15822:   void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
15823:   void *pVdbeBranchArg;                                     /* 1st argument */
15824: #endif
15825: #ifndef SQLITE_OMIT_BUILTIN_TEST
15826:   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
15827: #endif
15828:   int bLocaltimeFault;              /* True to fail localtime() calls */
15829: };
15830: 
15831: /*
15832: ** This macro is used inside of assert() statements to indicate that
15833: ** the assert is only valid on a well-formed database.  Instead of:
15834: **
15835: **     assert( X );
15836: **
15837: ** One writes:
15838: **
15839: **     assert( X || CORRUPT_DB );
15840: **
15841: ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
15842: ** that the database is definitely corrupt, only that it might be corrupt.
15843: ** For most test cases, CORRUPT_DB is set to false using a special
15844: ** sqlite3_test_control().  This enables assert() statements to prove
15845: ** things that are always true for well-formed databases.
15846: */
15847: #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
15848: 
15849: /*
15850: ** Context pointer passed down through the tree-walk.
15851: */
15852: struct Walker {
15853:   Parse *pParse;                            /* Parser context.  */
15854:   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
15855:   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
15856:   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
15857:   int walkerDepth;                          /* Number of subqueries */
15858:   u8 eCode;                                 /* A small processing code */
15859:   union {                                   /* Extra data for callback */
15860:     NameContext *pNC;                          /* Naming context */
15861:     int n;                                     /* A counter */
15862:     int iCur;                                  /* A cursor number */
15863:     SrcList *pSrcList;                         /* FROM clause */
15864:     struct SrcCount *pSrcCount;                /* Counting column references */
15865:     struct CCurHint *pCCurHint;                /* Used by codeCursorHint() */
15866:     int *aiCol;                                /* array of column indexes */
15867:     struct IdxCover *pIdxCover;                /* Check for index coverage */
15868:   } u;
15869: };
15870: 
15871: /* Forward declarations */
15872: SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
15873: SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
15874: SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
15875: SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
15876: SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
15877: SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
15878: 
15879: /*
15880: ** Return code from the parse-tree walking primitives and their
15881: ** callbacks.
15882: */
15883: #define WRC_Continue    0   /* Continue down into children */
15884: #define WRC_Prune       1   /* Omit children but continue walking siblings */
15885: #define WRC_Abort       2   /* Abandon the tree walk */
15886: 
15887: /*
15888: ** An instance of this structure represents a set of one or more CTEs
15889: ** (common table expressions) created by a single WITH clause.
15890: */
15891: struct With {
15892:   int nCte;                       /* Number of CTEs in the WITH clause */
15893:   With *pOuter;                   /* Containing WITH clause, or NULL */
15894:   struct Cte {                    /* For each CTE in the WITH clause.... */
15895:     char *zName;                    /* Name of this CTE */
15896:     ExprList *pCols;                /* List of explicit column names, or NULL */
15897:     Select *pSelect;                /* The definition of this CTE */
15898:     const char *zCteErr;            /* Error message for circular references */
15899:   } a[1];
15900: };
15901: 
15902: #ifdef SQLITE_DEBUG
15903: /*
15904: ** An instance of the TreeView object is used for printing the content of
15905: ** data structures on sqlite3DebugPrintf() using a tree-like view.
15906: */
15907: struct TreeView {
15908:   int iLevel;             /* Which level of the tree we are on */
15909:   u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
15910: };
15911: #endif /* SQLITE_DEBUG */
15912: 
15913: /*
15914: ** Assuming zIn points to the first byte of a UTF-8 character,
15915: ** advance zIn to point to the first byte of the next UTF-8 character.
15916: */
15917: #define SQLITE_SKIP_UTF8(zIn) {                        \
15918:   if( (*(zIn++))>=0xc0 ){                              \
15919:     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
15920:   }                                                    \
15921: }
15922: 
15923: /*
15924: ** The SQLITE_*_BKPT macros are substitutes for the error codes with
15925: ** the same name but without the _BKPT suffix.  These macros invoke
15926: ** routines that report the line-number on which the error originated
15927: ** using sqlite3_log().  The routines also provide a convenient place
15928: ** to set a debugger breakpoint.
15929: */
15930: SQLITE_PRIVATE int sqlite3CorruptError(int);
15931: SQLITE_PRIVATE int sqlite3MisuseError(int);
15932: SQLITE_PRIVATE int sqlite3CantopenError(int);
15933: #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
15934: #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
15935: #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
15936: #ifdef SQLITE_DEBUG
15937: SQLITE_PRIVATE   int sqlite3NomemError(int);
15938: SQLITE_PRIVATE   int sqlite3IoerrnomemError(int);
15939: # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
15940: # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
15941: #else
15942: # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
15943: # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
15944: #endif
15945: 
15946: /*
15947: ** FTS3 and FTS4 both require virtual table support
15948: */
15949: #if defined(SQLITE_OMIT_VIRTUALTABLE)
15950: # undef SQLITE_ENABLE_FTS3
15951: # undef SQLITE_ENABLE_FTS4
15952: #endif
15953: 
15954: /*
15955: ** FTS4 is really an extension for FTS3.  It is enabled using the
15956: ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
15957: ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
15958: */
15959: #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
15960: # define SQLITE_ENABLE_FTS3 1
15961: #endif
15962: 
15963: /*
15964: ** The ctype.h header is needed for non-ASCII systems.  It is also
15965: ** needed by FTS3 when FTS3 is included in the amalgamation.
15966: */
15967: #if !defined(SQLITE_ASCII) || \
15968:     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
15969: # include <ctype.h>
15970: #endif
15971: 
15972: /*
15973: ** The following macros mimic the standard library functions toupper(),
15974: ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
15975: ** sqlite versions only work for ASCII characters, regardless of locale.
15976: */
15977: #ifdef SQLITE_ASCII
15978: # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
15979: # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
15980: # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
15981: # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
15982: # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
15983: # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
15984: # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
15985: # define sqlite3Isquote(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
15986: #else
15987: # define sqlite3Toupper(x)   toupper((unsigned char)(x))
15988: # define sqlite3Isspace(x)   isspace((unsigned char)(x))
15989: # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
15990: # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
15991: # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
15992: # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
15993: # define sqlite3Tolower(x)   tolower((unsigned char)(x))
15994: # define sqlite3Isquote(x)   ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
15995: #endif
15996: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
15997: SQLITE_PRIVATE int sqlite3IsIdChar(u8);
15998: #endif
15999: 
16000: /*
16001: ** Internal function prototypes
16002: */
16003: SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
16004: SQLITE_PRIVATE int sqlite3Strlen30(const char*);
16005: SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
16006: #define sqlite3StrNICmp sqlite3_strnicmp
16007: 
16008: SQLITE_PRIVATE int sqlite3MallocInit(void);
16009: SQLITE_PRIVATE void sqlite3MallocEnd(void);
16010: SQLITE_PRIVATE void *sqlite3Malloc(u64);
16011: SQLITE_PRIVATE void *sqlite3MallocZero(u64);
16012: SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
16013: SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
16014: SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
16015: SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
16016: SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
16017: SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
16018: SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
16019: SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
16020: SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
16021: SQLITE_PRIVATE int sqlite3MallocSize(void*);
16022: SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
16023: SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
16024: SQLITE_PRIVATE void sqlite3ScratchFree(void*);
16025: SQLITE_PRIVATE void *sqlite3PageMalloc(int);
16026: SQLITE_PRIVATE void sqlite3PageFree(void*);
16027: SQLITE_PRIVATE void sqlite3MemSetDefault(void);
16028: #ifndef SQLITE_OMIT_BUILTIN_TEST
16029: SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
16030: #endif
16031: SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
16032: 
16033: /*
16034: ** On systems with ample stack space and that support alloca(), make
16035: ** use of alloca() to obtain space for large automatic objects.  By default,
16036: ** obtain space from malloc().
16037: **
16038: ** The alloca() routine never returns NULL.  This will cause code paths
16039: ** that deal with sqlite3StackAlloc() failures to be unreachable.
16040: */
16041: #ifdef SQLITE_USE_ALLOCA
16042: # define sqlite3StackAllocRaw(D,N)   alloca(N)
16043: # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
16044: # define sqlite3StackFree(D,P)
16045: #else
16046: # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
16047: # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
16048: # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
16049: #endif
16050: 
16051: /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together.  If they
16052: ** are, disable MEMSYS3
16053: */
16054: #ifdef SQLITE_ENABLE_MEMSYS5
16055: SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
16056: #undef SQLITE_ENABLE_MEMSYS3
16057: #endif
16058: #ifdef SQLITE_ENABLE_MEMSYS3
16059: SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
16060: #endif
16061: 
16062: 
16063: #ifndef SQLITE_MUTEX_OMIT
16064: SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
16065: SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
16066: SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
16067: SQLITE_PRIVATE   int sqlite3MutexInit(void);
16068: SQLITE_PRIVATE   int sqlite3MutexEnd(void);
16069: #endif
16070: #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
16071: SQLITE_PRIVATE   void sqlite3MemoryBarrier(void);
16072: #else
16073: # define sqlite3MemoryBarrier()
16074: #endif
16075: 
16076: SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
16077: SQLITE_PRIVATE void sqlite3StatusUp(int, int);
16078: SQLITE_PRIVATE void sqlite3StatusDown(int, int);
16079: SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
16080: 
16081: /* Access to mutexes used by sqlite3_status() */
16082: SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
16083: SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
16084: 
16085: #ifndef SQLITE_OMIT_FLOATING_POINT
16086: SQLITE_PRIVATE   int sqlite3IsNaN(double);
16087: #else
16088: # define sqlite3IsNaN(X)  0
16089: #endif
16090: 
16091: /*
16092: ** An instance of the following structure holds information about SQL
16093: ** functions arguments that are the parameters to the printf() function.
16094: */
16095: struct PrintfArguments {
16096:   int nArg;                /* Total number of arguments */
16097:   int nUsed;               /* Number of arguments used so far */
16098:   sqlite3_value **apArg;   /* The argument values */
16099: };
16100: 
16101: SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
16102: SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
16103: SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
16104: SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
16105: #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
16106: SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
16107: #endif
16108: #if defined(SQLITE_TEST)
16109: SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
16110: #endif
16111: 
16112: #if defined(SQLITE_DEBUG)
16113: SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
16114: SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
16115: SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
16116: SQLITE_PRIVATE   void sqlite3TreeViewWith(TreeView*, const With*, u8);
16117: #endif
16118: 
16119: 
16120: SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
16121: SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
16122: SQLITE_PRIVATE void sqlite3Dequote(char*);
16123: SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
16124: SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
16125: SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
16126: SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
16127: SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
16128: SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
16129: SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
16130: SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
16131: SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
16132: #ifdef SQLITE_DEBUG
16133: SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
16134: #endif
16135: SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
16136: SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
16137: SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
16138: SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
16139: SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
16140: SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
16141: SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
16142: SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
16143: SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
16144: SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
16145: SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
16146: SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
16147: SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
16148: SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
16149: SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
16150: SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
16151: SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
16152: SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
16153: SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
16154: SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
16155: SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
16156: SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
16157: SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
16158: SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
16159: SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
16160: SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
16161: SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
16162: SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
16163: SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
16164: SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
16165: #if SQLITE_ENABLE_HIDDEN_COLUMNS
16166: SQLITE_PRIVATE   void sqlite3ColumnPropertiesFromName(Table*, Column*);
16167: #else
16168: # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
16169: #endif
16170: SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
16171: SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
16172: SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
16173: SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
16174: SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
16175: SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
16176: SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
16177: SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
16178:                     sqlite3_vfs**,char**,char **);
16179: SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
16180: SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
16181: 
16182: #ifdef SQLITE_OMIT_BUILTIN_TEST
16183: # define sqlite3FaultSim(X) SQLITE_OK
16184: #else
16185: SQLITE_PRIVATE   int sqlite3FaultSim(int);
16186: #endif
16187: 
16188: SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
16189: SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
16190: SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
16191: SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
16192: SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
16193: SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
16194: SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
16195: #ifndef SQLITE_OMIT_BUILTIN_TEST
16196: SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
16197: #endif
16198: 
16199: SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
16200: SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
16201: SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
16202: SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
16203: SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
16204: 
16205: SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
16206: 
16207: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
16208: SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
16209: #else
16210: # define sqlite3ViewGetColumnNames(A,B) 0
16211: #endif
16212: 
16213: #if SQLITE_MAX_ATTACHED>30
16214: SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
16215: #endif
16216: SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
16217: SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
16218: SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
16219: #ifndef SQLITE_OMIT_AUTOINCREMENT
16220: SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
16221: SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
16222: #else
16223: # define sqlite3AutoincrementBegin(X)
16224: # define sqlite3AutoincrementEnd(X)
16225: #endif
16226: SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
16227: SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
16228: SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
16229: SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
16230: SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
16231: SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
16232: SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
16233:                                       Token*, Select*, Expr*, IdList*);
16234: SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
16235: SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
16236: SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
16237: SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
16238: SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
16239: SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
16240: SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
16241: SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
16242: SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
16243:                           Expr*, int, int, u8);
16244: SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
16245: SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
16246: SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
16247:                          Expr*,ExprList*,u32,Expr*,Expr*);
16248: SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
16249: SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
16250: SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
16251: SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
16252: #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
16253: SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
16254: #endif
16255: SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
16256: SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
16257: SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
16258: SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
16259: SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
16260: SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
16261: SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
16262: SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
16263: SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
16264: SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
16265: SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
16266: SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
16267: #define ONEPASS_OFF      0        /* Use of ONEPASS not allowed */
16268: #define ONEPASS_SINGLE   1        /* ONEPASS valid for a single row update */
16269: #define ONEPASS_MULTI    2        /* ONEPASS is valid for multiple rows */
16270: SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
16271: SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
16272: SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
16273: SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
16274: SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
16275: SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
16276: SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
16277: SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
16278: SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
16279: SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
16280: SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
16281: SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
16282: SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
16283: SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
16284: SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
16285: SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
16286: SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
16287: SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
16288: SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
16289: #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
16290: #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
16291: #define SQLITE_ECEL_REF      0x04  /* Use ExprList.u.x.iOrderByCol */
16292: SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
16293: SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
16294: SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
16295: SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
16296: #define LOCATE_VIEW    0x01
16297: #define LOCATE_NOERR   0x02
16298: SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
16299: SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
16300: SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
16301: SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
16302: SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
16303: SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
16304: SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
16305: SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
16306: SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
16307: SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
16308: SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
16309: SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
16310: SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
16311: SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
16312: SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
16313: SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
16314: #ifndef SQLITE_OMIT_BUILTIN_TEST
16315: SQLITE_PRIVATE void sqlite3PrngSaveState(void);
16316: SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
16317: #endif
16318: SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
16319: SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
16320: SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
16321: SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
16322: SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
16323: SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
16324: SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
16325: SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
16326: SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
16327: SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
16328: SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
16329: SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
16330: SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
16331: #ifdef SQLITE_ENABLE_CURSOR_HINTS
16332: SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
16333: #endif
16334: SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
16335: SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
16336: SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
16337: SQLITE_PRIVATE int sqlite3IsRowid(const char*);
16338: SQLITE_PRIVATE void sqlite3GenerateRowDelete(
16339:     Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
16340: SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
16341: SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
16342: SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
16343: SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
16344:                                      u8,u8,int,int*,int*);
16345: SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
16346: SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
16347: SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
16348: SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
16349: SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
16350: SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
16351: SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
16352: SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
16353: SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
16354: SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
16355: SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
16356: SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
16357: SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
16358: #if SELECTTRACE_ENABLED
16359: SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
16360: #else
16361: # define sqlite3SelectSetName(A,B)
16362: #endif
16363: SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
16364: SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
16365: SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
16366: SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
16367: SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
16368: SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
16369: SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
16370: SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
16371: 
16372: #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
16373: SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
16374: #endif
16375: 
16376: #ifndef SQLITE_OMIT_TRIGGER
16377: SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
16378:                            Expr*,int, int);
16379: SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
16380: SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
16381: SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
16382: SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
16383: SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
16384: SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
16385:                             int, int, int);
16386: SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
16387:   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
16388: SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
16389: SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
16390: SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
16391:                                         Select*,u8);
16392: SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
16393: SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
16394: SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
16395: SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
16396: SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
16397: # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
16398: # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
16399: #else
16400: # define sqlite3TriggersExist(B,C,D,E,F) 0
16401: # define sqlite3DeleteTrigger(A,B)
16402: # define sqlite3DropTriggerPtr(A,B)
16403: # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
16404: # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
16405: # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
16406: # define sqlite3TriggerList(X, Y) 0
16407: # define sqlite3ParseToplevel(p) p
16408: # define sqlite3IsToplevel(p) 1
16409: # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
16410: #endif
16411: 
16412: SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
16413: SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
16414: SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
16415: #ifndef SQLITE_OMIT_AUTHORIZATION
16416: SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
16417: SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
16418: SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
16419: SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
16420: SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
16421: #else
16422: # define sqlite3AuthRead(a,b,c,d)
16423: # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
16424: # define sqlite3AuthContextPush(a,b,c)
16425: # define sqlite3AuthContextPop(a)  ((void)(a))
16426: #endif
16427: SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
16428: SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
16429: SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
16430: SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
16431: SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
16432: SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
16433: SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
16434: SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
16435: SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
16436: SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
16437: SQLITE_PRIVATE int sqlite3Atoi(const char*);
16438: SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
16439: SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
16440: SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
16441: SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
16442: SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
16443: #ifndef SQLITE_OMIT_VIRTUALTABLE
16444: SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
16445: #endif
16446: #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
16447:     defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
16448:     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
16449: SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
16450: #endif
16451: 
16452: /*
16453: ** Routines to read and write variable-length integers.  These used to
16454: ** be defined locally, but now we use the varint routines in the util.c
16455: ** file.
16456: */
16457: SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
16458: SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
16459: SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
16460: SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
16461: 
16462: /*
16463: ** The common case is for a varint to be a single byte.  They following
16464: ** macros handle the common case without a procedure call, but then call
16465: ** the procedure for larger varints.
16466: */
16467: #define getVarint32(A,B)  \
16468:   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
16469: #define putVarint32(A,B)  \
16470:   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
16471:   sqlite3PutVarint((A),(B)))
16472: #define getVarint    sqlite3GetVarint
16473: #define putVarint    sqlite3PutVarint
16474: 
16475: 
16476: SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
16477: SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
16478: SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
16479: SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
16480: SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
16481: SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
16482: SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
16483: SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
16484: SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
16485: SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
16486: SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
16487: SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
16488: SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
16489: 
16490: #if defined(SQLITE_NEED_ERR_NAME)
16491: SQLITE_PRIVATE const char *sqlite3ErrName(int);
16492: #endif
16493: 
16494: SQLITE_PRIVATE const char *sqlite3ErrStr(int);
16495: SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
16496: SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
16497: SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
16498: SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
16499: SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
16500: SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
16501: SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
16502: SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
16503: SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
16504: SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
16505: SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
16506: SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
16507: SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
16508: SQLITE_PRIVATE int sqlite3AbsInt32(int);
16509: #ifdef SQLITE_ENABLE_8_3_NAMES
16510: SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
16511: #else
16512: # define sqlite3FileSuffix3(X,Y)
16513: #endif
16514: SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
16515: 
16516: SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
16517: SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
16518: SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
16519:                         void(*)(void*));
16520: SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
16521: SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
16522: SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
16523: SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
16524: SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
16525: SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
16526: #ifndef SQLITE_AMALGAMATION
16527: SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
16528: SQLITE_PRIVATE const char sqlite3StrBINARY[];
16529: SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
16530: SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
16531: SQLITE_PRIVATE const Token sqlite3IntTokens[];
16532: SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
16533: SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
16534: #ifndef SQLITE_OMIT_WSD
16535: SQLITE_PRIVATE int sqlite3PendingByte;
16536: #endif
16537: #endif
16538: SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
16539: SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
16540: SQLITE_PRIVATE void sqlite3AlterFunctions(void);
16541: SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
16542: SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
16543: SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
16544: SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
16545: SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
16546: SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
16547: SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
16548: SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
16549: SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
16550: SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
16551: SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
16552: SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
16553: SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
16554: SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
16555: SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
16556: SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
16557: SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
16558: SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
16559: SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
16560: SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
16561: SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
16562: SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
16563: SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
16564: SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
16565: SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
16566: SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
16567: SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
16568: SQLITE_PRIVATE void sqlite3SchemaClear(void *);
16569: SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
16570: SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
16571: SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
16572: SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
16573: SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
16574: SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
16575: #ifdef SQLITE_DEBUG
16576: SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
16577: #endif
16578: SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
16579:   void (*)(sqlite3_context*,int,sqlite3_value **),
16580:   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
16581:   FuncDestructor *pDestructor
16582: );
16583: SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
16584: SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
16585: SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
16586: SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
16587: 
16588: SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
16589: SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
16590: SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
16591: SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
16592: SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
16593: SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
16594: SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
16595: SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
16596: 
16597: SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
16598: SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
16599: 
16600: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
16601: SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
16602: SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
16603: SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
16604: SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
16605: SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
16606: #endif
16607: 
16608: /*
16609: ** The interface to the LEMON-generated parser
16610: */
16611: SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
16612: SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
16613: SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
16614: #ifdef YYTRACKMAXSTACKDEPTH
16615: SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
16616: #endif
16617: 
16618: SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
16619: #ifndef SQLITE_OMIT_LOAD_EXTENSION
16620: SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
16621: #else
16622: # define sqlite3CloseExtensions(X)
16623: #endif
16624: 
16625: #ifndef SQLITE_OMIT_SHARED_CACHE
16626: SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
16627: #else
16628:   #define sqlite3TableLock(v,w,x,y,z)
16629: #endif
16630: 
16631: #ifdef SQLITE_TEST
16632: SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
16633: #endif
16634: 
16635: #ifdef SQLITE_OMIT_VIRTUALTABLE
16636: #  define sqlite3VtabClear(Y)
16637: #  define sqlite3VtabSync(X,Y) SQLITE_OK
16638: #  define sqlite3VtabRollback(X)
16639: #  define sqlite3VtabCommit(X)
16640: #  define sqlite3VtabInSync(db) 0
16641: #  define sqlite3VtabLock(X)
16642: #  define sqlite3VtabUnlock(X)
16643: #  define sqlite3VtabUnlockList(X)
16644: #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
16645: #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
16646: #else
16647: SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
16648: SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
16649: SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
16650: SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
16651: SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
16652: SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
16653: SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
16654: SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
16655: SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
16656: SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
16657: SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
16658: #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
16659: #endif
16660: SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
16661: SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
16662: SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
16663: SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
16664: SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
16665: SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
16666: SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
16667: SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
16668: SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
16669: SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
16670: SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
16671: SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
16672: SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
16673: SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
16674: SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
16675: SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
16676: SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
16677: SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
16678: SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
16679: SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
16680: SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
16681: SQLITE_PRIVATE const char *sqlite3JournalModename(int);
16682: #ifndef SQLITE_OMIT_WAL
16683: SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
16684: SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
16685: #endif
16686: #ifndef SQLITE_OMIT_CTE
16687: SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
16688: SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
16689: SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
16690: #else
16691: #define sqlite3WithPush(x,y,z)
16692: #define sqlite3WithDelete(x,y)
16693: #endif
16694: 
16695: /* Declarations for functions in fkey.c. All of these are replaced by
16696: ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
16697: ** key functionality is available. If OMIT_TRIGGER is defined but
16698: ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
16699: ** this case foreign keys are parsed, but no other functionality is
16700: ** provided (enforcement of FK constraints requires the triggers sub-system).
16701: */
16702: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
16703: SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
16704: SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
16705: SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
16706: SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
16707: SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
16708: SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
16709: #else
16710:   #define sqlite3FkActions(a,b,c,d,e,f)
16711:   #define sqlite3FkCheck(a,b,c,d,e,f)
16712:   #define sqlite3FkDropTable(a,b,c)
16713:   #define sqlite3FkOldmask(a,b)         0
16714:   #define sqlite3FkRequired(a,b,c,d)    0
16715: #endif
16716: #ifndef SQLITE_OMIT_FOREIGN_KEY
16717: SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
16718: SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
16719: #else
16720:   #define sqlite3FkDelete(a,b)
16721:   #define sqlite3FkLocateIndex(a,b,c,d,e)
16722: #endif
16723: 
16724: 
16725: /*
16726: ** Available fault injectors.  Should be numbered beginning with 0.
16727: */
16728: #define SQLITE_FAULTINJECTOR_MALLOC     0
16729: #define SQLITE_FAULTINJECTOR_COUNT      1
16730: 
16731: /*
16732: ** The interface to the code in fault.c used for identifying "benign"
16733: ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
16734: ** is not defined.
16735: */
16736: #ifndef SQLITE_OMIT_BUILTIN_TEST
16737: SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
16738: SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
16739: #else
16740:   #define sqlite3BeginBenignMalloc()
16741:   #define sqlite3EndBenignMalloc()
16742: #endif
16743: 
16744: /*
16745: ** Allowed return values from sqlite3FindInIndex()
16746: */
16747: #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
16748: #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
16749: #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
16750: #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
16751: #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
16752: /*
16753: ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
16754: */
16755: #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
16756: #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
16757: #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
16758: SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
16759: 
16760: SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
16761: SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
16762: #ifdef SQLITE_ENABLE_ATOMIC_WRITE
16763: SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
16764: #endif
16765: 
16766: SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
16767: SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
16768: 
16769: SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
16770: #if SQLITE_MAX_EXPR_DEPTH>0
16771: SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
16772: SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
16773: #else
16774:   #define sqlite3SelectExprHeight(x) 0
16775:   #define sqlite3ExprCheckHeight(x,y)
16776: #endif
16777: 
16778: SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
16779: SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
16780: 
16781: #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
16782: SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
16783: SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
16784: SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
16785: #else
16786:   #define sqlite3ConnectionBlocked(x,y)
16787:   #define sqlite3ConnectionUnlocked(x)
16788:   #define sqlite3ConnectionClosed(x)
16789: #endif
16790: 
16791: #ifdef SQLITE_DEBUG
16792: SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
16793: #endif
16794: 
16795: /*
16796: ** If the SQLITE_ENABLE IOTRACE exists then the global variable
16797: ** sqlite3IoTrace is a pointer to a printf-like routine used to
16798: ** print I/O tracing messages.
16799: */
16800: #ifdef SQLITE_ENABLE_IOTRACE
16801: # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
16802: SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
16803: SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
16804: #else
16805: # define IOTRACE(A)
16806: # define sqlite3VdbeIOTraceSql(X)
16807: #endif
16808: 
16809: /*
16810: ** These routines are available for the mem2.c debugging memory allocator
16811: ** only.  They are used to verify that different "types" of memory
16812: ** allocations are properly tracked by the system.
16813: **
16814: ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
16815: ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
16816: ** a single bit set.
16817: **
16818: ** sqlite3MemdebugHasType() returns true if any of the bits in its second
16819: ** argument match the type set by the previous sqlite3MemdebugSetType().
16820: ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
16821: **
16822: ** sqlite3MemdebugNoType() returns true if none of the bits in its second
16823: ** argument match the type set by the previous sqlite3MemdebugSetType().
16824: **
16825: ** Perhaps the most important point is the difference between MEMTYPE_HEAP
16826: ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
16827: ** it might have been allocated by lookaside, except the allocation was
16828: ** too large or lookaside was already full.  It is important to verify
16829: ** that allocations that might have been satisfied by lookaside are not
16830: ** passed back to non-lookaside free() routines.  Asserts such as the
16831: ** example above are placed on the non-lookaside free() routines to verify
16832: ** this constraint.
16833: **
16834: ** All of this is no-op for a production build.  It only comes into
16835: ** play when the SQLITE_MEMDEBUG compile-time option is used.
16836: */
16837: #ifdef SQLITE_MEMDEBUG
16838: SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
16839: SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
16840: SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
16841: #else
16842: # define sqlite3MemdebugSetType(X,Y)  /* no-op */
16843: # define sqlite3MemdebugHasType(X,Y)  1
16844: # define sqlite3MemdebugNoType(X,Y)   1
16845: #endif
16846: #define MEMTYPE_HEAP       0x01  /* General heap allocations */
16847: #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
16848: #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
16849: #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
16850: 
16851: /*
16852: ** Threading interface
16853: */
16854: #if SQLITE_MAX_WORKER_THREADS>0
16855: SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
16856: SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
16857: #endif
16858: 
16859: #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
16860: SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
16861: #endif
16862: 
16863: #endif /* SQLITEINT_H */
16864: 
16865: /************** End of sqliteInt.h *******************************************/
16866: /************** Begin file global.c ******************************************/
16867: /*
16868: ** 2008 June 13
16869: **
16870: ** The author disclaims copyright to this source code.  In place of
16871: ** a legal notice, here is a blessing:
16872: **
16873: **    May you do good and not evil.
16874: **    May you find forgiveness for yourself and forgive others.
16875: **    May you share freely, never taking more than you give.
16876: **
16877: *************************************************************************
16878: **
16879: ** This file contains definitions of global variables and constants.
16880: */
16881: /* #include "sqliteInt.h" */
16882: 
16883: /* An array to map all upper-case characters into their corresponding
16884: ** lower-case character. 
16885: **
16886: ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
16887: ** handle case conversions for the UTF character set since the tables
16888: ** involved are nearly as big or bigger than SQLite itself.
16889: */
16890: SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
16891: #ifdef SQLITE_ASCII
16892:       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
16893:      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
16894:      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
16895:      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
16896:     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
16897:     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
16898:     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
16899:     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
16900:     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
16901:     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
16902:     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
16903:     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
16904:     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
16905:     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
16906:     252,253,254,255
16907: #endif
16908: #ifdef SQLITE_EBCDIC
16909:       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
16910:      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
16911:      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
16912:      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
16913:      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
16914:      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
16915:      96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
16916:     112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
16917:     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
16918:     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
16919:     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
16920:     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
16921:     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
16922:     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
16923:     224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
16924:     240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
16925: #endif
16926: };
16927: 
16928: /*
16929: ** The following 256 byte lookup table is used to support SQLites built-in
16930: ** equivalents to the following standard library functions:
16931: **
16932: **   isspace()                        0x01
16933: **   isalpha()                        0x02
16934: **   isdigit()                        0x04
16935: **   isalnum()                        0x06
16936: **   isxdigit()                       0x08
16937: **   toupper()                        0x20
16938: **   SQLite identifier character      0x40
16939: **   Quote character                  0x80
16940: **
16941: ** Bit 0x20 is set if the mapped character requires translation to upper
16942: ** case. i.e. if the character is a lower-case ASCII character.
16943: ** If x is a lower-case ASCII character, then its upper-case equivalent
16944: ** is (x - 0x20). Therefore toupper() can be implemented as:
16945: **
16946: **   (x & ~(map[x]&0x20))
16947: **
16948: ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
16949: ** array. tolower() is used more often than toupper() by SQLite.
16950: **
16951: ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
16952: ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
16953: ** non-ASCII UTF character. Hence the test for whether or not a character is
16954: ** part of an identifier is 0x46.
16955: **
16956: ** SQLite's versions are identical to the standard versions assuming a
16957: ** locale of "C". They are implemented as macros in sqliteInt.h.
16958: */
16959: #ifdef SQLITE_ASCII
16960: SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
16961:   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
16962:   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
16963:   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
16964:   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
16965:   0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80,  /* 20..27     !"#$%&' */
16966:   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
16967:   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
16968:   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
16969: 
16970:   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
16971:   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
16972:   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
16973:   0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
16974:   0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
16975:   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
16976:   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
16977:   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
16978: 
16979:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
16980:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
16981:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
16982:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
16983:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
16984:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
16985:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
16986:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
16987: 
16988:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
16989:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
16990:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
16991:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
16992:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
16993:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
16994:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
16995:   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
16996: };
16997: #endif
16998: 
16999: /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
17000: ** compatibility for legacy applications, the URI filename capability is
17001: ** disabled by default.
17002: **
17003: ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
17004: ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
17005: **
17006: ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
17007: ** disabled. The default value may be changed by compiling with the
17008: ** SQLITE_USE_URI symbol defined.
17009: */
17010: #ifndef SQLITE_USE_URI
17011: # define  SQLITE_USE_URI 0
17012: #endif
17013: 
17014: /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
17015: ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
17016: ** that compile-time option is omitted.
17017: */
17018: #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
17019: # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
17020: #endif
17021: 
17022: /* The minimum PMA size is set to this value multiplied by the database
17023: ** page size in bytes.
17024: */
17025: #ifndef SQLITE_SORTER_PMASZ
17026: # define SQLITE_SORTER_PMASZ 250
17027: #endif
17028: 
17029: /* Statement journals spill to disk when their size exceeds the following
17030: ** threashold (in bytes). 0 means that statement journals are created and
17031: ** written to disk immediately (the default behavior for SQLite versions
17032: ** before 3.12.0).  -1 means always keep the entire statement journal in
17033: ** memory.  (The statement journal is also always held entirely in memory
17034: ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
17035: ** setting.)
17036: */
17037: #ifndef SQLITE_STMTJRNL_SPILL 
17038: # define SQLITE_STMTJRNL_SPILL (64*1024)
17039: #endif
17040: 
17041: /*
17042: ** The following singleton contains the global configuration for
17043: ** the SQLite library.
17044: */
17045: SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
17046:    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
17047:    1,                         /* bCoreMutex */
17048:    SQLITE_THREADSAFE==1,      /* bFullMutex */
17049:    SQLITE_USE_URI,            /* bOpenUri */
17050:    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
17051:    0x7ffffffe,                /* mxStrlen */
17052:    0,                         /* neverCorrupt */
17053:    128,                       /* szLookaside */
17054:    500,                       /* nLookaside */
17055:    SQLITE_STMTJRNL_SPILL,     /* nStmtSpill */
17056:    {0,0,0,0,0,0,0,0},         /* m */
17057:    {0,0,0,0,0,0,0,0,0},       /* mutex */
17058:    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
17059:    (void*)0,                  /* pHeap */
17060:    0,                         /* nHeap */
17061:    0, 0,                      /* mnHeap, mxHeap */
17062:    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
17063:    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
17064:    (void*)0,                  /* pScratch */
17065:    0,                         /* szScratch */
17066:    0,                         /* nScratch */
17067:    (void*)0,                  /* pPage */
17068:    0,                         /* szPage */
17069:    SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
17070:    0,                         /* mxParserStack */
17071:    0,                         /* sharedCacheEnabled */
17072:    SQLITE_SORTER_PMASZ,       /* szPma */
17073:    /* All the rest should always be initialized to zero */
17074:    0,                         /* isInit */
17075:    0,                         /* inProgress */
17076:    0,                         /* isMutexInit */
17077:    0,                         /* isMallocInit */
17078:    0,                         /* isPCacheInit */
17079:    0,                         /* nRefInitMutex */
17080:    0,                         /* pInitMutex */
17081:    0,                         /* xLog */
17082:    0,                         /* pLogArg */
17083: #ifdef SQLITE_ENABLE_SQLLOG
17084:    0,                         /* xSqllog */
17085:    0,                         /* pSqllogArg */
17086: #endif
17087: #ifdef SQLITE_VDBE_COVERAGE
17088:    0,                         /* xVdbeBranch */
17089:    0,                         /* pVbeBranchArg */
17090: #endif
17091: #ifndef SQLITE_OMIT_BUILTIN_TEST
17092:    0,                         /* xTestCallback */
17093: #endif
17094:    0                          /* bLocaltimeFault */
17095: };
17096: 
17097: /*
17098: ** Hash table for global functions - functions common to all
17099: ** database connections.  After initialization, this table is
17100: ** read-only.
17101: */
17102: SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
17103: 
17104: /*
17105: ** Constant tokens for values 0 and 1.
17106: */
17107: SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
17108:    { "0", 1 },
17109:    { "1", 1 }
17110: };
17111: 
17112: 
17113: /*
17114: ** The value of the "pending" byte must be 0x40000000 (1 byte past the
17115: ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
17116: ** the database page that contains the pending byte.  It never attempts
17117: ** to read or write that page.  The pending byte page is set assign
17118: ** for use by the VFS layers as space for managing file locks.
17119: **
17120: ** During testing, it is often desirable to move the pending byte to
17121: ** a different position in the file.  This allows code that has to
17122: ** deal with the pending byte to run on files that are much smaller
17123: ** than 1 GiB.  The sqlite3_test_control() interface can be used to
17124: ** move the pending byte.
17125: **
17126: ** IMPORTANT:  Changing the pending byte to any value other than
17127: ** 0x40000000 results in an incompatible database file format!
17128: ** Changing the pending byte during operation will result in undefined
17129: ** and incorrect behavior.
17130: */
17131: #ifndef SQLITE_OMIT_WSD
17132: SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
17133: #endif
17134: 
17135: /* #include "opcodes.h" */
17136: /*
17137: ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
17138: ** created by mkopcodeh.awk during compilation.  Data is obtained
17139: ** from the comments following the "case OP_xxxx:" statements in
17140: ** the vdbe.c file.  
17141: */
17142: SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
17143: 
17144: /*
17145: ** Name of the default collating sequence
17146: */
17147: SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
17148: 
17149: /************** End of global.c **********************************************/
17150: /************** Begin file ctime.c *******************************************/
17151: /*
17152: ** 2010 February 23
17153: **
17154: ** The author disclaims copyright to this source code.  In place of
17155: ** a legal notice, here is a blessing:
17156: **
17157: **    May you do good and not evil.
17158: **    May you find forgiveness for yourself and forgive others.
17159: **    May you share freely, never taking more than you give.
17160: **
17161: *************************************************************************
17162: **
17163: ** This file implements routines used to report what compile-time options
17164: ** SQLite was built with.
17165: */
17166: 
17167: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
17168: 
17169: /* #include "sqliteInt.h" */
17170: 
17171: /*
17172: ** An array of names of all compile-time options.  This array should 
17173: ** be sorted A-Z.
17174: **
17175: ** This array looks large, but in a typical installation actually uses
17176: ** only a handful of compile-time options, so most times this array is usually
17177: ** rather short and uses little memory space.
17178: */
17179: static const char * const azCompileOpt[] = {
17180: 
17181: /* These macros are provided to "stringify" the value of the define
17182: ** for those options in which the value is meaningful. */
17183: #define CTIMEOPT_VAL_(opt) #opt
17184: #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
17185: 
17186: #if SQLITE_32BIT_ROWID
17187:   "32BIT_ROWID",
17188: #endif
17189: #if SQLITE_4_BYTE_ALIGNED_MALLOC
17190:   "4_BYTE_ALIGNED_MALLOC",
17191: #endif
17192: #if SQLITE_CASE_SENSITIVE_LIKE
17193:   "CASE_SENSITIVE_LIKE",
17194: #endif
17195: #if SQLITE_CHECK_PAGES
17196:   "CHECK_PAGES",
17197: #endif
17198: #if defined(__clang__) && defined(__clang_major__)
17199:   "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
17200:                     CTIMEOPT_VAL(__clang_minor__) "."
17201:                     CTIMEOPT_VAL(__clang_patchlevel__),
17202: #elif defined(_MSC_VER)
17203:   "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
17204: #elif defined(__GNUC__) && defined(__VERSION__)
17205:   "COMPILER=gcc-" __VERSION__,
17206: #endif
17207: #if SQLITE_COVERAGE_TEST
17208:   "COVERAGE_TEST",
17209: #endif
17210: #if SQLITE_DEBUG
17211:   "DEBUG",
17212: #endif
17213: #if SQLITE_DEFAULT_LOCKING_MODE
17214:   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
17215: #endif
17216: #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
17217:   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
17218: #endif
17219: #if SQLITE_DISABLE_DIRSYNC
17220:   "DISABLE_DIRSYNC",
17221: #endif
17222: #if SQLITE_DISABLE_LFS
17223:   "DISABLE_LFS",
17224: #endif
17225: #if SQLITE_ENABLE_8_3_NAMES
17226:   "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
17227: #endif
17228: #if SQLITE_ENABLE_API_ARMOR
17229:   "ENABLE_API_ARMOR",
17230: #endif
17231: #if SQLITE_ENABLE_ATOMIC_WRITE
17232:   "ENABLE_ATOMIC_WRITE",
17233: #endif
17234: #if SQLITE_ENABLE_CEROD
17235:   "ENABLE_CEROD",
17236: #endif
17237: #if SQLITE_ENABLE_COLUMN_METADATA
17238:   "ENABLE_COLUMN_METADATA",
17239: #endif
17240: #if SQLITE_ENABLE_DBSTAT_VTAB
17241:   "ENABLE_DBSTAT_VTAB",
17242: #endif
17243: #if SQLITE_ENABLE_EXPENSIVE_ASSERT
17244:   "ENABLE_EXPENSIVE_ASSERT",
17245: #endif
17246: #if SQLITE_ENABLE_FTS1
17247:   "ENABLE_FTS1",
17248: #endif
17249: #if SQLITE_ENABLE_FTS2
17250:   "ENABLE_FTS2",
17251: #endif
17252: #if SQLITE_ENABLE_FTS3
17253:   "ENABLE_FTS3",
17254: #endif
17255: #if SQLITE_ENABLE_FTS3_PARENTHESIS
17256:   "ENABLE_FTS3_PARENTHESIS",
17257: #endif
17258: #if SQLITE_ENABLE_FTS4
17259:   "ENABLE_FTS4",
17260: #endif
17261: #if SQLITE_ENABLE_FTS5
17262:   "ENABLE_FTS5",
17263: #endif
17264: #if SQLITE_ENABLE_ICU
17265:   "ENABLE_ICU",
17266: #endif
17267: #if SQLITE_ENABLE_IOTRACE
17268:   "ENABLE_IOTRACE",
17269: #endif
17270: #if SQLITE_ENABLE_JSON1
17271:   "ENABLE_JSON1",
17272: #endif
17273: #if SQLITE_ENABLE_LOAD_EXTENSION
17274:   "ENABLE_LOAD_EXTENSION",
17275: #endif
17276: #if SQLITE_ENABLE_LOCKING_STYLE
17277:   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
17278: #endif
17279: #if SQLITE_ENABLE_MEMORY_MANAGEMENT
17280:   "ENABLE_MEMORY_MANAGEMENT",
17281: #endif
17282: #if SQLITE_ENABLE_MEMSYS3
17283:   "ENABLE_MEMSYS3",
17284: #endif
17285: #if SQLITE_ENABLE_MEMSYS5
17286:   "ENABLE_MEMSYS5",
17287: #endif
17288: #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
17289:   "ENABLE_OVERSIZE_CELL_CHECK",
17290: #endif
17291: #if SQLITE_ENABLE_RTREE
17292:   "ENABLE_RTREE",
17293: #endif
17294: #if defined(SQLITE_ENABLE_STAT4)
17295:   "ENABLE_STAT4",
17296: #elif defined(SQLITE_ENABLE_STAT3)
17297:   "ENABLE_STAT3",
17298: #endif
17299: #if SQLITE_ENABLE_UNLOCK_NOTIFY
17300:   "ENABLE_UNLOCK_NOTIFY",
17301: #endif
17302: #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
17303:   "ENABLE_UPDATE_DELETE_LIMIT",
17304: #endif
17305: #if SQLITE_HAS_CODEC
17306:   "HAS_CODEC",
17307: #endif
17308: #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
17309:   "HAVE_ISNAN",
17310: #endif
17311: #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17312:   "HOMEGROWN_RECURSIVE_MUTEX",
17313: #endif
17314: #if SQLITE_IGNORE_AFP_LOCK_ERRORS
17315:   "IGNORE_AFP_LOCK_ERRORS",
17316: #endif
17317: #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
17318:   "IGNORE_FLOCK_LOCK_ERRORS",
17319: #endif
17320: #ifdef SQLITE_INT64_TYPE
17321:   "INT64_TYPE",
17322: #endif
17323: #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17324:   "LIKE_DOESNT_MATCH_BLOBS",
17325: #endif
17326: #if SQLITE_LOCK_TRACE
17327:   "LOCK_TRACE",
17328: #endif
17329: #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
17330:   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
17331: #endif
17332: #ifdef SQLITE_MAX_SCHEMA_RETRY
17333:   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
17334: #endif
17335: #if SQLITE_MEMDEBUG
17336:   "MEMDEBUG",
17337: #endif
17338: #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
17339:   "MIXED_ENDIAN_64BIT_FLOAT",
17340: #endif
17341: #if SQLITE_NO_SYNC
17342:   "NO_SYNC",
17343: #endif
17344: #if SQLITE_OMIT_ALTERTABLE
17345:   "OMIT_ALTERTABLE",
17346: #endif
17347: #if SQLITE_OMIT_ANALYZE
17348:   "OMIT_ANALYZE",
17349: #endif
17350: #if SQLITE_OMIT_ATTACH
17351:   "OMIT_ATTACH",
17352: #endif
17353: #if SQLITE_OMIT_AUTHORIZATION
17354:   "OMIT_AUTHORIZATION",
17355: #endif
17356: #if SQLITE_OMIT_AUTOINCREMENT
17357:   "OMIT_AUTOINCREMENT",
17358: #endif
17359: #if SQLITE_OMIT_AUTOINIT
17360:   "OMIT_AUTOINIT",
17361: #endif
17362: #if SQLITE_OMIT_AUTOMATIC_INDEX
17363:   "OMIT_AUTOMATIC_INDEX",
17364: #endif
17365: #if SQLITE_OMIT_AUTORESET
17366:   "OMIT_AUTORESET",
17367: #endif
17368: #if SQLITE_OMIT_AUTOVACUUM
17369:   "OMIT_AUTOVACUUM",
17370: #endif
17371: #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
17372:   "OMIT_BETWEEN_OPTIMIZATION",
17373: #endif
17374: #if SQLITE_OMIT_BLOB_LITERAL
17375:   "OMIT_BLOB_LITERAL",
17376: #endif
17377: #if SQLITE_OMIT_BTREECOUNT
17378:   "OMIT_BTREECOUNT",
17379: #endif
17380: #if SQLITE_OMIT_BUILTIN_TEST
17381:   "OMIT_BUILTIN_TEST",
17382: #endif
17383: #if SQLITE_OMIT_CAST
17384:   "OMIT_CAST",
17385: #endif
17386: #if SQLITE_OMIT_CHECK
17387:   "OMIT_CHECK",
17388: #endif
17389: #if SQLITE_OMIT_COMPLETE
17390:   "OMIT_COMPLETE",
17391: #endif
17392: #if SQLITE_OMIT_COMPOUND_SELECT
17393:   "OMIT_COMPOUND_SELECT",
17394: #endif
17395: #if SQLITE_OMIT_CTE
17396:   "OMIT_CTE",
17397: #endif
17398: #if SQLITE_OMIT_DATETIME_FUNCS
17399:   "OMIT_DATETIME_FUNCS",
17400: #endif
17401: #if SQLITE_OMIT_DECLTYPE
17402:   "OMIT_DECLTYPE",
17403: #endif
17404: #if SQLITE_OMIT_DEPRECATED
17405:   "OMIT_DEPRECATED",
17406: #endif
17407: #if SQLITE_OMIT_DISKIO
17408:   "OMIT_DISKIO",
17409: #endif
17410: #if SQLITE_OMIT_EXPLAIN
17411:   "OMIT_EXPLAIN",
17412: #endif
17413: #if SQLITE_OMIT_FLAG_PRAGMAS
17414:   "OMIT_FLAG_PRAGMAS",
17415: #endif
17416: #if SQLITE_OMIT_FLOATING_POINT
17417:   "OMIT_FLOATING_POINT",
17418: #endif
17419: #if SQLITE_OMIT_FOREIGN_KEY
17420:   "OMIT_FOREIGN_KEY",
17421: #endif
17422: #if SQLITE_OMIT_GET_TABLE
17423:   "OMIT_GET_TABLE",
17424: #endif
17425: #if SQLITE_OMIT_INCRBLOB
17426:   "OMIT_INCRBLOB",
17427: #endif
17428: #if SQLITE_OMIT_INTEGRITY_CHECK
17429:   "OMIT_INTEGRITY_CHECK",
17430: #endif
17431: #if SQLITE_OMIT_LIKE_OPTIMIZATION
17432:   "OMIT_LIKE_OPTIMIZATION",
17433: #endif
17434: #if SQLITE_OMIT_LOAD_EXTENSION
17435:   "OMIT_LOAD_EXTENSION",
17436: #endif
17437: #if SQLITE_OMIT_LOCALTIME
17438:   "OMIT_LOCALTIME",
17439: #endif
17440: #if SQLITE_OMIT_LOOKASIDE
17441:   "OMIT_LOOKASIDE",
17442: #endif
17443: #if SQLITE_OMIT_MEMORYDB
17444:   "OMIT_MEMORYDB",
17445: #endif
17446: #if SQLITE_OMIT_OR_OPTIMIZATION
17447:   "OMIT_OR_OPTIMIZATION",
17448: #endif
17449: #if SQLITE_OMIT_PAGER_PRAGMAS
17450:   "OMIT_PAGER_PRAGMAS",
17451: #endif
17452: #if SQLITE_OMIT_PRAGMA
17453:   "OMIT_PRAGMA",
17454: #endif
17455: #if SQLITE_OMIT_PROGRESS_CALLBACK
17456:   "OMIT_PROGRESS_CALLBACK",
17457: #endif
17458: #if SQLITE_OMIT_QUICKBALANCE
17459:   "OMIT_QUICKBALANCE",
17460: #endif
17461: #if SQLITE_OMIT_REINDEX
17462:   "OMIT_REINDEX",
17463: #endif
17464: #if SQLITE_OMIT_SCHEMA_PRAGMAS
17465:   "OMIT_SCHEMA_PRAGMAS",
17466: #endif
17467: #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
17468:   "OMIT_SCHEMA_VERSION_PRAGMAS",
17469: #endif
17470: #if SQLITE_OMIT_SHARED_CACHE
17471:   "OMIT_SHARED_CACHE",
17472: #endif
17473: #if SQLITE_OMIT_SUBQUERY
17474:   "OMIT_SUBQUERY",
17475: #endif
17476: #if SQLITE_OMIT_TCL_VARIABLE
17477:   "OMIT_TCL_VARIABLE",
17478: #endif
17479: #if SQLITE_OMIT_TEMPDB
17480:   "OMIT_TEMPDB",
17481: #endif
17482: #if SQLITE_OMIT_TRACE
17483:   "OMIT_TRACE",
17484: #endif
17485: #if SQLITE_OMIT_TRIGGER
17486:   "OMIT_TRIGGER",
17487: #endif
17488: #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
17489:   "OMIT_TRUNCATE_OPTIMIZATION",
17490: #endif
17491: #if SQLITE_OMIT_UTF16
17492:   "OMIT_UTF16",
17493: #endif
17494: #if SQLITE_OMIT_VACUUM
17495:   "OMIT_VACUUM",
17496: #endif
17497: #if SQLITE_OMIT_VIEW
17498:   "OMIT_VIEW",
17499: #endif
17500: #if SQLITE_OMIT_VIRTUALTABLE
17501:   "OMIT_VIRTUALTABLE",
17502: #endif
17503: #if SQLITE_OMIT_WAL
17504:   "OMIT_WAL",
17505: #endif
17506: #if SQLITE_OMIT_WSD
17507:   "OMIT_WSD",
17508: #endif
17509: #if SQLITE_OMIT_XFER_OPT
17510:   "OMIT_XFER_OPT",
17511: #endif
17512: #if SQLITE_PERFORMANCE_TRACE
17513:   "PERFORMANCE_TRACE",
17514: #endif
17515: #if SQLITE_PROXY_DEBUG
17516:   "PROXY_DEBUG",
17517: #endif
17518: #if SQLITE_RTREE_INT_ONLY
17519:   "RTREE_INT_ONLY",
17520: #endif
17521: #if SQLITE_SECURE_DELETE
17522:   "SECURE_DELETE",
17523: #endif
17524: #if SQLITE_SMALL_STACK
17525:   "SMALL_STACK",
17526: #endif
17527: #if SQLITE_SOUNDEX
17528:   "SOUNDEX",
17529: #endif
17530: #if SQLITE_SYSTEM_MALLOC
17531:   "SYSTEM_MALLOC",
17532: #endif
17533: #if SQLITE_TCL
17534:   "TCL",
17535: #endif
17536: #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
17537:   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
17538: #endif
17539: #if SQLITE_TEST
17540:   "TEST",
17541: #endif
17542: #if defined(SQLITE_THREADSAFE)
17543:   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
17544: #endif
17545: #if SQLITE_USE_ALLOCA
17546:   "USE_ALLOCA",
17547: #endif
17548: #if SQLITE_USER_AUTHENTICATION
17549:   "USER_AUTHENTICATION",
17550: #endif
17551: #if SQLITE_WIN32_MALLOC
17552:   "WIN32_MALLOC",
17553: #endif
17554: #if SQLITE_ZERO_MALLOC
17555:   "ZERO_MALLOC"
17556: #endif
17557: };
17558: 
17559: /*
17560: ** Given the name of a compile-time option, return true if that option
17561: ** was used and false if not.
17562: **
17563: ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
17564: ** is not required for a match.
17565: */
17566: SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
17567:   int i, n;
17568: 
17569: #if SQLITE_ENABLE_API_ARMOR
17570:   if( zOptName==0 ){
17571:     (void)SQLITE_MISUSE_BKPT;
17572:     return 0;
17573:   }
17574: #endif
17575:   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
17576:   n = sqlite3Strlen30(zOptName);
17577: 
17578:   /* Since ArraySize(azCompileOpt) is normally in single digits, a
17579:   ** linear search is adequate.  No need for a binary search. */
17580:   for(i=0; i<ArraySize(azCompileOpt); i++){
17581:     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
17582:      && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
17583:     ){
17584:       return 1;
17585:     }
17586:   }
17587:   return 0;
17588: }
17589: 
17590: /*
17591: ** Return the N-th compile-time option string.  If N is out of range,
17592: ** return a NULL pointer.
17593: */
17594: SQLITE_API const char *sqlite3_compileoption_get(int N){
17595:   if( N>=0 && N<ArraySize(azCompileOpt) ){
17596:     return azCompileOpt[N];
17597:   }
17598:   return 0;
17599: }
17600: 
17601: #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17602: 
17603: /************** End of ctime.c ***********************************************/
17604: /************** Begin file status.c ******************************************/
17605: /*
17606: ** 2008 June 18
17607: **
17608: ** The author disclaims copyright to this source code.  In place of
17609: ** a legal notice, here is a blessing:
17610: **
17611: **    May you do good and not evil.
17612: **    May you find forgiveness for yourself and forgive others.
17613: **    May you share freely, never taking more than you give.
17614: **
17615: *************************************************************************
17616: **
17617: ** This module implements the sqlite3_status() interface and related
17618: ** functionality.
17619: */
17620: /* #include "sqliteInt.h" */
17621: /************** Include vdbeInt.h in the middle of status.c ******************/
17622: /************** Begin file vdbeInt.h *****************************************/
17623: /*
17624: ** 2003 September 6
17625: **
17626: ** The author disclaims copyright to this source code.  In place of
17627: ** a legal notice, here is a blessing:
17628: **
17629: **    May you do good and not evil.
17630: **    May you find forgiveness for yourself and forgive others.
17631: **    May you share freely, never taking more than you give.
17632: **
17633: *************************************************************************
17634: ** This is the header file for information that is private to the
17635: ** VDBE.  This information used to all be at the top of the single
17636: ** source code file "vdbe.c".  When that file became too big (over
17637: ** 6000 lines long) it was split up into several smaller files and
17638: ** this header information was factored out.
17639: */
17640: #ifndef SQLITE_VDBEINT_H
17641: #define SQLITE_VDBEINT_H
17642: 
17643: /*
17644: ** The maximum number of times that a statement will try to reparse
17645: ** itself before giving up and returning SQLITE_SCHEMA.
17646: */
17647: #ifndef SQLITE_MAX_SCHEMA_RETRY
17648: # define SQLITE_MAX_SCHEMA_RETRY 50
17649: #endif
17650: 
17651: /*
17652: ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
17653: ** "explain" P4 display logic is enabled.
17654: */
17655: #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
17656:      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17657: # define VDBE_DISPLAY_P4 1
17658: #else
17659: # define VDBE_DISPLAY_P4 0
17660: #endif
17661: 
17662: /*
17663: ** SQL is translated into a sequence of instructions to be
17664: ** executed by a virtual machine.  Each instruction is an instance
17665: ** of the following structure.
17666: */
17667: typedef struct VdbeOp Op;
17668: 
17669: /*
17670: ** Boolean values
17671: */
17672: typedef unsigned Bool;
17673: 
17674: /* Opaque type used by code in vdbesort.c */
17675: typedef struct VdbeSorter VdbeSorter;
17676: 
17677: /* Opaque type used by the explainer */
17678: typedef struct Explain Explain;
17679: 
17680: /* Elements of the linked list at Vdbe.pAuxData */
17681: typedef struct AuxData AuxData;
17682: 
17683: /* Types of VDBE cursors */
17684: #define CURTYPE_BTREE       0
17685: #define CURTYPE_SORTER      1
17686: #define CURTYPE_VTAB        2
17687: #define CURTYPE_PSEUDO      3
17688: 
17689: /*
17690: ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
17691: **
17692: **      * A b-tree cursor
17693: **          -  In the main database or in an ephemeral database
17694: **          -  On either an index or a table
17695: **      * A sorter
17696: **      * A virtual table
17697: **      * A one-row "pseudotable" stored in a single register
17698: */
17699: typedef struct VdbeCursor VdbeCursor;
17700: struct VdbeCursor {
17701:   u8 eCurType;          /* One of the CURTYPE_* values above */
17702:   i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
17703:   u8 nullRow;           /* True if pointing to a row with no data */
17704:   u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
17705:   u8 isTable;           /* True for rowid tables.  False for indexes */
17706: #ifdef SQLITE_DEBUG
17707:   u8 seekOp;            /* Most recent seek operation on this cursor */
17708:   u8 wrFlag;            /* The wrFlag argument to sqlite3BtreeCursor() */
17709: #endif
17710:   Bool isEphemeral:1;   /* True for an ephemeral table */
17711:   Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
17712:   Bool isOrdered:1;     /* True if the table is not BTREE_UNORDERED */
17713:   Pgno pgnoRoot;        /* Root page of the open btree cursor */
17714:   i16 nField;           /* Number of fields in the header */
17715:   u16 nHdrParsed;       /* Number of header fields parsed so far */
17716:   union {
17717:     BtCursor *pCursor;          /* CURTYPE_BTREE.  Btree cursor */
17718:     sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB.   Vtab cursor */
17719:     int pseudoTableReg;         /* CURTYPE_PSEUDO. Reg holding content. */
17720:     VdbeSorter *pSorter;        /* CURTYPE_SORTER. Sorter object */
17721:   } uc;
17722:   Btree *pBt;           /* Separate file holding temporary table */
17723:   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17724:   int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
17725:   i64 seqCount;         /* Sequence counter */
17726:   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17727:   VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
17728:   int *aAltMap;           /* Mapping from table to index column numbers */
17729: #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
17730:   u64 maskUsed;         /* Mask of columns used by this cursor */
17731: #endif
17732: 
17733:   /* Cached information about the header for the data record that the
17734:   ** cursor is currently pointing to.  Only valid if cacheStatus matches
17735:   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
17736:   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17737:   ** the cache is out of date.
17738:   **
17739:   ** aRow might point to (ephemeral) data for the current row, or it might
17740:   ** be NULL.
17741:   */
17742:   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17743:   u32 payloadSize;      /* Total number of bytes in the record */
17744:   u32 szRow;            /* Byte available in aRow */
17745:   u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
17746:   const u8 *aRow;       /* Data for the current row, if all on one page */
17747:   u32 *aOffset;         /* Pointer to aType[nField] */
17748:   u32 aType[1];         /* Type values for all entries in the record */
17749:   /* 2*nField extra array elements allocated for aType[], beyond the one
17750:   ** static element declared in the structure.  nField total array slots for
17751:   ** aType[] and nField+1 array slots for aOffset[] */
17752: };
17753: 
17754: /*
17755: ** When a sub-program is executed (OP_Program), a structure of this type
17756: ** is allocated to store the current value of the program counter, as
17757: ** well as the current memory cell array and various other frame specific
17758: ** values stored in the Vdbe struct. When the sub-program is finished, 
17759: ** these values are copied back to the Vdbe from the VdbeFrame structure,
17760: ** restoring the state of the VM to as it was before the sub-program
17761: ** began executing.
17762: **
17763: ** The memory for a VdbeFrame object is allocated and managed by a memory
17764: ** cell in the parent (calling) frame. When the memory cell is deleted or
17765: ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
17766: ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
17767: ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
17768: ** this instead of deleting the VdbeFrame immediately is to avoid recursive
17769: ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
17770: ** child frame are released.
17771: **
17772: ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
17773: ** set to NULL if the currently executing frame is the main program.
17774: */
17775: typedef struct VdbeFrame VdbeFrame;
17776: struct VdbeFrame {
17777:   Vdbe *v;                /* VM this frame belongs to */
17778:   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
17779:   Op *aOp;                /* Program instructions for parent frame */
17780:   i64 *anExec;            /* Event counters from parent frame */
17781:   Mem *aMem;              /* Array of memory cells for parent frame */
17782:   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
17783:   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
17784:   void *token;            /* Copy of SubProgram.token */
17785:   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
17786:   AuxData *pAuxData;      /* Linked list of auxdata allocations */
17787:   int nCursor;            /* Number of entries in apCsr */
17788:   int pc;                 /* Program Counter in parent (calling) frame */
17789:   int nOp;                /* Size of aOp array */
17790:   int nMem;               /* Number of entries in aMem */
17791:   int nOnceFlag;          /* Number of entries in aOnceFlag */
17792:   int nChildMem;          /* Number of memory cells for child frame */
17793:   int nChildCsr;          /* Number of cursors for child frame */
17794:   int nChange;            /* Statement changes (Vdbe.nChange)     */
17795:   int nDbChange;          /* Value of db->nChange */
17796: };
17797: 
17798: #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17799: 
17800: /*
17801: ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17802: */
17803: #define CACHE_STALE 0
17804: 
17805: /*
17806: ** Internally, the vdbe manipulates nearly all SQL values as Mem
17807: ** structures. Each Mem struct may cache multiple representations (string,
17808: ** integer etc.) of the same value.
17809: */
17810: struct Mem {
17811:   union MemValue {
17812:     double r;           /* Real value used when MEM_Real is set in flags */
17813:     i64 i;              /* Integer value used when MEM_Int is set in flags */
17814:     int nZero;          /* Used when bit MEM_Zero is set in flags */
17815:     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17816:     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
17817:     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
17818:   } u;
17819:   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17820:   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17821:   u8  eSubtype;       /* Subtype for this value */
17822:   int n;              /* Number of characters in string value, excluding '\0' */
17823:   char *z;            /* String or BLOB value */
17824:   /* ShallowCopy only needs to copy the information above */
17825:   char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
17826:   int szMalloc;       /* Size of the zMalloc allocation */
17827:   u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
17828:   sqlite3 *db;        /* The associated database connection */
17829:   void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
17830: #ifdef SQLITE_DEBUG
17831:   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
17832:   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
17833: #endif
17834: };
17835: 
17836: /*
17837: ** Size of struct Mem not including the Mem.zMalloc member or anything that
17838: ** follows.
17839: */
17840: #define MEMCELLSIZE offsetof(Mem,zMalloc)
17841: 
17842: /* One or more of the following flags are set to indicate the validOK
17843: ** representations of the value stored in the Mem struct.
17844: **
17845: ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17846: ** No other flags may be set in this case.
17847: **
17848: ** If the MEM_Str flag is set then Mem.z points at a string representation.
17849: ** Usually this is encoded in the same unicode encoding as the main
17850: ** database (see below for exceptions). If the MEM_Term flag is also
17851: ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
17852: ** flags may coexist with the MEM_Str flag.
17853: */
17854: #define MEM_Null      0x0001   /* Value is NULL */
17855: #define MEM_Str       0x0002   /* Value is a string */
17856: #define MEM_Int       0x0004   /* Value is an integer */
17857: #define MEM_Real      0x0008   /* Value is a real number */
17858: #define MEM_Blob      0x0010   /* Value is a BLOB */
17859: #define MEM_AffMask   0x001f   /* Mask of affinity bits */
17860: #define MEM_RowSet    0x0020   /* Value is a RowSet object */
17861: #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
17862: #define MEM_Undefined 0x0080   /* Value is undefined */
17863: #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
17864: #define MEM_TypeMask  0x81ff   /* Mask of type bits */
17865: 
17866: 
17867: /* Whenever Mem contains a valid string or blob representation, one of
17868: ** the following flags must be set to determine the memory management
17869: ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17870: ** string is \000 or \u0000 terminated
17871: */
17872: #define MEM_Term      0x0200   /* String rep is nul terminated */
17873: #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
17874: #define MEM_Static    0x0800   /* Mem.z points to a static string */
17875: #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
17876: #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
17877: #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
17878: #define MEM_Subtype   0x8000   /* Mem.eSubtype is valid */
17879: #ifdef SQLITE_OMIT_INCRBLOB
17880:   #undef MEM_Zero
17881:   #define MEM_Zero 0x0000
17882: #endif
17883: 
17884: /* Return TRUE if Mem X contains dynamically allocated content - anything
17885: ** that needs to be deallocated to avoid a leak.
17886: */
17887: #define VdbeMemDynamic(X)  \
17888:   (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
17889: 
17890: /*
17891: ** Clear any existing type flags from a Mem and replace them with f
17892: */
17893: #define MemSetTypeFlag(p, f) \
17894:    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17895: 
17896: /*
17897: ** Return true if a memory cell is not marked as invalid.  This macro
17898: ** is for use inside assert() statements only.
17899: */
17900: #ifdef SQLITE_DEBUG
17901: #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
17902: #endif
17903: 
17904: /*
17905: ** Each auxiliary data pointer stored by a user defined function 
17906: ** implementation calling sqlite3_set_auxdata() is stored in an instance
17907: ** of this structure. All such structures associated with a single VM
17908: ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
17909: ** when the VM is halted (if not before).
17910: */
17911: struct AuxData {
17912:   int iOp;                        /* Instruction number of OP_Function opcode */
17913:   int iArg;                       /* Index of function argument. */
17914:   void *pAux;                     /* Aux data pointer */
17915:   void (*xDelete)(void *);        /* Destructor for the aux data */
17916:   AuxData *pNext;                 /* Next element in list */
17917: };
17918: 
17919: /*
17920: ** The "context" argument for an installable function.  A pointer to an
17921: ** instance of this structure is the first argument to the routines used
17922: ** implement the SQL functions.
17923: **
17924: ** There is a typedef for this structure in sqlite.h.  So all routines,
17925: ** even the public interface to SQLite, can use a pointer to this structure.
17926: ** But this file is the only place where the internal details of this
17927: ** structure are known.
17928: **
17929: ** This structure is defined inside of vdbeInt.h because it uses substructures
17930: ** (Mem) which are only defined there.
17931: */
17932: struct sqlite3_context {
17933:   Mem *pOut;              /* The return value is stored here */
17934:   FuncDef *pFunc;         /* Pointer to function information */
17935:   Mem *pMem;              /* Memory cell used to store aggregate context */
17936:   Vdbe *pVdbe;            /* The VM that owns this context */
17937:   int iOp;                /* Instruction number of OP_Function */
17938:   int isError;            /* Error code returned by the function. */
17939:   u8 skipFlag;            /* Skip accumulator loading if true */
17940:   u8 fErrorOrAux;         /* isError!=0 or pVdbe->pAuxData modified */
17941:   u8 argc;                /* Number of arguments */
17942:   sqlite3_value *argv[1]; /* Argument set */
17943: };
17944: 
17945: /*
17946: ** An Explain object accumulates indented output which is helpful
17947: ** in describing recursive data structures.
17948: */
17949: struct Explain {
17950:   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
17951:   StrAccum str;      /* The string being accumulated */
17952:   int nIndent;       /* Number of elements in aIndent */
17953:   u16 aIndent[100];  /* Levels of indentation */
17954:   char zBase[100];   /* Initial space */
17955: };
17956: 
17957: /* A bitfield type for use inside of structures.  Always follow with :N where
17958: ** N is the number of bits.
17959: */
17960: typedef unsigned bft;  /* Bit Field Type */
17961: 
17962: typedef struct ScanStatus ScanStatus;
17963: struct ScanStatus {
17964:   int addrExplain;                /* OP_Explain for loop */
17965:   int addrLoop;                   /* Address of "loops" counter */
17966:   int addrVisit;                  /* Address of "rows visited" counter */
17967:   int iSelectID;                  /* The "Select-ID" for this loop */
17968:   LogEst nEst;                    /* Estimated output rows per loop */
17969:   char *zName;                    /* Name of table or index */
17970: };
17971: 
17972: /*
17973: ** An instance of the virtual machine.  This structure contains the complete
17974: ** state of the virtual machine.
17975: **
17976: ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
17977: ** is really a pointer to an instance of this structure.
17978: */
17979: struct Vdbe {
17980:   sqlite3 *db;            /* The database connection that owns this statement */
17981:   Op *aOp;                /* Space to hold the virtual machine's program */
17982:   Mem *aMem;              /* The memory locations */
17983:   Mem **apArg;            /* Arguments to currently executing user function */
17984:   Mem *aColName;          /* Column names to return */
17985:   Mem *pResultSet;        /* Pointer to an array of results */
17986:   Parse *pParse;          /* Parsing context used to create this Vdbe */
17987:   int nMem;               /* Number of memory locations currently allocated */
17988:   int nOp;                /* Number of instructions in the program */
17989:   int nCursor;            /* Number of slots in apCsr[] */
17990:   u32 magic;              /* Magic number for sanity checking */
17991:   char *zErrMsg;          /* Error message written here */
17992:   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
17993:   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
17994:   Mem *aVar;              /* Values for the OP_Variable opcode. */
17995:   char **azVar;           /* Name of variables */
17996:   ynVar nVar;             /* Number of entries in aVar[] */
17997:   ynVar nzVar;            /* Number of entries in azVar[] */
17998:   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
17999:   int pc;                 /* The program counter */
18000:   int rc;                 /* Value to return */
18001: #ifdef SQLITE_DEBUG
18002:   int rcApp;              /* errcode set by sqlite3_result_error_code() */
18003: #endif
18004:   u16 nResColumn;         /* Number of columns in one row of the result set */
18005:   u8 errorAction;         /* Recovery action to do in case of an error */
18006:   bft expired:1;          /* True if the VM needs to be recompiled */
18007:   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
18008:   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18009:   bft explain:2;          /* True if EXPLAIN present on SQL command */
18010:   bft changeCntOn:1;      /* True to update the change-counter */
18011:   bft runOnlyOnce:1;      /* Automatically expire on reset */
18012:   bft usesStmtJournal:1;  /* True if uses a statement journal */
18013:   bft readOnly:1;         /* True for statements that do not write */
18014:   bft bIsReader:1;        /* True for statements that read */
18015:   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
18016:   int nChange;            /* Number of db changes made since last reset */
18017:   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
18018:   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
18019:   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18020:   u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
18021: #ifndef SQLITE_OMIT_TRACE
18022:   i64 startTime;          /* Time when query started - used for profiling */
18023: #endif
18024:   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
18025:   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18026:   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18027:   i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
18028:   char *zSql;             /* Text of the SQL statement that generated this */
18029:   void *pFree;            /* Free this when deleting the vdbe */
18030:   VdbeFrame *pFrame;      /* Parent frame */
18031:   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
18032:   int nFrame;             /* Number of frames in pFrame list */
18033:   u32 expmask;            /* Binding to these vars invalidates VM */
18034:   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
18035:   int nOnceFlag;          /* Size of array aOnceFlag[] */
18036:   u8 *aOnceFlag;          /* Flags for OP_Once */
18037:   AuxData *pAuxData;      /* Linked list of auxdata allocations */
18038: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
18039:   i64 *anExec;            /* Number of times each op has been executed */
18040:   int nScan;              /* Entries in aScan[] */
18041:   ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
18042: #endif
18043: };
18044: 
18045: /*
18046: ** The following are allowed values for Vdbe.magic
18047: */
18048: #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18049: #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18050: #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18051: #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18052: 
18053: /*
18054: ** Structure used to store the context required by the 
18055: ** sqlite3_preupdate_*() API functions.
18056: */
18057: struct PreUpdate {
18058:   Vdbe *v;
18059:   VdbeCursor *pCsr;               /* Cursor to read old values from */
18060:   int op;                         /* One of SQLITE_INSERT, UPDATE, DELETE */
18061:   u8 *aRecord;                    /* old.* database record */
18062:   KeyInfo keyinfo;
18063:   UnpackedRecord *pUnpacked;      /* Unpacked version of aRecord[] */
18064:   UnpackedRecord *pNewUnpacked;   /* Unpacked version of new.* record */
18065:   int iNewReg;                    /* Register for new.* values */
18066:   i64 iKey1;                      /* First key value passed to hook */
18067:   i64 iKey2;                      /* Second key value passed to hook */
18068:   int iPKey;                      /* If not negative index of IPK column */
18069:   Mem *aNew;                      /* Array of new.* values */
18070: };
18071: 
18072: /*
18073: ** Function prototypes
18074: */
18075: SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
18076: SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18077: void sqliteVdbePopStack(Vdbe*,int);
18078: SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
18079: SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
18080: #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18081: SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18082: #endif
18083: SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18084: SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
18085: SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
18086: SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
18087: SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18088: SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
18089: 
18090: int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18091: SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
18092: SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
18093: SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18094: SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18095: SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18096: SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18097: SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18098: SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18099: SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18100: SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18101: SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18102: SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18103: SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18104: #ifdef SQLITE_OMIT_FLOATING_POINT
18105: # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18106: #else
18107: SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18108: #endif
18109: SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
18110: SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18111: SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18112: SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18113: SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18114: SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
18115: SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18116: SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18117: SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18118: SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18119: SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18120: SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18121: SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
18122: SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
18123: SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18124: SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18125: SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18126: SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18127: SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
18128: SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18129: SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18130: SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18131: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
18132: SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
18133: #endif
18134: SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
18135: 
18136: SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
18137: SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
18138: SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
18139: SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
18140: SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
18141: SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
18142: SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
18143: SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
18144: 
18145: #if !defined(SQLITE_OMIT_SHARED_CACHE) 
18146: SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
18147: #else
18148: # define sqlite3VdbeEnter(X)
18149: #endif
18150: 
18151: #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
18152: SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
18153: #else
18154: # define sqlite3VdbeLeave(X)
18155: #endif
18156: 
18157: #ifdef SQLITE_DEBUG
18158: SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
18159: SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
18160: #endif
18161: 
18162: #ifndef SQLITE_OMIT_FOREIGN_KEY
18163: SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18164: #else
18165: # define sqlite3VdbeCheckFk(p,i) 0
18166: #endif
18167: 
18168: SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18169: #ifdef SQLITE_DEBUG
18170: SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18171: SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18172: #endif
18173: SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18174: 
18175: #ifndef SQLITE_OMIT_INCRBLOB
18176: SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18177:   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
18178: #else
18179:   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18180:   #define ExpandBlob(P) SQLITE_OK
18181: #endif
18182: 
18183: #endif /* !defined(SQLITE_VDBEINT_H) */
18184: 
18185: /************** End of vdbeInt.h *********************************************/
18186: /************** Continuing where we left off in status.c *********************/
18187: 
18188: /*
18189: ** Variables in which to record status information.
18190: */
18191: #if SQLITE_PTRSIZE>4
18192: typedef sqlite3_int64 sqlite3StatValueType;
18193: #else
18194: typedef u32 sqlite3StatValueType;
18195: #endif
18196: typedef struct sqlite3StatType sqlite3StatType;
18197: static SQLITE_WSD struct sqlite3StatType {
18198:   sqlite3StatValueType nowValue[10];  /* Current value */
18199:   sqlite3StatValueType mxValue[10];   /* Maximum value */
18200: } sqlite3Stat = { {0,}, {0,} };
18201: 
18202: /*
18203: ** Elements of sqlite3Stat[] are protected by either the memory allocator
18204: ** mutex, or by the pcache1 mutex.  The following array determines which.
18205: */
18206: static const char statMutex[] = {
18207:   0,  /* SQLITE_STATUS_MEMORY_USED */
18208:   1,  /* SQLITE_STATUS_PAGECACHE_USED */
18209:   1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
18210:   0,  /* SQLITE_STATUS_SCRATCH_USED */
18211:   0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
18212:   0,  /* SQLITE_STATUS_MALLOC_SIZE */
18213:   0,  /* SQLITE_STATUS_PARSER_STACK */
18214:   1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
18215:   0,  /* SQLITE_STATUS_SCRATCH_SIZE */
18216:   0,  /* SQLITE_STATUS_MALLOC_COUNT */
18217: };
18218: 
18219: 
18220: /* The "wsdStat" macro will resolve to the status information
18221: ** state vector.  If writable static data is unsupported on the target,
18222: ** we have to locate the state vector at run-time.  In the more common
18223: ** case where writable static data is supported, wsdStat can refer directly
18224: ** to the "sqlite3Stat" state vector declared above.
18225: */
18226: #ifdef SQLITE_OMIT_WSD
18227: # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
18228: # define wsdStat x[0]
18229: #else
18230: # define wsdStatInit
18231: # define wsdStat sqlite3Stat
18232: #endif
18233: 
18234: /*
18235: ** Return the current value of a status parameter.  The caller must
18236: ** be holding the appropriate mutex.
18237: */
18238: SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
18239:   wsdStatInit;
18240:   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18241:   assert( op>=0 && op<ArraySize(statMutex) );
18242:   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18243:                                            : sqlite3MallocMutex()) );
18244:   return wsdStat.nowValue[op];
18245: }
18246: 
18247: /*
18248: ** Add N to the value of a status record.  The caller must hold the
18249: ** appropriate mutex.  (Locking is checked by assert()).
18250: **
18251: ** The StatusUp() routine can accept positive or negative values for N.
18252: ** The value of N is added to the current status value and the high-water
18253: ** mark is adjusted if necessary.
18254: **
18255: ** The StatusDown() routine lowers the current value by N.  The highwater
18256: ** mark is unchanged.  N must be non-negative for StatusDown().
18257: */
18258: SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
18259:   wsdStatInit;
18260:   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18261:   assert( op>=0 && op<ArraySize(statMutex) );
18262:   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18263:                                            : sqlite3MallocMutex()) );
18264:   wsdStat.nowValue[op] += N;
18265:   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
18266:     wsdStat.mxValue[op] = wsdStat.nowValue[op];
18267:   }
18268: }
18269: SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
18270:   wsdStatInit;
18271:   assert( N>=0 );
18272:   assert( op>=0 && op<ArraySize(statMutex) );
18273:   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18274:                                            : sqlite3MallocMutex()) );
18275:   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18276:   wsdStat.nowValue[op] -= N;
18277: }
18278: 
18279: /*
18280: ** Adjust the highwater mark if necessary.
18281: ** The caller must hold the appropriate mutex.
18282: */
18283: SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
18284:   sqlite3StatValueType newValue;
18285:   wsdStatInit;
18286:   assert( X>=0 );
18287:   newValue = (sqlite3StatValueType)X;
18288:   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18289:   assert( op>=0 && op<ArraySize(statMutex) );
18290:   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18291:                                            : sqlite3MallocMutex()) );
18292:   assert( op==SQLITE_STATUS_MALLOC_SIZE
18293:           || op==SQLITE_STATUS_PAGECACHE_SIZE
18294:           || op==SQLITE_STATUS_SCRATCH_SIZE
18295:           || op==SQLITE_STATUS_PARSER_STACK );
18296:   if( newValue>wsdStat.mxValue[op] ){
18297:     wsdStat.mxValue[op] = newValue;
18298:   }
18299: }
18300: 
18301: /*
18302: ** Query status information.
18303: */
18304: SQLITE_API int sqlite3_status64(
18305:   int op,
18306:   sqlite3_int64 *pCurrent,
18307:   sqlite3_int64 *pHighwater,
18308:   int resetFlag
18309: ){
18310:   sqlite3_mutex *pMutex;
18311:   wsdStatInit;
18312:   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
18313:     return SQLITE_MISUSE_BKPT;
18314:   }
18315: #ifdef SQLITE_ENABLE_API_ARMOR
18316:   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18317: #endif
18318:   pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
18319:   sqlite3_mutex_enter(pMutex);
18320:   *pCurrent = wsdStat.nowValue[op];
18321:   *pHighwater = wsdStat.mxValue[op];
18322:   if( resetFlag ){
18323:     wsdStat.mxValue[op] = wsdStat.nowValue[op];
18324:   }
18325:   sqlite3_mutex_leave(pMutex);
18326:   (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
18327:   return SQLITE_OK;
18328: }
18329: SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
18330:   sqlite3_int64 iCur = 0, iHwtr = 0;
18331:   int rc;
18332: #ifdef SQLITE_ENABLE_API_ARMOR
18333:   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18334: #endif
18335:   rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
18336:   if( rc==0 ){
18337:     *pCurrent = (int)iCur;
18338:     *pHighwater = (int)iHwtr;
18339:   }
18340:   return rc;
18341: }
18342: 
18343: /*
18344: ** Query status information for a single database connection
18345: */
18346: SQLITE_API int sqlite3_db_status(
18347:   sqlite3 *db,          /* The database connection whose status is desired */
18348:   int op,               /* Status verb */
18349:   int *pCurrent,        /* Write current value here */
18350:   int *pHighwater,      /* Write high-water mark here */
18351:   int resetFlag         /* Reset high-water mark if true */
18352: ){
18353:   int rc = SQLITE_OK;   /* Return code */
18354: #ifdef SQLITE_ENABLE_API_ARMOR
18355:   if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
18356:     return SQLITE_MISUSE_BKPT;
18357:   }
18358: #endif
18359:   sqlite3_mutex_enter(db->mutex);
18360:   switch( op ){
18361:     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
18362:       *pCurrent = db->lookaside.nOut;
18363:       *pHighwater = db->lookaside.mxOut;
18364:       if( resetFlag ){
18365:         db->lookaside.mxOut = db->lookaside.nOut;
18366:       }
18367:       break;
18368:     }
18369: 
18370:     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
18371:     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
18372:     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
18373:       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
18374:       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
18375:       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
18376:       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
18377:       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
18378:       *pCurrent = 0;
18379:       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
18380:       if( resetFlag ){
18381:         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
18382:       }
18383:       break;
18384:     }
18385: 
18386:     /* 
18387:     ** Return an approximation for the amount of memory currently used
18388:     ** by all pagers associated with the given database connection.  The
18389:     ** highwater mark is meaningless and is returned as zero.
18390:     */
18391:     case SQLITE_DBSTATUS_CACHE_USED_SHARED:
18392:     case SQLITE_DBSTATUS_CACHE_USED: {
18393:       int totalUsed = 0;
18394:       int i;
18395:       sqlite3BtreeEnterAll(db);
18396:       for(i=0; i<db->nDb; i++){
18397:         Btree *pBt = db->aDb[i].pBt;
18398:         if( pBt ){
18399:           Pager *pPager = sqlite3BtreePager(pBt);
18400:           int nByte = sqlite3PagerMemUsed(pPager);
18401:           if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
18402:             nByte = nByte / sqlite3BtreeConnectionCount(pBt);
18403:           }
18404:           totalUsed += nByte;
18405:         }
18406:       }
18407:       sqlite3BtreeLeaveAll(db);
18408:       *pCurrent = totalUsed;
18409:       *pHighwater = 0;
18410:       break;
18411:     }
18412: 
18413:     /*
18414:     ** *pCurrent gets an accurate estimate of the amount of memory used
18415:     ** to store the schema for all databases (main, temp, and any ATTACHed
18416:     ** databases.  *pHighwater is set to zero.
18417:     */
18418:     case SQLITE_DBSTATUS_SCHEMA_USED: {
18419:       int i;                      /* Used to iterate through schemas */
18420:       int nByte = 0;              /* Used to accumulate return value */
18421: 
18422:       sqlite3BtreeEnterAll(db);
18423:       db->pnBytesFreed = &nByte;
18424:       for(i=0; i<db->nDb; i++){
18425:         Schema *pSchema = db->aDb[i].pSchema;
18426:         if( ALWAYS(pSchema!=0) ){
18427:           HashElem *p;
18428: 
18429:           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
18430:               pSchema->tblHash.count 
18431:             + pSchema->trigHash.count
18432:             + pSchema->idxHash.count
18433:             + pSchema->fkeyHash.count
18434:           );
18435:           nByte += sqlite3_msize(pSchema->tblHash.ht);
18436:           nByte += sqlite3_msize(pSchema->trigHash.ht);
18437:           nByte += sqlite3_msize(pSchema->idxHash.ht);
18438:           nByte += sqlite3_msize(pSchema->fkeyHash.ht);
18439: 
18440:           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
18441:             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
18442:           }
18443:           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
18444:             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
18445:           }
18446:         }
18447:       }
18448:       db->pnBytesFreed = 0;
18449:       sqlite3BtreeLeaveAll(db);
18450: 
18451:       *pHighwater = 0;
18452:       *pCurrent = nByte;
18453:       break;
18454:     }
18455: 
18456:     /*
18457:     ** *pCurrent gets an accurate estimate of the amount of memory used
18458:     ** to store all prepared statements.
18459:     ** *pHighwater is set to zero.
18460:     */
18461:     case SQLITE_DBSTATUS_STMT_USED: {
18462:       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
18463:       int nByte = 0;              /* Used to accumulate return value */
18464: 
18465:       db->pnBytesFreed = &nByte;
18466:       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
18467:         sqlite3VdbeClearObject(db, pVdbe);
18468:         sqlite3DbFree(db, pVdbe);
18469:       }
18470:       db->pnBytesFreed = 0;
18471: 
18472:       *pHighwater = 0;  /* IMP: R-64479-57858 */
18473:       *pCurrent = nByte;
18474: 
18475:       break;
18476:     }
18477: 
18478:     /*
18479:     ** Set *pCurrent to the total cache hits or misses encountered by all
18480:     ** pagers the database handle is connected to. *pHighwater is always set 
18481:     ** to zero.
18482:     */
18483:     case SQLITE_DBSTATUS_CACHE_HIT:
18484:     case SQLITE_DBSTATUS_CACHE_MISS:
18485:     case SQLITE_DBSTATUS_CACHE_WRITE:{
18486:       int i;
18487:       int nRet = 0;
18488:       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
18489:       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
18490: 
18491:       for(i=0; i<db->nDb; i++){
18492:         if( db->aDb[i].pBt ){
18493:           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
18494:           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
18495:         }
18496:       }
18497:       *pHighwater = 0; /* IMP: R-42420-56072 */
18498:                        /* IMP: R-54100-20147 */
18499:                        /* IMP: R-29431-39229 */
18500:       *pCurrent = nRet;
18501:       break;
18502:     }
18503: 
18504:     /* Set *pCurrent to non-zero if there are unresolved deferred foreign
18505:     ** key constraints.  Set *pCurrent to zero if all foreign key constraints
18506:     ** have been satisfied.  The *pHighwater is always set to zero.
18507:     */
18508:     case SQLITE_DBSTATUS_DEFERRED_FKS: {
18509:       *pHighwater = 0;  /* IMP: R-11967-56545 */
18510:       *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
18511:       break;
18512:     }
18513: 
18514:     default: {
18515:       rc = SQLITE_ERROR;
18516:     }
18517:   }
18518:   sqlite3_mutex_leave(db->mutex);
18519:   return rc;
18520: }
18521: 
18522: /************** End of status.c **********************************************/
18523: /************** Begin file date.c ********************************************/
18524: /*
18525: ** 2003 October 31
18526: **
18527: ** The author disclaims copyright to this source code.  In place of
18528: ** a legal notice, here is a blessing:
18529: **
18530: **    May you do good and not evil.
18531: **    May you find forgiveness for yourself and forgive others.
18532: **    May you share freely, never taking more than you give.
18533: **
18534: *************************************************************************
18535: ** This file contains the C functions that implement date and time
18536: ** functions for SQLite.  
18537: **
18538: ** There is only one exported symbol in this file - the function
18539: ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
18540: ** All other code has file scope.
18541: **
18542: ** SQLite processes all times and dates as julian day numbers.  The
18543: ** dates and times are stored as the number of days since noon
18544: ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
18545: ** calendar system. 
18546: **
18547: ** 1970-01-01 00:00:00 is JD 2440587.5
18548: ** 2000-01-01 00:00:00 is JD 2451544.5
18549: **
18550: ** This implementation requires years to be expressed as a 4-digit number
18551: ** which means that only dates between 0000-01-01 and 9999-12-31 can
18552: ** be represented, even though julian day numbers allow a much wider
18553: ** range of dates.
18554: **
18555: ** The Gregorian calendar system is used for all dates and times,
18556: ** even those that predate the Gregorian calendar.  Historians usually
18557: ** use the julian calendar for dates prior to 1582-10-15 and for some
18558: ** dates afterwards, depending on locale.  Beware of this difference.
18559: **
18560: ** The conversion algorithms are implemented based on descriptions
18561: ** in the following text:
18562: **
18563: **      Jean Meeus
18564: **      Astronomical Algorithms, 2nd Edition, 1998
18565: **      ISBM 0-943396-61-1
18566: **      Willmann-Bell, Inc
18567: **      Richmond, Virginia (USA)
18568: */
18569: /* #include "sqliteInt.h" */
18570: /* #include <stdlib.h> */
18571: /* #include <assert.h> */
18572: #include <time.h>
18573: 
18574: #ifndef SQLITE_OMIT_DATETIME_FUNCS
18575: 
18576: /*
18577: ** The MSVC CRT on Windows CE may not have a localtime() function.
18578: ** So declare a substitute.  The substitute function itself is
18579: ** defined in "os_win.c".
18580: */
18581: #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18582:     (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18583: struct tm *__cdecl localtime(const time_t *);
18584: #endif
18585: 
18586: /*
18587: ** A structure for holding a single date and time.
18588: */
18589: typedef struct DateTime DateTime;
18590: struct DateTime {
18591:   sqlite3_int64 iJD; /* The julian day number times 86400000 */
18592:   int Y, M, D;       /* Year, month, and day */
18593:   int h, m;          /* Hour and minutes */
18594:   int tz;            /* Timezone offset in minutes */
18595:   double s;          /* Seconds */
18596:   char validYMD;     /* True (1) if Y,M,D are valid */
18597:   char validHMS;     /* True (1) if h,m,s are valid */
18598:   char validJD;      /* True (1) if iJD is valid */
18599:   char validTZ;      /* True (1) if tz is valid */
18600:   char tzSet;        /* Timezone was set explicitly */
18601: };
18602: 
18603: 
18604: /*
18605: ** Convert zDate into one or more integers according to the conversion
18606: ** specifier zFormat.
18607: **
18608: ** zFormat[] contains 4 characters for each integer converted, except for
18609: ** the last integer which is specified by three characters.  The meaning
18610: ** of a four-character format specifiers ABCD is:
18611: **
18612: **    A:   number of digits to convert.  Always "2" or "4".
18613: **    B:   minimum value.  Always "0" or "1".
18614: **    C:   maximum value, decoded as:
18615: **           a:  12
18616: **           b:  14
18617: **           c:  24
18618: **           d:  31
18619: **           e:  59
18620: **           f:  9999
18621: **    D:   the separator character, or \000 to indicate this is the
18622: **         last number to convert.
18623: **
18624: ** Example:  To translate an ISO-8601 date YYYY-MM-DD, the format would
18625: ** be "40f-21a-20c".  The "40f-" indicates the 4-digit year followed by "-".
18626: ** The "21a-" indicates the 2-digit month followed by "-".  The "20c" indicates
18627: ** the 2-digit day which is the last integer in the set.
18628: **
18629: ** The function returns the number of successful conversions.
18630: */
18631: static int getDigits(const char *zDate, const char *zFormat, ...){
18632:   /* The aMx[] array translates the 3rd character of each format
18633:   ** spec into a max size:    a   b   c   d   e     f */
18634:   static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
18635:   va_list ap;
18636:   int cnt = 0;
18637:   char nextC;
18638:   va_start(ap, zFormat);
18639:   do{
18640:     char N = zFormat[0] - '0';
18641:     char min = zFormat[1] - '0';
18642:     int val = 0;
18643:     u16 max;
18644: 
18645:     assert( zFormat[2]>='a' && zFormat[2]<='f' );
18646:     max = aMx[zFormat[2] - 'a'];
18647:     nextC = zFormat[3];
18648:     val = 0;
18649:     while( N-- ){
18650:       if( !sqlite3Isdigit(*zDate) ){
18651:         goto end_getDigits;
18652:       }
18653:       val = val*10 + *zDate - '0';
18654:       zDate++;
18655:     }
18656:     if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
18657:       goto end_getDigits;
18658:     }
18659:     *va_arg(ap,int*) = val;
18660:     zDate++;
18661:     cnt++;
18662:     zFormat += 4;
18663:   }while( nextC );
18664: end_getDigits:
18665:   va_end(ap);
18666:   return cnt;
18667: }
18668: 
18669: /*
18670: ** Parse a timezone extension on the end of a date-time.
18671: ** The extension is of the form:
18672: **
18673: **        (+/-)HH:MM
18674: **
18675: ** Or the "zulu" notation:
18676: **
18677: **        Z
18678: **
18679: ** If the parse is successful, write the number of minutes
18680: ** of change in p->tz and return 0.  If a parser error occurs,
18681: ** return non-zero.
18682: **
18683: ** A missing specifier is not considered an error.
18684: */
18685: static int parseTimezone(const char *zDate, DateTime *p){
18686:   int sgn = 0;
18687:   int nHr, nMn;
18688:   int c;
18689:   while( sqlite3Isspace(*zDate) ){ zDate++; }
18690:   p->tz = 0;
18691:   c = *zDate;
18692:   if( c=='-' ){
18693:     sgn = -1;
18694:   }else if( c=='+' ){
18695:     sgn = +1;
18696:   }else if( c=='Z' || c=='z' ){
18697:     zDate++;
18698:     goto zulu_time;
18699:   }else{
18700:     return c!=0;
18701:   }
18702:   zDate++;
18703:   if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
18704:     return 1;
18705:   }
18706:   zDate += 5;
18707:   p->tz = sgn*(nMn + nHr*60);
18708: zulu_time:
18709:   while( sqlite3Isspace(*zDate) ){ zDate++; }
18710:   p->tzSet = 1;
18711:   return *zDate!=0;
18712: }
18713: 
18714: /*
18715: ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
18716: ** The HH, MM, and SS must each be exactly 2 digits.  The
18717: ** fractional seconds FFFF can be one or more digits.
18718: **
18719: ** Return 1 if there is a parsing error and 0 on success.
18720: */
18721: static int parseHhMmSs(const char *zDate, DateTime *p){
18722:   int h, m, s;
18723:   double ms = 0.0;
18724:   if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
18725:     return 1;
18726:   }
18727:   zDate += 5;
18728:   if( *zDate==':' ){
18729:     zDate++;
18730:     if( getDigits(zDate, "20e", &s)!=1 ){
18731:       return 1;
18732:     }
18733:     zDate += 2;
18734:     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
18735:       double rScale = 1.0;
18736:       zDate++;
18737:       while( sqlite3Isdigit(*zDate) ){
18738:         ms = ms*10.0 + *zDate - '0';
18739:         rScale *= 10.0;
18740:         zDate++;
18741:       }
18742:       ms /= rScale;
18743:     }
18744:   }else{
18745:     s = 0;
18746:   }
18747:   p->validJD = 0;
18748:   p->validHMS = 1;
18749:   p->h = h;
18750:   p->m = m;
18751:   p->s = s + ms;
18752:   if( parseTimezone(zDate, p) ) return 1;
18753:   p->validTZ = (p->tz!=0)?1:0;
18754:   return 0;
18755: }
18756: 
18757: /*
18758: ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
18759: ** that the YYYY-MM-DD is according to the Gregorian calendar.
18760: **
18761: ** Reference:  Meeus page 61
18762: */
18763: static void computeJD(DateTime *p){
18764:   int Y, M, D, A, B, X1, X2;
18765: 
18766:   if( p->validJD ) return;
18767:   if( p->validYMD ){
18768:     Y = p->Y;
18769:     M = p->M;
18770:     D = p->D;
18771:   }else{
18772:     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
18773:     M = 1;
18774:     D = 1;
18775:   }
18776:   if( M<=2 ){
18777:     Y--;
18778:     M += 12;
18779:   }
18780:   A = Y/100;
18781:   B = 2 - A + (A/4);
18782:   X1 = 36525*(Y+4716)/100;
18783:   X2 = 306001*(M+1)/10000;
18784:   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
18785:   p->validJD = 1;
18786:   if( p->validHMS ){
18787:     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
18788:     if( p->validTZ ){
18789:       p->iJD -= p->tz*60000;
18790:       p->validYMD = 0;
18791:       p->validHMS = 0;
18792:       p->validTZ = 0;
18793:     }
18794:   }
18795: }
18796: 
18797: /*
18798: ** Parse dates of the form
18799: **
18800: **     YYYY-MM-DD HH:MM:SS.FFF
18801: **     YYYY-MM-DD HH:MM:SS
18802: **     YYYY-MM-DD HH:MM
18803: **     YYYY-MM-DD
18804: **
18805: ** Write the result into the DateTime structure and return 0
18806: ** on success and 1 if the input string is not a well-formed
18807: ** date.
18808: */
18809: static int parseYyyyMmDd(const char *zDate, DateTime *p){
18810:   int Y, M, D, neg;
18811: 
18812:   if( zDate[0]=='-' ){
18813:     zDate++;
18814:     neg = 1;
18815:   }else{
18816:     neg = 0;
18817:   }
18818:   if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
18819:     return 1;
18820:   }
18821:   zDate += 10;
18822:   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
18823:   if( parseHhMmSs(zDate, p)==0 ){
18824:     /* We got the time */
18825:   }else if( *zDate==0 ){
18826:     p->validHMS = 0;
18827:   }else{
18828:     return 1;
18829:   }
18830:   p->validJD = 0;
18831:   p->validYMD = 1;
18832:   p->Y = neg ? -Y : Y;
18833:   p->M = M;
18834:   p->D = D;
18835:   if( p->validTZ ){
18836:     computeJD(p);
18837:   }
18838:   return 0;
18839: }
18840: 
18841: /*
18842: ** Set the time to the current time reported by the VFS.
18843: **
18844: ** Return the number of errors.
18845: */
18846: static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
18847:   p->iJD = sqlite3StmtCurrentTime(context);
18848:   if( p->iJD>0 ){
18849:     p->validJD = 1;
18850:     return 0;
18851:   }else{
18852:     return 1;
18853:   }
18854: }
18855: 
18856: /*
18857: ** Attempt to parse the given string into a julian day number.  Return
18858: ** the number of errors.
18859: **
18860: ** The following are acceptable forms for the input string:
18861: **
18862: **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
18863: **      DDDD.DD 
18864: **      now
18865: **
18866: ** In the first form, the +/-HH:MM is always optional.  The fractional
18867: ** seconds extension (the ".FFF") is optional.  The seconds portion
18868: ** (":SS.FFF") is option.  The year and date can be omitted as long
18869: ** as there is a time string.  The time string can be omitted as long
18870: ** as there is a year and date.
18871: */
18872: static int parseDateOrTime(
18873:   sqlite3_context *context, 
18874:   const char *zDate, 
18875:   DateTime *p
18876: ){
18877:   double r;
18878:   if( parseYyyyMmDd(zDate,p)==0 ){
18879:     return 0;
18880:   }else if( parseHhMmSs(zDate, p)==0 ){
18881:     return 0;
18882:   }else if( sqlite3StrICmp(zDate,"now")==0){
18883:     return setDateTimeToCurrent(context, p);
18884:   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
18885:     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
18886:     p->validJD = 1;
18887:     return 0;
18888:   }
18889:   return 1;
18890: }
18891: 
18892: /*
18893: ** Compute the Year, Month, and Day from the julian day number.
18894: */
18895: static void computeYMD(DateTime *p){
18896:   int Z, A, B, C, D, E, X1;
18897:   if( p->validYMD ) return;
18898:   if( !p->validJD ){
18899:     p->Y = 2000;
18900:     p->M = 1;
18901:     p->D = 1;
18902:   }else{
18903:     Z = (int)((p->iJD + 43200000)/86400000);
18904:     A = (int)((Z - 1867216.25)/36524.25);
18905:     A = Z + 1 + A - (A/4);
18906:     B = A + 1524;
18907:     C = (int)((B - 122.1)/365.25);
18908:     D = (36525*(C&32767))/100;
18909:     E = (int)((B-D)/30.6001);
18910:     X1 = (int)(30.6001*E);
18911:     p->D = B - D - X1;
18912:     p->M = E<14 ? E-1 : E-13;
18913:     p->Y = p->M>2 ? C - 4716 : C - 4715;
18914:   }
18915:   p->validYMD = 1;
18916: }
18917: 
18918: /*
18919: ** Compute the Hour, Minute, and Seconds from the julian day number.
18920: */
18921: static void computeHMS(DateTime *p){
18922:   int s;
18923:   if( p->validHMS ) return;
18924:   computeJD(p);
18925:   s = (int)((p->iJD + 43200000) % 86400000);
18926:   p->s = s/1000.0;
18927:   s = (int)p->s;
18928:   p->s -= s;
18929:   p->h = s/3600;
18930:   s -= p->h*3600;
18931:   p->m = s/60;
18932:   p->s += s - p->m*60;
18933:   p->validHMS = 1;
18934: }
18935: 
18936: /*
18937: ** Compute both YMD and HMS
18938: */
18939: static void computeYMD_HMS(DateTime *p){
18940:   computeYMD(p);
18941:   computeHMS(p);
18942: }
18943: 
18944: /*
18945: ** Clear the YMD and HMS and the TZ
18946: */
18947: static void clearYMD_HMS_TZ(DateTime *p){
18948:   p->validYMD = 0;
18949:   p->validHMS = 0;
18950:   p->validTZ = 0;
18951: }
18952: 
18953: #ifndef SQLITE_OMIT_LOCALTIME
18954: /*
18955: ** On recent Windows platforms, the localtime_s() function is available
18956: ** as part of the "Secure CRT". It is essentially equivalent to 
18957: ** localtime_r() available under most POSIX platforms, except that the 
18958: ** order of the parameters is reversed.
18959: **
18960: ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
18961: **
18962: ** If the user has not indicated to use localtime_r() or localtime_s()
18963: ** already, check for an MSVC build environment that provides 
18964: ** localtime_s().
18965: */
18966: #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
18967:     && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
18968: #undef  HAVE_LOCALTIME_S
18969: #define HAVE_LOCALTIME_S 1
18970: #endif
18971: 
18972: /*
18973: ** The following routine implements the rough equivalent of localtime_r()
18974: ** using whatever operating-system specific localtime facility that
18975: ** is available.  This routine returns 0 on success and
18976: ** non-zero on any kind of error.
18977: **
18978: ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
18979: ** routine will always fail.
18980: **
18981: ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
18982: ** library function localtime_r() is used to assist in the calculation of
18983: ** local time.
18984: */
18985: static int osLocaltime(time_t *t, struct tm *pTm){
18986:   int rc;
18987: #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
18988:   struct tm *pX;
18989: #if SQLITE_THREADSAFE>0
18990:   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
18991: #endif
18992:   sqlite3_mutex_enter(mutex);
18993:   pX = localtime(t);
18994: #ifndef SQLITE_OMIT_BUILTIN_TEST
18995:   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
18996: #endif
18997:   if( pX ) *pTm = *pX;
18998:   sqlite3_mutex_leave(mutex);
18999:   rc = pX==0;
19000: #else
19001: #ifndef SQLITE_OMIT_BUILTIN_TEST
19002:   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
19003: #endif
19004: #if HAVE_LOCALTIME_R
19005:   rc = localtime_r(t, pTm)==0;
19006: #else
19007:   rc = localtime_s(pTm, t);
19008: #endif /* HAVE_LOCALTIME_R */
19009: #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
19010:   return rc;
19011: }
19012: #endif /* SQLITE_OMIT_LOCALTIME */
19013: 
19014: 
19015: #ifndef SQLITE_OMIT_LOCALTIME
19016: /*
19017: ** Compute the difference (in milliseconds) between localtime and UTC
19018: ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
19019: ** return this value and set *pRc to SQLITE_OK. 
19020: **
19021: ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
19022: ** is undefined in this case.
19023: */
19024: static sqlite3_int64 localtimeOffset(
19025:   DateTime *p,                    /* Date at which to calculate offset */
19026:   sqlite3_context *pCtx,          /* Write error here if one occurs */
19027:   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
19028: ){
19029:   DateTime x, y;
19030:   time_t t;
19031:   struct tm sLocal;
19032: 
19033:   /* Initialize the contents of sLocal to avoid a compiler warning. */
19034:   memset(&sLocal, 0, sizeof(sLocal));
19035: 
19036:   x = *p;
19037:   computeYMD_HMS(&x);
19038:   if( x.Y<1971 || x.Y>=2038 ){
19039:     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
19040:     ** works for years between 1970 and 2037. For dates outside this range,
19041:     ** SQLite attempts to map the year into an equivalent year within this
19042:     ** range, do the calculation, then map the year back.
19043:     */
19044:     x.Y = 2000;
19045:     x.M = 1;
19046:     x.D = 1;
19047:     x.h = 0;
19048:     x.m = 0;
19049:     x.s = 0.0;
19050:   } else {
19051:     int s = (int)(x.s + 0.5);
19052:     x.s = s;
19053:   }
19054:   x.tz = 0;
19055:   x.validJD = 0;
19056:   computeJD(&x);
19057:   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
19058:   if( osLocaltime(&t, &sLocal) ){
19059:     sqlite3_result_error(pCtx, "local time unavailable", -1);
19060:     *pRc = SQLITE_ERROR;
19061:     return 0;
19062:   }
19063:   y.Y = sLocal.tm_year + 1900;
19064:   y.M = sLocal.tm_mon + 1;
19065:   y.D = sLocal.tm_mday;
19066:   y.h = sLocal.tm_hour;
19067:   y.m = sLocal.tm_min;
19068:   y.s = sLocal.tm_sec;
19069:   y.validYMD = 1;
19070:   y.validHMS = 1;
19071:   y.validJD = 0;
19072:   y.validTZ = 0;
19073:   computeJD(&y);
19074:   *pRc = SQLITE_OK;
19075:   return y.iJD - x.iJD;
19076: }
19077: #endif /* SQLITE_OMIT_LOCALTIME */
19078: 
19079: /*
19080: ** Process a modifier to a date-time stamp.  The modifiers are
19081: ** as follows:
19082: **
19083: **     NNN days
19084: **     NNN hours
19085: **     NNN minutes
19086: **     NNN.NNNN seconds
19087: **     NNN months
19088: **     NNN years
19089: **     start of month
19090: **     start of year
19091: **     start of week
19092: **     start of day
19093: **     weekday N
19094: **     unixepoch
19095: **     localtime
19096: **     utc
19097: **
19098: ** Return 0 on success and 1 if there is any kind of error. If the error
19099: ** is in a system call (i.e. localtime()), then an error message is written
19100: ** to context pCtx. If the error is an unrecognized modifier, no error is
19101: ** written to pCtx.
19102: */
19103: static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
19104:   int rc = 1;
19105:   int n;
19106:   double r;
19107:   char *z, zBuf[30];
19108:   z = zBuf;
19109:   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
19110:     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
19111:   }
19112:   z[n] = 0;
19113:   switch( z[0] ){
19114: #ifndef SQLITE_OMIT_LOCALTIME
19115:     case 'l': {
19116:       /*    localtime
19117:       **
19118:       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
19119:       ** show local time.
19120:       */
19121:       if( strcmp(z, "localtime")==0 ){
19122:         computeJD(p);
19123:         p->iJD += localtimeOffset(p, pCtx, &rc);
19124:         clearYMD_HMS_TZ(p);
19125:       }
19126:       break;
19127:     }
19128: #endif
19129:     case 'u': {
19130:       /*
19131:       **    unixepoch
19132:       **
19133:       ** Treat the current value of p->iJD as the number of
19134:       ** seconds since 1970.  Convert to a real julian day number.
19135:       */
19136:       if( strcmp(z, "unixepoch")==0 && p->validJD ){
19137:         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
19138:         clearYMD_HMS_TZ(p);
19139:         rc = 0;
19140:       }
19141: #ifndef SQLITE_OMIT_LOCALTIME
19142:       else if( strcmp(z, "utc")==0 ){
19143:         if( p->tzSet==0 ){
19144:           sqlite3_int64 c1;
19145:           computeJD(p);
19146:           c1 = localtimeOffset(p, pCtx, &rc);
19147:           if( rc==SQLITE_OK ){
19148:             p->iJD -= c1;
19149:             clearYMD_HMS_TZ(p);
19150:             p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
19151:           }
19152:           p->tzSet = 1;
19153:         }else{
19154:           rc = SQLITE_OK;
19155:         }
19156:       }
19157: #endif
19158:       break;
19159:     }
19160:     case 'w': {
19161:       /*
19162:       **    weekday N
19163:       **
19164:       ** Move the date to the same time on the next occurrence of
19165:       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
19166:       ** date is already on the appropriate weekday, this is a no-op.
19167:       */
19168:       if( strncmp(z, "weekday ", 8)==0
19169:                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
19170:                && (n=(int)r)==r && n>=0 && r<7 ){
19171:         sqlite3_int64 Z;
19172:         computeYMD_HMS(p);
19173:         p->validTZ = 0;
19174:         p->validJD = 0;
19175:         computeJD(p);
19176:         Z = ((p->iJD + 129600000)/86400000) % 7;
19177:         if( Z>n ) Z -= 7;
19178:         p->iJD += (n - Z)*86400000;
19179:         clearYMD_HMS_TZ(p);
19180:         rc = 0;
19181:       }
19182:       break;
19183:     }
19184:     case 's': {
19185:       /*
19186:       **    start of TTTTT
19187:       **
19188:       ** Move the date backwards to the beginning of the current day,
19189:       ** or month or year.
19190:       */
19191:       if( strncmp(z, "start of ", 9)!=0 ) break;
19192:       z += 9;
19193:       computeYMD(p);
19194:       p->validHMS = 1;
19195:       p->h = p->m = 0;
19196:       p->s = 0.0;
19197:       p->validTZ = 0;
19198:       p->validJD = 0;
19199:       if( strcmp(z,"month")==0 ){
19200:         p->D = 1;
19201:         rc = 0;
19202:       }else if( strcmp(z,"year")==0 ){
19203:         computeYMD(p);
19204:         p->M = 1;
19205:         p->D = 1;
19206:         rc = 0;
19207:       }else if( strcmp(z,"day")==0 ){
19208:         rc = 0;
19209:       }
19210:       break;
19211:     }
19212:     case '+':
19213:     case '-':
19214:     case '0':
19215:     case '1':
19216:     case '2':
19217:     case '3':
19218:     case '4':
19219:     case '5':
19220:     case '6':
19221:     case '7':
19222:     case '8':
19223:     case '9': {
19224:       double rRounder;
19225:       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
19226:       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
19227:         rc = 1;
19228:         break;
19229:       }
19230:       if( z[n]==':' ){
19231:         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
19232:         ** specified number of hours, minutes, seconds, and fractional seconds
19233:         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
19234:         ** omitted.
19235:         */
19236:         const char *z2 = z;
19237:         DateTime tx;
19238:         sqlite3_int64 day;
19239:         if( !sqlite3Isdigit(*z2) ) z2++;
19240:         memset(&tx, 0, sizeof(tx));
19241:         if( parseHhMmSs(z2, &tx) ) break;
19242:         computeJD(&tx);
19243:         tx.iJD -= 43200000;
19244:         day = tx.iJD/86400000;
19245:         tx.iJD -= day*86400000;
19246:         if( z[0]=='-' ) tx.iJD = -tx.iJD;
19247:         computeJD(p);
19248:         clearYMD_HMS_TZ(p);
19249:         p->iJD += tx.iJD;
19250:         rc = 0;
19251:         break;
19252:       }
19253:       z += n;
19254:       while( sqlite3Isspace(*z) ) z++;
19255:       n = sqlite3Strlen30(z);
19256:       if( n>10 || n<3 ) break;
19257:       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
19258:       computeJD(p);
19259:       rc = 0;
19260:       rRounder = r<0 ? -0.5 : +0.5;
19261:       if( n==3 && strcmp(z,"day")==0 ){
19262:         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
19263:       }else if( n==4 && strcmp(z,"hour")==0 ){
19264:         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
19265:       }else if( n==6 && strcmp(z,"minute")==0 ){
19266:         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
19267:       }else if( n==6 && strcmp(z,"second")==0 ){
19268:         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
19269:       }else if( n==5 && strcmp(z,"month")==0 ){
19270:         int x, y;
19271:         computeYMD_HMS(p);
19272:         p->M += (int)r;
19273:         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
19274:         p->Y += x;
19275:         p->M -= x*12;
19276:         p->validJD = 0;
19277:         computeJD(p);
19278:         y = (int)r;
19279:         if( y!=r ){
19280:           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
19281:         }
19282:       }else if( n==4 && strcmp(z,"year")==0 ){
19283:         int y = (int)r;
19284:         computeYMD_HMS(p);
19285:         p->Y += y;
19286:         p->validJD = 0;
19287:         computeJD(p);
19288:         if( y!=r ){
19289:           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
19290:         }
19291:       }else{
19292:         rc = 1;
19293:       }
19294:       clearYMD_HMS_TZ(p);
19295:       break;
19296:     }
19297:     default: {
19298:       break;
19299:     }
19300:   }
19301:   return rc;
19302: }
19303: 
19304: /*
19305: ** Process time function arguments.  argv[0] is a date-time stamp.
19306: ** argv[1] and following are modifiers.  Parse them all and write
19307: ** the resulting time into the DateTime structure p.  Return 0
19308: ** on success and 1 if there are any errors.
19309: **
19310: ** If there are zero parameters (if even argv[0] is undefined)
19311: ** then assume a default value of "now" for argv[0].
19312: */
19313: static int isDate(
19314:   sqlite3_context *context, 
19315:   int argc, 
19316:   sqlite3_value **argv, 
19317:   DateTime *p
19318: ){
19319:   int i;
19320:   const unsigned char *z;
19321:   int eType;
19322:   memset(p, 0, sizeof(*p));
19323:   if( argc==0 ){
19324:     return setDateTimeToCurrent(context, p);
19325:   }
19326:   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
19327:                    || eType==SQLITE_INTEGER ){
19328:     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
19329:     p->validJD = 1;
19330:   }else{
19331:     z = sqlite3_value_text(argv[0]);
19332:     if( !z || parseDateOrTime(context, (char*)z, p) ){
19333:       return 1;
19334:     }
19335:   }
19336:   for(i=1; i<argc; i++){
19337:     z = sqlite3_value_text(argv[i]);
19338:     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
19339:   }
19340:   return 0;
19341: }
19342: 
19343: 
19344: /*
19345: ** The following routines implement the various date and time functions
19346: ** of SQLite.
19347: */
19348: 
19349: /*
19350: **    julianday( TIMESTRING, MOD, MOD, ...)
19351: **
19352: ** Return the julian day number of the date specified in the arguments
19353: */
19354: static void juliandayFunc(
19355:   sqlite3_context *context,
19356:   int argc,
19357:   sqlite3_value **argv
19358: ){
19359:   DateTime x;
19360:   if( isDate(context, argc, argv, &x)==0 ){
19361:     computeJD(&x);
19362:     sqlite3_result_double(context, x.iJD/86400000.0);
19363:   }
19364: }
19365: 
19366: /*
19367: **    datetime( TIMESTRING, MOD, MOD, ...)
19368: **
19369: ** Return YYYY-MM-DD HH:MM:SS
19370: */
19371: static void datetimeFunc(
19372:   sqlite3_context *context,
19373:   int argc,
19374:   sqlite3_value **argv
19375: ){
19376:   DateTime x;
19377:   if( isDate(context, argc, argv, &x)==0 ){
19378:     char zBuf[100];
19379:     computeYMD_HMS(&x);
19380:     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
19381:                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
19382:     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19383:   }
19384: }
19385: 
19386: /*
19387: **    time( TIMESTRING, MOD, MOD, ...)
19388: **
19389: ** Return HH:MM:SS
19390: */
19391: static void timeFunc(
19392:   sqlite3_context *context,
19393:   int argc,
19394:   sqlite3_value **argv
19395: ){
19396:   DateTime x;
19397:   if( isDate(context, argc, argv, &x)==0 ){
19398:     char zBuf[100];
19399:     computeHMS(&x);
19400:     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
19401:     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19402:   }
19403: }
19404: 
19405: /*
19406: **    date( TIMESTRING, MOD, MOD, ...)
19407: **
19408: ** Return YYYY-MM-DD
19409: */
19410: static void dateFunc(
19411:   sqlite3_context *context,
19412:   int argc,
19413:   sqlite3_value **argv
19414: ){
19415:   DateTime x;
19416:   if( isDate(context, argc, argv, &x)==0 ){
19417:     char zBuf[100];
19418:     computeYMD(&x);
19419:     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
19420:     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19421:   }
19422: }
19423: 
19424: /*
19425: **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
19426: **
19427: ** Return a string described by FORMAT.  Conversions as follows:
19428: **
19429: **   %d  day of month
19430: **   %f  ** fractional seconds  SS.SSS
19431: **   %H  hour 00-24
19432: **   %j  day of year 000-366
19433: **   %J  ** julian day number
19434: **   %m  month 01-12
19435: **   %M  minute 00-59
19436: **   %s  seconds since 1970-01-01
19437: **   %S  seconds 00-59
19438: **   %w  day of week 0-6  sunday==0
19439: **   %W  week of year 00-53
19440: **   %Y  year 0000-9999
19441: **   %%  %
19442: */
19443: static void strftimeFunc(
19444:   sqlite3_context *context,
19445:   int argc,
19446:   sqlite3_value **argv
19447: ){
19448:   DateTime x;
19449:   u64 n;
19450:   size_t i,j;
19451:   char *z;
19452:   sqlite3 *db;
19453:   const char *zFmt;
19454:   char zBuf[100];
19455:   if( argc==0 ) return;
19456:   zFmt = (const char*)sqlite3_value_text(argv[0]);
19457:   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
19458:   db = sqlite3_context_db_handle(context);
19459:   for(i=0, n=1; zFmt[i]; i++, n++){
19460:     if( zFmt[i]=='%' ){
19461:       switch( zFmt[i+1] ){
19462:         case 'd':
19463:         case 'H':
19464:         case 'm':
19465:         case 'M':
19466:         case 'S':
19467:         case 'W':
19468:           n++;
19469:           /* fall thru */
19470:         case 'w':
19471:         case '%':
19472:           break;
19473:         case 'f':
19474:           n += 8;
19475:           break;
19476:         case 'j':
19477:           n += 3;
19478:           break;
19479:         case 'Y':
19480:           n += 8;
19481:           break;
19482:         case 's':
19483:         case 'J':
19484:           n += 50;
19485:           break;
19486:         default:
19487:           return;  /* ERROR.  return a NULL */
19488:       }
19489:       i++;
19490:     }
19491:   }
19492:   testcase( n==sizeof(zBuf)-1 );
19493:   testcase( n==sizeof(zBuf) );
19494:   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
19495:   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
19496:   if( n<sizeof(zBuf) ){
19497:     z = zBuf;
19498:   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
19499:     sqlite3_result_error_toobig(context);
19500:     return;
19501:   }else{
19502:     z = sqlite3DbMallocRawNN(db, (int)n);
19503:     if( z==0 ){
19504:       sqlite3_result_error_nomem(context);
19505:       return;
19506:     }
19507:   }
19508:   computeJD(&x);
19509:   computeYMD_HMS(&x);
19510:   for(i=j=0; zFmt[i]; i++){
19511:     if( zFmt[i]!='%' ){
19512:       z[j++] = zFmt[i];
19513:     }else{
19514:       i++;
19515:       switch( zFmt[i] ){
19516:         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
19517:         case 'f': {
19518:           double s = x.s;
19519:           if( s>59.999 ) s = 59.999;
19520:           sqlite3_snprintf(7, &z[j],"%06.3f", s);
19521:           j += sqlite3Strlen30(&z[j]);
19522:           break;
19523:         }
19524:         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
19525:         case 'W': /* Fall thru */
19526:         case 'j': {
19527:           int nDay;             /* Number of days since 1st day of year */
19528:           DateTime y = x;
19529:           y.validJD = 0;
19530:           y.M = 1;
19531:           y.D = 1;
19532:           computeJD(&y);
19533:           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
19534:           if( zFmt[i]=='W' ){
19535:             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
19536:             wd = (int)(((x.iJD+43200000)/86400000)%7);
19537:             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
19538:             j += 2;
19539:           }else{
19540:             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
19541:             j += 3;
19542:           }
19543:           break;
19544:         }
19545:         case 'J': {
19546:           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
19547:           j+=sqlite3Strlen30(&z[j]);
19548:           break;
19549:         }
19550:         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
19551:         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
19552:         case 's': {
19553:           sqlite3_snprintf(30,&z[j],"%lld",
19554:                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
19555:           j += sqlite3Strlen30(&z[j]);
19556:           break;
19557:         }
19558:         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
19559:         case 'w': {
19560:           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
19561:           break;
19562:         }
19563:         case 'Y': {
19564:           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
19565:           break;
19566:         }
19567:         default:   z[j++] = '%'; break;
19568:       }
19569:     }
19570:   }
19571:   z[j] = 0;
19572:   sqlite3_result_text(context, z, -1,
19573:                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
19574: }
19575: 
19576: /*
19577: ** current_time()
19578: **
19579: ** This function returns the same value as time('now').
19580: */
19581: static void ctimeFunc(
19582:   sqlite3_context *context,
19583:   int NotUsed,
19584:   sqlite3_value **NotUsed2
19585: ){
19586:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
19587:   timeFunc(context, 0, 0);
19588: }
19589: 
19590: /*
19591: ** current_date()
19592: **
19593: ** This function returns the same value as date('now').
19594: */
19595: static void cdateFunc(
19596:   sqlite3_context *context,
19597:   int NotUsed,
19598:   sqlite3_value **NotUsed2
19599: ){
19600:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
19601:   dateFunc(context, 0, 0);
19602: }
19603: 
19604: /*
19605: ** current_timestamp()
19606: **
19607: ** This function returns the same value as datetime('now').
19608: */
19609: static void ctimestampFunc(
19610:   sqlite3_context *context,
19611:   int NotUsed,
19612:   sqlite3_value **NotUsed2
19613: ){
19614:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
19615:   datetimeFunc(context, 0, 0);
19616: }
19617: #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
19618: 
19619: #ifdef SQLITE_OMIT_DATETIME_FUNCS
19620: /*
19621: ** If the library is compiled to omit the full-scale date and time
19622: ** handling (to get a smaller binary), the following minimal version
19623: ** of the functions current_time(), current_date() and current_timestamp()
19624: ** are included instead. This is to support column declarations that
19625: ** include "DEFAULT CURRENT_TIME" etc.
19626: **
19627: ** This function uses the C-library functions time(), gmtime()
19628: ** and strftime(). The format string to pass to strftime() is supplied
19629: ** as the user-data for the function.
19630: */
19631: static void currentTimeFunc(
19632:   sqlite3_context *context,
19633:   int argc,
19634:   sqlite3_value **argv
19635: ){
19636:   time_t t;
19637:   char *zFormat = (char *)sqlite3_user_data(context);
19638:   sqlite3_int64 iT;
19639:   struct tm *pTm;
19640:   struct tm sNow;
19641:   char zBuf[20];
19642: 
19643:   UNUSED_PARAMETER(argc);
19644:   UNUSED_PARAMETER(argv);
19645: 
19646:   iT = sqlite3StmtCurrentTime(context);
19647:   if( iT<=0 ) return;
19648:   t = iT/1000 - 10000*(sqlite3_int64)21086676;
19649: #if HAVE_GMTIME_R
19650:   pTm = gmtime_r(&t, &sNow);
19651: #else
19652:   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19653:   pTm = gmtime(&t);
19654:   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
19655:   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
19656: #endif
19657:   if( pTm ){
19658:     strftime(zBuf, 20, zFormat, &sNow);
19659:     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19660:   }
19661: }
19662: #endif
19663: 
19664: /*
19665: ** This function registered all of the above C functions as SQL
19666: ** functions.  This should be the only routine in this file with
19667: ** external linkage.
19668: */
19669: SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
19670:   static FuncDef aDateTimeFuncs[] = {
19671: #ifndef SQLITE_OMIT_DATETIME_FUNCS
19672:     DFUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
19673:     DFUNCTION(date,             -1, 0, 0, dateFunc      ),
19674:     DFUNCTION(time,             -1, 0, 0, timeFunc      ),
19675:     DFUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
19676:     DFUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
19677:     DFUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
19678:     DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
19679:     DFUNCTION(current_date,      0, 0, 0, cdateFunc     ),
19680: #else
19681:     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
19682:     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
19683:     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
19684: #endif
19685:   };
19686:   sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
19687: }
19688: 
19689: /************** End of date.c ************************************************/
19690: /************** Begin file os.c **********************************************/
19691: /*
19692: ** 2005 November 29
19693: **
19694: ** The author disclaims copyright to this source code.  In place of
19695: ** a legal notice, here is a blessing:
19696: **
19697: **    May you do good and not evil.
19698: **    May you find forgiveness for yourself and forgive others.
19699: **    May you share freely, never taking more than you give.
19700: **
19701: ******************************************************************************
19702: **
19703: ** This file contains OS interface code that is common to all
19704: ** architectures.
19705: */
19706: /* #include "sqliteInt.h" */
19707: 
19708: /*
19709: ** If we compile with the SQLITE_TEST macro set, then the following block
19710: ** of code will give us the ability to simulate a disk I/O error.  This
19711: ** is used for testing the I/O recovery logic.
19712: */
19713: #if defined(SQLITE_TEST)
19714: SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
19715: SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
19716: SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
19717: SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
19718: SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
19719: SQLITE_API int sqlite3_diskfull_pending = 0;
19720: SQLITE_API int sqlite3_diskfull = 0;
19721: #endif /* defined(SQLITE_TEST) */
19722: 
19723: /*
19724: ** When testing, also keep a count of the number of open files.
19725: */
19726: #if defined(SQLITE_TEST)
19727: SQLITE_API int sqlite3_open_file_count = 0;
19728: #endif /* defined(SQLITE_TEST) */
19729: 
19730: /*
19731: ** The default SQLite sqlite3_vfs implementations do not allocate
19732: ** memory (actually, os_unix.c allocates a small amount of memory
19733: ** from within OsOpen()), but some third-party implementations may.
19734: ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
19735: ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
19736: **
19737: ** The following functions are instrumented for malloc() failure
19738: ** testing:
19739: **
19740: **     sqlite3OsRead()
19741: **     sqlite3OsWrite()
19742: **     sqlite3OsSync()
19743: **     sqlite3OsFileSize()
19744: **     sqlite3OsLock()
19745: **     sqlite3OsCheckReservedLock()
19746: **     sqlite3OsFileControl()
19747: **     sqlite3OsShmMap()
19748: **     sqlite3OsOpen()
19749: **     sqlite3OsDelete()
19750: **     sqlite3OsAccess()
19751: **     sqlite3OsFullPathname()
19752: **
19753: */
19754: #if defined(SQLITE_TEST)
19755: SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
19756:   #define DO_OS_MALLOC_TEST(x)                                       \
19757:   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
19758:     void *pTstAlloc = sqlite3Malloc(10);                             \
19759:     if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT;                  \
19760:     sqlite3_free(pTstAlloc);                                         \
19761:   }
19762: #else
19763:   #define DO_OS_MALLOC_TEST(x)
19764: #endif
19765: 
19766: /*
19767: ** The following routines are convenience wrappers around methods
19768: ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
19769: ** of this would be completely automatic if SQLite were coded using
19770: ** C++ instead of plain old C.
19771: */
19772: SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
19773:   if( pId->pMethods ){
19774:     pId->pMethods->xClose(pId);
19775:     pId->pMethods = 0;
19776:   }
19777: }
19778: SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
19779:   DO_OS_MALLOC_TEST(id);
19780:   return id->pMethods->xRead(id, pBuf, amt, offset);
19781: }
19782: SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
19783:   DO_OS_MALLOC_TEST(id);
19784:   return id->pMethods->xWrite(id, pBuf, amt, offset);
19785: }
19786: SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
19787:   return id->pMethods->xTruncate(id, size);
19788: }
19789: SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
19790:   DO_OS_MALLOC_TEST(id);
19791:   return id->pMethods->xSync(id, flags);
19792: }
19793: SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
19794:   DO_OS_MALLOC_TEST(id);
19795:   return id->pMethods->xFileSize(id, pSize);
19796: }
19797: SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
19798:   DO_OS_MALLOC_TEST(id);
19799:   return id->pMethods->xLock(id, lockType);
19800: }
19801: SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
19802:   return id->pMethods->xUnlock(id, lockType);
19803: }
19804: SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
19805:   DO_OS_MALLOC_TEST(id);
19806:   return id->pMethods->xCheckReservedLock(id, pResOut);
19807: }
19808: 
19809: /*
19810: ** Use sqlite3OsFileControl() when we are doing something that might fail
19811: ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
19812: ** when simply tossing information over the wall to the VFS and we do not
19813: ** really care if the VFS receives and understands the information since it
19814: ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
19815: ** routine has no return value since the return value would be meaningless.
19816: */
19817: SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
19818: #ifdef SQLITE_TEST
19819:   if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
19820:     /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
19821:     ** is using a regular VFS, it is called after the corresponding
19822:     ** transaction has been committed. Injecting a fault at this point
19823:     ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
19824:     ** but the transaction is committed anyway.
19825:     **
19826:     ** The core must call OsFileControl() though, not OsFileControlHint(),
19827:     ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
19828:     ** means the commit really has failed and an error should be returned
19829:     ** to the user.  */
19830:     DO_OS_MALLOC_TEST(id);
19831:   }
19832: #endif
19833:   return id->pMethods->xFileControl(id, op, pArg);
19834: }
19835: SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
19836:   (void)id->pMethods->xFileControl(id, op, pArg);
19837: }
19838: 
19839: SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
19840:   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
19841:   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
19842: }
19843: SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
19844:   return id->pMethods->xDeviceCharacteristics(id);
19845: }
19846: SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
19847:   return id->pMethods->xShmLock(id, offset, n, flags);
19848: }
19849: SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
19850:   id->pMethods->xShmBarrier(id);
19851: }
19852: SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
19853:   return id->pMethods->xShmUnmap(id, deleteFlag);
19854: }
19855: SQLITE_PRIVATE int sqlite3OsShmMap(
19856:   sqlite3_file *id,               /* Database file handle */
19857:   int iPage,
19858:   int pgsz,
19859:   int bExtend,                    /* True to extend file if necessary */
19860:   void volatile **pp              /* OUT: Pointer to mapping */
19861: ){
19862:   DO_OS_MALLOC_TEST(id);
19863:   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
19864: }
19865: 
19866: #if SQLITE_MAX_MMAP_SIZE>0
19867: /* The real implementation of xFetch and xUnfetch */
19868: SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19869:   DO_OS_MALLOC_TEST(id);
19870:   return id->pMethods->xFetch(id, iOff, iAmt, pp);
19871: }
19872: SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19873:   return id->pMethods->xUnfetch(id, iOff, p);
19874: }
19875: #else
19876: /* No-op stubs to use when memory-mapped I/O is disabled */
19877: SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19878:   *pp = 0;
19879:   return SQLITE_OK;
19880: }
19881: SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19882:   return SQLITE_OK;
19883: }
19884: #endif
19885: 
19886: /*
19887: ** The next group of routines are convenience wrappers around the
19888: ** VFS methods.
19889: */
19890: SQLITE_PRIVATE int sqlite3OsOpen(
19891:   sqlite3_vfs *pVfs,
19892:   const char *zPath,
19893:   sqlite3_file *pFile,
19894:   int flags,
19895:   int *pFlagsOut
19896: ){
19897:   int rc;
19898:   DO_OS_MALLOC_TEST(0);
19899:   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
19900:   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
19901:   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
19902:   ** reaching the VFS. */
19903:   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
19904:   assert( rc==SQLITE_OK || pFile->pMethods==0 );
19905:   return rc;
19906: }
19907: SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
19908:   DO_OS_MALLOC_TEST(0);
19909:   assert( dirSync==0 || dirSync==1 );
19910:   return pVfs->xDelete(pVfs, zPath, dirSync);
19911: }
19912: SQLITE_PRIVATE int sqlite3OsAccess(
19913:   sqlite3_vfs *pVfs,
19914:   const char *zPath,
19915:   int flags,
19916:   int *pResOut
19917: ){
19918:   DO_OS_MALLOC_TEST(0);
19919:   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
19920: }
19921: SQLITE_PRIVATE int sqlite3OsFullPathname(
19922:   sqlite3_vfs *pVfs,
19923:   const char *zPath,
19924:   int nPathOut,
19925:   char *zPathOut
19926: ){
19927:   DO_OS_MALLOC_TEST(0);
19928:   zPathOut[0] = 0;
19929:   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
19930: }
19931: #ifndef SQLITE_OMIT_LOAD_EXTENSION
19932: SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
19933:   return pVfs->xDlOpen(pVfs, zPath);
19934: }
19935: SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19936:   pVfs->xDlError(pVfs, nByte, zBufOut);
19937: }
19938: SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
19939:   return pVfs->xDlSym(pVfs, pHdle, zSym);
19940: }
19941: SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
19942:   pVfs->xDlClose(pVfs, pHandle);
19943: }
19944: #endif /* SQLITE_OMIT_LOAD_EXTENSION */
19945: SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19946:   return pVfs->xRandomness(pVfs, nByte, zBufOut);
19947: }
19948: SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
19949:   return pVfs->xSleep(pVfs, nMicro);
19950: }
19951: SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
19952:   return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
19953: }
19954: SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
19955:   int rc;
19956:   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
19957:   ** method to get the current date and time if that method is available
19958:   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
19959:   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
19960:   ** unavailable.
19961:   */
19962:   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
19963:     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
19964:   }else{
19965:     double r;
19966:     rc = pVfs->xCurrentTime(pVfs, &r);
19967:     *pTimeOut = (sqlite3_int64)(r*86400000.0);
19968:   }
19969:   return rc;
19970: }
19971: 
19972: SQLITE_PRIVATE int sqlite3OsOpenMalloc(
19973:   sqlite3_vfs *pVfs,
19974:   const char *zFile,
19975:   sqlite3_file **ppFile,
19976:   int flags,
19977:   int *pOutFlags
19978: ){
19979:   int rc;
19980:   sqlite3_file *pFile;
19981:   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
19982:   if( pFile ){
19983:     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
19984:     if( rc!=SQLITE_OK ){
19985:       sqlite3_free(pFile);
19986:     }else{
19987:       *ppFile = pFile;
19988:     }
19989:   }else{
19990:     rc = SQLITE_NOMEM_BKPT;
19991:   }
19992:   return rc;
19993: }
19994: SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
19995:   assert( pFile );
19996:   sqlite3OsClose(pFile);
19997:   sqlite3_free(pFile);
19998: }
19999: 
20000: /*
20001: ** This function is a wrapper around the OS specific implementation of
20002: ** sqlite3_os_init(). The purpose of the wrapper is to provide the
20003: ** ability to simulate a malloc failure, so that the handling of an
20004: ** error in sqlite3_os_init() by the upper layers can be tested.
20005: */
20006: SQLITE_PRIVATE int sqlite3OsInit(void){
20007:   void *p = sqlite3_malloc(10);
20008:   if( p==0 ) return SQLITE_NOMEM_BKPT;
20009:   sqlite3_free(p);
20010:   return sqlite3_os_init();
20011: }
20012: 
20013: /*
20014: ** The list of all registered VFS implementations.
20015: */
20016: static sqlite3_vfs * SQLITE_WSD vfsList = 0;
20017: #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
20018: 
20019: /*
20020: ** Locate a VFS by name.  If no name is given, simply return the
20021: ** first VFS on the list.
20022: */
20023: SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
20024:   sqlite3_vfs *pVfs = 0;
20025: #if SQLITE_THREADSAFE
20026:   sqlite3_mutex *mutex;
20027: #endif
20028: #ifndef SQLITE_OMIT_AUTOINIT
20029:   int rc = sqlite3_initialize();
20030:   if( rc ) return 0;
20031: #endif
20032: #if SQLITE_THREADSAFE
20033:   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20034: #endif
20035:   sqlite3_mutex_enter(mutex);
20036:   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
20037:     if( zVfs==0 ) break;
20038:     if( strcmp(zVfs, pVfs->zName)==0 ) break;
20039:   }
20040:   sqlite3_mutex_leave(mutex);
20041:   return pVfs;
20042: }
20043: 
20044: /*
20045: ** Unlink a VFS from the linked list
20046: */
20047: static void vfsUnlink(sqlite3_vfs *pVfs){
20048:   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
20049:   if( pVfs==0 ){
20050:     /* No-op */
20051:   }else if( vfsList==pVfs ){
20052:     vfsList = pVfs->pNext;
20053:   }else if( vfsList ){
20054:     sqlite3_vfs *p = vfsList;
20055:     while( p->pNext && p->pNext!=pVfs ){
20056:       p = p->pNext;
20057:     }
20058:     if( p->pNext==pVfs ){
20059:       p->pNext = pVfs->pNext;
20060:     }
20061:   }
20062: }
20063: 
20064: /*
20065: ** Register a VFS with the system.  It is harmless to register the same
20066: ** VFS multiple times.  The new VFS becomes the default if makeDflt is
20067: ** true.
20068: */
20069: SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
20070:   MUTEX_LOGIC(sqlite3_mutex *mutex;)
20071: #ifndef SQLITE_OMIT_AUTOINIT
20072:   int rc = sqlite3_initialize();
20073:   if( rc ) return rc;
20074: #endif
20075: #ifdef SQLITE_ENABLE_API_ARMOR
20076:   if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
20077: #endif
20078: 
20079:   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
20080:   sqlite3_mutex_enter(mutex);
20081:   vfsUnlink(pVfs);
20082:   if( makeDflt || vfsList==0 ){
20083:     pVfs->pNext = vfsList;
20084:     vfsList = pVfs;
20085:   }else{
20086:     pVfs->pNext = vfsList->pNext;
20087:     vfsList->pNext = pVfs;
20088:   }
20089:   assert(vfsList);
20090:   sqlite3_mutex_leave(mutex);
20091:   return SQLITE_OK;
20092: }
20093: 
20094: /*
20095: ** Unregister a VFS so that it is no longer accessible.
20096: */
20097: SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
20098: #if SQLITE_THREADSAFE
20099:   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
20100: #endif
20101:   sqlite3_mutex_enter(mutex);
20102:   vfsUnlink(pVfs);
20103:   sqlite3_mutex_leave(mutex);
20104:   return SQLITE_OK;
20105: }
20106: 
20107: /************** End of os.c **************************************************/
20108: /************** Begin file fault.c *******************************************/
20109: /*
20110: ** 2008 Jan 22
20111: **
20112: ** The author disclaims copyright to this source code.  In place of
20113: ** a legal notice, here is a blessing:
20114: **
20115: **    May you do good and not evil.
20116: **    May you find forgiveness for yourself and forgive others.
20117: **    May you share freely, never taking more than you give.
20118: **
20119: *************************************************************************
20120: **
20121: ** This file contains code to support the concept of "benign" 
20122: ** malloc failures (when the xMalloc() or xRealloc() method of the
20123: ** sqlite3_mem_methods structure fails to allocate a block of memory
20124: ** and returns 0). 
20125: **
20126: ** Most malloc failures are non-benign. After they occur, SQLite
20127: ** abandons the current operation and returns an error code (usually
20128: ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
20129: ** fatal. For example, if a malloc fails while resizing a hash table, this 
20130: ** is completely recoverable simply by not carrying out the resize. The 
20131: ** hash table will continue to function normally.  So a malloc failure 
20132: ** during a hash table resize is a benign fault.
20133: */
20134: 
20135: /* #include "sqliteInt.h" */
20136: 
20137: #ifndef SQLITE_OMIT_BUILTIN_TEST
20138: 
20139: /*
20140: ** Global variables.
20141: */
20142: typedef struct BenignMallocHooks BenignMallocHooks;
20143: static SQLITE_WSD struct BenignMallocHooks {
20144:   void (*xBenignBegin)(void);
20145:   void (*xBenignEnd)(void);
20146: } sqlite3Hooks = { 0, 0 };
20147: 
20148: /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
20149: ** structure.  If writable static data is unsupported on the target,
20150: ** we have to locate the state vector at run-time.  In the more common
20151: ** case where writable static data is supported, wsdHooks can refer directly
20152: ** to the "sqlite3Hooks" state vector declared above.
20153: */
20154: #ifdef SQLITE_OMIT_WSD
20155: # define wsdHooksInit \
20156:   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
20157: # define wsdHooks x[0]
20158: #else
20159: # define wsdHooksInit
20160: # define wsdHooks sqlite3Hooks
20161: #endif
20162: 
20163: 
20164: /*
20165: ** Register hooks to call when sqlite3BeginBenignMalloc() and
20166: ** sqlite3EndBenignMalloc() are called, respectively.
20167: */
20168: SQLITE_PRIVATE void sqlite3BenignMallocHooks(
20169:   void (*xBenignBegin)(void),
20170:   void (*xBenignEnd)(void)
20171: ){
20172:   wsdHooksInit;
20173:   wsdHooks.xBenignBegin = xBenignBegin;
20174:   wsdHooks.xBenignEnd = xBenignEnd;
20175: }
20176: 
20177: /*
20178: ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
20179: ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
20180: ** indicates that subsequent malloc failures are non-benign.
20181: */
20182: SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
20183:   wsdHooksInit;
20184:   if( wsdHooks.xBenignBegin ){
20185:     wsdHooks.xBenignBegin();
20186:   }
20187: }
20188: SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
20189:   wsdHooksInit;
20190:   if( wsdHooks.xBenignEnd ){
20191:     wsdHooks.xBenignEnd();
20192:   }
20193: }
20194: 
20195: #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
20196: 
20197: /************** End of fault.c ***********************************************/
20198: /************** Begin file mem0.c ********************************************/
20199: /*
20200: ** 2008 October 28
20201: **
20202: ** The author disclaims copyright to this source code.  In place of
20203: ** a legal notice, here is a blessing:
20204: **
20205: **    May you do good and not evil.
20206: **    May you find forgiveness for yourself and forgive others.
20207: **    May you share freely, never taking more than you give.
20208: **
20209: *************************************************************************
20210: **
20211: ** This file contains a no-op memory allocation drivers for use when
20212: ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
20213: ** here always fail.  SQLite will not operate with these drivers.  These
20214: ** are merely placeholders.  Real drivers must be substituted using
20215: ** sqlite3_config() before SQLite will operate.
20216: */
20217: /* #include "sqliteInt.h" */
20218: 
20219: /*
20220: ** This version of the memory allocator is the default.  It is
20221: ** used when no other memory allocator is specified using compile-time
20222: ** macros.
20223: */
20224: #ifdef SQLITE_ZERO_MALLOC
20225: 
20226: /*
20227: ** No-op versions of all memory allocation routines
20228: */
20229: static void *sqlite3MemMalloc(int nByte){ return 0; }
20230: static void sqlite3MemFree(void *pPrior){ return; }
20231: static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
20232: static int sqlite3MemSize(void *pPrior){ return 0; }
20233: static int sqlite3MemRoundup(int n){ return n; }
20234: static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
20235: static void sqlite3MemShutdown(void *NotUsed){ return; }
20236: 
20237: /*
20238: ** This routine is the only routine in this file with external linkage.
20239: **
20240: ** Populate the low-level memory allocation function pointers in
20241: ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20242: */
20243: SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20244:   static const sqlite3_mem_methods defaultMethods = {
20245:      sqlite3MemMalloc,
20246:      sqlite3MemFree,
20247:      sqlite3MemRealloc,
20248:      sqlite3MemSize,
20249:      sqlite3MemRoundup,
20250:      sqlite3MemInit,
20251:      sqlite3MemShutdown,
20252:      0
20253:   };
20254:   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20255: }
20256: 
20257: #endif /* SQLITE_ZERO_MALLOC */
20258: 
20259: /************** End of mem0.c ************************************************/
20260: /************** Begin file mem1.c ********************************************/
20261: /*
20262: ** 2007 August 14
20263: **
20264: ** The author disclaims copyright to this source code.  In place of
20265: ** a legal notice, here is a blessing:
20266: **
20267: **    May you do good and not evil.
20268: **    May you find forgiveness for yourself and forgive others.
20269: **    May you share freely, never taking more than you give.
20270: **
20271: *************************************************************************
20272: **
20273: ** This file contains low-level memory allocation drivers for when
20274: ** SQLite will use the standard C-library malloc/realloc/free interface
20275: ** to obtain the memory it needs.
20276: **
20277: ** This file contains implementations of the low-level memory allocation
20278: ** routines specified in the sqlite3_mem_methods object.  The content of
20279: ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
20280: ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
20281: ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
20282: ** default configuration is to use memory allocation routines in this
20283: ** file.
20284: **
20285: ** C-preprocessor macro summary:
20286: **
20287: **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
20288: **                                the malloc_usable_size() interface exists
20289: **                                on the target platform.  Or, this symbol
20290: **                                can be set manually, if desired.
20291: **                                If an equivalent interface exists by
20292: **                                a different name, using a separate -D
20293: **                                option to rename it.
20294: **
20295: **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
20296: **                                memory allocator.  Set this symbol to enable
20297: **                                building on older macs.
20298: **
20299: **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
20300: **                                _msize() on windows systems.  This might
20301: **                                be necessary when compiling for Delphi,
20302: **                                for example.
20303: */
20304: /* #include "sqliteInt.h" */
20305: 
20306: /*
20307: ** This version of the memory allocator is the default.  It is
20308: ** used when no other memory allocator is specified using compile-time
20309: ** macros.
20310: */
20311: #ifdef SQLITE_SYSTEM_MALLOC
20312: #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20313: 
20314: /*
20315: ** Use the zone allocator available on apple products unless the
20316: ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
20317: */
20318: #include <sys/sysctl.h>
20319: #include <malloc/malloc.h>
20320: #include <libkern/OSAtomic.h>
20321: static malloc_zone_t* _sqliteZone_;
20322: #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
20323: #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
20324: #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
20325: #define SQLITE_MALLOCSIZE(x) \
20326:         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
20327: 
20328: #else /* if not __APPLE__ */
20329: 
20330: /*
20331: ** Use standard C library malloc and free on non-Apple systems.  
20332: ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
20333: */
20334: #define SQLITE_MALLOC(x)             malloc(x)
20335: #define SQLITE_FREE(x)               free(x)
20336: #define SQLITE_REALLOC(x,y)          realloc((x),(y))
20337: 
20338: /*
20339: ** The malloc.h header file is needed for malloc_usable_size() function
20340: ** on some systems (e.g. Linux).
20341: */
20342: #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
20343: #  define SQLITE_USE_MALLOC_H 1
20344: #  define SQLITE_USE_MALLOC_USABLE_SIZE 1
20345: /*
20346: ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
20347: ** use of _msize() is automatic, but can be disabled by compiling with
20348: ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
20349: ** the malloc.h header file.
20350: */
20351: #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
20352: #  define SQLITE_USE_MALLOC_H
20353: #  define SQLITE_USE_MSIZE
20354: #endif
20355: 
20356: /*
20357: ** Include the malloc.h header file, if necessary.  Also set define macro
20358: ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
20359: ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
20360: ** The memory size function can always be overridden manually by defining
20361: ** the macro SQLITE_MALLOCSIZE to the desired function name.
20362: */
20363: #if defined(SQLITE_USE_MALLOC_H)
20364: #  include <malloc.h>
20365: #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
20366: #    if !defined(SQLITE_MALLOCSIZE)
20367: #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
20368: #    endif
20369: #  elif defined(SQLITE_USE_MSIZE)
20370: #    if !defined(SQLITE_MALLOCSIZE)
20371: #      define SQLITE_MALLOCSIZE      _msize
20372: #    endif
20373: #  endif
20374: #endif /* defined(SQLITE_USE_MALLOC_H) */
20375: 
20376: #endif /* __APPLE__ or not __APPLE__ */
20377: 
20378: /*
20379: ** Like malloc(), but remember the size of the allocation
20380: ** so that we can find it later using sqlite3MemSize().
20381: **
20382: ** For this low-level routine, we are guaranteed that nByte>0 because
20383: ** cases of nByte<=0 will be intercepted and dealt with by higher level
20384: ** routines.
20385: */
20386: static void *sqlite3MemMalloc(int nByte){
20387: #ifdef SQLITE_MALLOCSIZE
20388:   void *p = SQLITE_MALLOC( nByte );
20389:   if( p==0 ){
20390:     testcase( sqlite3GlobalConfig.xLog!=0 );
20391:     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20392:   }
20393:   return p;
20394: #else
20395:   sqlite3_int64 *p;
20396:   assert( nByte>0 );
20397:   nByte = ROUND8(nByte);
20398:   p = SQLITE_MALLOC( nByte+8 );
20399:   if( p ){
20400:     p[0] = nByte;
20401:     p++;
20402:   }else{
20403:     testcase( sqlite3GlobalConfig.xLog!=0 );
20404:     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20405:   }
20406:   return (void *)p;
20407: #endif
20408: }
20409: 
20410: /*
20411: ** Like free() but works for allocations obtained from sqlite3MemMalloc()
20412: ** or sqlite3MemRealloc().
20413: **
20414: ** For this low-level routine, we already know that pPrior!=0 since
20415: ** cases where pPrior==0 will have been intecepted and dealt with
20416: ** by higher-level routines.
20417: */
20418: static void sqlite3MemFree(void *pPrior){
20419: #ifdef SQLITE_MALLOCSIZE
20420:   SQLITE_FREE(pPrior);
20421: #else
20422:   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20423:   assert( pPrior!=0 );
20424:   p--;
20425:   SQLITE_FREE(p);
20426: #endif
20427: }
20428: 
20429: /*
20430: ** Report the allocated size of a prior return from xMalloc()
20431: ** or xRealloc().
20432: */
20433: static int sqlite3MemSize(void *pPrior){
20434: #ifdef SQLITE_MALLOCSIZE
20435:   assert( pPrior!=0 );
20436:   return (int)SQLITE_MALLOCSIZE(pPrior);
20437: #else
20438:   sqlite3_int64 *p;
20439:   assert( pPrior!=0 );
20440:   p = (sqlite3_int64*)pPrior;
20441:   p--;
20442:   return (int)p[0];
20443: #endif
20444: }
20445: 
20446: /*
20447: ** Like realloc().  Resize an allocation previously obtained from
20448: ** sqlite3MemMalloc().
20449: **
20450: ** For this low-level interface, we know that pPrior!=0.  Cases where
20451: ** pPrior==0 while have been intercepted by higher-level routine and
20452: ** redirected to xMalloc.  Similarly, we know that nByte>0 because
20453: ** cases where nByte<=0 will have been intercepted by higher-level
20454: ** routines and redirected to xFree.
20455: */
20456: static void *sqlite3MemRealloc(void *pPrior, int nByte){
20457: #ifdef SQLITE_MALLOCSIZE
20458:   void *p = SQLITE_REALLOC(pPrior, nByte);
20459:   if( p==0 ){
20460:     testcase( sqlite3GlobalConfig.xLog!=0 );
20461:     sqlite3_log(SQLITE_NOMEM,
20462:       "failed memory resize %u to %u bytes",
20463:       SQLITE_MALLOCSIZE(pPrior), nByte);
20464:   }
20465:   return p;
20466: #else
20467:   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20468:   assert( pPrior!=0 && nByte>0 );
20469:   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
20470:   p--;
20471:   p = SQLITE_REALLOC(p, nByte+8 );
20472:   if( p ){
20473:     p[0] = nByte;
20474:     p++;
20475:   }else{
20476:     testcase( sqlite3GlobalConfig.xLog!=0 );
20477:     sqlite3_log(SQLITE_NOMEM,
20478:       "failed memory resize %u to %u bytes",
20479:       sqlite3MemSize(pPrior), nByte);
20480:   }
20481:   return (void*)p;
20482: #endif
20483: }
20484: 
20485: /*
20486: ** Round up a request size to the next valid allocation size.
20487: */
20488: static int sqlite3MemRoundup(int n){
20489:   return ROUND8(n);
20490: }
20491: 
20492: /*
20493: ** Initialize this module.
20494: */
20495: static int sqlite3MemInit(void *NotUsed){
20496: #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20497:   int cpuCount;
20498:   size_t len;
20499:   if( _sqliteZone_ ){
20500:     return SQLITE_OK;
20501:   }
20502:   len = sizeof(cpuCount);
20503:   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
20504:   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
20505:   if( cpuCount>1 ){
20506:     /* defer MT decisions to system malloc */
20507:     _sqliteZone_ = malloc_default_zone();
20508:   }else{
20509:     /* only 1 core, use our own zone to contention over global locks, 
20510:     ** e.g. we have our own dedicated locks */
20511:     bool success;
20512:     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
20513:     malloc_set_zone_name(newzone, "Sqlite_Heap");
20514:     do{
20515:       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
20516:                                  (void * volatile *)&_sqliteZone_);
20517:     }while(!_sqliteZone_);
20518:     if( !success ){
20519:       /* somebody registered a zone first */
20520:       malloc_destroy_zone(newzone);
20521:     }
20522:   }
20523: #endif
20524:   UNUSED_PARAMETER(NotUsed);
20525:   return SQLITE_OK;
20526: }
20527: 
20528: /*
20529: ** Deinitialize this module.
20530: */
20531: static void sqlite3MemShutdown(void *NotUsed){
20532:   UNUSED_PARAMETER(NotUsed);
20533:   return;
20534: }
20535: 
20536: /*
20537: ** This routine is the only routine in this file with external linkage.
20538: **
20539: ** Populate the low-level memory allocation function pointers in
20540: ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20541: */
20542: SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20543:   static const sqlite3_mem_methods defaultMethods = {
20544:      sqlite3MemMalloc,
20545:      sqlite3MemFree,
20546:      sqlite3MemRealloc,
20547:      sqlite3MemSize,
20548:      sqlite3MemRoundup,
20549:      sqlite3MemInit,
20550:      sqlite3MemShutdown,
20551:      0
20552:   };
20553:   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20554: }
20555: 
20556: #endif /* SQLITE_SYSTEM_MALLOC */
20557: 
20558: /************** End of mem1.c ************************************************/
20559: /************** Begin file mem2.c ********************************************/
20560: /*
20561: ** 2007 August 15
20562: **
20563: ** The author disclaims copyright to this source code.  In place of
20564: ** a legal notice, here is a blessing:
20565: **
20566: **    May you do good and not evil.
20567: **    May you find forgiveness for yourself and forgive others.
20568: **    May you share freely, never taking more than you give.
20569: **
20570: *************************************************************************
20571: **
20572: ** This file contains low-level memory allocation drivers for when
20573: ** SQLite will use the standard C-library malloc/realloc/free interface
20574: ** to obtain the memory it needs while adding lots of additional debugging
20575: ** information to each allocation in order to help detect and fix memory
20576: ** leaks and memory usage errors.
20577: **
20578: ** This file contains implementations of the low-level memory allocation
20579: ** routines specified in the sqlite3_mem_methods object.
20580: */
20581: /* #include "sqliteInt.h" */
20582: 
20583: /*
20584: ** This version of the memory allocator is used only if the
20585: ** SQLITE_MEMDEBUG macro is defined
20586: */
20587: #ifdef SQLITE_MEMDEBUG
20588: 
20589: /*
20590: ** The backtrace functionality is only available with GLIBC
20591: */
20592: #ifdef __GLIBC__
20593:   extern int backtrace(void**,int);
20594:   extern void backtrace_symbols_fd(void*const*,int,int);
20595: #else
20596: # define backtrace(A,B) 1
20597: # define backtrace_symbols_fd(A,B,C)
20598: #endif
20599: /* #include <stdio.h> */
20600: 
20601: /*
20602: ** Each memory allocation looks like this:
20603: **
20604: **  ------------------------------------------------------------------------
20605: **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
20606: **  ------------------------------------------------------------------------
20607: **
20608: ** The application code sees only a pointer to the allocation.  We have
20609: ** to back up from the allocation pointer to find the MemBlockHdr.  The
20610: ** MemBlockHdr tells us the size of the allocation and the number of
20611: ** backtrace pointers.  There is also a guard word at the end of the
20612: ** MemBlockHdr.
20613: */
20614: struct MemBlockHdr {
20615:   i64 iSize;                          /* Size of this allocation */
20616:   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
20617:   char nBacktrace;                    /* Number of backtraces on this alloc */
20618:   char nBacktraceSlots;               /* Available backtrace slots */
20619:   u8 nTitle;                          /* Bytes of title; includes '\0' */
20620:   u8 eType;                           /* Allocation type code */
20621:   int iForeGuard;                     /* Guard word for sanity */
20622: };
20623: 
20624: /*
20625: ** Guard words
20626: */
20627: #define FOREGUARD 0x80F5E153
20628: #define REARGUARD 0xE4676B53
20629: 
20630: /*
20631: ** Number of malloc size increments to track.
20632: */
20633: #define NCSIZE  1000
20634: 
20635: /*
20636: ** All of the static variables used by this module are collected
20637: ** into a single structure named "mem".  This is to keep the
20638: ** static variables organized and to reduce namespace pollution
20639: ** when this module is combined with other in the amalgamation.
20640: */
20641: static struct {
20642:   
20643:   /*
20644:   ** Mutex to control access to the memory allocation subsystem.
20645:   */
20646:   sqlite3_mutex *mutex;
20647: 
20648:   /*
20649:   ** Head and tail of a linked list of all outstanding allocations
20650:   */
20651:   struct MemBlockHdr *pFirst;
20652:   struct MemBlockHdr *pLast;
20653:   
20654:   /*
20655:   ** The number of levels of backtrace to save in new allocations.
20656:   */
20657:   int nBacktrace;
20658:   void (*xBacktrace)(int, int, void **);
20659: 
20660:   /*
20661:   ** Title text to insert in front of each block
20662:   */
20663:   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
20664:   char zTitle[100];  /* The title text */
20665: 
20666:   /* 
20667:   ** sqlite3MallocDisallow() increments the following counter.
20668:   ** sqlite3MallocAllow() decrements it.
20669:   */
20670:   int disallow; /* Do not allow memory allocation */
20671: 
20672:   /*
20673:   ** Gather statistics on the sizes of memory allocations.
20674:   ** nAlloc[i] is the number of allocation attempts of i*8
20675:   ** bytes.  i==NCSIZE is the number of allocation attempts for
20676:   ** sizes more than NCSIZE*8 bytes.
20677:   */
20678:   int nAlloc[NCSIZE];      /* Total number of allocations */
20679:   int nCurrent[NCSIZE];    /* Current number of allocations */
20680:   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
20681: 
20682: } mem;
20683: 
20684: 
20685: /*
20686: ** Adjust memory usage statistics
20687: */
20688: static void adjustStats(int iSize, int increment){
20689:   int i = ROUND8(iSize)/8;
20690:   if( i>NCSIZE-1 ){
20691:     i = NCSIZE - 1;
20692:   }
20693:   if( increment>0 ){
20694:     mem.nAlloc[i]++;
20695:     mem.nCurrent[i]++;
20696:     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
20697:       mem.mxCurrent[i] = mem.nCurrent[i];
20698:     }
20699:   }else{
20700:     mem.nCurrent[i]--;
20701:     assert( mem.nCurrent[i]>=0 );
20702:   }
20703: }
20704: 
20705: /*
20706: ** Given an allocation, find the MemBlockHdr for that allocation.
20707: **
20708: ** This routine checks the guards at either end of the allocation and
20709: ** if they are incorrect it asserts.
20710: */
20711: static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
20712:   struct MemBlockHdr *p;
20713:   int *pInt;
20714:   u8 *pU8;
20715:   int nReserve;
20716: 
20717:   p = (struct MemBlockHdr*)pAllocation;
20718:   p--;
20719:   assert( p->iForeGuard==(int)FOREGUARD );
20720:   nReserve = ROUND8(p->iSize);
20721:   pInt = (int*)pAllocation;
20722:   pU8 = (u8*)pAllocation;
20723:   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
20724:   /* This checks any of the "extra" bytes allocated due
20725:   ** to rounding up to an 8 byte boundary to ensure 
20726:   ** they haven't been overwritten.
20727:   */
20728:   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
20729:   return p;
20730: }
20731: 
20732: /*
20733: ** Return the number of bytes currently allocated at address p.
20734: */
20735: static int sqlite3MemSize(void *p){
20736:   struct MemBlockHdr *pHdr;
20737:   if( !p ){
20738:     return 0;
20739:   }
20740:   pHdr = sqlite3MemsysGetHeader(p);
20741:   return (int)pHdr->iSize;
20742: }
20743: 
20744: /*
20745: ** Initialize the memory allocation subsystem.
20746: */
20747: static int sqlite3MemInit(void *NotUsed){
20748:   UNUSED_PARAMETER(NotUsed);
20749:   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
20750:   if( !sqlite3GlobalConfig.bMemstat ){
20751:     /* If memory status is enabled, then the malloc.c wrapper will already
20752:     ** hold the STATIC_MEM mutex when the routines here are invoked. */
20753:     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20754:   }
20755:   return SQLITE_OK;
20756: }
20757: 
20758: /*
20759: ** Deinitialize the memory allocation subsystem.
20760: */
20761: static void sqlite3MemShutdown(void *NotUsed){
20762:   UNUSED_PARAMETER(NotUsed);
20763:   mem.mutex = 0;
20764: }
20765: 
20766: /*
20767: ** Round up a request size to the next valid allocation size.
20768: */
20769: static int sqlite3MemRoundup(int n){
20770:   return ROUND8(n);
20771: }
20772: 
20773: /*
20774: ** Fill a buffer with pseudo-random bytes.  This is used to preset
20775: ** the content of a new memory allocation to unpredictable values and
20776: ** to clear the content of a freed allocation to unpredictable values.
20777: */
20778: static void randomFill(char *pBuf, int nByte){
20779:   unsigned int x, y, r;
20780:   x = SQLITE_PTR_TO_INT(pBuf);
20781:   y = nByte | 1;
20782:   while( nByte >= 4 ){
20783:     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20784:     y = y*1103515245 + 12345;
20785:     r = x ^ y;
20786:     *(int*)pBuf = r;
20787:     pBuf += 4;
20788:     nByte -= 4;
20789:   }
20790:   while( nByte-- > 0 ){
20791:     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20792:     y = y*1103515245 + 12345;
20793:     r = x ^ y;
20794:     *(pBuf++) = r & 0xff;
20795:   }
20796: }
20797: 
20798: /*
20799: ** Allocate nByte bytes of memory.
20800: */
20801: static void *sqlite3MemMalloc(int nByte){
20802:   struct MemBlockHdr *pHdr;
20803:   void **pBt;
20804:   char *z;
20805:   int *pInt;
20806:   void *p = 0;
20807:   int totalSize;
20808:   int nReserve;
20809:   sqlite3_mutex_enter(mem.mutex);
20810:   assert( mem.disallow==0 );
20811:   nReserve = ROUND8(nByte);
20812:   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
20813:                mem.nBacktrace*sizeof(void*) + mem.nTitle;
20814:   p = malloc(totalSize);
20815:   if( p ){
20816:     z = p;
20817:     pBt = (void**)&z[mem.nTitle];
20818:     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
20819:     pHdr->pNext = 0;
20820:     pHdr->pPrev = mem.pLast;
20821:     if( mem.pLast ){
20822:       mem.pLast->pNext = pHdr;
20823:     }else{
20824:       mem.pFirst = pHdr;
20825:     }
20826:     mem.pLast = pHdr;
20827:     pHdr->iForeGuard = FOREGUARD;
20828:     pHdr->eType = MEMTYPE_HEAP;
20829:     pHdr->nBacktraceSlots = mem.nBacktrace;
20830:     pHdr->nTitle = mem.nTitle;
20831:     if( mem.nBacktrace ){
20832:       void *aAddr[40];
20833:       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
20834:       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
20835:       assert(pBt[0]);
20836:       if( mem.xBacktrace ){
20837:         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
20838:       }
20839:     }else{
20840:       pHdr->nBacktrace = 0;
20841:     }
20842:     if( mem.nTitle ){
20843:       memcpy(z, mem.zTitle, mem.nTitle);
20844:     }
20845:     pHdr->iSize = nByte;
20846:     adjustStats(nByte, +1);
20847:     pInt = (int*)&pHdr[1];
20848:     pInt[nReserve/sizeof(int)] = REARGUARD;
20849:     randomFill((char*)pInt, nByte);
20850:     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
20851:     p = (void*)pInt;
20852:   }
20853:   sqlite3_mutex_leave(mem.mutex);
20854:   return p; 
20855: }
20856: 
20857: /*
20858: ** Free memory.
20859: */
20860: static void sqlite3MemFree(void *pPrior){
20861:   struct MemBlockHdr *pHdr;
20862:   void **pBt;
20863:   char *z;
20864:   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
20865:        || mem.mutex!=0 );
20866:   pHdr = sqlite3MemsysGetHeader(pPrior);
20867:   pBt = (void**)pHdr;
20868:   pBt -= pHdr->nBacktraceSlots;
20869:   sqlite3_mutex_enter(mem.mutex);
20870:   if( pHdr->pPrev ){
20871:     assert( pHdr->pPrev->pNext==pHdr );
20872:     pHdr->pPrev->pNext = pHdr->pNext;
20873:   }else{
20874:     assert( mem.pFirst==pHdr );
20875:     mem.pFirst = pHdr->pNext;
20876:   }
20877:   if( pHdr->pNext ){
20878:     assert( pHdr->pNext->pPrev==pHdr );
20879:     pHdr->pNext->pPrev = pHdr->pPrev;
20880:   }else{
20881:     assert( mem.pLast==pHdr );
20882:     mem.pLast = pHdr->pPrev;
20883:   }
20884:   z = (char*)pBt;
20885:   z -= pHdr->nTitle;
20886:   adjustStats((int)pHdr->iSize, -1);
20887:   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
20888:                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
20889:   free(z);
20890:   sqlite3_mutex_leave(mem.mutex);  
20891: }
20892: 
20893: /*
20894: ** Change the size of an existing memory allocation.
20895: **
20896: ** For this debugging implementation, we *always* make a copy of the
20897: ** allocation into a new place in memory.  In this way, if the 
20898: ** higher level code is using pointer to the old allocation, it is 
20899: ** much more likely to break and we are much more liking to find
20900: ** the error.
20901: */
20902: static void *sqlite3MemRealloc(void *pPrior, int nByte){
20903:   struct MemBlockHdr *pOldHdr;
20904:   void *pNew;
20905:   assert( mem.disallow==0 );
20906:   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
20907:   pOldHdr = sqlite3MemsysGetHeader(pPrior);
20908:   pNew = sqlite3MemMalloc(nByte);
20909:   if( pNew ){
20910:     memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
20911:     if( nByte>pOldHdr->iSize ){
20912:       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
20913:     }
20914:     sqlite3MemFree(pPrior);
20915:   }
20916:   return pNew;
20917: }
20918: 
20919: /*
20920: ** Populate the low-level memory allocation function pointers in
20921: ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20922: */
20923: SQLITE_PRIVATE void sqlite3MemSetDefault(void){
20924:   static const sqlite3_mem_methods defaultMethods = {
20925:      sqlite3MemMalloc,
20926:      sqlite3MemFree,
20927:      sqlite3MemRealloc,
20928:      sqlite3MemSize,
20929:      sqlite3MemRoundup,
20930:      sqlite3MemInit,
20931:      sqlite3MemShutdown,
20932:      0
20933:   };
20934:   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20935: }
20936: 
20937: /*
20938: ** Set the "type" of an allocation.
20939: */
20940: SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
20941:   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20942:     struct MemBlockHdr *pHdr;
20943:     pHdr = sqlite3MemsysGetHeader(p);
20944:     assert( pHdr->iForeGuard==FOREGUARD );
20945:     pHdr->eType = eType;
20946:   }
20947: }
20948: 
20949: /*
20950: ** Return TRUE if the mask of type in eType matches the type of the
20951: ** allocation p.  Also return true if p==NULL.
20952: **
20953: ** This routine is designed for use within an assert() statement, to
20954: ** verify the type of an allocation.  For example:
20955: **
20956: **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20957: */
20958: SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
20959:   int rc = 1;
20960:   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20961:     struct MemBlockHdr *pHdr;
20962:     pHdr = sqlite3MemsysGetHeader(p);
20963:     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
20964:     if( (pHdr->eType&eType)==0 ){
20965:       rc = 0;
20966:     }
20967:   }
20968:   return rc;
20969: }
20970: 
20971: /*
20972: ** Return TRUE if the mask of type in eType matches no bits of the type of the
20973: ** allocation p.  Also return true if p==NULL.
20974: **
20975: ** This routine is designed for use within an assert() statement, to
20976: ** verify the type of an allocation.  For example:
20977: **
20978: **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20979: */
20980: SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
20981:   int rc = 1;
20982:   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20983:     struct MemBlockHdr *pHdr;
20984:     pHdr = sqlite3MemsysGetHeader(p);
20985:     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
20986:     if( (pHdr->eType&eType)!=0 ){
20987:       rc = 0;
20988:     }
20989:   }
20990:   return rc;
20991: }
20992: 
20993: /*
20994: ** Set the number of backtrace levels kept for each allocation.
20995: ** A value of zero turns off backtracing.  The number is always rounded
20996: ** up to a multiple of 2.
20997: */
20998: SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
20999:   if( depth<0 ){ depth = 0; }
21000:   if( depth>20 ){ depth = 20; }
21001:   depth = (depth+1)&0xfe;
21002:   mem.nBacktrace = depth;
21003: }
21004: 
21005: SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
21006:   mem.xBacktrace = xBacktrace;
21007: }
21008: 
21009: /*
21010: ** Set the title string for subsequent allocations.
21011: */
21012: SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
21013:   unsigned int n = sqlite3Strlen30(zTitle) + 1;
21014:   sqlite3_mutex_enter(mem.mutex);
21015:   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
21016:   memcpy(mem.zTitle, zTitle, n);
21017:   mem.zTitle[n] = 0;
21018:   mem.nTitle = ROUND8(n);
21019:   sqlite3_mutex_leave(mem.mutex);
21020: }
21021: 
21022: SQLITE_PRIVATE void sqlite3MemdebugSync(){
21023:   struct MemBlockHdr *pHdr;
21024:   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21025:     void **pBt = (void**)pHdr;
21026:     pBt -= pHdr->nBacktraceSlots;
21027:     mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
21028:   }
21029: }
21030: 
21031: /*
21032: ** Open the file indicated and write a log of all unfreed memory 
21033: ** allocations into that log.
21034: */
21035: SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
21036:   FILE *out;
21037:   struct MemBlockHdr *pHdr;
21038:   void **pBt;
21039:   int i;
21040:   out = fopen(zFilename, "w");
21041:   if( out==0 ){
21042:     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21043:                     zFilename);
21044:     return;
21045:   }
21046:   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
21047:     char *z = (char*)pHdr;
21048:     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
21049:     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
21050:             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
21051:     if( pHdr->nBacktrace ){
21052:       fflush(out);
21053:       pBt = (void**)pHdr;
21054:       pBt -= pHdr->nBacktraceSlots;
21055:       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
21056:       fprintf(out, "\n");
21057:     }
21058:   }
21059:   fprintf(out, "COUNTS:\n");
21060:   for(i=0; i<NCSIZE-1; i++){
21061:     if( mem.nAlloc[i] ){
21062:       fprintf(out, "   %5d: %10d %10d %10d\n", 
21063:             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
21064:     }
21065:   }
21066:   if( mem.nAlloc[NCSIZE-1] ){
21067:     fprintf(out, "   %5d: %10d %10d %10d\n",
21068:              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
21069:              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
21070:   }
21071:   fclose(out);
21072: }
21073: 
21074: /*
21075: ** Return the number of times sqlite3MemMalloc() has been called.
21076: */
21077: SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
21078:   int i;
21079:   int nTotal = 0;
21080:   for(i=0; i<NCSIZE; i++){
21081:     nTotal += mem.nAlloc[i];
21082:   }
21083:   return nTotal;
21084: }
21085: 
21086: 
21087: #endif /* SQLITE_MEMDEBUG */
21088: 
21089: /************** End of mem2.c ************************************************/
21090: /************** Begin file mem3.c ********************************************/
21091: /*
21092: ** 2007 October 14
21093: **
21094: ** The author disclaims copyright to this source code.  In place of
21095: ** a legal notice, here is a blessing:
21096: **
21097: **    May you do good and not evil.
21098: **    May you find forgiveness for yourself and forgive others.
21099: **    May you share freely, never taking more than you give.
21100: **
21101: *************************************************************************
21102: ** This file contains the C functions that implement a memory
21103: ** allocation subsystem for use by SQLite. 
21104: **
21105: ** This version of the memory allocation subsystem omits all
21106: ** use of malloc(). The SQLite user supplies a block of memory
21107: ** before calling sqlite3_initialize() from which allocations
21108: ** are made and returned by the xMalloc() and xRealloc() 
21109: ** implementations. Once sqlite3_initialize() has been called,
21110: ** the amount of memory available to SQLite is fixed and cannot
21111: ** be changed.
21112: **
21113: ** This version of the memory allocation subsystem is included
21114: ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
21115: */
21116: /* #include "sqliteInt.h" */
21117: 
21118: /*
21119: ** This version of the memory allocator is only built into the library
21120: ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
21121: ** mean that the library will use a memory-pool by default, just that
21122: ** it is available. The mempool allocator is activated by calling
21123: ** sqlite3_config().
21124: */
21125: #ifdef SQLITE_ENABLE_MEMSYS3
21126: 
21127: /*
21128: ** Maximum size (in Mem3Blocks) of a "small" chunk.
21129: */
21130: #define MX_SMALL 10
21131: 
21132: 
21133: /*
21134: ** Number of freelist hash slots
21135: */
21136: #define N_HASH  61
21137: 
21138: /*
21139: ** A memory allocation (also called a "chunk") consists of two or 
21140: ** more blocks where each block is 8 bytes.  The first 8 bytes are 
21141: ** a header that is not returned to the user.
21142: **
21143: ** A chunk is two or more blocks that is either checked out or
21144: ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
21145: ** size of the allocation in blocks if the allocation is free.
21146: ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
21147: ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
21148: ** is true if the previous chunk is checked out and false if the
21149: ** previous chunk is free.  The u.hdr.prevSize field is the size of
21150: ** the previous chunk in blocks if the previous chunk is on the
21151: ** freelist. If the previous chunk is checked out, then
21152: ** u.hdr.prevSize can be part of the data for that chunk and should
21153: ** not be read or written.
21154: **
21155: ** We often identify a chunk by its index in mem3.aPool[].  When
21156: ** this is done, the chunk index refers to the second block of
21157: ** the chunk.  In this way, the first chunk has an index of 1.
21158: ** A chunk index of 0 means "no such chunk" and is the equivalent
21159: ** of a NULL pointer.
21160: **
21161: ** The second block of free chunks is of the form u.list.  The
21162: ** two fields form a double-linked list of chunks of related sizes.
21163: ** Pointers to the head of the list are stored in mem3.aiSmall[] 
21164: ** for smaller chunks and mem3.aiHash[] for larger chunks.
21165: **
21166: ** The second block of a chunk is user data if the chunk is checked 
21167: ** out.  If a chunk is checked out, the user data may extend into
21168: ** the u.hdr.prevSize value of the following chunk.
21169: */
21170: typedef struct Mem3Block Mem3Block;
21171: struct Mem3Block {
21172:   union {
21173:     struct {
21174:       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
21175:       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
21176:     } hdr;
21177:     struct {
21178:       u32 next;       /* Index in mem3.aPool[] of next free chunk */
21179:       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
21180:     } list;
21181:   } u;
21182: };
21183: 
21184: /*
21185: ** All of the static variables used by this module are collected
21186: ** into a single structure named "mem3".  This is to keep the
21187: ** static variables organized and to reduce namespace pollution
21188: ** when this module is combined with other in the amalgamation.
21189: */
21190: static SQLITE_WSD struct Mem3Global {
21191:   /*
21192:   ** Memory available for allocation. nPool is the size of the array
21193:   ** (in Mem3Blocks) pointed to by aPool less 2.
21194:   */
21195:   u32 nPool;
21196:   Mem3Block *aPool;
21197: 
21198:   /*
21199:   ** True if we are evaluating an out-of-memory callback.
21200:   */
21201:   int alarmBusy;
21202:   
21203:   /*
21204:   ** Mutex to control access to the memory allocation subsystem.
21205:   */
21206:   sqlite3_mutex *mutex;
21207:   
21208:   /*
21209:   ** The minimum amount of free space that we have seen.
21210:   */
21211:   u32 mnMaster;
21212: 
21213:   /*
21214:   ** iMaster is the index of the master chunk.  Most new allocations
21215:   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
21216:   ** of the current master.  iMaster is 0 if there is not master chunk.
21217:   ** The master chunk is not in either the aiHash[] or aiSmall[].
21218:   */
21219:   u32 iMaster;
21220:   u32 szMaster;
21221: 
21222:   /*
21223:   ** Array of lists of free blocks according to the block size 
21224:   ** for smaller chunks, or a hash on the block size for larger
21225:   ** chunks.
21226:   */
21227:   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
21228:   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
21229: } mem3 = { 97535575 };
21230: 
21231: #define mem3 GLOBAL(struct Mem3Global, mem3)
21232: 
21233: /*
21234: ** Unlink the chunk at mem3.aPool[i] from list it is currently
21235: ** on.  *pRoot is the list that i is a member of.
21236: */
21237: static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
21238:   u32 next = mem3.aPool[i].u.list.next;
21239:   u32 prev = mem3.aPool[i].u.list.prev;
21240:   assert( sqlite3_mutex_held(mem3.mutex) );
21241:   if( prev==0 ){
21242:     *pRoot = next;
21243:   }else{
21244:     mem3.aPool[prev].u.list.next = next;
21245:   }
21246:   if( next ){
21247:     mem3.aPool[next].u.list.prev = prev;
21248:   }
21249:   mem3.aPool[i].u.list.next = 0;
21250:   mem3.aPool[i].u.list.prev = 0;
21251: }
21252: 
21253: /*
21254: ** Unlink the chunk at index i from 
21255: ** whatever list is currently a member of.
21256: */
21257: static void memsys3Unlink(u32 i){
21258:   u32 size, hash;
21259:   assert( sqlite3_mutex_held(mem3.mutex) );
21260:   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21261:   assert( i>=1 );
21262:   size = mem3.aPool[i-1].u.hdr.size4x/4;
21263:   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21264:   assert( size>=2 );
21265:   if( size <= MX_SMALL ){
21266:     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
21267:   }else{
21268:     hash = size % N_HASH;
21269:     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21270:   }
21271: }
21272: 
21273: /*
21274: ** Link the chunk at mem3.aPool[i] so that is on the list rooted
21275: ** at *pRoot.
21276: */
21277: static void memsys3LinkIntoList(u32 i, u32 *pRoot){
21278:   assert( sqlite3_mutex_held(mem3.mutex) );
21279:   mem3.aPool[i].u.list.next = *pRoot;
21280:   mem3.aPool[i].u.list.prev = 0;
21281:   if( *pRoot ){
21282:     mem3.aPool[*pRoot].u.list.prev = i;
21283:   }
21284:   *pRoot = i;
21285: }
21286: 
21287: /*
21288: ** Link the chunk at index i into either the appropriate
21289: ** small chunk list, or into the large chunk hash table.
21290: */
21291: static void memsys3Link(u32 i){
21292:   u32 size, hash;
21293:   assert( sqlite3_mutex_held(mem3.mutex) );
21294:   assert( i>=1 );
21295:   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21296:   size = mem3.aPool[i-1].u.hdr.size4x/4;
21297:   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21298:   assert( size>=2 );
21299:   if( size <= MX_SMALL ){
21300:     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
21301:   }else{
21302:     hash = size % N_HASH;
21303:     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
21304:   }
21305: }
21306: 
21307: /*
21308: ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
21309: ** will already be held (obtained by code in malloc.c) if
21310: ** sqlite3GlobalConfig.bMemStat is true.
21311: */
21312: static void memsys3Enter(void){
21313:   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
21314:     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
21315:   }
21316:   sqlite3_mutex_enter(mem3.mutex);
21317: }
21318: static void memsys3Leave(void){
21319:   sqlite3_mutex_leave(mem3.mutex);
21320: }
21321: 
21322: /*
21323: ** Called when we are unable to satisfy an allocation of nBytes.
21324: */
21325: static void memsys3OutOfMemory(int nByte){
21326:   if( !mem3.alarmBusy ){
21327:     mem3.alarmBusy = 1;
21328:     assert( sqlite3_mutex_held(mem3.mutex) );
21329:     sqlite3_mutex_leave(mem3.mutex);
21330:     sqlite3_release_memory(nByte);
21331:     sqlite3_mutex_enter(mem3.mutex);
21332:     mem3.alarmBusy = 0;
21333:   }
21334: }
21335: 
21336: 
21337: /*
21338: ** Chunk i is a free chunk that has been unlinked.  Adjust its 
21339: ** size parameters for check-out and return a pointer to the 
21340: ** user portion of the chunk.
21341: */
21342: static void *memsys3Checkout(u32 i, u32 nBlock){
21343:   u32 x;
21344:   assert( sqlite3_mutex_held(mem3.mutex) );
21345:   assert( i>=1 );
21346:   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
21347:   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
21348:   x = mem3.aPool[i-1].u.hdr.size4x;
21349:   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
21350:   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
21351:   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
21352:   return &mem3.aPool[i];
21353: }
21354: 
21355: /*
21356: ** Carve a piece off of the end of the mem3.iMaster free chunk.
21357: ** Return a pointer to the new allocation.  Or, if the master chunk
21358: ** is not large enough, return 0.
21359: */
21360: static void *memsys3FromMaster(u32 nBlock){
21361:   assert( sqlite3_mutex_held(mem3.mutex) );
21362:   assert( mem3.szMaster>=nBlock );
21363:   if( nBlock>=mem3.szMaster-1 ){
21364:     /* Use the entire master */
21365:     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
21366:     mem3.iMaster = 0;
21367:     mem3.szMaster = 0;
21368:     mem3.mnMaster = 0;
21369:     return p;
21370:   }else{
21371:     /* Split the master block.  Return the tail. */
21372:     u32 newi, x;
21373:     newi = mem3.iMaster + mem3.szMaster - nBlock;
21374:     assert( newi > mem3.iMaster+1 );
21375:     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
21376:     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
21377:     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
21378:     mem3.szMaster -= nBlock;
21379:     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
21380:     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21381:     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21382:     if( mem3.szMaster < mem3.mnMaster ){
21383:       mem3.mnMaster = mem3.szMaster;
21384:     }
21385:     return (void*)&mem3.aPool[newi];
21386:   }
21387: }
21388: 
21389: /*
21390: ** *pRoot is the head of a list of free chunks of the same size
21391: ** or same size hash.  In other words, *pRoot is an entry in either
21392: ** mem3.aiSmall[] or mem3.aiHash[].  
21393: **
21394: ** This routine examines all entries on the given list and tries
21395: ** to coalesce each entries with adjacent free chunks.  
21396: **
21397: ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
21398: ** the current mem3.iMaster with the new larger chunk.  In order for
21399: ** this mem3.iMaster replacement to work, the master chunk must be
21400: ** linked into the hash tables.  That is not the normal state of
21401: ** affairs, of course.  The calling routine must link the master
21402: ** chunk before invoking this routine, then must unlink the (possibly
21403: ** changed) master chunk once this routine has finished.
21404: */
21405: static void memsys3Merge(u32 *pRoot){
21406:   u32 iNext, prev, size, i, x;
21407: 
21408:   assert( sqlite3_mutex_held(mem3.mutex) );
21409:   for(i=*pRoot; i>0; i=iNext){
21410:     iNext = mem3.aPool[i].u.list.next;
21411:     size = mem3.aPool[i-1].u.hdr.size4x;
21412:     assert( (size&1)==0 );
21413:     if( (size&2)==0 ){
21414:       memsys3UnlinkFromList(i, pRoot);
21415:       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
21416:       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
21417:       if( prev==iNext ){
21418:         iNext = mem3.aPool[prev].u.list.next;
21419:       }
21420:       memsys3Unlink(prev);
21421:       size = i + size/4 - prev;
21422:       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
21423:       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
21424:       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
21425:       memsys3Link(prev);
21426:       i = prev;
21427:     }else{
21428:       size /= 4;
21429:     }
21430:     if( size>mem3.szMaster ){
21431:       mem3.iMaster = i;
21432:       mem3.szMaster = size;
21433:     }
21434:   }
21435: }
21436: 
21437: /*
21438: ** Return a block of memory of at least nBytes in size.
21439: ** Return NULL if unable.
21440: **
21441: ** This function assumes that the necessary mutexes, if any, are
21442: ** already held by the caller. Hence "Unsafe".
21443: */
21444: static void *memsys3MallocUnsafe(int nByte){
21445:   u32 i;
21446:   u32 nBlock;
21447:   u32 toFree;
21448: 
21449:   assert( sqlite3_mutex_held(mem3.mutex) );
21450:   assert( sizeof(Mem3Block)==8 );
21451:   if( nByte<=12 ){
21452:     nBlock = 2;
21453:   }else{
21454:     nBlock = (nByte + 11)/8;
21455:   }
21456:   assert( nBlock>=2 );
21457: 
21458:   /* STEP 1:
21459:   ** Look for an entry of the correct size in either the small
21460:   ** chunk table or in the large chunk hash table.  This is
21461:   ** successful most of the time (about 9 times out of 10).
21462:   */
21463:   if( nBlock <= MX_SMALL ){
21464:     i = mem3.aiSmall[nBlock-2];
21465:     if( i>0 ){
21466:       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
21467:       return memsys3Checkout(i, nBlock);
21468:     }
21469:   }else{
21470:     int hash = nBlock % N_HASH;
21471:     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
21472:       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
21473:         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21474:         return memsys3Checkout(i, nBlock);
21475:       }
21476:     }
21477:   }
21478: 
21479:   /* STEP 2:
21480:   ** Try to satisfy the allocation by carving a piece off of the end
21481:   ** of the master chunk.  This step usually works if step 1 fails.
21482:   */
21483:   if( mem3.szMaster>=nBlock ){
21484:     return memsys3FromMaster(nBlock);
21485:   }
21486: 
21487: 
21488:   /* STEP 3:  
21489:   ** Loop through the entire memory pool.  Coalesce adjacent free
21490:   ** chunks.  Recompute the master chunk as the largest free chunk.
21491:   ** Then try again to satisfy the allocation by carving a piece off
21492:   ** of the end of the master chunk.  This step happens very
21493:   ** rarely (we hope!)
21494:   */
21495:   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
21496:     memsys3OutOfMemory(toFree);
21497:     if( mem3.iMaster ){
21498:       memsys3Link(mem3.iMaster);
21499:       mem3.iMaster = 0;
21500:       mem3.szMaster = 0;
21501:     }
21502:     for(i=0; i<N_HASH; i++){
21503:       memsys3Merge(&mem3.aiHash[i]);
21504:     }
21505:     for(i=0; i<MX_SMALL-1; i++){
21506:       memsys3Merge(&mem3.aiSmall[i]);
21507:     }
21508:     if( mem3.szMaster ){
21509:       memsys3Unlink(mem3.iMaster);
21510:       if( mem3.szMaster>=nBlock ){
21511:         return memsys3FromMaster(nBlock);
21512:       }
21513:     }
21514:   }
21515: 
21516:   /* If none of the above worked, then we fail. */
21517:   return 0;
21518: }
21519: 
21520: /*
21521: ** Free an outstanding memory allocation.
21522: **
21523: ** This function assumes that the necessary mutexes, if any, are
21524: ** already held by the caller. Hence "Unsafe".
21525: */
21526: static void memsys3FreeUnsafe(void *pOld){
21527:   Mem3Block *p = (Mem3Block*)pOld;
21528:   int i;
21529:   u32 size, x;
21530:   assert( sqlite3_mutex_held(mem3.mutex) );
21531:   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
21532:   i = p - mem3.aPool;
21533:   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
21534:   size = mem3.aPool[i-1].u.hdr.size4x/4;
21535:   assert( i+size<=mem3.nPool+1 );
21536:   mem3.aPool[i-1].u.hdr.size4x &= ~1;
21537:   mem3.aPool[i+size-1].u.hdr.prevSize = size;
21538:   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
21539:   memsys3Link(i);
21540: 
21541:   /* Try to expand the master using the newly freed chunk */
21542:   if( mem3.iMaster ){
21543:     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
21544:       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
21545:       mem3.iMaster -= size;
21546:       mem3.szMaster += size;
21547:       memsys3Unlink(mem3.iMaster);
21548:       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21549:       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21550:       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21551:     }
21552:     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21553:     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
21554:       memsys3Unlink(mem3.iMaster+mem3.szMaster);
21555:       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
21556:       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21557:       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21558:     }
21559:   }
21560: }
21561: 
21562: /*
21563: ** Return the size of an outstanding allocation, in bytes.  The
21564: ** size returned omits the 8-byte header overhead.  This only
21565: ** works for chunks that are currently checked out.
21566: */
21567: static int memsys3Size(void *p){
21568:   Mem3Block *pBlock;
21569:   assert( p!=0 );
21570:   pBlock = (Mem3Block*)p;
21571:   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
21572:   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
21573: }
21574: 
21575: /*
21576: ** Round up a request size to the next valid allocation size.
21577: */
21578: static int memsys3Roundup(int n){
21579:   if( n<=12 ){
21580:     return 12;
21581:   }else{
21582:     return ((n+11)&~7) - 4;
21583:   }
21584: }
21585: 
21586: /*
21587: ** Allocate nBytes of memory.
21588: */
21589: static void *memsys3Malloc(int nBytes){
21590:   sqlite3_int64 *p;
21591:   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
21592:   memsys3Enter();
21593:   p = memsys3MallocUnsafe(nBytes);
21594:   memsys3Leave();
21595:   return (void*)p; 
21596: }
21597: 
21598: /*
21599: ** Free memory.
21600: */
21601: static void memsys3Free(void *pPrior){
21602:   assert( pPrior );
21603:   memsys3Enter();
21604:   memsys3FreeUnsafe(pPrior);
21605:   memsys3Leave();
21606: }
21607: 
21608: /*
21609: ** Change the size of an existing memory allocation
21610: */
21611: static void *memsys3Realloc(void *pPrior, int nBytes){
21612:   int nOld;
21613:   void *p;
21614:   if( pPrior==0 ){
21615:     return sqlite3_malloc(nBytes);
21616:   }
21617:   if( nBytes<=0 ){
21618:     sqlite3_free(pPrior);
21619:     return 0;
21620:   }
21621:   nOld = memsys3Size(pPrior);
21622:   if( nBytes<=nOld && nBytes>=nOld-128 ){
21623:     return pPrior;
21624:   }
21625:   memsys3Enter();
21626:   p = memsys3MallocUnsafe(nBytes);
21627:   if( p ){
21628:     if( nOld<nBytes ){
21629:       memcpy(p, pPrior, nOld);
21630:     }else{
21631:       memcpy(p, pPrior, nBytes);
21632:     }
21633:     memsys3FreeUnsafe(pPrior);
21634:   }
21635:   memsys3Leave();
21636:   return p;
21637: }
21638: 
21639: /*
21640: ** Initialize this module.
21641: */
21642: static int memsys3Init(void *NotUsed){
21643:   UNUSED_PARAMETER(NotUsed);
21644:   if( !sqlite3GlobalConfig.pHeap ){
21645:     return SQLITE_ERROR;
21646:   }
21647: 
21648:   /* Store a pointer to the memory block in global structure mem3. */
21649:   assert( sizeof(Mem3Block)==8 );
21650:   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
21651:   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
21652: 
21653:   /* Initialize the master block. */
21654:   mem3.szMaster = mem3.nPool;
21655:   mem3.mnMaster = mem3.szMaster;
21656:   mem3.iMaster = 1;
21657:   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
21658:   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
21659:   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
21660: 
21661:   return SQLITE_OK;
21662: }
21663: 
21664: /*
21665: ** Deinitialize this module.
21666: */
21667: static void memsys3Shutdown(void *NotUsed){
21668:   UNUSED_PARAMETER(NotUsed);
21669:   mem3.mutex = 0;
21670:   return;
21671: }
21672: 
21673: 
21674: 
21675: /*
21676: ** Open the file indicated and write a log of all unfreed memory 
21677: ** allocations into that log.
21678: */
21679: SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
21680: #ifdef SQLITE_DEBUG
21681:   FILE *out;
21682:   u32 i, j;
21683:   u32 size;
21684:   if( zFilename==0 || zFilename[0]==0 ){
21685:     out = stdout;
21686:   }else{
21687:     out = fopen(zFilename, "w");
21688:     if( out==0 ){
21689:       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21690:                       zFilename);
21691:       return;
21692:     }
21693:   }
21694:   memsys3Enter();
21695:   fprintf(out, "CHUNKS:\n");
21696:   for(i=1; i<=mem3.nPool; i+=size/4){
21697:     size = mem3.aPool[i-1].u.hdr.size4x;
21698:     if( size/4<=1 ){
21699:       fprintf(out, "%p size error\n", &mem3.aPool[i]);
21700:       assert( 0 );
21701:       break;
21702:     }
21703:     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
21704:       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
21705:       assert( 0 );
21706:       break;
21707:     }
21708:     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
21709:       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
21710:       assert( 0 );
21711:       break;
21712:     }
21713:     if( size&1 ){
21714:       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
21715:     }else{
21716:       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
21717:                   i==mem3.iMaster ? " **master**" : "");
21718:     }
21719:   }
21720:   for(i=0; i<MX_SMALL-1; i++){
21721:     if( mem3.aiSmall[i]==0 ) continue;
21722:     fprintf(out, "small(%2d):", i);
21723:     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
21724:       fprintf(out, " %p(%d)", &mem3.aPool[j],
21725:               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21726:     }
21727:     fprintf(out, "\n"); 
21728:   }
21729:   for(i=0; i<N_HASH; i++){
21730:     if( mem3.aiHash[i]==0 ) continue;
21731:     fprintf(out, "hash(%2d):", i);
21732:     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
21733:       fprintf(out, " %p(%d)", &mem3.aPool[j],
21734:               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21735:     }
21736:     fprintf(out, "\n"); 
21737:   }
21738:   fprintf(out, "master=%d\n", mem3.iMaster);
21739:   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
21740:   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
21741:   sqlite3_mutex_leave(mem3.mutex);
21742:   if( out==stdout ){
21743:     fflush(stdout);
21744:   }else{
21745:     fclose(out);
21746:   }
21747: #else
21748:   UNUSED_PARAMETER(zFilename);
21749: #endif
21750: }
21751: 
21752: /*
21753: ** This routine is the only routine in this file with external 
21754: ** linkage.
21755: **
21756: ** Populate the low-level memory allocation function pointers in
21757: ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
21758: ** arguments specify the block of memory to manage.
21759: **
21760: ** This routine is only called by sqlite3_config(), and therefore
21761: ** is not required to be threadsafe (it is not).
21762: */
21763: SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
21764:   static const sqlite3_mem_methods mempoolMethods = {
21765:      memsys3Malloc,
21766:      memsys3Free,
21767:      memsys3Realloc,
21768:      memsys3Size,
21769:      memsys3Roundup,
21770:      memsys3Init,
21771:      memsys3Shutdown,
21772:      0
21773:   };
21774:   return &mempoolMethods;
21775: }
21776: 
21777: #endif /* SQLITE_ENABLE_MEMSYS3 */
21778: 
21779: /************** End of mem3.c ************************************************/
21780: /************** Begin file mem5.c ********************************************/
21781: /*
21782: ** 2007 October 14
21783: **
21784: ** The author disclaims copyright to this source code.  In place of
21785: ** a legal notice, here is a blessing:
21786: **
21787: **    May you do good and not evil.
21788: **    May you find forgiveness for yourself and forgive others.
21789: **    May you share freely, never taking more than you give.
21790: **
21791: *************************************************************************
21792: ** This file contains the C functions that implement a memory
21793: ** allocation subsystem for use by SQLite. 
21794: **
21795: ** This version of the memory allocation subsystem omits all
21796: ** use of malloc(). The application gives SQLite a block of memory
21797: ** before calling sqlite3_initialize() from which allocations
21798: ** are made and returned by the xMalloc() and xRealloc() 
21799: ** implementations. Once sqlite3_initialize() has been called,
21800: ** the amount of memory available to SQLite is fixed and cannot
21801: ** be changed.
21802: **
21803: ** This version of the memory allocation subsystem is included
21804: ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
21805: **
21806: ** This memory allocator uses the following algorithm:
21807: **
21808: **   1.  All memory allocation sizes are rounded up to a power of 2.
21809: **
21810: **   2.  If two adjacent free blocks are the halves of a larger block,
21811: **       then the two blocks are coalesced into the single larger block.
21812: **
21813: **   3.  New memory is allocated from the first available free block.
21814: **
21815: ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
21816: ** Concerning Dynamic Storage Allocation". Journal of the Association for
21817: ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
21818: ** 
21819: ** Let n be the size of the largest allocation divided by the minimum
21820: ** allocation size (after rounding all sizes up to a power of 2.)  Let M
21821: ** be the maximum amount of memory ever outstanding at one time.  Let
21822: ** N be the total amount of memory available for allocation.  Robson
21823: ** proved that this memory allocator will never breakdown due to 
21824: ** fragmentation as long as the following constraint holds:
21825: **
21826: **      N >=  M*(1 + log2(n)/2) - n + 1
21827: **
21828: ** The sqlite3_status() logic tracks the maximum values of n and M so
21829: ** that an application can, at any time, verify this constraint.
21830: */
21831: /* #include "sqliteInt.h" */
21832: 
21833: /*
21834: ** This version of the memory allocator is used only when 
21835: ** SQLITE_ENABLE_MEMSYS5 is defined.
21836: */
21837: #ifdef SQLITE_ENABLE_MEMSYS5
21838: 
21839: /*
21840: ** A minimum allocation is an instance of the following structure.
21841: ** Larger allocations are an array of these structures where the
21842: ** size of the array is a power of 2.
21843: **
21844: ** The size of this object must be a power of two.  That fact is
21845: ** verified in memsys5Init().
21846: */
21847: typedef struct Mem5Link Mem5Link;
21848: struct Mem5Link {
21849:   int next;       /* Index of next free chunk */
21850:   int prev;       /* Index of previous free chunk */
21851: };
21852: 
21853: /*
21854: ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
21855: ** mem5.szAtom is always at least 8 and 32-bit integers are used,
21856: ** it is not actually possible to reach this limit.
21857: */
21858: #define LOGMAX 30
21859: 
21860: /*
21861: ** Masks used for mem5.aCtrl[] elements.
21862: */
21863: #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
21864: #define CTRL_FREE     0x20    /* True if not checked out */
21865: 
21866: /*
21867: ** All of the static variables used by this module are collected
21868: ** into a single structure named "mem5".  This is to keep the
21869: ** static variables organized and to reduce namespace pollution
21870: ** when this module is combined with other in the amalgamation.
21871: */
21872: static SQLITE_WSD struct Mem5Global {
21873:   /*
21874:   ** Memory available for allocation
21875:   */
21876:   int szAtom;      /* Smallest possible allocation in bytes */
21877:   int nBlock;      /* Number of szAtom sized blocks in zPool */
21878:   u8 *zPool;       /* Memory available to be allocated */
21879:   
21880:   /*
21881:   ** Mutex to control access to the memory allocation subsystem.
21882:   */
21883:   sqlite3_mutex *mutex;
21884: 
21885: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21886:   /*
21887:   ** Performance statistics
21888:   */
21889:   u64 nAlloc;         /* Total number of calls to malloc */
21890:   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
21891:   u64 totalExcess;    /* Total internal fragmentation */
21892:   u32 currentOut;     /* Current checkout, including internal fragmentation */
21893:   u32 currentCount;   /* Current number of distinct checkouts */
21894:   u32 maxOut;         /* Maximum instantaneous currentOut */
21895:   u32 maxCount;       /* Maximum instantaneous currentCount */
21896:   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
21897: #endif
21898:   
21899:   /*
21900:   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
21901:   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
21902:   ** aiFreelist[2] holds free blocks of size szAtom*4.  And so forth.
21903:   */
21904:   int aiFreelist[LOGMAX+1];
21905: 
21906:   /*
21907:   ** Space for tracking which blocks are checked out and the size
21908:   ** of each block.  One byte per block.
21909:   */
21910:   u8 *aCtrl;
21911: 
21912: } mem5;
21913: 
21914: /*
21915: ** Access the static variable through a macro for SQLITE_OMIT_WSD.
21916: */
21917: #define mem5 GLOBAL(struct Mem5Global, mem5)
21918: 
21919: /*
21920: ** Assuming mem5.zPool is divided up into an array of Mem5Link
21921: ** structures, return a pointer to the idx-th such link.
21922: */
21923: #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
21924: 
21925: /*
21926: ** Unlink the chunk at mem5.aPool[i] from list it is currently
21927: ** on.  It should be found on mem5.aiFreelist[iLogsize].
21928: */
21929: static void memsys5Unlink(int i, int iLogsize){
21930:   int next, prev;
21931:   assert( i>=0 && i<mem5.nBlock );
21932:   assert( iLogsize>=0 && iLogsize<=LOGMAX );
21933:   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21934: 
21935:   next = MEM5LINK(i)->next;
21936:   prev = MEM5LINK(i)->prev;
21937:   if( prev<0 ){
21938:     mem5.aiFreelist[iLogsize] = next;
21939:   }else{
21940:     MEM5LINK(prev)->next = next;
21941:   }
21942:   if( next>=0 ){
21943:     MEM5LINK(next)->prev = prev;
21944:   }
21945: }
21946: 
21947: /*
21948: ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
21949: ** free list.
21950: */
21951: static void memsys5Link(int i, int iLogsize){
21952:   int x;
21953:   assert( sqlite3_mutex_held(mem5.mutex) );
21954:   assert( i>=0 && i<mem5.nBlock );
21955:   assert( iLogsize>=0 && iLogsize<=LOGMAX );
21956:   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21957: 
21958:   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
21959:   MEM5LINK(i)->prev = -1;
21960:   if( x>=0 ){
21961:     assert( x<mem5.nBlock );
21962:     MEM5LINK(x)->prev = i;
21963:   }
21964:   mem5.aiFreelist[iLogsize] = i;
21965: }
21966: 
21967: /*
21968: ** Obtain or release the mutex needed to access global data structures.
21969: */
21970: static void memsys5Enter(void){
21971:   sqlite3_mutex_enter(mem5.mutex);
21972: }
21973: static void memsys5Leave(void){
21974:   sqlite3_mutex_leave(mem5.mutex);
21975: }
21976: 
21977: /*
21978: ** Return the size of an outstanding allocation, in bytes.
21979: ** This only works for chunks that are currently checked out.
21980: */
21981: static int memsys5Size(void *p){
21982:   int iSize, i;
21983:   assert( p!=0 );
21984:   i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
21985:   assert( i>=0 && i<mem5.nBlock );
21986:   iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
21987:   return iSize;
21988: }
21989: 
21990: /*
21991: ** Return a block of memory of at least nBytes in size.
21992: ** Return NULL if unable.  Return NULL if nBytes==0.
21993: **
21994: ** The caller guarantees that nByte is positive.
21995: **
21996: ** The caller has obtained a mutex prior to invoking this
21997: ** routine so there is never any chance that two or more
21998: ** threads can be in this routine at the same time.
21999: */
22000: static void *memsys5MallocUnsafe(int nByte){
22001:   int i;           /* Index of a mem5.aPool[] slot */
22002:   int iBin;        /* Index into mem5.aiFreelist[] */
22003:   int iFullSz;     /* Size of allocation rounded up to power of 2 */
22004:   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
22005: 
22006:   /* nByte must be a positive */
22007:   assert( nByte>0 );
22008: 
22009:   /* No more than 1GiB per allocation */
22010:   if( nByte > 0x40000000 ) return 0;
22011: 
22012: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22013:   /* Keep track of the maximum allocation request.  Even unfulfilled
22014:   ** requests are counted */
22015:   if( (u32)nByte>mem5.maxRequest ){
22016:     mem5.maxRequest = nByte;
22017:   }
22018: #endif
22019: 
22020: 
22021:   /* Round nByte up to the next valid power of two */
22022:   for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
22023: 
22024:   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
22025:   ** block.  If not, then split a block of the next larger power of
22026:   ** two in order to create a new free block of size iLogsize.
22027:   */
22028:   for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
22029:   if( iBin>LOGMAX ){
22030:     testcase( sqlite3GlobalConfig.xLog!=0 );
22031:     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
22032:     return 0;
22033:   }
22034:   i = mem5.aiFreelist[iBin];
22035:   memsys5Unlink(i, iBin);
22036:   while( iBin>iLogsize ){
22037:     int newSize;
22038: 
22039:     iBin--;
22040:     newSize = 1 << iBin;
22041:     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
22042:     memsys5Link(i+newSize, iBin);
22043:   }
22044:   mem5.aCtrl[i] = iLogsize;
22045: 
22046: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22047:   /* Update allocator performance statistics. */
22048:   mem5.nAlloc++;
22049:   mem5.totalAlloc += iFullSz;
22050:   mem5.totalExcess += iFullSz - nByte;
22051:   mem5.currentCount++;
22052:   mem5.currentOut += iFullSz;
22053:   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
22054:   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
22055: #endif
22056: 
22057: #ifdef SQLITE_DEBUG
22058:   /* Make sure the allocated memory does not assume that it is set to zero
22059:   ** or retains a value from a previous allocation */
22060:   memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
22061: #endif
22062: 
22063:   /* Return a pointer to the allocated memory. */
22064:   return (void*)&mem5.zPool[i*mem5.szAtom];
22065: }
22066: 
22067: /*
22068: ** Free an outstanding memory allocation.
22069: */
22070: static void memsys5FreeUnsafe(void *pOld){
22071:   u32 size, iLogsize;
22072:   int iBlock;
22073: 
22074:   /* Set iBlock to the index of the block pointed to by pOld in 
22075:   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
22076:   */
22077:   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
22078: 
22079:   /* Check that the pointer pOld points to a valid, non-free block. */
22080:   assert( iBlock>=0 && iBlock<mem5.nBlock );
22081:   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
22082:   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
22083: 
22084:   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
22085:   size = 1<<iLogsize;
22086:   assert( iBlock+size-1<(u32)mem5.nBlock );
22087: 
22088:   mem5.aCtrl[iBlock] |= CTRL_FREE;
22089:   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
22090: 
22091: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
22092:   assert( mem5.currentCount>0 );
22093:   assert( mem5.currentOut>=(size*mem5.szAtom) );
22094:   mem5.currentCount--;
22095:   mem5.currentOut -= size*mem5.szAtom;
22096:   assert( mem5.currentOut>0 || mem5.currentCount==0 );
22097:   assert( mem5.currentCount>0 || mem5.currentOut==0 );
22098: #endif
22099: 
22100:   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22101:   while( ALWAYS(iLogsize<LOGMAX) ){
22102:     int iBuddy;
22103:     if( (iBlock>>iLogsize) & 1 ){
22104:       iBuddy = iBlock - size;
22105:       assert( iBuddy>=0 );
22106:     }else{
22107:       iBuddy = iBlock + size;
22108:       if( iBuddy>=mem5.nBlock ) break;
22109:     }
22110:     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
22111:     memsys5Unlink(iBuddy, iLogsize);
22112:     iLogsize++;
22113:     if( iBuddy<iBlock ){
22114:       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
22115:       mem5.aCtrl[iBlock] = 0;
22116:       iBlock = iBuddy;
22117:     }else{
22118:       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
22119:       mem5.aCtrl[iBuddy] = 0;
22120:     }
22121:     size *= 2;
22122:   }
22123: 
22124: #ifdef SQLITE_DEBUG
22125:   /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
22126:   ** not used after being freed */
22127:   memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
22128: #endif
22129: 
22130:   memsys5Link(iBlock, iLogsize);
22131: }
22132: 
22133: /*
22134: ** Allocate nBytes of memory.
22135: */
22136: static void *memsys5Malloc(int nBytes){
22137:   sqlite3_int64 *p = 0;
22138:   if( nBytes>0 ){
22139:     memsys5Enter();
22140:     p = memsys5MallocUnsafe(nBytes);
22141:     memsys5Leave();
22142:   }
22143:   return (void*)p; 
22144: }
22145: 
22146: /*
22147: ** Free memory.
22148: **
22149: ** The outer layer memory allocator prevents this routine from
22150: ** being called with pPrior==0.
22151: */
22152: static void memsys5Free(void *pPrior){
22153:   assert( pPrior!=0 );
22154:   memsys5Enter();
22155:   memsys5FreeUnsafe(pPrior);
22156:   memsys5Leave();  
22157: }
22158: 
22159: /*
22160: ** Change the size of an existing memory allocation.
22161: **
22162: ** The outer layer memory allocator prevents this routine from
22163: ** being called with pPrior==0.  
22164: **
22165: ** nBytes is always a value obtained from a prior call to
22166: ** memsys5Round().  Hence nBytes is always a non-negative power
22167: ** of two.  If nBytes==0 that means that an oversize allocation
22168: ** (an allocation larger than 0x40000000) was requested and this
22169: ** routine should return 0 without freeing pPrior.
22170: */
22171: static void *memsys5Realloc(void *pPrior, int nBytes){
22172:   int nOld;
22173:   void *p;
22174:   assert( pPrior!=0 );
22175:   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
22176:   assert( nBytes>=0 );
22177:   if( nBytes==0 ){
22178:     return 0;
22179:   }
22180:   nOld = memsys5Size(pPrior);
22181:   if( nBytes<=nOld ){
22182:     return pPrior;
22183:   }
22184:   p = memsys5Malloc(nBytes);
22185:   if( p ){
22186:     memcpy(p, pPrior, nOld);
22187:     memsys5Free(pPrior);
22188:   }
22189:   return p;
22190: }
22191: 
22192: /*
22193: ** Round up a request size to the next valid allocation size.  If
22194: ** the allocation is too large to be handled by this allocation system,
22195: ** return 0.
22196: **
22197: ** All allocations must be a power of two and must be expressed by a
22198: ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
22199: ** or 1073741824 bytes.
22200: */
22201: static int memsys5Roundup(int n){
22202:   int iFullSz;
22203:   if( n > 0x40000000 ) return 0;
22204:   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
22205:   return iFullSz;
22206: }
22207: 
22208: /*
22209: ** Return the ceiling of the logarithm base 2 of iValue.
22210: **
22211: ** Examples:   memsys5Log(1) -> 0
22212: **             memsys5Log(2) -> 1
22213: **             memsys5Log(4) -> 2
22214: **             memsys5Log(5) -> 3
22215: **             memsys5Log(8) -> 3
22216: **             memsys5Log(9) -> 4
22217: */
22218: static int memsys5Log(int iValue){
22219:   int iLog;
22220:   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
22221:   return iLog;
22222: }
22223: 
22224: /*
22225: ** Initialize the memory allocator.
22226: **
22227: ** This routine is not threadsafe.  The caller must be holding a mutex
22228: ** to prevent multiple threads from entering at the same time.
22229: */
22230: static int memsys5Init(void *NotUsed){
22231:   int ii;            /* Loop counter */
22232:   int nByte;         /* Number of bytes of memory available to this allocator */
22233:   u8 *zByte;         /* Memory usable by this allocator */
22234:   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
22235:   int iOffset;       /* An offset into mem5.aCtrl[] */
22236: 
22237:   UNUSED_PARAMETER(NotUsed);
22238: 
22239:   /* For the purposes of this routine, disable the mutex */
22240:   mem5.mutex = 0;
22241: 
22242:   /* The size of a Mem5Link object must be a power of two.  Verify that
22243:   ** this is case.
22244:   */
22245:   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
22246: 
22247:   nByte = sqlite3GlobalConfig.nHeap;
22248:   zByte = (u8*)sqlite3GlobalConfig.pHeap;
22249:   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
22250: 
22251:   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
22252:   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
22253:   mem5.szAtom = (1<<nMinLog);
22254:   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
22255:     mem5.szAtom = mem5.szAtom << 1;
22256:   }
22257: 
22258:   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
22259:   mem5.zPool = zByte;
22260:   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
22261: 
22262:   for(ii=0; ii<=LOGMAX; ii++){
22263:     mem5.aiFreelist[ii] = -1;
22264:   }
22265: 
22266:   iOffset = 0;
22267:   for(ii=LOGMAX; ii>=0; ii--){
22268:     int nAlloc = (1<<ii);
22269:     if( (iOffset+nAlloc)<=mem5.nBlock ){
22270:       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
22271:       memsys5Link(iOffset, ii);
22272:       iOffset += nAlloc;
22273:     }
22274:     assert((iOffset+nAlloc)>mem5.nBlock);
22275:   }
22276: 
22277:   /* If a mutex is required for normal operation, allocate one */
22278:   if( sqlite3GlobalConfig.bMemstat==0 ){
22279:     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
22280:   }
22281: 
22282:   return SQLITE_OK;
22283: }
22284: 
22285: /*
22286: ** Deinitialize this module.
22287: */
22288: static void memsys5Shutdown(void *NotUsed){
22289:   UNUSED_PARAMETER(NotUsed);
22290:   mem5.mutex = 0;
22291:   return;
22292: }
22293: 
22294: #ifdef SQLITE_TEST
22295: /*
22296: ** Open the file indicated and write a log of all unfreed memory 
22297: ** allocations into that log.
22298: */
22299: SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
22300:   FILE *out;
22301:   int i, j, n;
22302:   int nMinLog;
22303: 
22304:   if( zFilename==0 || zFilename[0]==0 ){
22305:     out = stdout;
22306:   }else{
22307:     out = fopen(zFilename, "w");
22308:     if( out==0 ){
22309:       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22310:                       zFilename);
22311:       return;
22312:     }
22313:   }
22314:   memsys5Enter();
22315:   nMinLog = memsys5Log(mem5.szAtom);
22316:   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
22317:     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
22318:     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
22319:   }
22320:   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
22321:   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
22322:   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
22323:   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
22324:   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
22325:   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
22326:   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
22327:   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
22328:   memsys5Leave();
22329:   if( out==stdout ){
22330:     fflush(stdout);
22331:   }else{
22332:     fclose(out);
22333:   }
22334: }
22335: #endif
22336: 
22337: /*
22338: ** This routine is the only routine in this file with external 
22339: ** linkage. It returns a pointer to a static sqlite3_mem_methods
22340: ** struct populated with the memsys5 methods.
22341: */
22342: SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
22343:   static const sqlite3_mem_methods memsys5Methods = {
22344:      memsys5Malloc,
22345:      memsys5Free,
22346:      memsys5Realloc,
22347:      memsys5Size,
22348:      memsys5Roundup,
22349:      memsys5Init,
22350:      memsys5Shutdown,
22351:      0
22352:   };
22353:   return &memsys5Methods;
22354: }
22355: 
22356: #endif /* SQLITE_ENABLE_MEMSYS5 */
22357: 
22358: /************** End of mem5.c ************************************************/
22359: /************** Begin file mutex.c *******************************************/
22360: /*
22361: ** 2007 August 14
22362: **
22363: ** The author disclaims copyright to this source code.  In place of
22364: ** a legal notice, here is a blessing:
22365: **
22366: **    May you do good and not evil.
22367: **    May you find forgiveness for yourself and forgive others.
22368: **    May you share freely, never taking more than you give.
22369: **
22370: *************************************************************************
22371: ** This file contains the C functions that implement mutexes.
22372: **
22373: ** This file contains code that is common across all mutex implementations.
22374: */
22375: /* #include "sqliteInt.h" */
22376: 
22377: #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
22378: /*
22379: ** For debugging purposes, record when the mutex subsystem is initialized
22380: ** and uninitialized so that we can assert() if there is an attempt to
22381: ** allocate a mutex while the system is uninitialized.
22382: */
22383: static SQLITE_WSD int mutexIsInit = 0;
22384: #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
22385: 
22386: 
22387: #ifndef SQLITE_MUTEX_OMIT
22388: /*
22389: ** Initialize the mutex system.
22390: */
22391: SQLITE_PRIVATE int sqlite3MutexInit(void){ 
22392:   int rc = SQLITE_OK;
22393:   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
22394:     /* If the xMutexAlloc method has not been set, then the user did not
22395:     ** install a mutex implementation via sqlite3_config() prior to 
22396:     ** sqlite3_initialize() being called. This block copies pointers to
22397:     ** the default implementation into the sqlite3GlobalConfig structure.
22398:     */
22399:     sqlite3_mutex_methods const *pFrom;
22400:     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
22401: 
22402:     if( sqlite3GlobalConfig.bCoreMutex ){
22403:       pFrom = sqlite3DefaultMutex();
22404:     }else{
22405:       pFrom = sqlite3NoopMutex();
22406:     }
22407:     pTo->xMutexInit = pFrom->xMutexInit;
22408:     pTo->xMutexEnd = pFrom->xMutexEnd;
22409:     pTo->xMutexFree = pFrom->xMutexFree;
22410:     pTo->xMutexEnter = pFrom->xMutexEnter;
22411:     pTo->xMutexTry = pFrom->xMutexTry;
22412:     pTo->xMutexLeave = pFrom->xMutexLeave;
22413:     pTo->xMutexHeld = pFrom->xMutexHeld;
22414:     pTo->xMutexNotheld = pFrom->xMutexNotheld;
22415:     sqlite3MemoryBarrier();
22416:     pTo->xMutexAlloc = pFrom->xMutexAlloc;
22417:   }
22418:   assert( sqlite3GlobalConfig.mutex.xMutexInit );
22419:   rc = sqlite3GlobalConfig.mutex.xMutexInit();
22420: 
22421: #ifdef SQLITE_DEBUG
22422:   GLOBAL(int, mutexIsInit) = 1;
22423: #endif
22424: 
22425:   return rc;
22426: }
22427: 
22428: /*
22429: ** Shutdown the mutex system. This call frees resources allocated by
22430: ** sqlite3MutexInit().
22431: */
22432: SQLITE_PRIVATE int sqlite3MutexEnd(void){
22433:   int rc = SQLITE_OK;
22434:   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
22435:     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
22436:   }
22437: 
22438: #ifdef SQLITE_DEBUG
22439:   GLOBAL(int, mutexIsInit) = 0;
22440: #endif
22441: 
22442:   return rc;
22443: }
22444: 
22445: /*
22446: ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
22447: */
22448: SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
22449: #ifndef SQLITE_OMIT_AUTOINIT
22450:   if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
22451:   if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
22452: #endif
22453:   assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22454:   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22455: }
22456: 
22457: SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
22458:   if( !sqlite3GlobalConfig.bCoreMutex ){
22459:     return 0;
22460:   }
22461:   assert( GLOBAL(int, mutexIsInit) );
22462:   assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22463:   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22464: }
22465: 
22466: /*
22467: ** Free a dynamic mutex.
22468: */
22469: SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
22470:   if( p ){
22471:     assert( sqlite3GlobalConfig.mutex.xMutexFree );
22472:     sqlite3GlobalConfig.mutex.xMutexFree(p);
22473:   }
22474: }
22475: 
22476: /*
22477: ** Obtain the mutex p. If some other thread already has the mutex, block
22478: ** until it can be obtained.
22479: */
22480: SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
22481:   if( p ){
22482:     assert( sqlite3GlobalConfig.mutex.xMutexEnter );
22483:     sqlite3GlobalConfig.mutex.xMutexEnter(p);
22484:   }
22485: }
22486: 
22487: /*
22488: ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
22489: ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
22490: */
22491: SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
22492:   int rc = SQLITE_OK;
22493:   if( p ){
22494:     assert( sqlite3GlobalConfig.mutex.xMutexTry );
22495:     return sqlite3GlobalConfig.mutex.xMutexTry(p);
22496:   }
22497:   return rc;
22498: }
22499: 
22500: /*
22501: ** The sqlite3_mutex_leave() routine exits a mutex that was previously
22502: ** entered by the same thread.  The behavior is undefined if the mutex 
22503: ** is not currently entered. If a NULL pointer is passed as an argument
22504: ** this function is a no-op.
22505: */
22506: SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
22507:   if( p ){
22508:     assert( sqlite3GlobalConfig.mutex.xMutexLeave );
22509:     sqlite3GlobalConfig.mutex.xMutexLeave(p);
22510:   }
22511: }
22512: 
22513: #ifndef NDEBUG
22514: /*
22515: ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22516: ** intended for use inside assert() statements.
22517: */
22518: SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
22519:   assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
22520:   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
22521: }
22522: SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
22523:   assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
22524:   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
22525: }
22526: #endif
22527: 
22528: #endif /* !defined(SQLITE_MUTEX_OMIT) */
22529: 
22530: /************** End of mutex.c ***********************************************/
22531: /************** Begin file mutex_noop.c **************************************/
22532: /*
22533: ** 2008 October 07
22534: **
22535: ** The author disclaims copyright to this source code.  In place of
22536: ** a legal notice, here is a blessing:
22537: **
22538: **    May you do good and not evil.
22539: **    May you find forgiveness for yourself and forgive others.
22540: **    May you share freely, never taking more than you give.
22541: **
22542: *************************************************************************
22543: ** This file contains the C functions that implement mutexes.
22544: **
22545: ** This implementation in this file does not provide any mutual
22546: ** exclusion and is thus suitable for use only in applications
22547: ** that use SQLite in a single thread.  The routines defined
22548: ** here are place-holders.  Applications can substitute working
22549: ** mutex routines at start-time using the
22550: **
22551: **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
22552: **
22553: ** interface.
22554: **
22555: ** If compiled with SQLITE_DEBUG, then additional logic is inserted
22556: ** that does error checking on mutexes to make sure they are being
22557: ** called correctly.
22558: */
22559: /* #include "sqliteInt.h" */
22560: 
22561: #ifndef SQLITE_MUTEX_OMIT
22562: 
22563: #ifndef SQLITE_DEBUG
22564: /*
22565: ** Stub routines for all mutex methods.
22566: **
22567: ** This routines provide no mutual exclusion or error checking.
22568: */
22569: static int noopMutexInit(void){ return SQLITE_OK; }
22570: static int noopMutexEnd(void){ return SQLITE_OK; }
22571: static sqlite3_mutex *noopMutexAlloc(int id){ 
22572:   UNUSED_PARAMETER(id);
22573:   return (sqlite3_mutex*)8; 
22574: }
22575: static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22576: static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22577: static int noopMutexTry(sqlite3_mutex *p){
22578:   UNUSED_PARAMETER(p);
22579:   return SQLITE_OK;
22580: }
22581: static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22582: 
22583: SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22584:   static const sqlite3_mutex_methods sMutex = {
22585:     noopMutexInit,
22586:     noopMutexEnd,
22587:     noopMutexAlloc,
22588:     noopMutexFree,
22589:     noopMutexEnter,
22590:     noopMutexTry,
22591:     noopMutexLeave,
22592: 
22593:     0,
22594:     0,
22595:   };
22596: 
22597:   return &sMutex;
22598: }
22599: #endif /* !SQLITE_DEBUG */
22600: 
22601: #ifdef SQLITE_DEBUG
22602: /*
22603: ** In this implementation, error checking is provided for testing
22604: ** and debugging purposes.  The mutexes still do not provide any
22605: ** mutual exclusion.
22606: */
22607: 
22608: /*
22609: ** The mutex object
22610: */
22611: typedef struct sqlite3_debug_mutex {
22612:   int id;     /* The mutex type */
22613:   int cnt;    /* Number of entries without a matching leave */
22614: } sqlite3_debug_mutex;
22615: 
22616: /*
22617: ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22618: ** intended for use inside assert() statements.
22619: */
22620: static int debugMutexHeld(sqlite3_mutex *pX){
22621:   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22622:   return p==0 || p->cnt>0;
22623: }
22624: static int debugMutexNotheld(sqlite3_mutex *pX){
22625:   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22626:   return p==0 || p->cnt==0;
22627: }
22628: 
22629: /*
22630: ** Initialize and deinitialize the mutex subsystem.
22631: */
22632: static int debugMutexInit(void){ return SQLITE_OK; }
22633: static int debugMutexEnd(void){ return SQLITE_OK; }
22634: 
22635: /*
22636: ** The sqlite3_mutex_alloc() routine allocates a new
22637: ** mutex and returns a pointer to it.  If it returns NULL
22638: ** that means that a mutex could not be allocated. 
22639: */
22640: static sqlite3_mutex *debugMutexAlloc(int id){
22641:   static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
22642:   sqlite3_debug_mutex *pNew = 0;
22643:   switch( id ){
22644:     case SQLITE_MUTEX_FAST:
22645:     case SQLITE_MUTEX_RECURSIVE: {
22646:       pNew = sqlite3Malloc(sizeof(*pNew));
22647:       if( pNew ){
22648:         pNew->id = id;
22649:         pNew->cnt = 0;
22650:       }
22651:       break;
22652:     }
22653:     default: {
22654: #ifdef SQLITE_ENABLE_API_ARMOR
22655:       if( id-2<0 || id-2>=ArraySize(aStatic) ){
22656:         (void)SQLITE_MISUSE_BKPT;
22657:         return 0;
22658:       }
22659: #endif
22660:       pNew = &aStatic[id-2];
22661:       pNew->id = id;
22662:       break;
22663:     }
22664:   }
22665:   return (sqlite3_mutex*)pNew;
22666: }
22667: 
22668: /*
22669: ** This routine deallocates a previously allocated mutex.
22670: */
22671: static void debugMutexFree(sqlite3_mutex *pX){
22672:   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22673:   assert( p->cnt==0 );
22674:   if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
22675:     sqlite3_free(p);
22676:   }else{
22677: #ifdef SQLITE_ENABLE_API_ARMOR
22678:     (void)SQLITE_MISUSE_BKPT;
22679: #endif
22680:   }
22681: }
22682: 
22683: /*
22684: ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22685: ** to enter a mutex.  If another thread is already within the mutex,
22686: ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22687: ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
22688: ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
22689: ** be entered multiple times by the same thread.  In such cases the,
22690: ** mutex must be exited an equal number of times before another thread
22691: ** can enter.  If the same thread tries to enter any other kind of mutex
22692: ** more than once, the behavior is undefined.
22693: */
22694: static void debugMutexEnter(sqlite3_mutex *pX){
22695:   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22696:   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22697:   p->cnt++;
22698: }
22699: static int debugMutexTry(sqlite3_mutex *pX){
22700:   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22701:   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22702:   p->cnt++;
22703:   return SQLITE_OK;
22704: }
22705: 
22706: /*
22707: ** The sqlite3_mutex_leave() routine exits a mutex that was
22708: ** previously entered by the same thread.  The behavior
22709: ** is undefined if the mutex is not currently entered or
22710: ** is not currently allocated.  SQLite will never do either.
22711: */
22712: static void debugMutexLeave(sqlite3_mutex *pX){
22713:   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22714:   assert( debugMutexHeld(pX) );
22715:   p->cnt--;
22716:   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22717: }
22718: 
22719: SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
22720:   static const sqlite3_mutex_methods sMutex = {
22721:     debugMutexInit,
22722:     debugMutexEnd,
22723:     debugMutexAlloc,
22724:     debugMutexFree,
22725:     debugMutexEnter,
22726:     debugMutexTry,
22727:     debugMutexLeave,
22728: 
22729:     debugMutexHeld,
22730:     debugMutexNotheld
22731:   };
22732: 
22733:   return &sMutex;
22734: }
22735: #endif /* SQLITE_DEBUG */
22736: 
22737: /*
22738: ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
22739: ** is used regardless of the run-time threadsafety setting.
22740: */
22741: #ifdef SQLITE_MUTEX_NOOP
22742: SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
22743:   return sqlite3NoopMutex();
22744: }
22745: #endif /* defined(SQLITE_MUTEX_NOOP) */
22746: #endif /* !defined(SQLITE_MUTEX_OMIT) */
22747: 
22748: /************** End of mutex_noop.c ******************************************/
22749: /************** Begin file mutex_unix.c **************************************/
22750: /*
22751: ** 2007 August 28
22752: **
22753: ** The author disclaims copyright to this source code.  In place of
22754: ** a legal notice, here is a blessing:
22755: **
22756: **    May you do good and not evil.
22757: **    May you find forgiveness for yourself and forgive others.
22758: **    May you share freely, never taking more than you give.
22759: **
22760: *************************************************************************
22761: ** This file contains the C functions that implement mutexes for pthreads
22762: */
22763: /* #include "sqliteInt.h" */
22764: 
22765: /*
22766: ** The code in this file is only used if we are compiling threadsafe
22767: ** under unix with pthreads.
22768: **
22769: ** Note that this implementation requires a version of pthreads that
22770: ** supports recursive mutexes.
22771: */
22772: #ifdef SQLITE_MUTEX_PTHREADS
22773: 
22774: #include <pthread.h>
22775: 
22776: /*
22777: ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
22778: ** are necessary under two condidtions:  (1) Debug builds and (2) using
22779: ** home-grown mutexes.  Encapsulate these conditions into a single #define.
22780: */
22781: #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
22782: # define SQLITE_MUTEX_NREF 1
22783: #else
22784: # define SQLITE_MUTEX_NREF 0
22785: #endif
22786: 
22787: /*
22788: ** Each recursive mutex is an instance of the following structure.
22789: */
22790: struct sqlite3_mutex {
22791:   pthread_mutex_t mutex;     /* Mutex controlling the lock */
22792: #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22793:   int id;                    /* Mutex type */
22794: #endif
22795: #if SQLITE_MUTEX_NREF
22796:   volatile int nRef;         /* Number of entrances */
22797:   volatile pthread_t owner;  /* Thread that is within this mutex */
22798:   int trace;                 /* True to trace changes */
22799: #endif
22800: };
22801: #if SQLITE_MUTEX_NREF
22802: #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
22803: #elif defined(SQLITE_ENABLE_API_ARMOR)
22804: #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
22805: #else
22806: #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
22807: #endif
22808: 
22809: /*
22810: ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22811: ** intended for use only inside assert() statements.  On some platforms,
22812: ** there might be race conditions that can cause these routines to
22813: ** deliver incorrect results.  In particular, if pthread_equal() is
22814: ** not an atomic operation, then these routines might delivery
22815: ** incorrect results.  On most platforms, pthread_equal() is a 
22816: ** comparison of two integers and is therefore atomic.  But we are
22817: ** told that HPUX is not such a platform.  If so, then these routines
22818: ** will not always work correctly on HPUX.
22819: **
22820: ** On those platforms where pthread_equal() is not atomic, SQLite
22821: ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
22822: ** make sure no assert() statements are evaluated and hence these
22823: ** routines are never called.
22824: */
22825: #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
22826: static int pthreadMutexHeld(sqlite3_mutex *p){
22827:   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
22828: }
22829: static int pthreadMutexNotheld(sqlite3_mutex *p){
22830:   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
22831: }
22832: #endif
22833: 
22834: /*
22835: ** Try to provide a memory barrier operation, needed for initialization
22836: ** and also for the implementation of xShmBarrier in the VFS in cases
22837: ** where SQLite is compiled without mutexes.
22838: */
22839: SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
22840: #if defined(SQLITE_MEMORY_BARRIER)
22841:   SQLITE_MEMORY_BARRIER;
22842: #elif defined(__GNUC__) && GCC_VERSION>=4001000
22843:   __sync_synchronize();
22844: #endif
22845: }
22846: 
22847: /*
22848: ** Initialize and deinitialize the mutex subsystem.
22849: */
22850: static int pthreadMutexInit(void){ return SQLITE_OK; }
22851: static int pthreadMutexEnd(void){ return SQLITE_OK; }
22852: 
22853: /*
22854: ** The sqlite3_mutex_alloc() routine allocates a new
22855: ** mutex and returns a pointer to it.  If it returns NULL
22856: ** that means that a mutex could not be allocated.  SQLite
22857: ** will unwind its stack and return an error.  The argument
22858: ** to sqlite3_mutex_alloc() is one of these integer constants:
22859: **
22860: ** <ul>
22861: ** <li>  SQLITE_MUTEX_FAST
22862: ** <li>  SQLITE_MUTEX_RECURSIVE
22863: ** <li>  SQLITE_MUTEX_STATIC_MASTER
22864: ** <li>  SQLITE_MUTEX_STATIC_MEM
22865: ** <li>  SQLITE_MUTEX_STATIC_OPEN
22866: ** <li>  SQLITE_MUTEX_STATIC_PRNG
22867: ** <li>  SQLITE_MUTEX_STATIC_LRU
22868: ** <li>  SQLITE_MUTEX_STATIC_PMEM
22869: ** <li>  SQLITE_MUTEX_STATIC_APP1
22870: ** <li>  SQLITE_MUTEX_STATIC_APP2
22871: ** <li>  SQLITE_MUTEX_STATIC_APP3
22872: ** <li>  SQLITE_MUTEX_STATIC_VFS1
22873: ** <li>  SQLITE_MUTEX_STATIC_VFS2
22874: ** <li>  SQLITE_MUTEX_STATIC_VFS3
22875: ** </ul>
22876: **
22877: ** The first two constants cause sqlite3_mutex_alloc() to create
22878: ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
22879: ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
22880: ** The mutex implementation does not need to make a distinction
22881: ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
22882: ** not want to.  But SQLite will only request a recursive mutex in
22883: ** cases where it really needs one.  If a faster non-recursive mutex
22884: ** implementation is available on the host platform, the mutex subsystem
22885: ** might return such a mutex in response to SQLITE_MUTEX_FAST.
22886: **
22887: ** The other allowed parameters to sqlite3_mutex_alloc() each return
22888: ** a pointer to a static preexisting mutex.  Six static mutexes are
22889: ** used by the current version of SQLite.  Future versions of SQLite
22890: ** may add additional static mutexes.  Static mutexes are for internal
22891: ** use by SQLite only.  Applications that use SQLite mutexes should
22892: ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
22893: ** SQLITE_MUTEX_RECURSIVE.
22894: **
22895: ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
22896: ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
22897: ** returns a different mutex on every call.  But for the static 
22898: ** mutex types, the same mutex is returned on every call that has
22899: ** the same type number.
22900: */
22901: static sqlite3_mutex *pthreadMutexAlloc(int iType){
22902:   static sqlite3_mutex staticMutexes[] = {
22903:     SQLITE3_MUTEX_INITIALIZER,
22904:     SQLITE3_MUTEX_INITIALIZER,
22905:     SQLITE3_MUTEX_INITIALIZER,
22906:     SQLITE3_MUTEX_INITIALIZER,
22907:     SQLITE3_MUTEX_INITIALIZER,
22908:     SQLITE3_MUTEX_INITIALIZER,
22909:     SQLITE3_MUTEX_INITIALIZER,
22910:     SQLITE3_MUTEX_INITIALIZER,
22911:     SQLITE3_MUTEX_INITIALIZER,
22912:     SQLITE3_MUTEX_INITIALIZER,
22913:     SQLITE3_MUTEX_INITIALIZER,
22914:     SQLITE3_MUTEX_INITIALIZER
22915:   };
22916:   sqlite3_mutex *p;
22917:   switch( iType ){
22918:     case SQLITE_MUTEX_RECURSIVE: {
22919:       p = sqlite3MallocZero( sizeof(*p) );
22920:       if( p ){
22921: #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22922:         /* If recursive mutexes are not available, we will have to
22923:         ** build our own.  See below. */
22924:         pthread_mutex_init(&p->mutex, 0);
22925: #else
22926:         /* Use a recursive mutex if it is available */
22927:         pthread_mutexattr_t recursiveAttr;
22928:         pthread_mutexattr_init(&recursiveAttr);
22929:         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
22930:         pthread_mutex_init(&p->mutex, &recursiveAttr);
22931:         pthread_mutexattr_destroy(&recursiveAttr);
22932: #endif
22933:       }
22934:       break;
22935:     }
22936:     case SQLITE_MUTEX_FAST: {
22937:       p = sqlite3MallocZero( sizeof(*p) );
22938:       if( p ){
22939:         pthread_mutex_init(&p->mutex, 0);
22940:       }
22941:       break;
22942:     }
22943:     default: {
22944: #ifdef SQLITE_ENABLE_API_ARMOR
22945:       if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
22946:         (void)SQLITE_MISUSE_BKPT;
22947:         return 0;
22948:       }
22949: #endif
22950:       p = &staticMutexes[iType-2];
22951:       break;
22952:     }
22953:   }
22954: #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22955:   if( p ) p->id = iType;
22956: #endif
22957:   return p;
22958: }
22959: 
22960: 
22961: /*
22962: ** This routine deallocates a previously
22963: ** allocated mutex.  SQLite is careful to deallocate every
22964: ** mutex that it allocates.
22965: */
22966: static void pthreadMutexFree(sqlite3_mutex *p){
22967:   assert( p->nRef==0 );
22968: #if SQLITE_ENABLE_API_ARMOR
22969:   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
22970: #endif
22971:   {
22972:     pthread_mutex_destroy(&p->mutex);
22973:     sqlite3_free(p);
22974:   }
22975: #ifdef SQLITE_ENABLE_API_ARMOR
22976:   else{
22977:     (void)SQLITE_MISUSE_BKPT;
22978:   }
22979: #endif
22980: }
22981: 
22982: /*
22983: ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22984: ** to enter a mutex.  If another thread is already within the mutex,
22985: ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22986: ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
22987: ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
22988: ** be entered multiple times by the same thread.  In such cases the,
22989: ** mutex must be exited an equal number of times before another thread
22990: ** can enter.  If the same thread tries to enter any other kind of mutex
22991: ** more than once, the behavior is undefined.
22992: */
22993: static void pthreadMutexEnter(sqlite3_mutex *p){
22994:   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
22995: 
22996: #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22997:   /* If recursive mutexes are not available, then we have to grow
22998:   ** our own.  This implementation assumes that pthread_equal()
22999:   ** is atomic - that it cannot be deceived into thinking self
23000:   ** and p->owner are equal if p->owner changes between two values
23001:   ** that are not equal to self while the comparison is taking place.
23002:   ** This implementation also assumes a coherent cache - that 
23003:   ** separate processes cannot read different values from the same
23004:   ** address at the same time.  If either of these two conditions
23005:   ** are not met, then the mutexes will fail and problems will result.
23006:   */
23007:   {
23008:     pthread_t self = pthread_self();
23009:     if( p->nRef>0 && pthread_equal(p->owner, self) ){
23010:       p->nRef++;
23011:     }else{
23012:       pthread_mutex_lock(&p->mutex);
23013:       assert( p->nRef==0 );
23014:       p->owner = self;
23015:       p->nRef = 1;
23016:     }
23017:   }
23018: #else
23019:   /* Use the built-in recursive mutexes if they are available.
23020:   */
23021:   pthread_mutex_lock(&p->mutex);
23022: #if SQLITE_MUTEX_NREF
23023:   assert( p->nRef>0 || p->owner==0 );
23024:   p->owner = pthread_self();
23025:   p->nRef++;
23026: #endif
23027: #endif
23028: 
23029: #ifdef SQLITE_DEBUG
23030:   if( p->trace ){
23031:     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23032:   }
23033: #endif
23034: }
23035: static int pthreadMutexTry(sqlite3_mutex *p){
23036:   int rc;
23037:   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
23038: 
23039: #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23040:   /* If recursive mutexes are not available, then we have to grow
23041:   ** our own.  This implementation assumes that pthread_equal()
23042:   ** is atomic - that it cannot be deceived into thinking self
23043:   ** and p->owner are equal if p->owner changes between two values
23044:   ** that are not equal to self while the comparison is taking place.
23045:   ** This implementation also assumes a coherent cache - that 
23046:   ** separate processes cannot read different values from the same
23047:   ** address at the same time.  If either of these two conditions
23048:   ** are not met, then the mutexes will fail and problems will result.
23049:   */
23050:   {
23051:     pthread_t self = pthread_self();
23052:     if( p->nRef>0 && pthread_equal(p->owner, self) ){
23053:       p->nRef++;
23054:       rc = SQLITE_OK;
23055:     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
23056:       assert( p->nRef==0 );
23057:       p->owner = self;
23058:       p->nRef = 1;
23059:       rc = SQLITE_OK;
23060:     }else{
23061:       rc = SQLITE_BUSY;
23062:     }
23063:   }
23064: #else
23065:   /* Use the built-in recursive mutexes if they are available.
23066:   */
23067:   if( pthread_mutex_trylock(&p->mutex)==0 ){
23068: #if SQLITE_MUTEX_NREF
23069:     p->owner = pthread_self();
23070:     p->nRef++;
23071: #endif
23072:     rc = SQLITE_OK;
23073:   }else{
23074:     rc = SQLITE_BUSY;
23075:   }
23076: #endif
23077: 
23078: #ifdef SQLITE_DEBUG
23079:   if( rc==SQLITE_OK && p->trace ){
23080:     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23081:   }
23082: #endif
23083:   return rc;
23084: }
23085: 
23086: /*
23087: ** The sqlite3_mutex_leave() routine exits a mutex that was
23088: ** previously entered by the same thread.  The behavior
23089: ** is undefined if the mutex is not currently entered or
23090: ** is not currently allocated.  SQLite will never do either.
23091: */
23092: static void pthreadMutexLeave(sqlite3_mutex *p){
23093:   assert( pthreadMutexHeld(p) );
23094: #if SQLITE_MUTEX_NREF
23095:   p->nRef--;
23096:   if( p->nRef==0 ) p->owner = 0;
23097: #endif
23098:   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23099: 
23100: #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
23101:   if( p->nRef==0 ){
23102:     pthread_mutex_unlock(&p->mutex);
23103:   }
23104: #else
23105:   pthread_mutex_unlock(&p->mutex);
23106: #endif
23107: 
23108: #ifdef SQLITE_DEBUG
23109:   if( p->trace ){
23110:     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
23111:   }
23112: #endif
23113: }
23114: 
23115: SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23116:   static const sqlite3_mutex_methods sMutex = {
23117:     pthreadMutexInit,
23118:     pthreadMutexEnd,
23119:     pthreadMutexAlloc,
23120:     pthreadMutexFree,
23121:     pthreadMutexEnter,
23122:     pthreadMutexTry,
23123:     pthreadMutexLeave,
23124: #ifdef SQLITE_DEBUG
23125:     pthreadMutexHeld,
23126:     pthreadMutexNotheld
23127: #else
23128:     0,
23129:     0
23130: #endif
23131:   };
23132: 
23133:   return &sMutex;
23134: }
23135: 
23136: #endif /* SQLITE_MUTEX_PTHREADS */
23137: 
23138: /************** End of mutex_unix.c ******************************************/
23139: /************** Begin file mutex_w32.c ***************************************/
23140: /*
23141: ** 2007 August 14
23142: **
23143: ** The author disclaims copyright to this source code.  In place of
23144: ** a legal notice, here is a blessing:
23145: **
23146: **    May you do good and not evil.
23147: **    May you find forgiveness for yourself and forgive others.
23148: **    May you share freely, never taking more than you give.
23149: **
23150: *************************************************************************
23151: ** This file contains the C functions that implement mutexes for Win32.
23152: */
23153: /* #include "sqliteInt.h" */
23154: 
23155: #if SQLITE_OS_WIN
23156: /*
23157: ** Include code that is common to all os_*.c files
23158: */
23159: /************** Include os_common.h in the middle of mutex_w32.c *************/
23160: /************** Begin file os_common.h ***************************************/
23161: /*
23162: ** 2004 May 22
23163: **
23164: ** The author disclaims copyright to this source code.  In place of
23165: ** a legal notice, here is a blessing:
23166: **
23167: **    May you do good and not evil.
23168: **    May you find forgiveness for yourself and forgive others.
23169: **    May you share freely, never taking more than you give.
23170: **
23171: ******************************************************************************
23172: **
23173: ** This file contains macros and a little bit of code that is common to
23174: ** all of the platform-specific files (os_*.c) and is #included into those
23175: ** files.
23176: **
23177: ** This file should be #included by the os_*.c files only.  It is not a
23178: ** general purpose header file.
23179: */
23180: #ifndef _OS_COMMON_H_
23181: #define _OS_COMMON_H_
23182: 
23183: /*
23184: ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23185: ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23186: ** switch.  The following code should catch this problem at compile-time.
23187: */
23188: #ifdef MEMORY_DEBUG
23189: # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23190: #endif
23191: 
23192: /*
23193: ** Macros for performance tracing.  Normally turned off.  Only works
23194: ** on i486 hardware.
23195: */
23196: #ifdef SQLITE_PERFORMANCE_TRACE
23197: 
23198: /*
23199: ** hwtime.h contains inline assembler code for implementing
23200: ** high-performance timing routines.
23201: */
23202: /************** Include hwtime.h in the middle of os_common.h ****************/
23203: /************** Begin file hwtime.h ******************************************/
23204: /*
23205: ** 2008 May 27
23206: **
23207: ** The author disclaims copyright to this source code.  In place of
23208: ** a legal notice, here is a blessing:
23209: **
23210: **    May you do good and not evil.
23211: **    May you find forgiveness for yourself and forgive others.
23212: **    May you share freely, never taking more than you give.
23213: **
23214: ******************************************************************************
23215: **
23216: ** This file contains inline asm code for retrieving "high-performance"
23217: ** counters for x86 class CPUs.
23218: */
23219: #ifndef SQLITE_HWTIME_H
23220: #define SQLITE_HWTIME_H
23221: 
23222: /*
23223: ** The following routine only works on pentium-class (or newer) processors.
23224: ** It uses the RDTSC opcode to read the cycle count value out of the
23225: ** processor and returns that value.  This can be used for high-res
23226: ** profiling.
23227: */
23228: #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23229:       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23230: 
23231:   #if defined(__GNUC__)
23232: 
23233:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23234:      unsigned int lo, hi;
23235:      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23236:      return (sqlite_uint64)hi << 32 | lo;
23237:   }
23238: 
23239:   #elif defined(_MSC_VER)
23240: 
23241:   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23242:      __asm {
23243:         rdtsc
23244:         ret       ; return value at EDX:EAX
23245:      }
23246:   }
23247: 
23248:   #endif
23249: 
23250: #elif (defined(__GNUC__) && defined(__x86_64__))
23251: 
23252:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23253:       unsigned long val;
23254:       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23255:       return val;
23256:   }
23257:  
23258: #elif (defined(__GNUC__) && defined(__ppc__))
23259: 
23260:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23261:       unsigned long long retval;
23262:       unsigned long junk;
23263:       __asm__ __volatile__ ("\n\
23264:           1:      mftbu   %1\n\
23265:                   mftb    %L0\n\
23266:                   mftbu   %0\n\
23267:                   cmpw    %0,%1\n\
23268:                   bne     1b"
23269:                   : "=r" (retval), "=r" (junk));
23270:       return retval;
23271:   }
23272: 
23273: #else
23274: 
23275:   #error Need implementation of sqlite3Hwtime() for your platform.
23276: 
23277:   /*
23278:   ** To compile without implementing sqlite3Hwtime() for your platform,
23279:   ** you can remove the above #error and use the following
23280:   ** stub function.  You will lose timing support for many
23281:   ** of the debugging and testing utilities, but it should at
23282:   ** least compile and run.
23283:   */
23284: SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23285: 
23286: #endif
23287: 
23288: #endif /* !defined(SQLITE_HWTIME_H) */
23289: 
23290: /************** End of hwtime.h **********************************************/
23291: /************** Continuing where we left off in os_common.h ******************/
23292: 
23293: static sqlite_uint64 g_start;
23294: static sqlite_uint64 g_elapsed;
23295: #define TIMER_START       g_start=sqlite3Hwtime()
23296: #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23297: #define TIMER_ELAPSED     g_elapsed
23298: #else
23299: #define TIMER_START
23300: #define TIMER_END
23301: #define TIMER_ELAPSED     ((sqlite_uint64)0)
23302: #endif
23303: 
23304: /*
23305: ** If we compile with the SQLITE_TEST macro set, then the following block
23306: ** of code will give us the ability to simulate a disk I/O error.  This
23307: ** is used for testing the I/O recovery logic.
23308: */
23309: #if defined(SQLITE_TEST)
23310: SQLITE_API extern int sqlite3_io_error_hit;
23311: SQLITE_API extern int sqlite3_io_error_hardhit;
23312: SQLITE_API extern int sqlite3_io_error_pending;
23313: SQLITE_API extern int sqlite3_io_error_persist;
23314: SQLITE_API extern int sqlite3_io_error_benign;
23315: SQLITE_API extern int sqlite3_diskfull_pending;
23316: SQLITE_API extern int sqlite3_diskfull;
23317: #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23318: #define SimulateIOError(CODE)  \
23319:   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23320:        || sqlite3_io_error_pending-- == 1 )  \
23321:               { local_ioerr(); CODE; }
23322: static void local_ioerr(){
23323:   IOTRACE(("IOERR\n"));
23324:   sqlite3_io_error_hit++;
23325:   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23326: }
23327: #define SimulateDiskfullError(CODE) \
23328:    if( sqlite3_diskfull_pending ){ \
23329:      if( sqlite3_diskfull_pending == 1 ){ \
23330:        local_ioerr(); \
23331:        sqlite3_diskfull = 1; \
23332:        sqlite3_io_error_hit = 1; \
23333:        CODE; \
23334:      }else{ \
23335:        sqlite3_diskfull_pending--; \
23336:      } \
23337:    }
23338: #else
23339: #define SimulateIOErrorBenign(X)
23340: #define SimulateIOError(A)
23341: #define SimulateDiskfullError(A)
23342: #endif /* defined(SQLITE_TEST) */
23343: 
23344: /*
23345: ** When testing, keep a count of the number of open files.
23346: */
23347: #if defined(SQLITE_TEST)
23348: SQLITE_API extern int sqlite3_open_file_count;
23349: #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23350: #else
23351: #define OpenCounter(X)
23352: #endif /* defined(SQLITE_TEST) */
23353: 
23354: #endif /* !defined(_OS_COMMON_H_) */
23355: 
23356: /************** End of os_common.h *******************************************/
23357: /************** Continuing where we left off in mutex_w32.c ******************/
23358: 
23359: /*
23360: ** Include the header file for the Windows VFS.
23361: */
23362: /************** Include os_win.h in the middle of mutex_w32.c ****************/
23363: /************** Begin file os_win.h ******************************************/
23364: /*
23365: ** 2013 November 25
23366: **
23367: ** The author disclaims copyright to this source code.  In place of
23368: ** a legal notice, here is a blessing:
23369: **
23370: **    May you do good and not evil.
23371: **    May you find forgiveness for yourself and forgive others.
23372: **    May you share freely, never taking more than you give.
23373: **
23374: ******************************************************************************
23375: **
23376: ** This file contains code that is specific to Windows.
23377: */
23378: #ifndef SQLITE_OS_WIN_H
23379: #define SQLITE_OS_WIN_H
23380: 
23381: /*
23382: ** Include the primary Windows SDK header file.
23383: */
23384: #include "windows.h"
23385: 
23386: #ifdef __CYGWIN__
23387: # include <sys/cygwin.h>
23388: # include <errno.h> /* amalgamator: dontcache */
23389: #endif
23390: 
23391: /*
23392: ** Determine if we are dealing with Windows NT.
23393: **
23394: ** We ought to be able to determine if we are compiling for Windows 9x or
23395: ** Windows NT using the _WIN32_WINNT macro as follows:
23396: **
23397: ** #if defined(_WIN32_WINNT)
23398: ** # define SQLITE_OS_WINNT 1
23399: ** #else
23400: ** # define SQLITE_OS_WINNT 0
23401: ** #endif
23402: **
23403: ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
23404: ** it ought to, so the above test does not work.  We'll just assume that
23405: ** everything is Windows NT unless the programmer explicitly says otherwise
23406: ** by setting SQLITE_OS_WINNT to 0.
23407: */
23408: #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
23409: # define SQLITE_OS_WINNT 1
23410: #endif
23411: 
23412: /*
23413: ** Determine if we are dealing with Windows CE - which has a much reduced
23414: ** API.
23415: */
23416: #if defined(_WIN32_WCE)
23417: # define SQLITE_OS_WINCE 1
23418: #else
23419: # define SQLITE_OS_WINCE 0
23420: #endif
23421: 
23422: /*
23423: ** Determine if we are dealing with WinRT, which provides only a subset of
23424: ** the full Win32 API.
23425: */
23426: #if !defined(SQLITE_OS_WINRT)
23427: # define SQLITE_OS_WINRT 0
23428: #endif
23429: 
23430: /*
23431: ** For WinCE, some API function parameters do not appear to be declared as
23432: ** volatile.
23433: */
23434: #if SQLITE_OS_WINCE
23435: # define SQLITE_WIN32_VOLATILE
23436: #else
23437: # define SQLITE_WIN32_VOLATILE volatile
23438: #endif
23439: 
23440: /*
23441: ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
23442: ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
23443: */
23444: #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
23445:     SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
23446: # define SQLITE_OS_WIN_THREADS 1
23447: #else
23448: # define SQLITE_OS_WIN_THREADS 0
23449: #endif
23450: 
23451: #endif /* SQLITE_OS_WIN_H */
23452: 
23453: /************** End of os_win.h **********************************************/
23454: /************** Continuing where we left off in mutex_w32.c ******************/
23455: #endif
23456: 
23457: /*
23458: ** The code in this file is only used if we are compiling multithreaded
23459: ** on a Win32 system.
23460: */
23461: #ifdef SQLITE_MUTEX_W32
23462: 
23463: /*
23464: ** Each recursive mutex is an instance of the following structure.
23465: */
23466: struct sqlite3_mutex {
23467:   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
23468:   int id;                    /* Mutex type */
23469: #ifdef SQLITE_DEBUG
23470:   volatile int nRef;         /* Number of enterances */
23471:   volatile DWORD owner;      /* Thread holding this mutex */
23472:   volatile int trace;        /* True to trace changes */
23473: #endif
23474: };
23475: 
23476: /*
23477: ** These are the initializer values used when declaring a "static" mutex
23478: ** on Win32.  It should be noted that all mutexes require initialization
23479: ** on the Win32 platform.
23480: */
23481: #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
23482: 
23483: #ifdef SQLITE_DEBUG
23484: #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
23485:                                     0L, (DWORD)0, 0 }
23486: #else
23487: #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
23488: #endif
23489: 
23490: #ifdef SQLITE_DEBUG
23491: /*
23492: ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23493: ** intended for use only inside assert() statements.
23494: */
23495: static int winMutexHeld(sqlite3_mutex *p){
23496:   return p->nRef!=0 && p->owner==GetCurrentThreadId();
23497: }
23498: 
23499: static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
23500:   return p->nRef==0 || p->owner!=tid;
23501: }
23502: 
23503: static int winMutexNotheld(sqlite3_mutex *p){
23504:   DWORD tid = GetCurrentThreadId();
23505:   return winMutexNotheld2(p, tid);
23506: }
23507: #endif
23508: 
23509: /*
23510: ** Try to provide a memory barrier operation, needed for initialization
23511: ** and also for the xShmBarrier method of the VFS in cases when SQLite is
23512: ** compiled without mutexes (SQLITE_THREADSAFE=0).
23513: */
23514: SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
23515: #if defined(SQLITE_MEMORY_BARRIER)
23516:   SQLITE_MEMORY_BARRIER;
23517: #elif defined(__GNUC__)
23518:   __sync_synchronize();
23519: #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
23520:       defined(_MSC_VER) && _MSC_VER>=1300
23521:   _ReadWriteBarrier();
23522: #elif defined(MemoryBarrier)
23523:   MemoryBarrier();
23524: #endif
23525: }
23526: 
23527: /*
23528: ** Initialize and deinitialize the mutex subsystem.
23529: */
23530: static sqlite3_mutex winMutex_staticMutexes[] = {
23531:   SQLITE3_MUTEX_INITIALIZER,
23532:   SQLITE3_MUTEX_INITIALIZER,
23533:   SQLITE3_MUTEX_INITIALIZER,
23534:   SQLITE3_MUTEX_INITIALIZER,
23535:   SQLITE3_MUTEX_INITIALIZER,
23536:   SQLITE3_MUTEX_INITIALIZER,
23537:   SQLITE3_MUTEX_INITIALIZER,
23538:   SQLITE3_MUTEX_INITIALIZER,
23539:   SQLITE3_MUTEX_INITIALIZER,
23540:   SQLITE3_MUTEX_INITIALIZER,
23541:   SQLITE3_MUTEX_INITIALIZER,
23542:   SQLITE3_MUTEX_INITIALIZER
23543: };
23544: 
23545: static int winMutex_isInit = 0;
23546: static int winMutex_isNt = -1; /* <0 means "need to query" */
23547: 
23548: /* As the winMutexInit() and winMutexEnd() functions are called as part
23549: ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
23550: ** "interlocked" magic used here is probably not strictly necessary.
23551: */
23552: static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
23553: 
23554: SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
23555: SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
23556: 
23557: static int winMutexInit(void){
23558:   /* The first to increment to 1 does actual initialization */
23559:   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
23560:     int i;
23561:     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23562: #if SQLITE_OS_WINRT
23563:       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
23564: #else
23565:       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
23566: #endif
23567:     }
23568:     winMutex_isInit = 1;
23569:   }else{
23570:     /* Another thread is (in the process of) initializing the static
23571:     ** mutexes */
23572:     while( !winMutex_isInit ){
23573:       sqlite3_win32_sleep(1);
23574:     }
23575:   }
23576:   return SQLITE_OK;
23577: }
23578: 
23579: static int winMutexEnd(void){
23580:   /* The first to decrement to 0 does actual shutdown
23581:   ** (which should be the last to shutdown.) */
23582:   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
23583:     if( winMutex_isInit==1 ){
23584:       int i;
23585:       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23586:         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
23587:       }
23588:       winMutex_isInit = 0;
23589:     }
23590:   }
23591:   return SQLITE_OK;
23592: }
23593: 
23594: /*
23595: ** The sqlite3_mutex_alloc() routine allocates a new
23596: ** mutex and returns a pointer to it.  If it returns NULL
23597: ** that means that a mutex could not be allocated.  SQLite
23598: ** will unwind its stack and return an error.  The argument
23599: ** to sqlite3_mutex_alloc() is one of these integer constants:
23600: **
23601: ** <ul>
23602: ** <li>  SQLITE_MUTEX_FAST
23603: ** <li>  SQLITE_MUTEX_RECURSIVE
23604: ** <li>  SQLITE_MUTEX_STATIC_MASTER
23605: ** <li>  SQLITE_MUTEX_STATIC_MEM
23606: ** <li>  SQLITE_MUTEX_STATIC_OPEN
23607: ** <li>  SQLITE_MUTEX_STATIC_PRNG
23608: ** <li>  SQLITE_MUTEX_STATIC_LRU
23609: ** <li>  SQLITE_MUTEX_STATIC_PMEM
23610: ** <li>  SQLITE_MUTEX_STATIC_APP1
23611: ** <li>  SQLITE_MUTEX_STATIC_APP2
23612: ** <li>  SQLITE_MUTEX_STATIC_APP3
23613: ** <li>  SQLITE_MUTEX_STATIC_VFS1
23614: ** <li>  SQLITE_MUTEX_STATIC_VFS2
23615: ** <li>  SQLITE_MUTEX_STATIC_VFS3
23616: ** </ul>
23617: **
23618: ** The first two constants cause sqlite3_mutex_alloc() to create
23619: ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23620: ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23621: ** The mutex implementation does not need to make a distinction
23622: ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23623: ** not want to.  But SQLite will only request a recursive mutex in
23624: ** cases where it really needs one.  If a faster non-recursive mutex
23625: ** implementation is available on the host platform, the mutex subsystem
23626: ** might return such a mutex in response to SQLITE_MUTEX_FAST.
23627: **
23628: ** The other allowed parameters to sqlite3_mutex_alloc() each return
23629: ** a pointer to a static preexisting mutex.  Six static mutexes are
23630: ** used by the current version of SQLite.  Future versions of SQLite
23631: ** may add additional static mutexes.  Static mutexes are for internal
23632: ** use by SQLite only.  Applications that use SQLite mutexes should
23633: ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23634: ** SQLITE_MUTEX_RECURSIVE.
23635: **
23636: ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23637: ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23638: ** returns a different mutex on every call.  But for the static
23639: ** mutex types, the same mutex is returned on every call that has
23640: ** the same type number.
23641: */
23642: static sqlite3_mutex *winMutexAlloc(int iType){
23643:   sqlite3_mutex *p;
23644: 
23645:   switch( iType ){
23646:     case SQLITE_MUTEX_FAST:
23647:     case SQLITE_MUTEX_RECURSIVE: {
23648:       p = sqlite3MallocZero( sizeof(*p) );
23649:       if( p ){
23650:         p->id = iType;
23651: #ifdef SQLITE_DEBUG
23652: #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
23653:         p->trace = 1;
23654: #endif
23655: #endif
23656: #if SQLITE_OS_WINRT
23657:         InitializeCriticalSectionEx(&p->mutex, 0, 0);
23658: #else
23659:         InitializeCriticalSection(&p->mutex);
23660: #endif
23661:       }
23662:       break;
23663:     }
23664:     default: {
23665: #ifdef SQLITE_ENABLE_API_ARMOR
23666:       if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
23667:         (void)SQLITE_MISUSE_BKPT;
23668:         return 0;
23669:       }
23670: #endif
23671:       p = &winMutex_staticMutexes[iType-2];
23672:       p->id = iType;
23673: #ifdef SQLITE_DEBUG
23674: #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
23675:       p->trace = 1;
23676: #endif
23677: #endif
23678:       break;
23679:     }
23680:   }
23681:   return p;
23682: }
23683: 
23684: 
23685: /*
23686: ** This routine deallocates a previously
23687: ** allocated mutex.  SQLite is careful to deallocate every
23688: ** mutex that it allocates.
23689: */
23690: static void winMutexFree(sqlite3_mutex *p){
23691:   assert( p );
23692:   assert( p->nRef==0 && p->owner==0 );
23693:   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
23694:     DeleteCriticalSection(&p->mutex);
23695:     sqlite3_free(p);
23696:   }else{
23697: #ifdef SQLITE_ENABLE_API_ARMOR
23698:     (void)SQLITE_MISUSE_BKPT;
23699: #endif
23700:   }
23701: }
23702: 
23703: /*
23704: ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23705: ** to enter a mutex.  If another thread is already within the mutex,
23706: ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23707: ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
23708: ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
23709: ** be entered multiple times by the same thread.  In such cases the,
23710: ** mutex must be exited an equal number of times before another thread
23711: ** can enter.  If the same thread tries to enter any other kind of mutex
23712: ** more than once, the behavior is undefined.
23713: */
23714: static void winMutexEnter(sqlite3_mutex *p){
23715: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23716:   DWORD tid = GetCurrentThreadId();
23717: #endif
23718: #ifdef SQLITE_DEBUG
23719:   assert( p );
23720:   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23721: #else
23722:   assert( p );
23723: #endif
23724:   assert( winMutex_isInit==1 );
23725:   EnterCriticalSection(&p->mutex);
23726: #ifdef SQLITE_DEBUG
23727:   assert( p->nRef>0 || p->owner==0 );
23728:   p->owner = tid;
23729:   p->nRef++;
23730:   if( p->trace ){
23731:     OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23732:              tid, p, p->trace, p->nRef));
23733:   }
23734: #endif
23735: }
23736: 
23737: static int winMutexTry(sqlite3_mutex *p){
23738: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23739:   DWORD tid = GetCurrentThreadId();
23740: #endif
23741:   int rc = SQLITE_BUSY;
23742:   assert( p );
23743:   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23744:   /*
23745:   ** The sqlite3_mutex_try() routine is very rarely used, and when it
23746:   ** is used it is merely an optimization.  So it is OK for it to always
23747:   ** fail.
23748:   **
23749:   ** The TryEnterCriticalSection() interface is only available on WinNT.
23750:   ** And some windows compilers complain if you try to use it without
23751:   ** first doing some #defines that prevent SQLite from building on Win98.
23752:   ** For that reason, we will omit this optimization for now.  See
23753:   ** ticket #2685.
23754:   */
23755: #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
23756:   assert( winMutex_isInit==1 );
23757:   assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
23758:   if( winMutex_isNt<0 ){
23759:     winMutex_isNt = sqlite3_win32_is_nt();
23760:   }
23761:   assert( winMutex_isNt==0 || winMutex_isNt==1 );
23762:   if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
23763: #ifdef SQLITE_DEBUG
23764:     p->owner = tid;
23765:     p->nRef++;
23766: #endif
23767:     rc = SQLITE_OK;
23768:   }
23769: #else
23770:   UNUSED_PARAMETER(p);
23771: #endif
23772: #ifdef SQLITE_DEBUG
23773:   if( p->trace ){
23774:     OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
23775:              tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
23776:   }
23777: #endif
23778:   return rc;
23779: }
23780: 
23781: /*
23782: ** The sqlite3_mutex_leave() routine exits a mutex that was
23783: ** previously entered by the same thread.  The behavior
23784: ** is undefined if the mutex is not currently entered or
23785: ** is not currently allocated.  SQLite will never do either.
23786: */
23787: static void winMutexLeave(sqlite3_mutex *p){
23788: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23789:   DWORD tid = GetCurrentThreadId();
23790: #endif
23791:   assert( p );
23792: #ifdef SQLITE_DEBUG
23793:   assert( p->nRef>0 );
23794:   assert( p->owner==tid );
23795:   p->nRef--;
23796:   if( p->nRef==0 ) p->owner = 0;
23797:   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23798: #endif
23799:   assert( winMutex_isInit==1 );
23800:   LeaveCriticalSection(&p->mutex);
23801: #ifdef SQLITE_DEBUG
23802:   if( p->trace ){
23803:     OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23804:              tid, p, p->trace, p->nRef));
23805:   }
23806: #endif
23807: }
23808: 
23809: SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
23810:   static const sqlite3_mutex_methods sMutex = {
23811:     winMutexInit,
23812:     winMutexEnd,
23813:     winMutexAlloc,
23814:     winMutexFree,
23815:     winMutexEnter,
23816:     winMutexTry,
23817:     winMutexLeave,
23818: #ifdef SQLITE_DEBUG
23819:     winMutexHeld,
23820:     winMutexNotheld
23821: #else
23822:     0,
23823:     0
23824: #endif
23825:   };
23826:   return &sMutex;
23827: }
23828: 
23829: #endif /* SQLITE_MUTEX_W32 */
23830: 
23831: /************** End of mutex_w32.c *******************************************/
23832: /************** Begin file malloc.c ******************************************/
23833: /*
23834: ** 2001 September 15
23835: **
23836: ** The author disclaims copyright to this source code.  In place of
23837: ** a legal notice, here is a blessing:
23838: **
23839: **    May you do good and not evil.
23840: **    May you find forgiveness for yourself and forgive others.
23841: **    May you share freely, never taking more than you give.
23842: **
23843: *************************************************************************
23844: **
23845: ** Memory allocation functions used throughout sqlite.
23846: */
23847: /* #include "sqliteInt.h" */
23848: /* #include <stdarg.h> */
23849: 
23850: /*
23851: ** Attempt to release up to n bytes of non-essential memory currently
23852: ** held by SQLite. An example of non-essential memory is memory used to
23853: ** cache database pages that are not currently in use.
23854: */
23855: SQLITE_API int sqlite3_release_memory(int n){
23856: #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23857:   return sqlite3PcacheReleaseMemory(n);
23858: #else
23859:   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
23860:   ** is a no-op returning zero if SQLite is not compiled with
23861:   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
23862:   UNUSED_PARAMETER(n);
23863:   return 0;
23864: #endif
23865: }
23866: 
23867: /*
23868: ** An instance of the following object records the location of
23869: ** each unused scratch buffer.
23870: */
23871: typedef struct ScratchFreeslot {
23872:   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
23873: } ScratchFreeslot;
23874: 
23875: /*
23876: ** State information local to the memory allocation subsystem.
23877: */
23878: static SQLITE_WSD struct Mem0Global {
23879:   sqlite3_mutex *mutex;         /* Mutex to serialize access */
23880:   sqlite3_int64 alarmThreshold; /* The soft heap limit */
23881: 
23882:   /*
23883:   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
23884:   ** (so that a range test can be used to determine if an allocation
23885:   ** being freed came from pScratch) and a pointer to the list of
23886:   ** unused scratch allocations.
23887:   */
23888:   void *pScratchEnd;
23889:   ScratchFreeslot *pScratchFree;
23890:   u32 nScratchFree;
23891: 
23892:   /*
23893:   ** True if heap is nearly "full" where "full" is defined by the
23894:   ** sqlite3_soft_heap_limit() setting.
23895:   */
23896:   int nearlyFull;
23897: } mem0 = { 0, 0, 0, 0, 0, 0 };
23898: 
23899: #define mem0 GLOBAL(struct Mem0Global, mem0)
23900: 
23901: /*
23902: ** Return the memory allocator mutex. sqlite3_status() needs it.
23903: */
23904: SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
23905:   return mem0.mutex;
23906: }
23907: 
23908: #ifndef SQLITE_OMIT_DEPRECATED
23909: /*
23910: ** Deprecated external interface.  It used to set an alarm callback
23911: ** that was invoked when memory usage grew too large.  Now it is a
23912: ** no-op.
23913: */
23914: SQLITE_API int sqlite3_memory_alarm(
23915:   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
23916:   void *pArg,
23917:   sqlite3_int64 iThreshold
23918: ){
23919:   (void)xCallback;
23920:   (void)pArg;
23921:   (void)iThreshold;
23922:   return SQLITE_OK;
23923: }
23924: #endif
23925: 
23926: /*
23927: ** Set the soft heap-size limit for the library. Passing a zero or 
23928: ** negative value indicates no limit.
23929: */
23930: SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
23931:   sqlite3_int64 priorLimit;
23932:   sqlite3_int64 excess;
23933:   sqlite3_int64 nUsed;
23934: #ifndef SQLITE_OMIT_AUTOINIT
23935:   int rc = sqlite3_initialize();
23936:   if( rc ) return -1;
23937: #endif
23938:   sqlite3_mutex_enter(mem0.mutex);
23939:   priorLimit = mem0.alarmThreshold;
23940:   if( n<0 ){
23941:     sqlite3_mutex_leave(mem0.mutex);
23942:     return priorLimit;
23943:   }
23944:   mem0.alarmThreshold = n;
23945:   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
23946:   mem0.nearlyFull = (n>0 && n<=nUsed);
23947:   sqlite3_mutex_leave(mem0.mutex);
23948:   excess = sqlite3_memory_used() - n;
23949:   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
23950:   return priorLimit;
23951: }
23952: SQLITE_API void sqlite3_soft_heap_limit(int n){
23953:   if( n<0 ) n = 0;
23954:   sqlite3_soft_heap_limit64(n);
23955: }
23956: 
23957: /*
23958: ** Initialize the memory allocation subsystem.
23959: */
23960: SQLITE_PRIVATE int sqlite3MallocInit(void){
23961:   int rc;
23962:   if( sqlite3GlobalConfig.m.xMalloc==0 ){
23963:     sqlite3MemSetDefault();
23964:   }
23965:   memset(&mem0, 0, sizeof(mem0));
23966:   mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
23967:   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
23968:       && sqlite3GlobalConfig.nScratch>0 ){
23969:     int i, n, sz;
23970:     ScratchFreeslot *pSlot;
23971:     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
23972:     sqlite3GlobalConfig.szScratch = sz;
23973:     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
23974:     n = sqlite3GlobalConfig.nScratch;
23975:     mem0.pScratchFree = pSlot;
23976:     mem0.nScratchFree = n;
23977:     for(i=0; i<n-1; i++){
23978:       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
23979:       pSlot = pSlot->pNext;
23980:     }
23981:     pSlot->pNext = 0;
23982:     mem0.pScratchEnd = (void*)&pSlot[1];
23983:   }else{
23984:     mem0.pScratchEnd = 0;
23985:     sqlite3GlobalConfig.pScratch = 0;
23986:     sqlite3GlobalConfig.szScratch = 0;
23987:     sqlite3GlobalConfig.nScratch = 0;
23988:   }
23989:   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
23990:       || sqlite3GlobalConfig.nPage<=0 ){
23991:     sqlite3GlobalConfig.pPage = 0;
23992:     sqlite3GlobalConfig.szPage = 0;
23993:   }
23994:   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
23995:   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
23996:   return rc;
23997: }
23998: 
23999: /*
24000: ** Return true if the heap is currently under memory pressure - in other
24001: ** words if the amount of heap used is close to the limit set by
24002: ** sqlite3_soft_heap_limit().
24003: */
24004: SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
24005:   return mem0.nearlyFull;
24006: }
24007: 
24008: /*
24009: ** Deinitialize the memory allocation subsystem.
24010: */
24011: SQLITE_PRIVATE void sqlite3MallocEnd(void){
24012:   if( sqlite3GlobalConfig.m.xShutdown ){
24013:     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
24014:   }
24015:   memset(&mem0, 0, sizeof(mem0));
24016: }
24017: 
24018: /*
24019: ** Return the amount of memory currently checked out.
24020: */
24021: SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
24022:   sqlite3_int64 res, mx;
24023:   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
24024:   return res;
24025: }
24026: 
24027: /*
24028: ** Return the maximum amount of memory that has ever been
24029: ** checked out since either the beginning of this process
24030: ** or since the most recent reset.
24031: */
24032: SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
24033:   sqlite3_int64 res, mx;
24034:   sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
24035:   return mx;
24036: }
24037: 
24038: /*
24039: ** Trigger the alarm 
24040: */
24041: static void sqlite3MallocAlarm(int nByte){
24042:   if( mem0.alarmThreshold<=0 ) return;
24043:   sqlite3_mutex_leave(mem0.mutex);
24044:   sqlite3_release_memory(nByte);
24045:   sqlite3_mutex_enter(mem0.mutex);
24046: }
24047: 
24048: /*
24049: ** Do a memory allocation with statistics and alarms.  Assume the
24050: ** lock is already held.
24051: */
24052: static int mallocWithAlarm(int n, void **pp){
24053:   int nFull;
24054:   void *p;
24055:   assert( sqlite3_mutex_held(mem0.mutex) );
24056:   nFull = sqlite3GlobalConfig.m.xRoundup(n);
24057:   sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
24058:   if( mem0.alarmThreshold>0 ){
24059:     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
24060:     if( nUsed >= mem0.alarmThreshold - nFull ){
24061:       mem0.nearlyFull = 1;
24062:       sqlite3MallocAlarm(nFull);
24063:     }else{
24064:       mem0.nearlyFull = 0;
24065:     }
24066:   }
24067:   p = sqlite3GlobalConfig.m.xMalloc(nFull);
24068: #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
24069:   if( p==0 && mem0.alarmThreshold>0 ){
24070:     sqlite3MallocAlarm(nFull);
24071:     p = sqlite3GlobalConfig.m.xMalloc(nFull);
24072:   }
24073: #endif
24074:   if( p ){
24075:     nFull = sqlite3MallocSize(p);
24076:     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
24077:     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
24078:   }
24079:   *pp = p;
24080:   return nFull;
24081: }
24082: 
24083: /*
24084: ** Allocate memory.  This routine is like sqlite3_malloc() except that it
24085: ** assumes the memory subsystem has already been initialized.
24086: */
24087: SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
24088:   void *p;
24089:   if( n==0 || n>=0x7fffff00 ){
24090:     /* A memory allocation of a number of bytes which is near the maximum
24091:     ** signed integer value might cause an integer overflow inside of the
24092:     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
24093:     ** 255 bytes of overhead.  SQLite itself will never use anything near
24094:     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
24095:     p = 0;
24096:   }else if( sqlite3GlobalConfig.bMemstat ){
24097:     sqlite3_mutex_enter(mem0.mutex);
24098:     mallocWithAlarm((int)n, &p);
24099:     sqlite3_mutex_leave(mem0.mutex);
24100:   }else{
24101:     p = sqlite3GlobalConfig.m.xMalloc((int)n);
24102:   }
24103:   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
24104:   return p;
24105: }
24106: 
24107: /*
24108: ** This version of the memory allocation is for use by the application.
24109: ** First make sure the memory subsystem is initialized, then do the
24110: ** allocation.
24111: */
24112: SQLITE_API void *sqlite3_malloc(int n){
24113: #ifndef SQLITE_OMIT_AUTOINIT
24114:   if( sqlite3_initialize() ) return 0;
24115: #endif
24116:   return n<=0 ? 0 : sqlite3Malloc(n);
24117: }
24118: SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
24119: #ifndef SQLITE_OMIT_AUTOINIT
24120:   if( sqlite3_initialize() ) return 0;
24121: #endif
24122:   return sqlite3Malloc(n);
24123: }
24124: 
24125: /*
24126: ** Each thread may only have a single outstanding allocation from
24127: ** xScratchMalloc().  We verify this constraint in the single-threaded
24128: ** case by setting scratchAllocOut to 1 when an allocation
24129: ** is outstanding clearing it when the allocation is freed.
24130: */
24131: #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24132: static int scratchAllocOut = 0;
24133: #endif
24134: 
24135: 
24136: /*
24137: ** Allocate memory that is to be used and released right away.
24138: ** This routine is similar to alloca() in that it is not intended
24139: ** for situations where the memory might be held long-term.  This
24140: ** routine is intended to get memory to old large transient data
24141: ** structures that would not normally fit on the stack of an
24142: ** embedded processor.
24143: */
24144: SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
24145:   void *p;
24146:   assert( n>0 );
24147: 
24148:   sqlite3_mutex_enter(mem0.mutex);
24149:   sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
24150:   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
24151:     p = mem0.pScratchFree;
24152:     mem0.pScratchFree = mem0.pScratchFree->pNext;
24153:     mem0.nScratchFree--;
24154:     sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
24155:     sqlite3_mutex_leave(mem0.mutex);
24156:   }else{
24157:     sqlite3_mutex_leave(mem0.mutex);
24158:     p = sqlite3Malloc(n);
24159:     if( sqlite3GlobalConfig.bMemstat && p ){
24160:       sqlite3_mutex_enter(mem0.mutex);
24161:       sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
24162:       sqlite3_mutex_leave(mem0.mutex);
24163:     }
24164:     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
24165:   }
24166:   assert( sqlite3_mutex_notheld(mem0.mutex) );
24167: 
24168: 
24169: #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24170:   /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
24171:   ** buffers per thread.
24172:   **
24173:   ** This can only be checked in single-threaded mode.
24174:   */
24175:   assert( scratchAllocOut==0 );
24176:   if( p ) scratchAllocOut++;
24177: #endif
24178: 
24179:   return p;
24180: }
24181: SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
24182:   if( p ){
24183: 
24184: #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
24185:     /* Verify that no more than two scratch allocation per thread
24186:     ** is outstanding at one time.  (This is only checked in the
24187:     ** single-threaded case since checking in the multi-threaded case
24188:     ** would be much more complicated.) */
24189:     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
24190:     scratchAllocOut--;
24191: #endif
24192: 
24193:     if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
24194:       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
24195:       ScratchFreeslot *pSlot;
24196:       pSlot = (ScratchFreeslot*)p;
24197:       sqlite3_mutex_enter(mem0.mutex);
24198:       pSlot->pNext = mem0.pScratchFree;
24199:       mem0.pScratchFree = pSlot;
24200:       mem0.nScratchFree++;
24201:       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
24202:       sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
24203:       sqlite3_mutex_leave(mem0.mutex);
24204:     }else{
24205:       /* Release memory back to the heap */
24206:       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
24207:       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
24208:       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24209:       if( sqlite3GlobalConfig.bMemstat ){
24210:         int iSize = sqlite3MallocSize(p);
24211:         sqlite3_mutex_enter(mem0.mutex);
24212:         sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
24213:         sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
24214:         sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24215:         sqlite3GlobalConfig.m.xFree(p);
24216:         sqlite3_mutex_leave(mem0.mutex);
24217:       }else{
24218:         sqlite3GlobalConfig.m.xFree(p);
24219:       }
24220:     }
24221:   }
24222: }
24223: 
24224: /*
24225: ** TRUE if p is a lookaside memory allocation from db
24226: */
24227: #ifndef SQLITE_OMIT_LOOKASIDE
24228: static int isLookaside(sqlite3 *db, void *p){
24229:   return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
24230: }
24231: #else
24232: #define isLookaside(A,B) 0
24233: #endif
24234: 
24235: /*
24236: ** Return the size of a memory allocation previously obtained from
24237: ** sqlite3Malloc() or sqlite3_malloc().
24238: */
24239: SQLITE_PRIVATE int sqlite3MallocSize(void *p){
24240:   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24241:   return sqlite3GlobalConfig.m.xSize(p);
24242: }
24243: SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
24244:   assert( p!=0 );
24245:   if( db==0 || !isLookaside(db,p) ){
24246: #if SQLITE_DEBUG
24247:     if( db==0 ){
24248:       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24249:       assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24250:     }else{
24251:       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24252:       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24253:     }
24254: #endif
24255:     return sqlite3GlobalConfig.m.xSize(p);
24256:   }else{
24257:     assert( sqlite3_mutex_held(db->mutex) );
24258:     return db->lookaside.sz;
24259:   }
24260: }
24261: SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
24262:   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24263:   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24264:   return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
24265: }
24266: 
24267: /*
24268: ** Free memory previously obtained from sqlite3Malloc().
24269: */
24270: SQLITE_API void sqlite3_free(void *p){
24271:   if( p==0 ) return;  /* IMP: R-49053-54554 */
24272:   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
24273:   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
24274:   if( sqlite3GlobalConfig.bMemstat ){
24275:     sqlite3_mutex_enter(mem0.mutex);
24276:     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
24277:     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
24278:     sqlite3GlobalConfig.m.xFree(p);
24279:     sqlite3_mutex_leave(mem0.mutex);
24280:   }else{
24281:     sqlite3GlobalConfig.m.xFree(p);
24282:   }
24283: }
24284: 
24285: /*
24286: ** Add the size of memory allocation "p" to the count in
24287: ** *db->pnBytesFreed.
24288: */
24289: static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
24290:   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
24291: }
24292: 
24293: /*
24294: ** Free memory that might be associated with a particular database
24295: ** connection.
24296: */
24297: SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
24298:   assert( db==0 || sqlite3_mutex_held(db->mutex) );
24299:   if( p==0 ) return;
24300:   if( db ){
24301:     if( db->pnBytesFreed ){
24302:       measureAllocationSize(db, p);
24303:       return;
24304:     }
24305:     if( isLookaside(db, p) ){
24306:       LookasideSlot *pBuf = (LookasideSlot*)p;
24307: #if SQLITE_DEBUG
24308:       /* Trash all content in the buffer being freed */
24309:       memset(p, 0xaa, db->lookaside.sz);
24310: #endif
24311:       pBuf->pNext = db->lookaside.pFree;
24312:       db->lookaside.pFree = pBuf;
24313:       db->lookaside.nOut--;
24314:       return;
24315:     }
24316:   }
24317:   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24318:   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24319:   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
24320:   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24321:   sqlite3_free(p);
24322: }
24323: 
24324: /*
24325: ** Change the size of an existing memory allocation
24326: */
24327: SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
24328:   int nOld, nNew, nDiff;
24329:   void *pNew;
24330:   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
24331:   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
24332:   if( pOld==0 ){
24333:     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
24334:   }
24335:   if( nBytes==0 ){
24336:     sqlite3_free(pOld); /* IMP: R-26507-47431 */
24337:     return 0;
24338:   }
24339:   if( nBytes>=0x7fffff00 ){
24340:     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
24341:     return 0;
24342:   }
24343:   nOld = sqlite3MallocSize(pOld);
24344:   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
24345:   ** argument to xRealloc is always a value returned by a prior call to
24346:   ** xRoundup. */
24347:   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
24348:   if( nOld==nNew ){
24349:     pNew = pOld;
24350:   }else if( sqlite3GlobalConfig.bMemstat ){
24351:     sqlite3_mutex_enter(mem0.mutex);
24352:     sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
24353:     nDiff = nNew - nOld;
24354:     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
24355:           mem0.alarmThreshold-nDiff ){
24356:       sqlite3MallocAlarm(nDiff);
24357:     }
24358:     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24359:     if( pNew==0 && mem0.alarmThreshold>0 ){
24360:       sqlite3MallocAlarm((int)nBytes);
24361:       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24362:     }
24363:     if( pNew ){
24364:       nNew = sqlite3MallocSize(pNew);
24365:       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
24366:     }
24367:     sqlite3_mutex_leave(mem0.mutex);
24368:   }else{
24369:     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24370:   }
24371:   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
24372:   return pNew;
24373: }
24374: 
24375: /*
24376: ** The public interface to sqlite3Realloc.  Make sure that the memory
24377: ** subsystem is initialized prior to invoking sqliteRealloc.
24378: */
24379: SQLITE_API void *sqlite3_realloc(void *pOld, int n){
24380: #ifndef SQLITE_OMIT_AUTOINIT
24381:   if( sqlite3_initialize() ) return 0;
24382: #endif
24383:   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
24384:   return sqlite3Realloc(pOld, n);
24385: }
24386: SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
24387: #ifndef SQLITE_OMIT_AUTOINIT
24388:   if( sqlite3_initialize() ) return 0;
24389: #endif
24390:   return sqlite3Realloc(pOld, n);
24391: }
24392: 
24393: 
24394: /*
24395: ** Allocate and zero memory.
24396: */ 
24397: SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
24398:   void *p = sqlite3Malloc(n);
24399:   if( p ){
24400:     memset(p, 0, (size_t)n);
24401:   }
24402:   return p;
24403: }
24404: 
24405: /*
24406: ** Allocate and zero memory.  If the allocation fails, make
24407: ** the mallocFailed flag in the connection pointer.
24408: */
24409: SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
24410:   void *p;
24411:   testcase( db==0 );
24412:   p = sqlite3DbMallocRaw(db, n);
24413:   if( p ) memset(p, 0, (size_t)n);
24414:   return p;
24415: }
24416: 
24417: 
24418: /* Finish the work of sqlite3DbMallocRawNN for the unusual and
24419: ** slower case when the allocation cannot be fulfilled using lookaside.
24420: */
24421: static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
24422:   void *p;
24423:   assert( db!=0 );
24424:   p = sqlite3Malloc(n);
24425:   if( !p ) sqlite3OomFault(db);
24426:   sqlite3MemdebugSetType(p, 
24427:          (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
24428:   return p;
24429: }
24430: 
24431: /*
24432: ** Allocate memory, either lookaside (if possible) or heap.  
24433: ** If the allocation fails, set the mallocFailed flag in
24434: ** the connection pointer.
24435: **
24436: ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
24437: ** failure on the same database connection) then always return 0.
24438: ** Hence for a particular database connection, once malloc starts
24439: ** failing, it fails consistently until mallocFailed is reset.
24440: ** This is an important assumption.  There are many places in the
24441: ** code that do things like this:
24442: **
24443: **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
24444: **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
24445: **         if( b ) a[10] = 9;
24446: **
24447: ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
24448: ** that all prior mallocs (ex: "a") worked too.
24449: **
24450: ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
24451: ** not a NULL pointer.
24452: */
24453: SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
24454:   void *p;
24455:   if( db ) return sqlite3DbMallocRawNN(db, n);
24456:   p = sqlite3Malloc(n);
24457:   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24458:   return p;
24459: }
24460: SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
24461: #ifndef SQLITE_OMIT_LOOKASIDE
24462:   LookasideSlot *pBuf;
24463:   assert( db!=0 );
24464:   assert( sqlite3_mutex_held(db->mutex) );
24465:   assert( db->pnBytesFreed==0 );
24466:   if( db->lookaside.bDisable==0 ){
24467:     assert( db->mallocFailed==0 );
24468:     if( n>db->lookaside.sz ){
24469:       db->lookaside.anStat[1]++;
24470:     }else if( (pBuf = db->lookaside.pFree)==0 ){
24471:       db->lookaside.anStat[2]++;
24472:     }else{
24473:       db->lookaside.pFree = pBuf->pNext;
24474:       db->lookaside.nOut++;
24475:       db->lookaside.anStat[0]++;
24476:       if( db->lookaside.nOut>db->lookaside.mxOut ){
24477:         db->lookaside.mxOut = db->lookaside.nOut;
24478:       }
24479:       return (void*)pBuf;
24480:     }
24481:   }else if( db->mallocFailed ){
24482:     return 0;
24483:   }
24484: #else
24485:   assert( db!=0 );
24486:   assert( sqlite3_mutex_held(db->mutex) );
24487:   assert( db->pnBytesFreed==0 );
24488:   if( db->mallocFailed ){
24489:     return 0;
24490:   }
24491: #endif
24492:   return dbMallocRawFinish(db, n);
24493: }
24494: 
24495: /* Forward declaration */
24496: static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
24497: 
24498: /*
24499: ** Resize the block of memory pointed to by p to n bytes. If the
24500: ** resize fails, set the mallocFailed flag in the connection object.
24501: */
24502: SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
24503:   assert( db!=0 );
24504:   if( p==0 ) return sqlite3DbMallocRawNN(db, n);
24505:   assert( sqlite3_mutex_held(db->mutex) );
24506:   if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
24507:   return dbReallocFinish(db, p, n);
24508: }
24509: static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
24510:   void *pNew = 0;
24511:   assert( db!=0 );
24512:   assert( p!=0 );
24513:   if( db->mallocFailed==0 ){
24514:     if( isLookaside(db, p) ){
24515:       pNew = sqlite3DbMallocRawNN(db, n);
24516:       if( pNew ){
24517:         memcpy(pNew, p, db->lookaside.sz);
24518:         sqlite3DbFree(db, p);
24519:       }
24520:     }else{
24521:       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24522:       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
24523:       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
24524:       pNew = sqlite3_realloc64(p, n);
24525:       if( !pNew ){
24526:         sqlite3OomFault(db);
24527:       }
24528:       sqlite3MemdebugSetType(pNew,
24529:             (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
24530:     }
24531:   }
24532:   return pNew;
24533: }
24534: 
24535: /*
24536: ** Attempt to reallocate p.  If the reallocation fails, then free p
24537: ** and set the mallocFailed flag in the database connection.
24538: */
24539: SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
24540:   void *pNew;
24541:   pNew = sqlite3DbRealloc(db, p, n);
24542:   if( !pNew ){
24543:     sqlite3DbFree(db, p);
24544:   }
24545:   return pNew;
24546: }
24547: 
24548: /*
24549: ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
24550: ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
24551: ** is because when memory debugging is turned on, these two functions are 
24552: ** called via macros that record the current file and line number in the
24553: ** ThreadData structure.
24554: */
24555: SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
24556:   char *zNew;
24557:   size_t n;
24558:   if( z==0 ){
24559:     return 0;
24560:   }
24561:   n = sqlite3Strlen30(z) + 1;
24562:   assert( (n&0x7fffffff)==n );
24563:   zNew = sqlite3DbMallocRaw(db, (int)n);
24564:   if( zNew ){
24565:     memcpy(zNew, z, n);
24566:   }
24567:   return zNew;
24568: }
24569: SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
24570:   char *zNew;
24571:   assert( db!=0 );
24572:   if( z==0 ){
24573:     return 0;
24574:   }
24575:   assert( (n&0x7fffffff)==n );
24576:   zNew = sqlite3DbMallocRawNN(db, n+1);
24577:   if( zNew ){
24578:     memcpy(zNew, z, (size_t)n);
24579:     zNew[n] = 0;
24580:   }
24581:   return zNew;
24582: }
24583: 
24584: /*
24585: ** Free any prior content in *pz and replace it with a copy of zNew.
24586: */
24587: SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
24588:   sqlite3DbFree(db, *pz);
24589:   *pz = sqlite3DbStrDup(db, zNew);
24590: }
24591: 
24592: /*
24593: ** Call this routine to record the fact that an OOM (out-of-memory) error
24594: ** has happened.  This routine will set db->mallocFailed, and also
24595: ** temporarily disable the lookaside memory allocator and interrupt
24596: ** any running VDBEs.
24597: */
24598: SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
24599:   if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
24600:     db->mallocFailed = 1;
24601:     if( db->nVdbeExec>0 ){
24602:       db->u1.isInterrupted = 1;
24603:     }
24604:     db->lookaside.bDisable++;
24605:   }
24606: }
24607: 
24608: /*
24609: ** This routine reactivates the memory allocator and clears the
24610: ** db->mallocFailed flag as necessary.
24611: **
24612: ** The memory allocator is not restarted if there are running
24613: ** VDBEs.
24614: */
24615: SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
24616:   if( db->mallocFailed && db->nVdbeExec==0 ){
24617:     db->mallocFailed = 0;
24618:     db->u1.isInterrupted = 0;
24619:     assert( db->lookaside.bDisable>0 );
24620:     db->lookaside.bDisable--;
24621:   }
24622: }
24623: 
24624: /*
24625: ** Take actions at the end of an API call to indicate an OOM error
24626: */
24627: static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
24628:   sqlite3OomClear(db);
24629:   sqlite3Error(db, SQLITE_NOMEM);
24630:   return SQLITE_NOMEM_BKPT;
24631: }
24632: 
24633: /*
24634: ** This function must be called before exiting any API function (i.e. 
24635: ** returning control to the user) that has called sqlite3_malloc or
24636: ** sqlite3_realloc.
24637: **
24638: ** The returned value is normally a copy of the second argument to this
24639: ** function. However, if a malloc() failure has occurred since the previous
24640: ** invocation SQLITE_NOMEM is returned instead. 
24641: **
24642: ** If an OOM as occurred, then the connection error-code (the value
24643: ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
24644: */
24645: SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
24646:   /* If the db handle must hold the connection handle mutex here.
24647:   ** Otherwise the read (and possible write) of db->mallocFailed 
24648:   ** is unsafe, as is the call to sqlite3Error().
24649:   */
24650:   assert( db!=0 );
24651:   assert( sqlite3_mutex_held(db->mutex) );
24652:   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
24653:     return apiOomError(db);
24654:   }
24655:   return rc & db->errMask;
24656: }
24657: 
24658: /************** End of malloc.c **********************************************/
24659: /************** Begin file printf.c ******************************************/
24660: /*
24661: ** The "printf" code that follows dates from the 1980's.  It is in
24662: ** the public domain. 
24663: **
24664: **************************************************************************
24665: **
24666: ** This file contains code for a set of "printf"-like routines.  These
24667: ** routines format strings much like the printf() from the standard C
24668: ** library, though the implementation here has enhancements to support
24669: ** SQLite.
24670: */
24671: /* #include "sqliteInt.h" */
24672: 
24673: /*
24674: ** Conversion types fall into various categories as defined by the
24675: ** following enumeration.
24676: */
24677: #define etRADIX       0 /* Integer types.  %d, %x, %o, and so forth */
24678: #define etFLOAT       1 /* Floating point.  %f */
24679: #define etEXP         2 /* Exponentional notation. %e and %E */
24680: #define etGENERIC     3 /* Floating or exponential, depending on exponent. %g */
24681: #define etSIZE        4 /* Return number of characters processed so far. %n */
24682: #define etSTRING      5 /* Strings. %s */
24683: #define etDYNSTRING   6 /* Dynamically allocated strings. %z */
24684: #define etPERCENT     7 /* Percent symbol. %% */
24685: #define etCHARX       8 /* Characters. %c */
24686: /* The rest are extensions, not normally found in printf() */
24687: #define etSQLESCAPE   9 /* Strings with '\'' doubled.  %q */
24688: #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
24689:                           NULL pointers replaced by SQL NULL.  %Q */
24690: #define etTOKEN      11 /* a pointer to a Token structure */
24691: #define etSRCLIST    12 /* a pointer to a SrcList */
24692: #define etPOINTER    13 /* The %p conversion */
24693: #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24694: #define etORDINAL    15 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
24695: 
24696: #define etINVALID    16 /* Any unrecognized conversion type */
24697: 
24698: 
24699: /*
24700: ** An "etByte" is an 8-bit unsigned value.
24701: */
24702: typedef unsigned char etByte;
24703: 
24704: /*
24705: ** Each builtin conversion character (ex: the 'd' in "%d") is described
24706: ** by an instance of the following structure
24707: */
24708: typedef struct et_info {   /* Information about each format field */
24709:   char fmttype;            /* The format field code letter */
24710:   etByte base;             /* The base for radix conversion */
24711:   etByte flags;            /* One or more of FLAG_ constants below */
24712:   etByte type;             /* Conversion paradigm */
24713:   etByte charset;          /* Offset into aDigits[] of the digits string */
24714:   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
24715: } et_info;
24716: 
24717: /*
24718: ** Allowed values for et_info.flags
24719: */
24720: #define FLAG_SIGNED  1     /* True if the value to convert is signed */
24721: #define FLAG_INTERN  2     /* True if for internal use only */
24722: #define FLAG_STRING  4     /* Allow infinity precision */
24723: 
24724: 
24725: /*
24726: ** The following table is searched linearly, so it is good to put the
24727: ** most frequently used conversion types first.
24728: */
24729: static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
24730: static const char aPrefix[] = "-x0\000X0";
24731: static const et_info fmtinfo[] = {
24732:   {  'd', 10, 1, etRADIX,      0,  0 },
24733:   {  's',  0, 4, etSTRING,     0,  0 },
24734:   {  'g',  0, 1, etGENERIC,    30, 0 },
24735:   {  'z',  0, 4, etDYNSTRING,  0,  0 },
24736:   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
24737:   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
24738:   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
24739:   {  'c',  0, 0, etCHARX,      0,  0 },
24740:   {  'o',  8, 0, etRADIX,      0,  2 },
24741:   {  'u', 10, 0, etRADIX,      0,  0 },
24742:   {  'x', 16, 0, etRADIX,      16, 1 },
24743:   {  'X', 16, 0, etRADIX,      0,  4 },
24744: #ifndef SQLITE_OMIT_FLOATING_POINT
24745:   {  'f',  0, 1, etFLOAT,      0,  0 },
24746:   {  'e',  0, 1, etEXP,        30, 0 },
24747:   {  'E',  0, 1, etEXP,        14, 0 },
24748:   {  'G',  0, 1, etGENERIC,    14, 0 },
24749: #endif
24750:   {  'i', 10, 1, etRADIX,      0,  0 },
24751:   {  'n',  0, 0, etSIZE,       0,  0 },
24752:   {  '%',  0, 0, etPERCENT,    0,  0 },
24753:   {  'p', 16, 0, etPOINTER,    0,  1 },
24754: 
24755: /* All the rest have the FLAG_INTERN bit set and are thus for internal
24756: ** use only */
24757:   {  'T',  0, 2, etTOKEN,      0,  0 },
24758:   {  'S',  0, 2, etSRCLIST,    0,  0 },
24759:   {  'r', 10, 3, etORDINAL,    0,  0 },
24760: };
24761: 
24762: /*
24763: ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
24764: ** conversions will work.
24765: */
24766: #ifndef SQLITE_OMIT_FLOATING_POINT
24767: /*
24768: ** "*val" is a double such that 0.1 <= *val < 10.0
24769: ** Return the ascii code for the leading digit of *val, then
24770: ** multiply "*val" by 10.0 to renormalize.
24771: **
24772: ** Example:
24773: **     input:     *val = 3.14159
24774: **     output:    *val = 1.4159    function return = '3'
24775: **
24776: ** The counter *cnt is incremented each time.  After counter exceeds
24777: ** 16 (the number of significant digits in a 64-bit float) '0' is
24778: ** always returned.
24779: */
24780: static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
24781:   int digit;
24782:   LONGDOUBLE_TYPE d;
24783:   if( (*cnt)<=0 ) return '0';
24784:   (*cnt)--;
24785:   digit = (int)*val;
24786:   d = digit;
24787:   digit += '0';
24788:   *val = (*val - d)*10.0;
24789:   return (char)digit;
24790: }
24791: #endif /* SQLITE_OMIT_FLOATING_POINT */
24792: 
24793: /*
24794: ** Set the StrAccum object to an error mode.
24795: */
24796: static void setStrAccumError(StrAccum *p, u8 eError){
24797:   assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
24798:   p->accError = eError;
24799:   p->nAlloc = 0;
24800: }
24801: 
24802: /*
24803: ** Extra argument values from a PrintfArguments object
24804: */
24805: static sqlite3_int64 getIntArg(PrintfArguments *p){
24806:   if( p->nArg<=p->nUsed ) return 0;
24807:   return sqlite3_value_int64(p->apArg[p->nUsed++]);
24808: }
24809: static double getDoubleArg(PrintfArguments *p){
24810:   if( p->nArg<=p->nUsed ) return 0.0;
24811:   return sqlite3_value_double(p->apArg[p->nUsed++]);
24812: }
24813: static char *getTextArg(PrintfArguments *p){
24814:   if( p->nArg<=p->nUsed ) return 0;
24815:   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
24816: }
24817: 
24818: 
24819: /*
24820: ** On machines with a small stack size, you can redefine the
24821: ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
24822: */
24823: #ifndef SQLITE_PRINT_BUF_SIZE
24824: # define SQLITE_PRINT_BUF_SIZE 70
24825: #endif
24826: #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
24827: 
24828: /*
24829: ** Render a string given by "fmt" into the StrAccum object.
24830: */
24831: SQLITE_PRIVATE void sqlite3VXPrintf(
24832:   StrAccum *pAccum,          /* Accumulate results here */
24833:   const char *fmt,           /* Format string */
24834:   va_list ap                 /* arguments */
24835: ){
24836:   int c;                     /* Next character in the format string */
24837:   char *bufpt;               /* Pointer to the conversion buffer */
24838:   int precision;             /* Precision of the current field */
24839:   int length;                /* Length of the field */
24840:   int idx;                   /* A general purpose loop counter */
24841:   int width;                 /* Width of the current field */
24842:   etByte flag_leftjustify;   /* True if "-" flag is present */
24843:   etByte flag_plussign;      /* True if "+" flag is present */
24844:   etByte flag_blanksign;     /* True if " " flag is present */
24845:   etByte flag_alternateform; /* True if "#" flag is present */
24846:   etByte flag_altform2;      /* True if "!" flag is present */
24847:   etByte flag_zeropad;       /* True if field width constant starts with zero */
24848:   etByte flag_long;          /* True if "l" flag is present */
24849:   etByte flag_longlong;      /* True if the "ll" flag is present */
24850:   etByte done;               /* Loop termination flag */
24851:   etByte xtype = etINVALID;  /* Conversion paradigm */
24852:   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
24853:   u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
24854:   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
24855:   sqlite_uint64 longvalue;   /* Value for integer types */
24856:   LONGDOUBLE_TYPE realvalue; /* Value for real types */
24857:   const et_info *infop;      /* Pointer to the appropriate info structure */
24858:   char *zOut;                /* Rendering buffer */
24859:   int nOut;                  /* Size of the rendering buffer */
24860:   char *zExtra = 0;          /* Malloced memory used by some conversion */
24861: #ifndef SQLITE_OMIT_FLOATING_POINT
24862:   int  exp, e2;              /* exponent of real numbers */
24863:   int nsd;                   /* Number of significant digits returned */
24864:   double rounder;            /* Used for rounding floating point values */
24865:   etByte flag_dp;            /* True if decimal point should be shown */
24866:   etByte flag_rtz;           /* True if trailing zeros should be removed */
24867: #endif
24868:   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
24869:   char buf[etBUFSIZE];       /* Conversion buffer */
24870: 
24871:   bufpt = 0;
24872:   if( pAccum->printfFlags ){
24873:     if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
24874:       pArgList = va_arg(ap, PrintfArguments*);
24875:     }
24876:     useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL;
24877:   }else{
24878:     bArgList = useIntern = 0;
24879:   }
24880:   for(; (c=(*fmt))!=0; ++fmt){
24881:     if( c!='%' ){
24882:       bufpt = (char *)fmt;
24883: #if HAVE_STRCHRNUL
24884:       fmt = strchrnul(fmt, '%');
24885: #else
24886:       do{ fmt++; }while( *fmt && *fmt != '%' );
24887: #endif
24888:       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
24889:       if( *fmt==0 ) break;
24890:     }
24891:     if( (c=(*++fmt))==0 ){
24892:       sqlite3StrAccumAppend(pAccum, "%", 1);
24893:       break;
24894:     }
24895:     /* Find out what flags are present */
24896:     flag_leftjustify = flag_plussign = flag_blanksign = 
24897:      flag_alternateform = flag_altform2 = flag_zeropad = 0;
24898:     done = 0;
24899:     do{
24900:       switch( c ){
24901:         case '-':   flag_leftjustify = 1;     break;
24902:         case '+':   flag_plussign = 1;        break;
24903:         case ' ':   flag_blanksign = 1;       break;
24904:         case '#':   flag_alternateform = 1;   break;
24905:         case '!':   flag_altform2 = 1;        break;
24906:         case '0':   flag_zeropad = 1;         break;
24907:         default:    done = 1;                 break;
24908:       }
24909:     }while( !done && (c=(*++fmt))!=0 );
24910:     /* Get the field width */
24911:     if( c=='*' ){
24912:       if( bArgList ){
24913:         width = (int)getIntArg(pArgList);
24914:       }else{
24915:         width = va_arg(ap,int);
24916:       }
24917:       if( width<0 ){
24918:         flag_leftjustify = 1;
24919:         width = width >= -2147483647 ? -width : 0;
24920:       }
24921:       c = *++fmt;
24922:     }else{
24923:       unsigned wx = 0;
24924:       while( c>='0' && c<='9' ){
24925:         wx = wx*10 + c - '0';
24926:         c = *++fmt;
24927:       }
24928:       testcase( wx>0x7fffffff );
24929:       width = wx & 0x7fffffff;
24930:     }
24931:     assert( width>=0 );
24932: #ifdef SQLITE_PRINTF_PRECISION_LIMIT
24933:     if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
24934:       width = SQLITE_PRINTF_PRECISION_LIMIT;
24935:     }
24936: #endif
24937: 
24938:     /* Get the precision */
24939:     if( c=='.' ){
24940:       c = *++fmt;
24941:       if( c=='*' ){
24942:         if( bArgList ){
24943:           precision = (int)getIntArg(pArgList);
24944:         }else{
24945:           precision = va_arg(ap,int);
24946:         }
24947:         c = *++fmt;
24948:         if( precision<0 ){
24949:           precision = precision >= -2147483647 ? -precision : -1;
24950:         }
24951:       }else{
24952:         unsigned px = 0;
24953:         while( c>='0' && c<='9' ){
24954:           px = px*10 + c - '0';
24955:           c = *++fmt;
24956:         }
24957:         testcase( px>0x7fffffff );
24958:         precision = px & 0x7fffffff;
24959:       }
24960:     }else{
24961:       precision = -1;
24962:     }
24963:     assert( precision>=(-1) );
24964: #ifdef SQLITE_PRINTF_PRECISION_LIMIT
24965:     if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
24966:       precision = SQLITE_PRINTF_PRECISION_LIMIT;
24967:     }
24968: #endif
24969: 
24970: 
24971:     /* Get the conversion type modifier */
24972:     if( c=='l' ){
24973:       flag_long = 1;
24974:       c = *++fmt;
24975:       if( c=='l' ){
24976:         flag_longlong = 1;
24977:         c = *++fmt;
24978:       }else{
24979:         flag_longlong = 0;
24980:       }
24981:     }else{
24982:       flag_long = flag_longlong = 0;
24983:     }
24984:     /* Fetch the info entry for the field */
24985:     infop = &fmtinfo[0];
24986:     xtype = etINVALID;
24987:     for(idx=0; idx<ArraySize(fmtinfo); idx++){
24988:       if( c==fmtinfo[idx].fmttype ){
24989:         infop = &fmtinfo[idx];
24990:         if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
24991:           xtype = infop->type;
24992:         }else{
24993:           return;
24994:         }
24995:         break;
24996:       }
24997:     }
24998: 
24999:     /*
25000:     ** At this point, variables are initialized as follows:
25001:     **
25002:     **   flag_alternateform          TRUE if a '#' is present.
25003:     **   flag_altform2               TRUE if a '!' is present.
25004:     **   flag_plussign               TRUE if a '+' is present.
25005:     **   flag_leftjustify            TRUE if a '-' is present or if the
25006:     **                               field width was negative.
25007:     **   flag_zeropad                TRUE if the width began with 0.
25008:     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
25009:     **                               the conversion character.
25010:     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
25011:     **                               the conversion character.
25012:     **   flag_blanksign              TRUE if a ' ' is present.
25013:     **   width                       The specified field width.  This is
25014:     **                               always non-negative.  Zero is the default.
25015:     **   precision                   The specified precision.  The default
25016:     **                               is -1.
25017:     **   xtype                       The class of the conversion.
25018:     **   infop                       Pointer to the appropriate info struct.
25019:     */
25020:     switch( xtype ){
25021:       case etPOINTER:
25022:         flag_longlong = sizeof(char*)==sizeof(i64);
25023:         flag_long = sizeof(char*)==sizeof(long int);
25024:         /* Fall through into the next case */
25025:       case etORDINAL:
25026:       case etRADIX:
25027:         if( infop->flags & FLAG_SIGNED ){
25028:           i64 v;
25029:           if( bArgList ){
25030:             v = getIntArg(pArgList);
25031:           }else if( flag_longlong ){
25032:             v = va_arg(ap,i64);
25033:           }else if( flag_long ){
25034:             v = va_arg(ap,long int);
25035:           }else{
25036:             v = va_arg(ap,int);
25037:           }
25038:           if( v<0 ){
25039:             if( v==SMALLEST_INT64 ){
25040:               longvalue = ((u64)1)<<63;
25041:             }else{
25042:               longvalue = -v;
25043:             }
25044:             prefix = '-';
25045:           }else{
25046:             longvalue = v;
25047:             if( flag_plussign )        prefix = '+';
25048:             else if( flag_blanksign )  prefix = ' ';
25049:             else                       prefix = 0;
25050:           }
25051:         }else{
25052:           if( bArgList ){
25053:             longvalue = (u64)getIntArg(pArgList);
25054:           }else if( flag_longlong ){
25055:             longvalue = va_arg(ap,u64);
25056:           }else if( flag_long ){
25057:             longvalue = va_arg(ap,unsigned long int);
25058:           }else{
25059:             longvalue = va_arg(ap,unsigned int);
25060:           }
25061:           prefix = 0;
25062:         }
25063:         if( longvalue==0 ) flag_alternateform = 0;
25064:         if( flag_zeropad && precision<width-(prefix!=0) ){
25065:           precision = width-(prefix!=0);
25066:         }
25067:         if( precision<etBUFSIZE-10 ){
25068:           nOut = etBUFSIZE;
25069:           zOut = buf;
25070:         }else{
25071:           nOut = precision + 10;
25072:           zOut = zExtra = sqlite3Malloc( nOut );
25073:           if( zOut==0 ){
25074:             setStrAccumError(pAccum, STRACCUM_NOMEM);
25075:             return;
25076:           }
25077:         }
25078:         bufpt = &zOut[nOut-1];
25079:         if( xtype==etORDINAL ){
25080:           static const char zOrd[] = "thstndrd";
25081:           int x = (int)(longvalue % 10);
25082:           if( x>=4 || (longvalue/10)%10==1 ){
25083:             x = 0;
25084:           }
25085:           *(--bufpt) = zOrd[x*2+1];
25086:           *(--bufpt) = zOrd[x*2];
25087:         }
25088:         {
25089:           const char *cset = &aDigits[infop->charset];
25090:           u8 base = infop->base;
25091:           do{                                           /* Convert to ascii */
25092:             *(--bufpt) = cset[longvalue%base];
25093:             longvalue = longvalue/base;
25094:           }while( longvalue>0 );
25095:         }
25096:         length = (int)(&zOut[nOut-1]-bufpt);
25097:         for(idx=precision-length; idx>0; idx--){
25098:           *(--bufpt) = '0';                             /* Zero pad */
25099:         }
25100:         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
25101:         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
25102:           const char *pre;
25103:           char x;
25104:           pre = &aPrefix[infop->prefix];
25105:           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
25106:         }
25107:         length = (int)(&zOut[nOut-1]-bufpt);
25108:         break;
25109:       case etFLOAT:
25110:       case etEXP:
25111:       case etGENERIC:
25112:         if( bArgList ){
25113:           realvalue = getDoubleArg(pArgList);
25114:         }else{
25115:           realvalue = va_arg(ap,double);
25116:         }
25117: #ifdef SQLITE_OMIT_FLOATING_POINT
25118:         length = 0;
25119: #else
25120:         if( precision<0 ) precision = 6;         /* Set default precision */
25121:         if( realvalue<0.0 ){
25122:           realvalue = -realvalue;
25123:           prefix = '-';
25124:         }else{
25125:           if( flag_plussign )          prefix = '+';
25126:           else if( flag_blanksign )    prefix = ' ';
25127:           else                         prefix = 0;
25128:         }
25129:         if( xtype==etGENERIC && precision>0 ) precision--;
25130:         testcase( precision>0xfff );
25131:         for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
25132:         if( xtype==etFLOAT ) realvalue += rounder;
25133:         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
25134:         exp = 0;
25135:         if( sqlite3IsNaN((double)realvalue) ){
25136:           bufpt = "NaN";
25137:           length = 3;
25138:           break;
25139:         }
25140:         if( realvalue>0.0 ){
25141:           LONGDOUBLE_TYPE scale = 1.0;
25142:           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
25143:           while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
25144:           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
25145:           realvalue /= scale;
25146:           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
25147:           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
25148:           if( exp>350 ){
25149:             bufpt = buf;
25150:             buf[0] = prefix;
25151:             memcpy(buf+(prefix!=0),"Inf",4);
25152:             length = 3+(prefix!=0);
25153:             break;
25154:           }
25155:         }
25156:         bufpt = buf;
25157:         /*
25158:         ** If the field type is etGENERIC, then convert to either etEXP
25159:         ** or etFLOAT, as appropriate.
25160:         */
25161:         if( xtype!=etFLOAT ){
25162:           realvalue += rounder;
25163:           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
25164:         }
25165:         if( xtype==etGENERIC ){
25166:           flag_rtz = !flag_alternateform;
25167:           if( exp<-4 || exp>precision ){
25168:             xtype = etEXP;
25169:           }else{
25170:             precision = precision - exp;
25171:             xtype = etFLOAT;
25172:           }
25173:         }else{
25174:           flag_rtz = flag_altform2;
25175:         }
25176:         if( xtype==etEXP ){
25177:           e2 = 0;
25178:         }else{
25179:           e2 = exp;
25180:         }
25181:         if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
25182:           bufpt = zExtra 
25183:               = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
25184:           if( bufpt==0 ){
25185:             setStrAccumError(pAccum, STRACCUM_NOMEM);
25186:             return;
25187:           }
25188:         }
25189:         zOut = bufpt;
25190:         nsd = 16 + flag_altform2*10;
25191:         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
25192:         /* The sign in front of the number */
25193:         if( prefix ){
25194:           *(bufpt++) = prefix;
25195:         }
25196:         /* Digits prior to the decimal point */
25197:         if( e2<0 ){
25198:           *(bufpt++) = '0';
25199:         }else{
25200:           for(; e2>=0; e2--){
25201:             *(bufpt++) = et_getdigit(&realvalue,&nsd);
25202:           }
25203:         }
25204:         /* The decimal point */
25205:         if( flag_dp ){
25206:           *(bufpt++) = '.';
25207:         }
25208:         /* "0" digits after the decimal point but before the first
25209:         ** significant digit of the number */
25210:         for(e2++; e2<0; precision--, e2++){
25211:           assert( precision>0 );
25212:           *(bufpt++) = '0';
25213:         }
25214:         /* Significant digits after the decimal point */
25215:         while( (precision--)>0 ){
25216:           *(bufpt++) = et_getdigit(&realvalue,&nsd);
25217:         }
25218:         /* Remove trailing zeros and the "." if no digits follow the "." */
25219:         if( flag_rtz && flag_dp ){
25220:           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
25221:           assert( bufpt>zOut );
25222:           if( bufpt[-1]=='.' ){
25223:             if( flag_altform2 ){
25224:               *(bufpt++) = '0';
25225:             }else{
25226:               *(--bufpt) = 0;
25227:             }
25228:           }
25229:         }
25230:         /* Add the "eNNN" suffix */
25231:         if( xtype==etEXP ){
25232:           *(bufpt++) = aDigits[infop->charset];
25233:           if( exp<0 ){
25234:             *(bufpt++) = '-'; exp = -exp;
25235:           }else{
25236:             *(bufpt++) = '+';
25237:           }
25238:           if( exp>=100 ){
25239:             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
25240:             exp %= 100;
25241:           }
25242:           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
25243:           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
25244:         }
25245:         *bufpt = 0;
25246: 
25247:         /* The converted number is in buf[] and zero terminated. Output it.
25248:         ** Note that the number is in the usual order, not reversed as with
25249:         ** integer conversions. */
25250:         length = (int)(bufpt-zOut);
25251:         bufpt = zOut;
25252: 
25253:         /* Special case:  Add leading zeros if the flag_zeropad flag is
25254:         ** set and we are not left justified */
25255:         if( flag_zeropad && !flag_leftjustify && length < width){
25256:           int i;
25257:           int nPad = width - length;
25258:           for(i=width; i>=nPad; i--){
25259:             bufpt[i] = bufpt[i-nPad];
25260:           }
25261:           i = prefix!=0;
25262:           while( nPad-- ) bufpt[i++] = '0';
25263:           length = width;
25264:         }
25265: #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
25266:         break;
25267:       case etSIZE:
25268:         if( !bArgList ){
25269:           *(va_arg(ap,int*)) = pAccum->nChar;
25270:         }
25271:         length = width = 0;
25272:         break;
25273:       case etPERCENT:
25274:         buf[0] = '%';
25275:         bufpt = buf;
25276:         length = 1;
25277:         break;
25278:       case etCHARX:
25279:         if( bArgList ){
25280:           bufpt = getTextArg(pArgList);
25281:           c = bufpt ? bufpt[0] : 0;
25282:         }else{
25283:           c = va_arg(ap,int);
25284:         }
25285:         if( precision>1 ){
25286:           width -= precision-1;
25287:           if( width>1 && !flag_leftjustify ){
25288:             sqlite3AppendChar(pAccum, width-1, ' ');
25289:             width = 0;
25290:           }
25291:           sqlite3AppendChar(pAccum, precision-1, c);
25292:         }
25293:         length = 1;
25294:         buf[0] = c;
25295:         bufpt = buf;
25296:         break;
25297:       case etSTRING:
25298:       case etDYNSTRING:
25299:         if( bArgList ){
25300:           bufpt = getTextArg(pArgList);
25301:           xtype = etSTRING;
25302:         }else{
25303:           bufpt = va_arg(ap,char*);
25304:         }
25305:         if( bufpt==0 ){
25306:           bufpt = "";
25307:         }else if( xtype==etDYNSTRING ){
25308:           zExtra = bufpt;
25309:         }
25310:         if( precision>=0 ){
25311:           for(length=0; length<precision && bufpt[length]; length++){}
25312:         }else{
25313:           length = sqlite3Strlen30(bufpt);
25314:         }
25315:         break;
25316:       case etSQLESCAPE:           /* Escape ' characters */
25317:       case etSQLESCAPE2:          /* Escape ' and enclose in '...' */
25318:       case etSQLESCAPE3: {        /* Escape " characters */
25319:         int i, j, k, n, isnull;
25320:         int needQuote;
25321:         char ch;
25322:         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
25323:         char *escarg;
25324: 
25325:         if( bArgList ){
25326:           escarg = getTextArg(pArgList);
25327:         }else{
25328:           escarg = va_arg(ap,char*);
25329:         }
25330:         isnull = escarg==0;
25331:         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25332:         k = precision;
25333:         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
25334:           if( ch==q )  n++;
25335:         }
25336:         needQuote = !isnull && xtype==etSQLESCAPE2;
25337:         n += i + 3;
25338:         if( n>etBUFSIZE ){
25339:           bufpt = zExtra = sqlite3Malloc( n );
25340:           if( bufpt==0 ){
25341:             setStrAccumError(pAccum, STRACCUM_NOMEM);
25342:             return;
25343:           }
25344:         }else{
25345:           bufpt = buf;
25346:         }
25347:         j = 0;
25348:         if( needQuote ) bufpt[j++] = q;
25349:         k = i;
25350:         for(i=0; i<k; i++){
25351:           bufpt[j++] = ch = escarg[i];
25352:           if( ch==q ) bufpt[j++] = ch;
25353:         }
25354:         if( needQuote ) bufpt[j++] = q;
25355:         bufpt[j] = 0;
25356:         length = j;
25357:         /* The precision in %q and %Q means how many input characters to
25358:         ** consume, not the length of the output...
25359:         ** if( precision>=0 && precision<length ) length = precision; */
25360:         break;
25361:       }
25362:       case etTOKEN: {
25363:         Token *pToken = va_arg(ap, Token*);
25364:         assert( bArgList==0 );
25365:         if( pToken && pToken->n ){
25366:           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
25367:         }
25368:         length = width = 0;
25369:         break;
25370:       }
25371:       case etSRCLIST: {
25372:         SrcList *pSrc = va_arg(ap, SrcList*);
25373:         int k = va_arg(ap, int);
25374:         struct SrcList_item *pItem = &pSrc->a[k];
25375:         assert( bArgList==0 );
25376:         assert( k>=0 && k<pSrc->nSrc );
25377:         if( pItem->zDatabase ){
25378:           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
25379:           sqlite3StrAccumAppend(pAccum, ".", 1);
25380:         }
25381:         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
25382:         length = width = 0;
25383:         break;
25384:       }
25385:       default: {
25386:         assert( xtype==etINVALID );
25387:         return;
25388:       }
25389:     }/* End switch over the format type */
25390:     /*
25391:     ** The text of the conversion is pointed to by "bufpt" and is
25392:     ** "length" characters long.  The field width is "width".  Do
25393:     ** the output.
25394:     */
25395:     width -= length;
25396:     if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25397:     sqlite3StrAccumAppend(pAccum, bufpt, length);
25398:     if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25399: 
25400:     if( zExtra ){
25401:       sqlite3DbFree(pAccum->db, zExtra);
25402:       zExtra = 0;
25403:     }
25404:   }/* End for loop over the format string */
25405: } /* End of function */
25406: 
25407: /*
25408: ** Enlarge the memory allocation on a StrAccum object so that it is
25409: ** able to accept at least N more bytes of text.
25410: **
25411: ** Return the number of bytes of text that StrAccum is able to accept
25412: ** after the attempted enlargement.  The value returned might be zero.
25413: */
25414: static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
25415:   char *zNew;
25416:   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
25417:   if( p->accError ){
25418:     testcase(p->accError==STRACCUM_TOOBIG);
25419:     testcase(p->accError==STRACCUM_NOMEM);
25420:     return 0;
25421:   }
25422:   if( p->mxAlloc==0 ){
25423:     N = p->nAlloc - p->nChar - 1;
25424:     setStrAccumError(p, STRACCUM_TOOBIG);
25425:     return N;
25426:   }else{
25427:     char *zOld = isMalloced(p) ? p->zText : 0;
25428:     i64 szNew = p->nChar;
25429:     assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25430:     szNew += N + 1;
25431:     if( szNew+p->nChar<=p->mxAlloc ){
25432:       /* Force exponential buffer size growth as long as it does not overflow,
25433:       ** to avoid having to call this routine too often */
25434:       szNew += p->nChar;
25435:     }
25436:     if( szNew > p->mxAlloc ){
25437:       sqlite3StrAccumReset(p);
25438:       setStrAccumError(p, STRACCUM_TOOBIG);
25439:       return 0;
25440:     }else{
25441:       p->nAlloc = (int)szNew;
25442:     }
25443:     if( p->db ){
25444:       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
25445:     }else{
25446:       zNew = sqlite3_realloc64(zOld, p->nAlloc);
25447:     }
25448:     if( zNew ){
25449:       assert( p->zText!=0 || p->nChar==0 );
25450:       if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
25451:       p->zText = zNew;
25452:       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
25453:       p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25454:     }else{
25455:       sqlite3StrAccumReset(p);
25456:       setStrAccumError(p, STRACCUM_NOMEM);
25457:       return 0;
25458:     }
25459:   }
25460:   return N;
25461: }
25462: 
25463: /*
25464: ** Append N copies of character c to the given string buffer.
25465: */
25466: SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
25467:   testcase( p->nChar + (i64)N > 0x7fffffff );
25468:   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
25469:     return;
25470:   }
25471:   assert( (p->zText==p->zBase)==!isMalloced(p) );
25472:   while( (N--)>0 ) p->zText[p->nChar++] = c;
25473: }
25474: 
25475: /*
25476: ** The StrAccum "p" is not large enough to accept N new bytes of z[].
25477: ** So enlarge if first, then do the append.
25478: **
25479: ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
25480: ** work (enlarging the buffer) using tail recursion, so that the
25481: ** sqlite3StrAccumAppend() routine can use fast calling semantics.
25482: */
25483: static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
25484:   N = sqlite3StrAccumEnlarge(p, N);
25485:   if( N>0 ){
25486:     memcpy(&p->zText[p->nChar], z, N);
25487:     p->nChar += N;
25488:   }
25489:   assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25490: }
25491: 
25492: /*
25493: ** Append N bytes of text from z to the StrAccum object.  Increase the
25494: ** size of the memory allocation for StrAccum if necessary.
25495: */
25496: SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
25497:   assert( z!=0 || N==0 );
25498:   assert( p->zText!=0 || p->nChar==0 || p->accError );
25499:   assert( N>=0 );
25500:   assert( p->accError==0 || p->nAlloc==0 );
25501:   if( p->nChar+N >= p->nAlloc ){
25502:     enlargeAndAppend(p,z,N);
25503:   }else{
25504:     assert( p->zText );
25505:     p->nChar += N;
25506:     memcpy(&p->zText[p->nChar-N], z, N);
25507:   }
25508: }
25509: 
25510: /*
25511: ** Append the complete text of zero-terminated string z[] to the p string.
25512: */
25513: SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
25514:   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
25515: }
25516: 
25517: 
25518: /*
25519: ** Finish off a string by making sure it is zero-terminated.
25520: ** Return a pointer to the resulting string.  Return a NULL
25521: ** pointer if any kind of error was encountered.
25522: */
25523: SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
25524:   if( p->zText ){
25525:     assert( (p->zText==p->zBase)==!isMalloced(p) );
25526:     p->zText[p->nChar] = 0;
25527:     if( p->mxAlloc>0 && !isMalloced(p) ){
25528:       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
25529:       if( p->zText ){
25530:         memcpy(p->zText, p->zBase, p->nChar+1);
25531:         p->printfFlags |= SQLITE_PRINTF_MALLOCED;
25532:       }else{
25533:         setStrAccumError(p, STRACCUM_NOMEM);
25534:       }
25535:     }
25536:   }
25537:   return p->zText;
25538: }
25539: 
25540: /*
25541: ** Reset an StrAccum string.  Reclaim all malloced memory.
25542: */
25543: SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
25544:   assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25545:   if( isMalloced(p) ){
25546:     sqlite3DbFree(p->db, p->zText);
25547:     p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
25548:   }
25549:   p->zText = 0;
25550: }
25551: 
25552: /*
25553: ** Initialize a string accumulator.
25554: **
25555: ** p:     The accumulator to be initialized.
25556: ** db:    Pointer to a database connection.  May be NULL.  Lookaside
25557: **        memory is used if not NULL. db->mallocFailed is set appropriately
25558: **        when not NULL.
25559: ** zBase: An initial buffer.  May be NULL in which case the initial buffer
25560: **        is malloced.
25561: ** n:     Size of zBase in bytes.  If total space requirements never exceed
25562: **        n then no memory allocations ever occur.
25563: ** mx:    Maximum number of bytes to accumulate.  If mx==0 then no memory
25564: **        allocations will ever occur.
25565: */
25566: SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
25567:   p->zText = p->zBase = zBase;
25568:   p->db = db;
25569:   p->nChar = 0;
25570:   p->nAlloc = n;
25571:   p->mxAlloc = mx;
25572:   p->accError = 0;
25573:   p->printfFlags = 0;
25574: }
25575: 
25576: /*
25577: ** Print into memory obtained from sqliteMalloc().  Use the internal
25578: ** %-conversion extensions.
25579: */
25580: SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
25581:   char *z;
25582:   char zBase[SQLITE_PRINT_BUF_SIZE];
25583:   StrAccum acc;
25584:   assert( db!=0 );
25585:   sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
25586:                       db->aLimit[SQLITE_LIMIT_LENGTH]);
25587:   acc.printfFlags = SQLITE_PRINTF_INTERNAL;
25588:   sqlite3VXPrintf(&acc, zFormat, ap);
25589:   z = sqlite3StrAccumFinish(&acc);
25590:   if( acc.accError==STRACCUM_NOMEM ){
25591:     sqlite3OomFault(db);
25592:   }
25593:   return z;
25594: }
25595: 
25596: /*
25597: ** Print into memory obtained from sqliteMalloc().  Use the internal
25598: ** %-conversion extensions.
25599: */
25600: SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
25601:   va_list ap;
25602:   char *z;
25603:   va_start(ap, zFormat);
25604:   z = sqlite3VMPrintf(db, zFormat, ap);
25605:   va_end(ap);
25606:   return z;
25607: }
25608: 
25609: /*
25610: ** Print into memory obtained from sqlite3_malloc().  Omit the internal
25611: ** %-conversion extensions.
25612: */
25613: SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
25614:   char *z;
25615:   char zBase[SQLITE_PRINT_BUF_SIZE];
25616:   StrAccum acc;
25617: 
25618: #ifdef SQLITE_ENABLE_API_ARMOR  
25619:   if( zFormat==0 ){
25620:     (void)SQLITE_MISUSE_BKPT;
25621:     return 0;
25622:   }
25623: #endif
25624: #ifndef SQLITE_OMIT_AUTOINIT
25625:   if( sqlite3_initialize() ) return 0;
25626: #endif
25627:   sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
25628:   sqlite3VXPrintf(&acc, zFormat, ap);
25629:   z = sqlite3StrAccumFinish(&acc);
25630:   return z;
25631: }
25632: 
25633: /*
25634: ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
25635: ** %-conversion extensions.
25636: */
25637: SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
25638:   va_list ap;
25639:   char *z;
25640: #ifndef SQLITE_OMIT_AUTOINIT
25641:   if( sqlite3_initialize() ) return 0;
25642: #endif
25643:   va_start(ap, zFormat);
25644:   z = sqlite3_vmprintf(zFormat, ap);
25645:   va_end(ap);
25646:   return z;
25647: }
25648: 
25649: /*
25650: ** sqlite3_snprintf() works like snprintf() except that it ignores the
25651: ** current locale settings.  This is important for SQLite because we
25652: ** are not able to use a "," as the decimal point in place of "." as
25653: ** specified by some locales.
25654: **
25655: ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
25656: ** from the snprintf() standard.  Unfortunately, it is too late to change
25657: ** this without breaking compatibility, so we just have to live with the
25658: ** mistake.
25659: **
25660: ** sqlite3_vsnprintf() is the varargs version.
25661: */
25662: SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
25663:   StrAccum acc;
25664:   if( n<=0 ) return zBuf;
25665: #ifdef SQLITE_ENABLE_API_ARMOR
25666:   if( zBuf==0 || zFormat==0 ) {
25667:     (void)SQLITE_MISUSE_BKPT;
25668:     if( zBuf ) zBuf[0] = 0;
25669:     return zBuf;
25670:   }
25671: #endif
25672:   sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
25673:   sqlite3VXPrintf(&acc, zFormat, ap);
25674:   return sqlite3StrAccumFinish(&acc);
25675: }
25676: SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
25677:   char *z;
25678:   va_list ap;
25679:   va_start(ap,zFormat);
25680:   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
25681:   va_end(ap);
25682:   return z;
25683: }
25684: 
25685: /*
25686: ** This is the routine that actually formats the sqlite3_log() message.
25687: ** We house it in a separate routine from sqlite3_log() to avoid using
25688: ** stack space on small-stack systems when logging is disabled.
25689: **
25690: ** sqlite3_log() must render into a static buffer.  It cannot dynamically
25691: ** allocate memory because it might be called while the memory allocator
25692: ** mutex is held.
25693: **
25694: ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
25695: ** certain format characters (%q) or for very large precisions or widths.
25696: ** Care must be taken that any sqlite3_log() calls that occur while the
25697: ** memory mutex is held do not use these mechanisms.
25698: */
25699: static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
25700:   StrAccum acc;                          /* String accumulator */
25701:   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
25702: 
25703:   sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
25704:   sqlite3VXPrintf(&acc, zFormat, ap);
25705:   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
25706:                            sqlite3StrAccumFinish(&acc));
25707: }
25708: 
25709: /*
25710: ** Format and write a message to the log if logging is enabled.
25711: */
25712: SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
25713:   va_list ap;                             /* Vararg list */
25714:   if( sqlite3GlobalConfig.xLog ){
25715:     va_start(ap, zFormat);
25716:     renderLogMsg(iErrCode, zFormat, ap);
25717:     va_end(ap);
25718:   }
25719: }
25720: 
25721: #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
25722: /*
25723: ** A version of printf() that understands %lld.  Used for debugging.
25724: ** The printf() built into some versions of windows does not understand %lld
25725: ** and segfaults if you give it a long long int.
25726: */
25727: SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
25728:   va_list ap;
25729:   StrAccum acc;
25730:   char zBuf[500];
25731:   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25732:   va_start(ap,zFormat);
25733:   sqlite3VXPrintf(&acc, zFormat, ap);
25734:   va_end(ap);
25735:   sqlite3StrAccumFinish(&acc);
25736:   fprintf(stdout,"%s", zBuf);
25737:   fflush(stdout);
25738: }
25739: #endif
25740: 
25741: 
25742: /*
25743: ** variable-argument wrapper around sqlite3VXPrintf().  The bFlags argument
25744: ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
25745: */
25746: SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
25747:   va_list ap;
25748:   va_start(ap,zFormat);
25749:   sqlite3VXPrintf(p, zFormat, ap);
25750:   va_end(ap);
25751: }
25752: 
25753: /************** End of printf.c **********************************************/
25754: /************** Begin file treeview.c ****************************************/
25755: /*
25756: ** 2015-06-08
25757: **
25758: ** The author disclaims copyright to this source code.  In place of
25759: ** a legal notice, here is a blessing:
25760: **
25761: **    May you do good and not evil.
25762: **    May you find forgiveness for yourself and forgive others.
25763: **    May you share freely, never taking more than you give.
25764: **
25765: *************************************************************************
25766: **
25767: ** This file contains C code to implement the TreeView debugging routines.
25768: ** These routines print a parse tree to standard output for debugging and
25769: ** analysis. 
25770: **
25771: ** The interfaces in this file is only available when compiling
25772: ** with SQLITE_DEBUG.
25773: */
25774: /* #include "sqliteInt.h" */
25775: #ifdef SQLITE_DEBUG
25776: 
25777: /*
25778: ** Add a new subitem to the tree.  The moreToFollow flag indicates that this
25779: ** is not the last item in the tree.
25780: */
25781: static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
25782:   if( p==0 ){
25783:     p = sqlite3_malloc64( sizeof(*p) );
25784:     if( p==0 ) return 0;
25785:     memset(p, 0, sizeof(*p));
25786:   }else{
25787:     p->iLevel++;
25788:   }
25789:   assert( moreToFollow==0 || moreToFollow==1 );
25790:   if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
25791:   return p;
25792: }
25793: 
25794: /*
25795: ** Finished with one layer of the tree
25796: */
25797: static void sqlite3TreeViewPop(TreeView *p){
25798:   if( p==0 ) return;
25799:   p->iLevel--;
25800:   if( p->iLevel<0 ) sqlite3_free(p);
25801: }
25802: 
25803: /*
25804: ** Generate a single line of output for the tree, with a prefix that contains
25805: ** all the appropriate tree lines
25806: */
25807: static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
25808:   va_list ap;
25809:   int i;
25810:   StrAccum acc;
25811:   char zBuf[500];
25812:   sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25813:   if( p ){
25814:     for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
25815:       sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
25816:     }
25817:     sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
25818:   }
25819:   va_start(ap, zFormat);
25820:   sqlite3VXPrintf(&acc, zFormat, ap);
25821:   va_end(ap);
25822:   if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
25823:   sqlite3StrAccumFinish(&acc);
25824:   fprintf(stdout,"%s", zBuf);
25825:   fflush(stdout);
25826: }
25827: 
25828: /*
25829: ** Shorthand for starting a new tree item that consists of a single label
25830: */
25831: static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
25832:   p = sqlite3TreeViewPush(p, moreFollows);
25833:   sqlite3TreeViewLine(p, "%s", zLabel);
25834: }
25835: 
25836: /*
25837: ** Generate a human-readable description of a WITH clause.
25838: */
25839: SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
25840:   int i;
25841:   if( pWith==0 ) return;
25842:   if( pWith->nCte==0 ) return;
25843:   if( pWith->pOuter ){
25844:     sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
25845:   }else{
25846:     sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
25847:   }
25848:   if( pWith->nCte>0 ){
25849:     pView = sqlite3TreeViewPush(pView, 1);
25850:     for(i=0; i<pWith->nCte; i++){
25851:       StrAccum x;
25852:       char zLine[1000];
25853:       const struct Cte *pCte = &pWith->a[i];
25854:       sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25855:       sqlite3XPrintf(&x, "%s", pCte->zName);
25856:       if( pCte->pCols && pCte->pCols->nExpr>0 ){
25857:         char cSep = '(';
25858:         int j;
25859:         for(j=0; j<pCte->pCols->nExpr; j++){
25860:           sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
25861:           cSep = ',';
25862:         }
25863:         sqlite3XPrintf(&x, ")");
25864:       }
25865:       sqlite3XPrintf(&x, " AS");
25866:       sqlite3StrAccumFinish(&x);
25867:       sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
25868:       sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
25869:       sqlite3TreeViewPop(pView);
25870:     }
25871:     sqlite3TreeViewPop(pView);
25872:   }
25873: }
25874: 
25875: 
25876: /*
25877: ** Generate a human-readable description of a the Select object.
25878: */
25879: SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
25880:   int n = 0;
25881:   int cnt = 0;
25882:   pView = sqlite3TreeViewPush(pView, moreToFollow);
25883:   if( p->pWith ){
25884:     sqlite3TreeViewWith(pView, p->pWith, 1);
25885:     cnt = 1;
25886:     sqlite3TreeViewPush(pView, 1);
25887:   }
25888:   do{
25889:     sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
25890:       ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
25891:       ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
25892:       (int)p->nSelectRow
25893:     );
25894:     if( cnt++ ) sqlite3TreeViewPop(pView);
25895:     if( p->pPrior ){
25896:       n = 1000;
25897:     }else{
25898:       n = 0;
25899:       if( p->pSrc && p->pSrc->nSrc ) n++;
25900:       if( p->pWhere ) n++;
25901:       if( p->pGroupBy ) n++;
25902:       if( p->pHaving ) n++;
25903:       if( p->pOrderBy ) n++;
25904:       if( p->pLimit ) n++;
25905:       if( p->pOffset ) n++;
25906:     }
25907:     sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
25908:     if( p->pSrc && p->pSrc->nSrc ){
25909:       int i;
25910:       pView = sqlite3TreeViewPush(pView, (n--)>0);
25911:       sqlite3TreeViewLine(pView, "FROM");
25912:       for(i=0; i<p->pSrc->nSrc; i++){
25913:         struct SrcList_item *pItem = &p->pSrc->a[i];
25914:         StrAccum x;
25915:         char zLine[100];
25916:         sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25917:         sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
25918:         if( pItem->zDatabase ){
25919:           sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
25920:         }else if( pItem->zName ){
25921:           sqlite3XPrintf(&x, " %s", pItem->zName);
25922:         }
25923:         if( pItem->pTab ){
25924:           sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
25925:         }
25926:         if( pItem->zAlias ){
25927:           sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
25928:         }
25929:         if( pItem->fg.jointype & JT_LEFT ){
25930:           sqlite3XPrintf(&x, " LEFT-JOIN");
25931:         }
25932:         sqlite3StrAccumFinish(&x);
25933:         sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); 
25934:         if( pItem->pSelect ){
25935:           sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
25936:         }
25937:         if( pItem->fg.isTabFunc ){
25938:           sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
25939:         }
25940:         sqlite3TreeViewPop(pView);
25941:       }
25942:       sqlite3TreeViewPop(pView);
25943:     }
25944:     if( p->pWhere ){
25945:       sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
25946:       sqlite3TreeViewExpr(pView, p->pWhere, 0);
25947:       sqlite3TreeViewPop(pView);
25948:     }
25949:     if( p->pGroupBy ){
25950:       sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
25951:     }
25952:     if( p->pHaving ){
25953:       sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
25954:       sqlite3TreeViewExpr(pView, p->pHaving, 0);
25955:       sqlite3TreeViewPop(pView);
25956:     }
25957:     if( p->pOrderBy ){
25958:       sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
25959:     }
25960:     if( p->pLimit ){
25961:       sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
25962:       sqlite3TreeViewExpr(pView, p->pLimit, 0);
25963:       sqlite3TreeViewPop(pView);
25964:     }
25965:     if( p->pOffset ){
25966:       sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
25967:       sqlite3TreeViewExpr(pView, p->pOffset, 0);
25968:       sqlite3TreeViewPop(pView);
25969:     }
25970:     if( p->pPrior ){
25971:       const char *zOp = "UNION";
25972:       switch( p->op ){
25973:         case TK_ALL:         zOp = "UNION ALL";  break;
25974:         case TK_INTERSECT:   zOp = "INTERSECT";  break;
25975:         case TK_EXCEPT:      zOp = "EXCEPT";     break;
25976:       }
25977:       sqlite3TreeViewItem(pView, zOp, 1);
25978:     }
25979:     p = p->pPrior;
25980:   }while( p!=0 );
25981:   sqlite3TreeViewPop(pView);
25982: }
25983: 
25984: /*
25985: ** Generate a human-readable explanation of an expression tree.
25986: */
25987: SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
25988:   const char *zBinOp = 0;   /* Binary operator */
25989:   const char *zUniOp = 0;   /* Unary operator */
25990:   char zFlgs[30];
25991:   pView = sqlite3TreeViewPush(pView, moreToFollow);
25992:   if( pExpr==0 ){
25993:     sqlite3TreeViewLine(pView, "nil");
25994:     sqlite3TreeViewPop(pView);
25995:     return;
25996:   }
25997:   if( pExpr->flags ){
25998:     sqlite3_snprintf(sizeof(zFlgs),zFlgs,"  flags=0x%x",pExpr->flags);
25999:   }else{
26000:     zFlgs[0] = 0;
26001:   }
26002:   switch( pExpr->op ){
26003:     case TK_AGG_COLUMN: {
26004:       sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
26005:             pExpr->iTable, pExpr->iColumn, zFlgs);
26006:       break;
26007:     }
26008:     case TK_COLUMN: {
26009:       if( pExpr->iTable<0 ){
26010:         /* This only happens when coding check constraints */
26011:         sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
26012:       }else{
26013:         sqlite3TreeViewLine(pView, "{%d:%d}%s",
26014:                              pExpr->iTable, pExpr->iColumn, zFlgs);
26015:       }
26016:       break;
26017:     }
26018:     case TK_INTEGER: {
26019:       if( pExpr->flags & EP_IntValue ){
26020:         sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
26021:       }else{
26022:         sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
26023:       }
26024:       break;
26025:     }
26026: #ifndef SQLITE_OMIT_FLOATING_POINT
26027:     case TK_FLOAT: {
26028:       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26029:       break;
26030:     }
26031: #endif
26032:     case TK_STRING: {
26033:       sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
26034:       break;
26035:     }
26036:     case TK_NULL: {
26037:       sqlite3TreeViewLine(pView,"NULL");
26038:       break;
26039:     }
26040: #ifndef SQLITE_OMIT_BLOB_LITERAL
26041:     case TK_BLOB: {
26042:       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
26043:       break;
26044:     }
26045: #endif
26046:     case TK_VARIABLE: {
26047:       sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
26048:                           pExpr->u.zToken, pExpr->iColumn);
26049:       break;
26050:     }
26051:     case TK_REGISTER: {
26052:       sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
26053:       break;
26054:     }
26055:     case TK_ID: {
26056:       sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
26057:       break;
26058:     }
26059: #ifndef SQLITE_OMIT_CAST
26060:     case TK_CAST: {
26061:       /* Expressions of the form:   CAST(pLeft AS token) */
26062:       sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
26063:       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26064:       break;
26065:     }
26066: #endif /* SQLITE_OMIT_CAST */
26067:     case TK_LT:      zBinOp = "LT";     break;
26068:     case TK_LE:      zBinOp = "LE";     break;
26069:     case TK_GT:      zBinOp = "GT";     break;
26070:     case TK_GE:      zBinOp = "GE";     break;
26071:     case TK_NE:      zBinOp = "NE";     break;
26072:     case TK_EQ:      zBinOp = "EQ";     break;
26073:     case TK_IS:      zBinOp = "IS";     break;
26074:     case TK_ISNOT:   zBinOp = "ISNOT";  break;
26075:     case TK_AND:     zBinOp = "AND";    break;
26076:     case TK_OR:      zBinOp = "OR";     break;
26077:     case TK_PLUS:    zBinOp = "ADD";    break;
26078:     case TK_STAR:    zBinOp = "MUL";    break;
26079:     case TK_MINUS:   zBinOp = "SUB";    break;
26080:     case TK_REM:     zBinOp = "REM";    break;
26081:     case TK_BITAND:  zBinOp = "BITAND"; break;
26082:     case TK_BITOR:   zBinOp = "BITOR";  break;
26083:     case TK_SLASH:   zBinOp = "DIV";    break;
26084:     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
26085:     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
26086:     case TK_CONCAT:  zBinOp = "CONCAT"; break;
26087:     case TK_DOT:     zBinOp = "DOT";    break;
26088: 
26089:     case TK_UMINUS:  zUniOp = "UMINUS"; break;
26090:     case TK_UPLUS:   zUniOp = "UPLUS";  break;
26091:     case TK_BITNOT:  zUniOp = "BITNOT"; break;
26092:     case TK_NOT:     zUniOp = "NOT";    break;
26093:     case TK_ISNULL:  zUniOp = "ISNULL"; break;
26094:     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
26095: 
26096:     case TK_SPAN: {
26097:       sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
26098:       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26099:       break;
26100:     }
26101: 
26102:     case TK_COLLATE: {
26103:       sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
26104:       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26105:       break;
26106:     }
26107: 
26108:     case TK_AGG_FUNCTION:
26109:     case TK_FUNCTION: {
26110:       ExprList *pFarg;       /* List of function arguments */
26111:       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
26112:         pFarg = 0;
26113:       }else{
26114:         pFarg = pExpr->x.pList;
26115:       }
26116:       if( pExpr->op==TK_AGG_FUNCTION ){
26117:         sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
26118:                              pExpr->op2, pExpr->u.zToken);
26119:       }else{
26120:         sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
26121:       }
26122:       if( pFarg ){
26123:         sqlite3TreeViewExprList(pView, pFarg, 0, 0);
26124:       }
26125:       break;
26126:     }
26127: #ifndef SQLITE_OMIT_SUBQUERY
26128:     case TK_EXISTS: {
26129:       sqlite3TreeViewLine(pView, "EXISTS-expr");
26130:       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26131:       break;
26132:     }
26133:     case TK_SELECT: {
26134:       sqlite3TreeViewLine(pView, "SELECT-expr");
26135:       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26136:       break;
26137:     }
26138:     case TK_IN: {
26139:       sqlite3TreeViewLine(pView, "IN");
26140:       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26141:       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
26142:         sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
26143:       }else{
26144:         sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26145:       }
26146:       break;
26147:     }
26148: #endif /* SQLITE_OMIT_SUBQUERY */
26149: 
26150:     /*
26151:     **    x BETWEEN y AND z
26152:     **
26153:     ** This is equivalent to
26154:     **
26155:     **    x>=y AND x<=z
26156:     **
26157:     ** X is stored in pExpr->pLeft.
26158:     ** Y is stored in pExpr->pList->a[0].pExpr.
26159:     ** Z is stored in pExpr->pList->a[1].pExpr.
26160:     */
26161:     case TK_BETWEEN: {
26162:       Expr *pX = pExpr->pLeft;
26163:       Expr *pY = pExpr->x.pList->a[0].pExpr;
26164:       Expr *pZ = pExpr->x.pList->a[1].pExpr;
26165:       sqlite3TreeViewLine(pView, "BETWEEN");
26166:       sqlite3TreeViewExpr(pView, pX, 1);
26167:       sqlite3TreeViewExpr(pView, pY, 1);
26168:       sqlite3TreeViewExpr(pView, pZ, 0);
26169:       break;
26170:     }
26171:     case TK_TRIGGER: {
26172:       /* If the opcode is TK_TRIGGER, then the expression is a reference
26173:       ** to a column in the new.* or old.* pseudo-tables available to
26174:       ** trigger programs. In this case Expr.iTable is set to 1 for the
26175:       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
26176:       ** is set to the column of the pseudo-table to read, or to -1 to
26177:       ** read the rowid field.
26178:       */
26179:       sqlite3TreeViewLine(pView, "%s(%d)", 
26180:           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
26181:       break;
26182:     }
26183:     case TK_CASE: {
26184:       sqlite3TreeViewLine(pView, "CASE");
26185:       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26186:       sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
26187:       break;
26188:     }
26189: #ifndef SQLITE_OMIT_TRIGGER
26190:     case TK_RAISE: {
26191:       const char *zType = "unk";
26192:       switch( pExpr->affinity ){
26193:         case OE_Rollback:   zType = "rollback";  break;
26194:         case OE_Abort:      zType = "abort";     break;
26195:         case OE_Fail:       zType = "fail";      break;
26196:         case OE_Ignore:     zType = "ignore";    break;
26197:       }
26198:       sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
26199:       break;
26200:     }
26201: #endif
26202:     case TK_MATCH: {
26203:       sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
26204:                           pExpr->iTable, pExpr->iColumn, zFlgs);
26205:       sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26206:       break;
26207:     }
26208:     default: {
26209:       sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
26210:       break;
26211:     }
26212:   }
26213:   if( zBinOp ){
26214:     sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
26215:     sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
26216:     sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
26217:   }else if( zUniOp ){
26218:     sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
26219:     sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
26220:   }
26221:   sqlite3TreeViewPop(pView);
26222: }
26223: 
26224: /*
26225: ** Generate a human-readable explanation of an expression list.
26226: */
26227: SQLITE_PRIVATE void sqlite3TreeViewExprList(
26228:   TreeView *pView,
26229:   const ExprList *pList,
26230:   u8 moreToFollow,
26231:   const char *zLabel
26232: ){
26233:   int i;
26234:   pView = sqlite3TreeViewPush(pView, moreToFollow);
26235:   if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
26236:   if( pList==0 ){
26237:     sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
26238:   }else{
26239:     sqlite3TreeViewLine(pView, "%s", zLabel);
26240:     for(i=0; i<pList->nExpr; i++){
26241:       int j = pList->a[i].u.x.iOrderByCol;
26242:       if( j ){
26243:         sqlite3TreeViewPush(pView, 0);
26244:         sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
26245:       }
26246:       sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
26247:       if( j ) sqlite3TreeViewPop(pView);
26248:     }
26249:   }
26250:   sqlite3TreeViewPop(pView);
26251: }
26252: 
26253: #endif /* SQLITE_DEBUG */
26254: 
26255: /************** End of treeview.c ********************************************/
26256: /************** Begin file random.c ******************************************/
26257: /*
26258: ** 2001 September 15
26259: **
26260: ** The author disclaims copyright to this source code.  In place of
26261: ** a legal notice, here is a blessing:
26262: **
26263: **    May you do good and not evil.
26264: **    May you find forgiveness for yourself and forgive others.
26265: **    May you share freely, never taking more than you give.
26266: **
26267: *************************************************************************
26268: ** This file contains code to implement a pseudo-random number
26269: ** generator (PRNG) for SQLite.
26270: **
26271: ** Random numbers are used by some of the database backends in order
26272: ** to generate random integer keys for tables or random filenames.
26273: */
26274: /* #include "sqliteInt.h" */
26275: 
26276: 
26277: /* All threads share a single random number generator.
26278: ** This structure is the current state of the generator.
26279: */
26280: static SQLITE_WSD struct sqlite3PrngType {
26281:   unsigned char isInit;          /* True if initialized */
26282:   unsigned char i, j;            /* State variables */
26283:   unsigned char s[256];          /* State variables */
26284: } sqlite3Prng;
26285: 
26286: /*
26287: ** Return N random bytes.
26288: */
26289: SQLITE_API void sqlite3_randomness(int N, void *pBuf){
26290:   unsigned char t;
26291:   unsigned char *zBuf = pBuf;
26292: 
26293:   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
26294:   ** state vector.  If writable static data is unsupported on the target,
26295:   ** we have to locate the state vector at run-time.  In the more common
26296:   ** case where writable static data is supported, wsdPrng can refer directly
26297:   ** to the "sqlite3Prng" state vector declared above.
26298:   */
26299: #ifdef SQLITE_OMIT_WSD
26300:   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
26301: # define wsdPrng p[0]
26302: #else
26303: # define wsdPrng sqlite3Prng
26304: #endif
26305: 
26306: #if SQLITE_THREADSAFE
26307:   sqlite3_mutex *mutex;
26308: #endif
26309: 
26310: #ifndef SQLITE_OMIT_AUTOINIT
26311:   if( sqlite3_initialize() ) return;
26312: #endif
26313: 
26314: #if SQLITE_THREADSAFE
26315:   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
26316: #endif
26317: 
26318:   sqlite3_mutex_enter(mutex);
26319:   if( N<=0 || pBuf==0 ){
26320:     wsdPrng.isInit = 0;
26321:     sqlite3_mutex_leave(mutex);
26322:     return;
26323:   }
26324: 
26325:   /* Initialize the state of the random number generator once,
26326:   ** the first time this routine is called.  The seed value does
26327:   ** not need to contain a lot of randomness since we are not
26328:   ** trying to do secure encryption or anything like that...
26329:   **
26330:   ** Nothing in this file or anywhere else in SQLite does any kind of
26331:   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
26332:   ** number generator) not as an encryption device.
26333:   */
26334:   if( !wsdPrng.isInit ){
26335:     int i;
26336:     char k[256];
26337:     wsdPrng.j = 0;
26338:     wsdPrng.i = 0;
26339:     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
26340:     for(i=0; i<256; i++){
26341:       wsdPrng.s[i] = (u8)i;
26342:     }
26343:     for(i=0; i<256; i++){
26344:       wsdPrng.j += wsdPrng.s[i] + k[i];
26345:       t = wsdPrng.s[wsdPrng.j];
26346:       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
26347:       wsdPrng.s[i] = t;
26348:     }
26349:     wsdPrng.isInit = 1;
26350:   }
26351: 
26352:   assert( N>0 );
26353:   do{
26354:     wsdPrng.i++;
26355:     t = wsdPrng.s[wsdPrng.i];
26356:     wsdPrng.j += t;
26357:     wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
26358:     wsdPrng.s[wsdPrng.j] = t;
26359:     t += wsdPrng.s[wsdPrng.i];
26360:     *(zBuf++) = wsdPrng.s[t];
26361:   }while( --N );
26362:   sqlite3_mutex_leave(mutex);
26363: }
26364: 
26365: #ifndef SQLITE_OMIT_BUILTIN_TEST
26366: /*
26367: ** For testing purposes, we sometimes want to preserve the state of
26368: ** PRNG and restore the PRNG to its saved state at a later time, or
26369: ** to reset the PRNG to its initial state.  These routines accomplish
26370: ** those tasks.
26371: **
26372: ** The sqlite3_test_control() interface calls these routines to
26373: ** control the PRNG.
26374: */
26375: static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
26376: SQLITE_PRIVATE void sqlite3PrngSaveState(void){
26377:   memcpy(
26378:     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26379:     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26380:     sizeof(sqlite3Prng)
26381:   );
26382: }
26383: SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
26384:   memcpy(
26385:     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
26386:     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
26387:     sizeof(sqlite3Prng)
26388:   );
26389: }
26390: #endif /* SQLITE_OMIT_BUILTIN_TEST */
26391: 
26392: /************** End of random.c **********************************************/
26393: /************** Begin file threads.c *****************************************/
26394: /*
26395: ** 2012 July 21
26396: **
26397: ** The author disclaims copyright to this source code.  In place of
26398: ** a legal notice, here is a blessing:
26399: **
26400: **    May you do good and not evil.
26401: **    May you find forgiveness for yourself and forgive others.
26402: **    May you share freely, never taking more than you give.
26403: **
26404: ******************************************************************************
26405: **
26406: ** This file presents a simple cross-platform threading interface for
26407: ** use internally by SQLite.
26408: **
26409: ** A "thread" can be created using sqlite3ThreadCreate().  This thread
26410: ** runs independently of its creator until it is joined using
26411: ** sqlite3ThreadJoin(), at which point it terminates.
26412: **
26413: ** Threads do not have to be real.  It could be that the work of the
26414: ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
26415: ** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
26416: ** single threaded systems.  Nothing in SQLite requires multiple threads.
26417: ** This interface exists so that applications that want to take advantage
26418: ** of multiple cores can do so, while also allowing applications to stay
26419: ** single-threaded if desired.
26420: */
26421: /* #include "sqliteInt.h" */
26422: #if SQLITE_OS_WIN
26423: /* #  include "os_win.h" */
26424: #endif
26425: 
26426: #if SQLITE_MAX_WORKER_THREADS>0
26427: 
26428: /********************************* Unix Pthreads ****************************/
26429: #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
26430: 
26431: #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
26432: /* #include <pthread.h> */
26433: 
26434: /* A running thread */
26435: struct SQLiteThread {
26436:   pthread_t tid;                 /* Thread ID */
26437:   int done;                      /* Set to true when thread finishes */
26438:   void *pOut;                    /* Result returned by the thread */
26439:   void *(*xTask)(void*);         /* The thread routine */
26440:   void *pIn;                     /* Argument to the thread */
26441: };
26442: 
26443: /* Create a new thread */
26444: SQLITE_PRIVATE int sqlite3ThreadCreate(
26445:   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26446:   void *(*xTask)(void*),    /* Routine to run in a separate thread */
26447:   void *pIn                 /* Argument passed into xTask() */
26448: ){
26449:   SQLiteThread *p;
26450:   int rc;
26451: 
26452:   assert( ppThread!=0 );
26453:   assert( xTask!=0 );
26454:   /* This routine is never used in single-threaded mode */
26455:   assert( sqlite3GlobalConfig.bCoreMutex!=0 );
26456: 
26457:   *ppThread = 0;
26458:   p = sqlite3Malloc(sizeof(*p));
26459:   if( p==0 ) return SQLITE_NOMEM_BKPT;
26460:   memset(p, 0, sizeof(*p));
26461:   p->xTask = xTask;
26462:   p->pIn = pIn;
26463:   /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
26464:   ** function that returns SQLITE_ERROR when passed the argument 200, that
26465:   ** forces worker threads to run sequentially and deterministically 
26466:   ** for testing purposes. */
26467:   if( sqlite3FaultSim(200) ){
26468:     rc = 1;
26469:   }else{    
26470:     rc = pthread_create(&p->tid, 0, xTask, pIn);
26471:   }
26472:   if( rc ){
26473:     p->done = 1;
26474:     p->pOut = xTask(pIn);
26475:   }
26476:   *ppThread = p;
26477:   return SQLITE_OK;
26478: }
26479: 
26480: /* Get the results of the thread */
26481: SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26482:   int rc;
26483: 
26484:   assert( ppOut!=0 );
26485:   if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26486:   if( p->done ){
26487:     *ppOut = p->pOut;
26488:     rc = SQLITE_OK;
26489:   }else{
26490:     rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
26491:   }
26492:   sqlite3_free(p);
26493:   return rc;
26494: }
26495: 
26496: #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
26497: /******************************** End Unix Pthreads *************************/
26498: 
26499: 
26500: /********************************* Win32 Threads ****************************/
26501: #if SQLITE_OS_WIN_THREADS
26502: 
26503: #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
26504: #include <process.h>
26505: 
26506: /* A running thread */
26507: struct SQLiteThread {
26508:   void *tid;               /* The thread handle */
26509:   unsigned id;             /* The thread identifier */
26510:   void *(*xTask)(void*);   /* The routine to run as a thread */
26511:   void *pIn;               /* Argument to xTask */
26512:   void *pResult;           /* Result of xTask */
26513: };
26514: 
26515: /* Thread procedure Win32 compatibility shim */
26516: static unsigned __stdcall sqlite3ThreadProc(
26517:   void *pArg  /* IN: Pointer to the SQLiteThread structure */
26518: ){
26519:   SQLiteThread *p = (SQLiteThread *)pArg;
26520: 
26521:   assert( p!=0 );
26522: #if 0
26523:   /*
26524:   ** This assert appears to trigger spuriously on certain
26525:   ** versions of Windows, possibly due to _beginthreadex()
26526:   ** and/or CreateThread() not fully setting their thread
26527:   ** ID parameter before starting the thread.
26528:   */
26529:   assert( p->id==GetCurrentThreadId() );
26530: #endif
26531:   assert( p->xTask!=0 );
26532:   p->pResult = p->xTask(p->pIn);
26533: 
26534:   _endthreadex(0);
26535:   return 0; /* NOT REACHED */
26536: }
26537: 
26538: /* Create a new thread */
26539: SQLITE_PRIVATE int sqlite3ThreadCreate(
26540:   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26541:   void *(*xTask)(void*),    /* Routine to run in a separate thread */
26542:   void *pIn                 /* Argument passed into xTask() */
26543: ){
26544:   SQLiteThread *p;
26545: 
26546:   assert( ppThread!=0 );
26547:   assert( xTask!=0 );
26548:   *ppThread = 0;
26549:   p = sqlite3Malloc(sizeof(*p));
26550:   if( p==0 ) return SQLITE_NOMEM_BKPT;
26551:   /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a 
26552:   ** function that returns SQLITE_ERROR when passed the argument 200, that
26553:   ** forces worker threads to run sequentially and deterministically 
26554:   ** (via the sqlite3FaultSim() term of the conditional) for testing
26555:   ** purposes. */
26556:   if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
26557:     memset(p, 0, sizeof(*p));
26558:   }else{
26559:     p->xTask = xTask;
26560:     p->pIn = pIn;
26561:     p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
26562:     if( p->tid==0 ){
26563:       memset(p, 0, sizeof(*p));
26564:     }
26565:   }
26566:   if( p->xTask==0 ){
26567:     p->id = GetCurrentThreadId();
26568:     p->pResult = xTask(pIn);
26569:   }
26570:   *ppThread = p;
26571:   return SQLITE_OK;
26572: }
26573: 
26574: SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
26575: 
26576: /* Get the results of the thread */
26577: SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26578:   DWORD rc;
26579:   BOOL bRc;
26580: 
26581:   assert( ppOut!=0 );
26582:   if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26583:   if( p->xTask==0 ){
26584:     /* assert( p->id==GetCurrentThreadId() ); */
26585:     rc = WAIT_OBJECT_0;
26586:     assert( p->tid==0 );
26587:   }else{
26588:     assert( p->id!=0 && p->id!=GetCurrentThreadId() );
26589:     rc = sqlite3Win32Wait((HANDLE)p->tid);
26590:     assert( rc!=WAIT_IO_COMPLETION );
26591:     bRc = CloseHandle((HANDLE)p->tid);
26592:     assert( bRc );
26593:   }
26594:   if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
26595:   sqlite3_free(p);
26596:   return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
26597: }
26598: 
26599: #endif /* SQLITE_OS_WIN_THREADS */
26600: /******************************** End Win32 Threads *************************/
26601: 
26602: 
26603: /********************************* Single-Threaded **************************/
26604: #ifndef SQLITE_THREADS_IMPLEMENTED
26605: /*
26606: ** This implementation does not actually create a new thread.  It does the
26607: ** work of the thread in the main thread, when either the thread is created
26608: ** or when it is joined
26609: */
26610: 
26611: /* A running thread */
26612: struct SQLiteThread {
26613:   void *(*xTask)(void*);   /* The routine to run as a thread */
26614:   void *pIn;               /* Argument to xTask */
26615:   void *pResult;           /* Result of xTask */
26616: };
26617: 
26618: /* Create a new thread */
26619: SQLITE_PRIVATE int sqlite3ThreadCreate(
26620:   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
26621:   void *(*xTask)(void*),    /* Routine to run in a separate thread */
26622:   void *pIn                 /* Argument passed into xTask() */
26623: ){
26624:   SQLiteThread *p;
26625: 
26626:   assert( ppThread!=0 );
26627:   assert( xTask!=0 );
26628:   *ppThread = 0;
26629:   p = sqlite3Malloc(sizeof(*p));
26630:   if( p==0 ) return SQLITE_NOMEM_BKPT;
26631:   if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
26632:     p->xTask = xTask;
26633:     p->pIn = pIn;
26634:   }else{
26635:     p->xTask = 0;
26636:     p->pResult = xTask(pIn);
26637:   }
26638:   *ppThread = p;
26639:   return SQLITE_OK;
26640: }
26641: 
26642: /* Get the results of the thread */
26643: SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26644: 
26645:   assert( ppOut!=0 );
26646:   if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26647:   if( p->xTask ){
26648:     *ppOut = p->xTask(p->pIn);
26649:   }else{
26650:     *ppOut = p->pResult;
26651:   }
26652:   sqlite3_free(p);
26653: 
26654: #if defined(SQLITE_TEST)
26655:   {
26656:     void *pTstAlloc = sqlite3Malloc(10);
26657:     if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
26658:     sqlite3_free(pTstAlloc);
26659:   }
26660: #endif
26661: 
26662:   return SQLITE_OK;
26663: }
26664: 
26665: #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
26666: /****************************** End Single-Threaded *************************/
26667: #endif /* SQLITE_MAX_WORKER_THREADS>0 */
26668: 
26669: /************** End of threads.c *********************************************/
26670: /************** Begin file utf.c *********************************************/
26671: /*
26672: ** 2004 April 13
26673: **
26674: ** The author disclaims copyright to this source code.  In place of
26675: ** a legal notice, here is a blessing:
26676: **
26677: **    May you do good and not evil.
26678: **    May you find forgiveness for yourself and forgive others.
26679: **    May you share freely, never taking more than you give.
26680: **
26681: *************************************************************************
26682: ** This file contains routines used to translate between UTF-8, 
26683: ** UTF-16, UTF-16BE, and UTF-16LE.
26684: **
26685: ** Notes on UTF-8:
26686: **
26687: **   Byte-0    Byte-1    Byte-2    Byte-3    Value
26688: **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
26689: **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
26690: **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
26691: **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
26692: **
26693: **
26694: ** Notes on UTF-16:  (with wwww+1==uuuuu)
26695: **
26696: **      Word-0               Word-1          Value
26697: **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
26698: **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
26699: **
26700: **
26701: ** BOM or Byte Order Mark:
26702: **     0xff 0xfe   little-endian utf-16 follows
26703: **     0xfe 0xff   big-endian utf-16 follows
26704: **
26705: */
26706: /* #include "sqliteInt.h" */
26707: /* #include <assert.h> */
26708: /* #include "vdbeInt.h" */
26709: 
26710: #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
26711: /*
26712: ** The following constant value is used by the SQLITE_BIGENDIAN and
26713: ** SQLITE_LITTLEENDIAN macros.
26714: */
26715: SQLITE_PRIVATE const int sqlite3one = 1;
26716: #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
26717: 
26718: /*
26719: ** This lookup table is used to help decode the first byte of
26720: ** a multi-byte UTF8 character.
26721: */
26722: static const unsigned char sqlite3Utf8Trans1[] = {
26723:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26724:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26725:   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
26726:   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
26727:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26728:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26729:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26730:   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
26731: };
26732: 
26733: 
26734: #define WRITE_UTF8(zOut, c) {                          \
26735:   if( c<0x00080 ){                                     \
26736:     *zOut++ = (u8)(c&0xFF);                            \
26737:   }                                                    \
26738:   else if( c<0x00800 ){                                \
26739:     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
26740:     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
26741:   }                                                    \
26742:   else if( c<0x10000 ){                                \
26743:     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
26744:     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
26745:     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
26746:   }else{                                               \
26747:     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
26748:     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
26749:     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
26750:     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
26751:   }                                                    \
26752: }
26753: 
26754: #define WRITE_UTF16LE(zOut, c) {                                    \
26755:   if( c<=0xFFFF ){                                                  \
26756:     *zOut++ = (u8)(c&0x00FF);                                       \
26757:     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
26758:   }else{                                                            \
26759:     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
26760:     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
26761:     *zOut++ = (u8)(c&0x00FF);                                       \
26762:     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
26763:   }                                                                 \
26764: }
26765: 
26766: #define WRITE_UTF16BE(zOut, c) {                                    \
26767:   if( c<=0xFFFF ){                                                  \
26768:     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
26769:     *zOut++ = (u8)(c&0x00FF);                                       \
26770:   }else{                                                            \
26771:     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
26772:     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
26773:     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
26774:     *zOut++ = (u8)(c&0x00FF);                                       \
26775:   }                                                                 \
26776: }
26777: 
26778: #define READ_UTF16LE(zIn, TERM, c){                                   \
26779:   c = (*zIn++);                                                       \
26780:   c += ((*zIn++)<<8);                                                 \
26781:   if( c>=0xD800 && c<0xE000 && TERM ){                                \
26782:     int c2 = (*zIn++);                                                \
26783:     c2 += ((*zIn++)<<8);                                              \
26784:     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
26785:   }                                                                   \
26786: }
26787: 
26788: #define READ_UTF16BE(zIn, TERM, c){                                   \
26789:   c = ((*zIn++)<<8);                                                  \
26790:   c += (*zIn++);                                                      \
26791:   if( c>=0xD800 && c<0xE000 && TERM ){                                \
26792:     int c2 = ((*zIn++)<<8);                                           \
26793:     c2 += (*zIn++);                                                   \
26794:     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
26795:   }                                                                   \
26796: }
26797: 
26798: /*
26799: ** Translate a single UTF-8 character.  Return the unicode value.
26800: **
26801: ** During translation, assume that the byte that zTerm points
26802: ** is a 0x00.
26803: **
26804: ** Write a pointer to the next unread byte back into *pzNext.
26805: **
26806: ** Notes On Invalid UTF-8:
26807: **
26808: **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
26809: **     be encoded as a multi-byte character.  Any multi-byte character that
26810: **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
26811: **
26812: **  *  This routine never allows a UTF16 surrogate value to be encoded.
26813: **     If a multi-byte character attempts to encode a value between
26814: **     0xd800 and 0xe000 then it is rendered as 0xfffd.
26815: **
26816: **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
26817: **     byte of a character are interpreted as single-byte characters
26818: **     and rendered as themselves even though they are technically
26819: **     invalid characters.
26820: **
26821: **  *  This routine accepts over-length UTF8 encodings
26822: **     for unicode values 0x80 and greater.  It does not change over-length
26823: **     encodings to 0xfffd as some systems recommend.
26824: */
26825: #define READ_UTF8(zIn, zTerm, c)                           \
26826:   c = *(zIn++);                                            \
26827:   if( c>=0xc0 ){                                           \
26828:     c = sqlite3Utf8Trans1[c-0xc0];                         \
26829:     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
26830:       c = (c<<6) + (0x3f & *(zIn++));                      \
26831:     }                                                      \
26832:     if( c<0x80                                             \
26833:         || (c&0xFFFFF800)==0xD800                          \
26834:         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
26835:   }
26836: SQLITE_PRIVATE u32 sqlite3Utf8Read(
26837:   const unsigned char **pz    /* Pointer to string from which to read char */
26838: ){
26839:   unsigned int c;
26840: 
26841:   /* Same as READ_UTF8() above but without the zTerm parameter.
26842:   ** For this routine, we assume the UTF8 string is always zero-terminated.
26843:   */
26844:   c = *((*pz)++);
26845:   if( c>=0xc0 ){
26846:     c = sqlite3Utf8Trans1[c-0xc0];
26847:     while( (*(*pz) & 0xc0)==0x80 ){
26848:       c = (c<<6) + (0x3f & *((*pz)++));
26849:     }
26850:     if( c<0x80
26851:         || (c&0xFFFFF800)==0xD800
26852:         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
26853:   }
26854:   return c;
26855: }
26856: 
26857: 
26858: 
26859: 
26860: /*
26861: ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
26862: ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
26863: */ 
26864: /* #define TRANSLATE_TRACE 1 */
26865: 
26866: #ifndef SQLITE_OMIT_UTF16
26867: /*
26868: ** This routine transforms the internal text encoding used by pMem to
26869: ** desiredEnc. It is an error if the string is already of the desired
26870: ** encoding, or if *pMem does not contain a string value.
26871: */
26872: SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
26873:   int len;                    /* Maximum length of output string in bytes */
26874:   unsigned char *zOut;                  /* Output buffer */
26875:   unsigned char *zIn;                   /* Input iterator */
26876:   unsigned char *zTerm;                 /* End of input */
26877:   unsigned char *z;                     /* Output iterator */
26878:   unsigned int c;
26879: 
26880:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
26881:   assert( pMem->flags&MEM_Str );
26882:   assert( pMem->enc!=desiredEnc );
26883:   assert( pMem->enc!=0 );
26884:   assert( pMem->n>=0 );
26885: 
26886: #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26887:   {
26888:     char zBuf[100];
26889:     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
26890:     fprintf(stderr, "INPUT:  %s\n", zBuf);
26891:   }
26892: #endif
26893: 
26894:   /* If the translation is between UTF-16 little and big endian, then 
26895:   ** all that is required is to swap the byte order. This case is handled
26896:   ** differently from the others.
26897:   */
26898:   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
26899:     u8 temp;
26900:     int rc;
26901:     rc = sqlite3VdbeMemMakeWriteable(pMem);
26902:     if( rc!=SQLITE_OK ){
26903:       assert( rc==SQLITE_NOMEM );
26904:       return SQLITE_NOMEM_BKPT;
26905:     }
26906:     zIn = (u8*)pMem->z;
26907:     zTerm = &zIn[pMem->n&~1];
26908:     while( zIn<zTerm ){
26909:       temp = *zIn;
26910:       *zIn = *(zIn+1);
26911:       zIn++;
26912:       *zIn++ = temp;
26913:     }
26914:     pMem->enc = desiredEnc;
26915:     goto translate_out;
26916:   }
26917: 
26918:   /* Set len to the maximum number of bytes required in the output buffer. */
26919:   if( desiredEnc==SQLITE_UTF8 ){
26920:     /* When converting from UTF-16, the maximum growth results from
26921:     ** translating a 2-byte character to a 4-byte UTF-8 character.
26922:     ** A single byte is required for the output string
26923:     ** nul-terminator.
26924:     */
26925:     pMem->n &= ~1;
26926:     len = pMem->n * 2 + 1;
26927:   }else{
26928:     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
26929:     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
26930:     ** character. Two bytes are required in the output buffer for the
26931:     ** nul-terminator.
26932:     */
26933:     len = pMem->n * 2 + 2;
26934:   }
26935: 
26936:   /* Set zIn to point at the start of the input buffer and zTerm to point 1
26937:   ** byte past the end.
26938:   **
26939:   ** Variable zOut is set to point at the output buffer, space obtained
26940:   ** from sqlite3_malloc().
26941:   */
26942:   zIn = (u8*)pMem->z;
26943:   zTerm = &zIn[pMem->n];
26944:   zOut = sqlite3DbMallocRaw(pMem->db, len);
26945:   if( !zOut ){
26946:     return SQLITE_NOMEM_BKPT;
26947:   }
26948:   z = zOut;
26949: 
26950:   if( pMem->enc==SQLITE_UTF8 ){
26951:     if( desiredEnc==SQLITE_UTF16LE ){
26952:       /* UTF-8 -> UTF-16 Little-endian */
26953:       while( zIn<zTerm ){
26954:         READ_UTF8(zIn, zTerm, c);
26955:         WRITE_UTF16LE(z, c);
26956:       }
26957:     }else{
26958:       assert( desiredEnc==SQLITE_UTF16BE );
26959:       /* UTF-8 -> UTF-16 Big-endian */
26960:       while( zIn<zTerm ){
26961:         READ_UTF8(zIn, zTerm, c);
26962:         WRITE_UTF16BE(z, c);
26963:       }
26964:     }
26965:     pMem->n = (int)(z - zOut);
26966:     *z++ = 0;
26967:   }else{
26968:     assert( desiredEnc==SQLITE_UTF8 );
26969:     if( pMem->enc==SQLITE_UTF16LE ){
26970:       /* UTF-16 Little-endian -> UTF-8 */
26971:       while( zIn<zTerm ){
26972:         READ_UTF16LE(zIn, zIn<zTerm, c); 
26973:         WRITE_UTF8(z, c);
26974:       }
26975:     }else{
26976:       /* UTF-16 Big-endian -> UTF-8 */
26977:       while( zIn<zTerm ){
26978:         READ_UTF16BE(zIn, zIn<zTerm, c); 
26979:         WRITE_UTF8(z, c);
26980:       }
26981:     }
26982:     pMem->n = (int)(z - zOut);
26983:   }
26984:   *z = 0;
26985:   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
26986: 
26987:   c = pMem->flags;
26988:   sqlite3VdbeMemRelease(pMem);
26989:   pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
26990:   pMem->enc = desiredEnc;
26991:   pMem->z = (char*)zOut;
26992:   pMem->zMalloc = pMem->z;
26993:   pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
26994: 
26995: translate_out:
26996: #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26997:   {
26998:     char zBuf[100];
26999:     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
27000:     fprintf(stderr, "OUTPUT: %s\n", zBuf);
27001:   }
27002: #endif
27003:   return SQLITE_OK;
27004: }
27005: 
27006: /*
27007: ** This routine checks for a byte-order mark at the beginning of the 
27008: ** UTF-16 string stored in *pMem. If one is present, it is removed and
27009: ** the encoding of the Mem adjusted. This routine does not do any
27010: ** byte-swapping, it just sets Mem.enc appropriately.
27011: **
27012: ** The allocation (static, dynamic etc.) and encoding of the Mem may be
27013: ** changed by this function.
27014: */
27015: SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
27016:   int rc = SQLITE_OK;
27017:   u8 bom = 0;
27018: 
27019:   assert( pMem->n>=0 );
27020:   if( pMem->n>1 ){
27021:     u8 b1 = *(u8 *)pMem->z;
27022:     u8 b2 = *(((u8 *)pMem->z) + 1);
27023:     if( b1==0xFE && b2==0xFF ){
27024:       bom = SQLITE_UTF16BE;
27025:     }
27026:     if( b1==0xFF && b2==0xFE ){
27027:       bom = SQLITE_UTF16LE;
27028:     }
27029:   }
27030:   
27031:   if( bom ){
27032:     rc = sqlite3VdbeMemMakeWriteable(pMem);
27033:     if( rc==SQLITE_OK ){
27034:       pMem->n -= 2;
27035:       memmove(pMem->z, &pMem->z[2], pMem->n);
27036:       pMem->z[pMem->n] = '\0';
27037:       pMem->z[pMem->n+1] = '\0';
27038:       pMem->flags |= MEM_Term;
27039:       pMem->enc = bom;
27040:     }
27041:   }
27042:   return rc;
27043: }
27044: #endif /* SQLITE_OMIT_UTF16 */
27045: 
27046: /*
27047: ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
27048: ** return the number of unicode characters in pZ up to (but not including)
27049: ** the first 0x00 byte. If nByte is not less than zero, return the
27050: ** number of unicode characters in the first nByte of pZ (or up to 
27051: ** the first 0x00, whichever comes first).
27052: */
27053: SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
27054:   int r = 0;
27055:   const u8 *z = (const u8*)zIn;
27056:   const u8 *zTerm;
27057:   if( nByte>=0 ){
27058:     zTerm = &z[nByte];
27059:   }else{
27060:     zTerm = (const u8*)(-1);
27061:   }
27062:   assert( z<=zTerm );
27063:   while( *z!=0 && z<zTerm ){
27064:     SQLITE_SKIP_UTF8(z);
27065:     r++;
27066:   }
27067:   return r;
27068: }
27069: 
27070: /* This test function is not currently used by the automated test-suite. 
27071: ** Hence it is only available in debug builds.
27072: */
27073: #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
27074: /*
27075: ** Translate UTF-8 to UTF-8.
27076: **
27077: ** This has the effect of making sure that the string is well-formed
27078: ** UTF-8.  Miscoded characters are removed.
27079: **
27080: ** The translation is done in-place and aborted if the output
27081: ** overruns the input.
27082: */
27083: SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
27084:   unsigned char *zOut = zIn;
27085:   unsigned char *zStart = zIn;
27086:   u32 c;
27087: 
27088:   while( zIn[0] && zOut<=zIn ){
27089:     c = sqlite3Utf8Read((const u8**)&zIn);
27090:     if( c!=0xfffd ){
27091:       WRITE_UTF8(zOut, c);
27092:     }
27093:   }
27094:   *zOut = 0;
27095:   return (int)(zOut - zStart);
27096: }
27097: #endif
27098: 
27099: #ifndef SQLITE_OMIT_UTF16
27100: /*
27101: ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
27102: ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
27103: ** be freed by the calling function.
27104: **
27105: ** NULL is returned if there is an allocation error.
27106: */
27107: SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
27108:   Mem m;
27109:   memset(&m, 0, sizeof(m));
27110:   m.db = db;
27111:   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
27112:   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
27113:   if( db->mallocFailed ){
27114:     sqlite3VdbeMemRelease(&m);
27115:     m.z = 0;
27116:   }
27117:   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
27118:   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
27119:   assert( m.z || db->mallocFailed );
27120:   return m.z;
27121: }
27122: 
27123: /*
27124: ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
27125: ** Return the number of bytes in the first nChar unicode characters
27126: ** in pZ.  nChar must be non-negative.
27127: */
27128: SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
27129:   int c;
27130:   unsigned char const *z = zIn;
27131:   int n = 0;
27132:   
27133:   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
27134:     while( n<nChar ){
27135:       READ_UTF16BE(z, 1, c);
27136:       n++;
27137:     }
27138:   }else{
27139:     while( n<nChar ){
27140:       READ_UTF16LE(z, 1, c);
27141:       n++;
27142:     }
27143:   }
27144:   return (int)(z-(unsigned char const *)zIn);
27145: }
27146: 
27147: #if defined(SQLITE_TEST)
27148: /*
27149: ** This routine is called from the TCL test function "translate_selftest".
27150: ** It checks that the primitives for serializing and deserializing
27151: ** characters in each encoding are inverses of each other.
27152: */
27153: SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
27154:   unsigned int i, t;
27155:   unsigned char zBuf[20];
27156:   unsigned char *z;
27157:   int n;
27158:   unsigned int c;
27159: 
27160:   for(i=0; i<0x00110000; i++){
27161:     z = zBuf;
27162:     WRITE_UTF8(z, i);
27163:     n = (int)(z-zBuf);
27164:     assert( n>0 && n<=4 );
27165:     z[0] = 0;
27166:     z = zBuf;
27167:     c = sqlite3Utf8Read((const u8**)&z);
27168:     t = i;
27169:     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
27170:     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
27171:     assert( c==t );
27172:     assert( (z-zBuf)==n );
27173:   }
27174:   for(i=0; i<0x00110000; i++){
27175:     if( i>=0xD800 && i<0xE000 ) continue;
27176:     z = zBuf;
27177:     WRITE_UTF16LE(z, i);
27178:     n = (int)(z-zBuf);
27179:     assert( n>0 && n<=4 );
27180:     z[0] = 0;
27181:     z = zBuf;
27182:     READ_UTF16LE(z, 1, c);
27183:     assert( c==i );
27184:     assert( (z-zBuf)==n );
27185:   }
27186:   for(i=0; i<0x00110000; i++){
27187:     if( i>=0xD800 && i<0xE000 ) continue;
27188:     z = zBuf;
27189:     WRITE_UTF16BE(z, i);
27190:     n = (int)(z-zBuf);
27191:     assert( n>0 && n<=4 );
27192:     z[0] = 0;
27193:     z = zBuf;
27194:     READ_UTF16BE(z, 1, c);
27195:     assert( c==i );
27196:     assert( (z-zBuf)==n );
27197:   }
27198: }
27199: #endif /* SQLITE_TEST */
27200: #endif /* SQLITE_OMIT_UTF16 */
27201: 
27202: /************** End of utf.c *************************************************/
27203: /************** Begin file util.c ********************************************/
27204: /*
27205: ** 2001 September 15
27206: **
27207: ** The author disclaims copyright to this source code.  In place of
27208: ** a legal notice, here is a blessing:
27209: **
27210: **    May you do good and not evil.
27211: **    May you find forgiveness for yourself and forgive others.
27212: **    May you share freely, never taking more than you give.
27213: **
27214: *************************************************************************
27215: ** Utility functions used throughout sqlite.
27216: **
27217: ** This file contains functions for allocating memory, comparing
27218: ** strings, and stuff like that.
27219: **
27220: */
27221: /* #include "sqliteInt.h" */
27222: /* #include <stdarg.h> */
27223: #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
27224: # include <math.h>
27225: #endif
27226: 
27227: /*
27228: ** Routine needed to support the testcase() macro.
27229: */
27230: #ifdef SQLITE_COVERAGE_TEST
27231: SQLITE_PRIVATE void sqlite3Coverage(int x){
27232:   static unsigned dummy = 0;
27233:   dummy += (unsigned)x;
27234: }
27235: #endif
27236: 
27237: /*
27238: ** Give a callback to the test harness that can be used to simulate faults
27239: ** in places where it is difficult or expensive to do so purely by means
27240: ** of inputs.
27241: **
27242: ** The intent of the integer argument is to let the fault simulator know
27243: ** which of multiple sqlite3FaultSim() calls has been hit.
27244: **
27245: ** Return whatever integer value the test callback returns, or return
27246: ** SQLITE_OK if no test callback is installed.
27247: */
27248: #ifndef SQLITE_OMIT_BUILTIN_TEST
27249: SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
27250:   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
27251:   return xCallback ? xCallback(iTest) : SQLITE_OK;
27252: }
27253: #endif
27254: 
27255: #ifndef SQLITE_OMIT_FLOATING_POINT
27256: /*
27257: ** Return true if the floating point value is Not a Number (NaN).
27258: **
27259: ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
27260: ** Otherwise, we have our own implementation that works on most systems.
27261: */
27262: SQLITE_PRIVATE int sqlite3IsNaN(double x){
27263:   int rc;   /* The value return */
27264: #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
27265:   /*
27266:   ** Systems that support the isnan() library function should probably
27267:   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
27268:   ** found that many systems do not have a working isnan() function so
27269:   ** this implementation is provided as an alternative.
27270:   **
27271:   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
27272:   ** On the other hand, the use of -ffast-math comes with the following
27273:   ** warning:
27274:   **
27275:   **      This option [-ffast-math] should never be turned on by any
27276:   **      -O option since it can result in incorrect output for programs
27277:   **      which depend on an exact implementation of IEEE or ISO 
27278:   **      rules/specifications for math functions.
27279:   **
27280:   ** Under MSVC, this NaN test may fail if compiled with a floating-
27281:   ** point precision mode other than /fp:precise.  From the MSDN 
27282:   ** documentation:
27283:   **
27284:   **      The compiler [with /fp:precise] will properly handle comparisons 
27285:   **      involving NaN. For example, x != x evaluates to true if x is NaN 
27286:   **      ...
27287:   */
27288: #ifdef __FAST_MATH__
27289: # error SQLite will not work correctly with the -ffast-math option of GCC.
27290: #endif
27291:   volatile double y = x;
27292:   volatile double z = y;
27293:   rc = (y!=z);
27294: #else  /* if HAVE_ISNAN */
27295:   rc = isnan(x);
27296: #endif /* HAVE_ISNAN */
27297:   testcase( rc );
27298:   return rc;
27299: }
27300: #endif /* SQLITE_OMIT_FLOATING_POINT */
27301: 
27302: /*
27303: ** Compute a string length that is limited to what can be stored in
27304: ** lower 30 bits of a 32-bit signed integer.
27305: **
27306: ** The value returned will never be negative.  Nor will it ever be greater
27307: ** than the actual length of the string.  For very long strings (greater
27308: ** than 1GiB) the value returned might be less than the true string length.
27309: */
27310: SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
27311:   if( z==0 ) return 0;
27312:   return 0x3fffffff & (int)strlen(z);
27313: }
27314: 
27315: /*
27316: ** Return the declared type of a column.  Or return zDflt if the column 
27317: ** has no declared type.
27318: **
27319: ** The column type is an extra string stored after the zero-terminator on
27320: ** the column name if and only if the COLFLAG_HASTYPE flag is set.
27321: */
27322: SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
27323:   if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
27324:   return pCol->zName + strlen(pCol->zName) + 1;
27325: }
27326: 
27327: /*
27328: ** Helper function for sqlite3Error() - called rarely.  Broken out into
27329: ** a separate routine to avoid unnecessary register saves on entry to
27330: ** sqlite3Error().
27331: */
27332: static SQLITE_NOINLINE void  sqlite3ErrorFinish(sqlite3 *db, int err_code){
27333:   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
27334:   sqlite3SystemError(db, err_code);
27335: }
27336: 
27337: /*
27338: ** Set the current error code to err_code and clear any prior error message.
27339: ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
27340: ** that would be appropriate.
27341: */
27342: SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
27343:   assert( db!=0 );
27344:   db->errCode = err_code;
27345:   if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
27346: }
27347: 
27348: /*
27349: ** Load the sqlite3.iSysErrno field if that is an appropriate thing
27350: ** to do based on the SQLite error code in rc.
27351: */
27352: SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
27353:   if( rc==SQLITE_IOERR_NOMEM ) return;
27354:   rc &= 0xff;
27355:   if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
27356:     db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
27357:   }
27358: }
27359: 
27360: /*
27361: ** Set the most recent error code and error string for the sqlite
27362: ** handle "db". The error code is set to "err_code".
27363: **
27364: ** If it is not NULL, string zFormat specifies the format of the
27365: ** error string in the style of the printf functions: The following
27366: ** format characters are allowed:
27367: **
27368: **      %s      Insert a string
27369: **      %z      A string that should be freed after use
27370: **      %d      Insert an integer
27371: **      %T      Insert a token
27372: **      %S      Insert the first element of a SrcList
27373: **
27374: ** zFormat and any string tokens that follow it are assumed to be
27375: ** encoded in UTF-8.
27376: **
27377: ** To clear the most recent error for sqlite handle "db", sqlite3Error
27378: ** should be called with err_code set to SQLITE_OK and zFormat set
27379: ** to NULL.
27380: */
27381: SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
27382:   assert( db!=0 );
27383:   db->errCode = err_code;
27384:   sqlite3SystemError(db, err_code);
27385:   if( zFormat==0 ){
27386:     sqlite3Error(db, err_code);
27387:   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
27388:     char *z;
27389:     va_list ap;
27390:     va_start(ap, zFormat);
27391:     z = sqlite3VMPrintf(db, zFormat, ap);
27392:     va_end(ap);
27393:     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
27394:   }
27395: }
27396: 
27397: /*
27398: ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
27399: ** The following formatting characters are allowed:
27400: **
27401: **      %s      Insert a string
27402: **      %z      A string that should be freed after use
27403: **      %d      Insert an integer
27404: **      %T      Insert a token
27405: **      %S      Insert the first element of a SrcList
27406: **
27407: ** This function should be used to report any error that occurs while
27408: ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
27409: ** last thing the sqlite3_prepare() function does is copy the error
27410: ** stored by this function into the database handle using sqlite3Error().
27411: ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
27412: ** during statement execution (sqlite3_step() etc.).
27413: */
27414: SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
27415:   char *zMsg;
27416:   va_list ap;
27417:   sqlite3 *db = pParse->db;
27418:   va_start(ap, zFormat);
27419:   zMsg = sqlite3VMPrintf(db, zFormat, ap);
27420:   va_end(ap);
27421:   if( db->suppressErr ){
27422:     sqlite3DbFree(db, zMsg);
27423:   }else{
27424:     pParse->nErr++;
27425:     sqlite3DbFree(db, pParse->zErrMsg);
27426:     pParse->zErrMsg = zMsg;
27427:     pParse->rc = SQLITE_ERROR;
27428:   }
27429: }
27430: 
27431: /*
27432: ** Convert an SQL-style quoted string into a normal string by removing
27433: ** the quote characters.  The conversion is done in-place.  If the
27434: ** input does not begin with a quote character, then this routine
27435: ** is a no-op.
27436: **
27437: ** The input string must be zero-terminated.  A new zero-terminator
27438: ** is added to the dequoted string.
27439: **
27440: ** The return value is -1 if no dequoting occurs or the length of the
27441: ** dequoted string, exclusive of the zero terminator, if dequoting does
27442: ** occur.
27443: **
27444: ** 2002-Feb-14: This routine is extended to remove MS-Access style
27445: ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
27446: ** "a-b-c".
27447: */
27448: SQLITE_PRIVATE void sqlite3Dequote(char *z){
27449:   char quote;
27450:   int i, j;
27451:   if( z==0 ) return;
27452:   quote = z[0];
27453:   if( !sqlite3Isquote(quote) ) return;
27454:   if( quote=='[' ) quote = ']';
27455:   for(i=1, j=0;; i++){
27456:     assert( z[i] );
27457:     if( z[i]==quote ){
27458:       if( z[i+1]==quote ){
27459:         z[j++] = quote;
27460:         i++;
27461:       }else{
27462:         break;
27463:       }
27464:     }else{
27465:       z[j++] = z[i];
27466:     }
27467:   }
27468:   z[j] = 0;
27469: }
27470: 
27471: /*
27472: ** Generate a Token object from a string
27473: */
27474: SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
27475:   p->z = z;
27476:   p->n = sqlite3Strlen30(z);
27477: }
27478: 
27479: /* Convenient short-hand */
27480: #define UpperToLower sqlite3UpperToLower
27481: 
27482: /*
27483: ** Some systems have stricmp().  Others have strcasecmp().  Because
27484: ** there is no consistency, we will define our own.
27485: **
27486: ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
27487: ** sqlite3_strnicmp() APIs allow applications and extensions to compare
27488: ** the contents of two buffers containing UTF-8 strings in a
27489: ** case-independent fashion, using the same definition of "case
27490: ** independence" that SQLite uses internally when comparing identifiers.
27491: */
27492: SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
27493:   if( zLeft==0 ){
27494:     return zRight ? -1 : 0;
27495:   }else if( zRight==0 ){
27496:     return 1;
27497:   }
27498:   return sqlite3StrICmp(zLeft, zRight);
27499: }
27500: SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
27501:   unsigned char *a, *b;
27502:   int c;
27503:   a = (unsigned char *)zLeft;
27504:   b = (unsigned char *)zRight;
27505:   for(;;){
27506:     c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
27507:     if( c || *a==0 ) break;
27508:     a++;
27509:     b++;
27510:   }
27511:   return c;
27512: }
27513: SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
27514:   register unsigned char *a, *b;
27515:   if( zLeft==0 ){
27516:     return zRight ? -1 : 0;
27517:   }else if( zRight==0 ){
27518:     return 1;
27519:   }
27520:   a = (unsigned char *)zLeft;
27521:   b = (unsigned char *)zRight;
27522:   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
27523:   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
27524: }
27525: 
27526: /*
27527: ** The string z[] is an text representation of a real number.
27528: ** Convert this string to a double and write it into *pResult.
27529: **
27530: ** The string z[] is length bytes in length (bytes, not characters) and
27531: ** uses the encoding enc.  The string is not necessarily zero-terminated.
27532: **
27533: ** Return TRUE if the result is a valid real number (or integer) and FALSE
27534: ** if the string is empty or contains extraneous text.  Valid numbers
27535: ** are in one of these formats:
27536: **
27537: **    [+-]digits[E[+-]digits]
27538: **    [+-]digits.[digits][E[+-]digits]
27539: **    [+-].digits[E[+-]digits]
27540: **
27541: ** Leading and trailing whitespace is ignored for the purpose of determining
27542: ** validity.
27543: **
27544: ** If some prefix of the input string is a valid number, this routine
27545: ** returns FALSE but it still converts the prefix and writes the result
27546: ** into *pResult.
27547: */
27548: SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
27549: #ifndef SQLITE_OMIT_FLOATING_POINT
27550:   int incr;
27551:   const char *zEnd = z + length;
27552:   /* sign * significand * (10 ^ (esign * exponent)) */
27553:   int sign = 1;    /* sign of significand */
27554:   i64 s = 0;       /* significand */
27555:   int d = 0;       /* adjust exponent for shifting decimal point */
27556:   int esign = 1;   /* sign of exponent */
27557:   int e = 0;       /* exponent */
27558:   int eValid = 1;  /* True exponent is either not used or is well-formed */
27559:   double result;
27560:   int nDigits = 0;
27561:   int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
27562: 
27563:   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27564:   *pResult = 0.0;   /* Default return value, in case of an error */
27565: 
27566:   if( enc==SQLITE_UTF8 ){
27567:     incr = 1;
27568:   }else{
27569:     int i;
27570:     incr = 2;
27571:     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27572:     for(i=3-enc; i<length && z[i]==0; i+=2){}
27573:     nonNum = i<length;
27574:     zEnd = &z[i^1];
27575:     z += (enc&1);
27576:   }
27577: 
27578:   /* skip leading spaces */
27579:   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27580:   if( z>=zEnd ) return 0;
27581: 
27582:   /* get sign of significand */
27583:   if( *z=='-' ){
27584:     sign = -1;
27585:     z+=incr;
27586:   }else if( *z=='+' ){
27587:     z+=incr;
27588:   }
27589: 
27590:   /* copy max significant digits to significand */
27591:   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
27592:     s = s*10 + (*z - '0');
27593:     z+=incr, nDigits++;
27594:   }
27595: 
27596:   /* skip non-significant significand digits
27597:   ** (increase exponent by d to shift decimal left) */
27598:   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
27599:   if( z>=zEnd ) goto do_atof_calc;
27600: 
27601:   /* if decimal point is present */
27602:   if( *z=='.' ){
27603:     z+=incr;
27604:     /* copy digits from after decimal to significand
27605:     ** (decrease exponent by d to shift decimal right) */
27606:     while( z<zEnd && sqlite3Isdigit(*z) ){
27607:       if( s<((LARGEST_INT64-9)/10) ){
27608:         s = s*10 + (*z - '0');
27609:         d--;
27610:       }
27611:       z+=incr, nDigits++;
27612:     }
27613:   }
27614:   if( z>=zEnd ) goto do_atof_calc;
27615: 
27616:   /* if exponent is present */
27617:   if( *z=='e' || *z=='E' ){
27618:     z+=incr;
27619:     eValid = 0;
27620: 
27621:     /* This branch is needed to avoid a (harmless) buffer overread.  The 
27622:     ** special comment alerts the mutation tester that the correct answer
27623:     ** is obtained even if the branch is omitted */
27624:     if( z>=zEnd ) goto do_atof_calc;              /*PREVENTS-HARMLESS-OVERREAD*/
27625: 
27626:     /* get sign of exponent */
27627:     if( *z=='-' ){
27628:       esign = -1;
27629:       z+=incr;
27630:     }else if( *z=='+' ){
27631:       z+=incr;
27632:     }
27633:     /* copy digits to exponent */
27634:     while( z<zEnd && sqlite3Isdigit(*z) ){
27635:       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
27636:       z+=incr;
27637:       eValid = 1;
27638:     }
27639:   }
27640: 
27641:   /* skip trailing spaces */
27642:   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27643: 
27644: do_atof_calc:
27645:   /* adjust exponent by d, and update sign */
27646:   e = (e*esign) + d;
27647:   if( e<0 ) {
27648:     esign = -1;
27649:     e *= -1;
27650:   } else {
27651:     esign = 1;
27652:   }
27653: 
27654:   if( s==0 ) {
27655:     /* In the IEEE 754 standard, zero is signed. */
27656:     result = sign<0 ? -(double)0 : (double)0;
27657:   } else {
27658:     /* Attempt to reduce exponent.
27659:     **
27660:     ** Branches that are not required for the correct answer but which only
27661:     ** help to obtain the correct answer faster are marked with special
27662:     ** comments, as a hint to the mutation tester.
27663:     */
27664:     while( e>0 ){                                       /*OPTIMIZATION-IF-TRUE*/
27665:       if( esign>0 ){
27666:         if( s>=(LARGEST_INT64/10) ) break;             /*OPTIMIZATION-IF-FALSE*/
27667:         s *= 10;
27668:       }else{
27669:         if( s%10!=0 ) break;                           /*OPTIMIZATION-IF-FALSE*/
27670:         s /= 10;
27671:       }
27672:       e--;
27673:     }
27674: 
27675:     /* adjust the sign of significand */
27676:     s = sign<0 ? -s : s;
27677: 
27678:     if( e==0 ){                                         /*OPTIMIZATION-IF-TRUE*/
27679:       result = (double)s;
27680:     }else{
27681:       LONGDOUBLE_TYPE scale = 1.0;
27682:       /* attempt to handle extremely small/large numbers better */
27683:       if( e>307 ){                                      /*OPTIMIZATION-IF-TRUE*/
27684:         if( e<342 ){                                    /*OPTIMIZATION-IF-TRUE*/
27685:           while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27686:           if( esign<0 ){
27687:             result = s / scale;
27688:             result /= 1.0e+308;
27689:           }else{
27690:             result = s * scale;
27691:             result *= 1.0e+308;
27692:           }
27693:         }else{ assert( e>=342 );
27694:           if( esign<0 ){
27695:             result = 0.0*s;
27696:           }else{
27697:             result = 1e308*1e308*s;  /* Infinity */
27698:           }
27699:         }
27700:       }else{
27701:         /* 1.0e+22 is the largest power of 10 than can be 
27702:         ** represented exactly. */
27703:         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
27704:         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
27705:         if( esign<0 ){
27706:           result = s / scale;
27707:         }else{
27708:           result = s * scale;
27709:         }
27710:       }
27711:     }
27712:   }
27713: 
27714:   /* store the result */
27715:   *pResult = result;
27716: 
27717:   /* return true if number and no extra non-whitespace chracters after */
27718:   return z==zEnd && nDigits>0 && eValid && nonNum==0;
27719: #else
27720:   return !sqlite3Atoi64(z, pResult, length, enc);
27721: #endif /* SQLITE_OMIT_FLOATING_POINT */
27722: }
27723: 
27724: /*
27725: ** Compare the 19-character string zNum against the text representation
27726: ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
27727: ** if zNum is less than, equal to, or greater than the string.
27728: ** Note that zNum must contain exactly 19 characters.
27729: **
27730: ** Unlike memcmp() this routine is guaranteed to return the difference
27731: ** in the values of the last digit if the only difference is in the
27732: ** last digit.  So, for example,
27733: **
27734: **      compare2pow63("9223372036854775800", 1)
27735: **
27736: ** will return -8.
27737: */
27738: static int compare2pow63(const char *zNum, int incr){
27739:   int c = 0;
27740:   int i;
27741:                     /* 012345678901234567 */
27742:   const char *pow63 = "922337203685477580";
27743:   for(i=0; c==0 && i<18; i++){
27744:     c = (zNum[i*incr]-pow63[i])*10;
27745:   }
27746:   if( c==0 ){
27747:     c = zNum[18*incr] - '8';
27748:     testcase( c==(-1) );
27749:     testcase( c==0 );
27750:     testcase( c==(+1) );
27751:   }
27752:   return c;
27753: }
27754: 
27755: /*
27756: ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
27757: ** routine does *not* accept hexadecimal notation.
27758: **
27759: ** If the zNum value is representable as a 64-bit twos-complement 
27760: ** integer, then write that value into *pNum and return 0.
27761: **
27762: ** If zNum is exactly 9223372036854775808, return 2.  This special
27763: ** case is broken out because while 9223372036854775808 cannot be a 
27764: ** signed 64-bit integer, its negative -9223372036854775808 can be.
27765: **
27766: ** If zNum is too big for a 64-bit integer and is not
27767: ** 9223372036854775808  or if zNum contains any non-numeric text,
27768: ** then return 1.
27769: **
27770: ** length is the number of bytes in the string (bytes, not characters).
27771: ** The string is not necessarily zero-terminated.  The encoding is
27772: ** given by enc.
27773: */
27774: SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
27775:   int incr;
27776:   u64 u = 0;
27777:   int neg = 0; /* assume positive */
27778:   int i;
27779:   int c = 0;
27780:   int nonNum = 0;  /* True if input contains UTF16 with high byte non-zero */
27781:   const char *zStart;
27782:   const char *zEnd = zNum + length;
27783:   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27784:   if( enc==SQLITE_UTF8 ){
27785:     incr = 1;
27786:   }else{
27787:     incr = 2;
27788:     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27789:     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
27790:     nonNum = i<length;
27791:     zEnd = &zNum[i^1];
27792:     zNum += (enc&1);
27793:   }
27794:   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
27795:   if( zNum<zEnd ){
27796:     if( *zNum=='-' ){
27797:       neg = 1;
27798:       zNum+=incr;
27799:     }else if( *zNum=='+' ){
27800:       zNum+=incr;
27801:     }
27802:   }
27803:   zStart = zNum;
27804:   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
27805:   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
27806:     u = u*10 + c - '0';
27807:   }
27808:   if( u>LARGEST_INT64 ){
27809:     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
27810:   }else if( neg ){
27811:     *pNum = -(i64)u;
27812:   }else{
27813:     *pNum = (i64)u;
27814:   }
27815:   testcase( i==18 );
27816:   testcase( i==19 );
27817:   testcase( i==20 );
27818:   if( &zNum[i]<zEnd              /* Extra bytes at the end */
27819:    || (i==0 && zStart==zNum)     /* No digits */
27820:    || i>19*incr                  /* Too many digits */
27821:    || nonNum                     /* UTF16 with high-order bytes non-zero */
27822:   ){
27823:     /* zNum is empty or contains non-numeric text or is longer
27824:     ** than 19 digits (thus guaranteeing that it is too large) */
27825:     return 1;
27826:   }else if( i<19*incr ){
27827:     /* Less than 19 digits, so we know that it fits in 64 bits */
27828:     assert( u<=LARGEST_INT64 );
27829:     return 0;
27830:   }else{
27831:     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
27832:     c = compare2pow63(zNum, incr);
27833:     if( c<0 ){
27834:       /* zNum is less than 9223372036854775808 so it fits */
27835:       assert( u<=LARGEST_INT64 );
27836:       return 0;
27837:     }else if( c>0 ){
27838:       /* zNum is greater than 9223372036854775808 so it overflows */
27839:       return 1;
27840:     }else{
27841:       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
27842:       ** special case 2 overflow if positive */
27843:       assert( u-1==LARGEST_INT64 );
27844:       return neg ? 0 : 2;
27845:     }
27846:   }
27847: }
27848: 
27849: /*
27850: ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
27851: ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
27852: ** whereas sqlite3Atoi64() does not.
27853: **
27854: ** Returns:
27855: **
27856: **     0    Successful transformation.  Fits in a 64-bit signed integer.
27857: **     1    Integer too large for a 64-bit signed integer or is malformed
27858: **     2    Special case of 9223372036854775808
27859: */
27860: SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
27861: #ifndef SQLITE_OMIT_HEX_INTEGER
27862:   if( z[0]=='0'
27863:    && (z[1]=='x' || z[1]=='X')
27864:   ){
27865:     u64 u = 0;
27866:     int i, k;
27867:     for(i=2; z[i]=='0'; i++){}
27868:     for(k=i; sqlite3Isxdigit(z[k]); k++){
27869:       u = u*16 + sqlite3HexToInt(z[k]);
27870:     }
27871:     memcpy(pOut, &u, 8);
27872:     return (z[k]==0 && k-i<=16) ? 0 : 1;
27873:   }else
27874: #endif /* SQLITE_OMIT_HEX_INTEGER */
27875:   {
27876:     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
27877:   }
27878: }
27879: 
27880: /*
27881: ** If zNum represents an integer that will fit in 32-bits, then set
27882: ** *pValue to that integer and return true.  Otherwise return false.
27883: **
27884: ** This routine accepts both decimal and hexadecimal notation for integers.
27885: **
27886: ** Any non-numeric characters that following zNum are ignored.
27887: ** This is different from sqlite3Atoi64() which requires the
27888: ** input number to be zero-terminated.
27889: */
27890: SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
27891:   sqlite_int64 v = 0;
27892:   int i, c;
27893:   int neg = 0;
27894:   if( zNum[0]=='-' ){
27895:     neg = 1;
27896:     zNum++;
27897:   }else if( zNum[0]=='+' ){
27898:     zNum++;
27899:   }
27900: #ifndef SQLITE_OMIT_HEX_INTEGER
27901:   else if( zNum[0]=='0'
27902:         && (zNum[1]=='x' || zNum[1]=='X')
27903:         && sqlite3Isxdigit(zNum[2])
27904:   ){
27905:     u32 u = 0;
27906:     zNum += 2;
27907:     while( zNum[0]=='0' ) zNum++;
27908:     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
27909:       u = u*16 + sqlite3HexToInt(zNum[i]);
27910:     }
27911:     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
27912:       memcpy(pValue, &u, 4);
27913:       return 1;
27914:     }else{
27915:       return 0;
27916:     }
27917:   }
27918: #endif
27919:   while( zNum[0]=='0' ) zNum++;
27920:   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
27921:     v = v*10 + c;
27922:   }
27923: 
27924:   /* The longest decimal representation of a 32 bit integer is 10 digits:
27925:   **
27926:   **             1234567890
27927:   **     2^31 -> 2147483648
27928:   */
27929:   testcase( i==10 );
27930:   if( i>10 ){
27931:     return 0;
27932:   }
27933:   testcase( v-neg==2147483647 );
27934:   if( v-neg>2147483647 ){
27935:     return 0;
27936:   }
27937:   if( neg ){
27938:     v = -v;
27939:   }
27940:   *pValue = (int)v;
27941:   return 1;
27942: }
27943: 
27944: /*
27945: ** Return a 32-bit integer value extracted from a string.  If the
27946: ** string is not an integer, just return 0.
27947: */
27948: SQLITE_PRIVATE int sqlite3Atoi(const char *z){
27949:   int x = 0;
27950:   if( z ) sqlite3GetInt32(z, &x);
27951:   return x;
27952: }
27953: 
27954: /*
27955: ** The variable-length integer encoding is as follows:
27956: **
27957: ** KEY:
27958: **         A = 0xxxxxxx    7 bits of data and one flag bit
27959: **         B = 1xxxxxxx    7 bits of data and one flag bit
27960: **         C = xxxxxxxx    8 bits of data
27961: **
27962: **  7 bits - A
27963: ** 14 bits - BA
27964: ** 21 bits - BBA
27965: ** 28 bits - BBBA
27966: ** 35 bits - BBBBA
27967: ** 42 bits - BBBBBA
27968: ** 49 bits - BBBBBBA
27969: ** 56 bits - BBBBBBBA
27970: ** 64 bits - BBBBBBBBC
27971: */
27972: 
27973: /*
27974: ** Write a 64-bit variable-length integer to memory starting at p[0].
27975: ** The length of data write will be between 1 and 9 bytes.  The number
27976: ** of bytes written is returned.
27977: **
27978: ** A variable-length integer consists of the lower 7 bits of each byte
27979: ** for all bytes that have the 8th bit set and one byte with the 8th
27980: ** bit clear.  Except, if we get to the 9th byte, it stores the full
27981: ** 8 bits and is the last byte.
27982: */
27983: static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
27984:   int i, j, n;
27985:   u8 buf[10];
27986:   if( v & (((u64)0xff000000)<<32) ){
27987:     p[8] = (u8)v;
27988:     v >>= 8;
27989:     for(i=7; i>=0; i--){
27990:       p[i] = (u8)((v & 0x7f) | 0x80);
27991:       v >>= 7;
27992:     }
27993:     return 9;
27994:   }    
27995:   n = 0;
27996:   do{
27997:     buf[n++] = (u8)((v & 0x7f) | 0x80);
27998:     v >>= 7;
27999:   }while( v!=0 );
28000:   buf[0] &= 0x7f;
28001:   assert( n<=9 );
28002:   for(i=0, j=n-1; j>=0; j--, i++){
28003:     p[i] = buf[j];
28004:   }
28005:   return n;
28006: }
28007: SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
28008:   if( v<=0x7f ){
28009:     p[0] = v&0x7f;
28010:     return 1;
28011:   }
28012:   if( v<=0x3fff ){
28013:     p[0] = ((v>>7)&0x7f)|0x80;
28014:     p[1] = v&0x7f;
28015:     return 2;
28016:   }
28017:   return putVarint64(p,v);
28018: }
28019: 
28020: /*
28021: ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
28022: ** are defined here rather than simply putting the constant expressions
28023: ** inline in order to work around bugs in the RVT compiler.
28024: **
28025: ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
28026: **
28027: ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
28028: */
28029: #define SLOT_2_0     0x001fc07f
28030: #define SLOT_4_2_0   0xf01fc07f
28031: 
28032: 
28033: /*
28034: ** Read a 64-bit variable-length integer from memory starting at p[0].
28035: ** Return the number of bytes read.  The value is stored in *v.
28036: */
28037: SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
28038:   u32 a,b,s;
28039: 
28040:   a = *p;
28041:   /* a: p0 (unmasked) */
28042:   if (!(a&0x80))
28043:   {
28044:     *v = a;
28045:     return 1;
28046:   }
28047: 
28048:   p++;
28049:   b = *p;
28050:   /* b: p1 (unmasked) */
28051:   if (!(b&0x80))
28052:   {
28053:     a &= 0x7f;
28054:     a = a<<7;
28055:     a |= b;
28056:     *v = a;
28057:     return 2;
28058:   }
28059: 
28060:   /* Verify that constants are precomputed correctly */
28061:   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
28062:   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
28063: 
28064:   p++;
28065:   a = a<<14;
28066:   a |= *p;
28067:   /* a: p0<<14 | p2 (unmasked) */
28068:   if (!(a&0x80))
28069:   {
28070:     a &= SLOT_2_0;
28071:     b &= 0x7f;
28072:     b = b<<7;
28073:     a |= b;
28074:     *v = a;
28075:     return 3;
28076:   }
28077: 
28078:   /* CSE1 from below */
28079:   a &= SLOT_2_0;
28080:   p++;
28081:   b = b<<14;
28082:   b |= *p;
28083:   /* b: p1<<14 | p3 (unmasked) */
28084:   if (!(b&0x80))
28085:   {
28086:     b &= SLOT_2_0;
28087:     /* moved CSE1 up */
28088:     /* a &= (0x7f<<14)|(0x7f); */
28089:     a = a<<7;
28090:     a |= b;
28091:     *v = a;
28092:     return 4;
28093:   }
28094: 
28095:   /* a: p0<<14 | p2 (masked) */
28096:   /* b: p1<<14 | p3 (unmasked) */
28097:   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28098:   /* moved CSE1 up */
28099:   /* a &= (0x7f<<14)|(0x7f); */
28100:   b &= SLOT_2_0;
28101:   s = a;
28102:   /* s: p0<<14 | p2 (masked) */
28103: 
28104:   p++;
28105:   a = a<<14;
28106:   a |= *p;
28107:   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28108:   if (!(a&0x80))
28109:   {
28110:     /* we can skip these cause they were (effectively) done above
28111:     ** while calculating s */
28112:     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28113:     /* b &= (0x7f<<14)|(0x7f); */
28114:     b = b<<7;
28115:     a |= b;
28116:     s = s>>18;
28117:     *v = ((u64)s)<<32 | a;
28118:     return 5;
28119:   }
28120: 
28121:   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28122:   s = s<<7;
28123:   s |= b;
28124:   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
28125: 
28126:   p++;
28127:   b = b<<14;
28128:   b |= *p;
28129:   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
28130:   if (!(b&0x80))
28131:   {
28132:     /* we can skip this cause it was (effectively) done above in calc'ing s */
28133:     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
28134:     a &= SLOT_2_0;
28135:     a = a<<7;
28136:     a |= b;
28137:     s = s>>18;
28138:     *v = ((u64)s)<<32 | a;
28139:     return 6;
28140:   }
28141: 
28142:   p++;
28143:   a = a<<14;
28144:   a |= *p;
28145:   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
28146:   if (!(a&0x80))
28147:   {
28148:     a &= SLOT_4_2_0;
28149:     b &= SLOT_2_0;
28150:     b = b<<7;
28151:     a |= b;
28152:     s = s>>11;
28153:     *v = ((u64)s)<<32 | a;
28154:     return 7;
28155:   }
28156: 
28157:   /* CSE2 from below */
28158:   a &= SLOT_2_0;
28159:   p++;
28160:   b = b<<14;
28161:   b |= *p;
28162:   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
28163:   if (!(b&0x80))
28164:   {
28165:     b &= SLOT_4_2_0;
28166:     /* moved CSE2 up */
28167:     /* a &= (0x7f<<14)|(0x7f); */
28168:     a = a<<7;
28169:     a |= b;
28170:     s = s>>4;
28171:     *v = ((u64)s)<<32 | a;
28172:     return 8;
28173:   }
28174: 
28175:   p++;
28176:   a = a<<15;
28177:   a |= *p;
28178:   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
28179: 
28180:   /* moved CSE2 up */
28181:   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
28182:   b &= SLOT_2_0;
28183:   b = b<<8;
28184:   a |= b;
28185: 
28186:   s = s<<4;
28187:   b = p[-4];
28188:   b &= 0x7f;
28189:   b = b>>3;
28190:   s |= b;
28191: 
28192:   *v = ((u64)s)<<32 | a;
28193: 
28194:   return 9;
28195: }
28196: 
28197: /*
28198: ** Read a 32-bit variable-length integer from memory starting at p[0].
28199: ** Return the number of bytes read.  The value is stored in *v.
28200: **
28201: ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
28202: ** integer, then set *v to 0xffffffff.
28203: **
28204: ** A MACRO version, getVarint32, is provided which inlines the 
28205: ** single-byte case.  All code should use the MACRO version as 
28206: ** this function assumes the single-byte case has already been handled.
28207: */
28208: SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
28209:   u32 a,b;
28210: 
28211:   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
28212:   ** by the getVarin32() macro */
28213:   a = *p;
28214:   /* a: p0 (unmasked) */
28215: #ifndef getVarint32
28216:   if (!(a&0x80))
28217:   {
28218:     /* Values between 0 and 127 */
28219:     *v = a;
28220:     return 1;
28221:   }
28222: #endif
28223: 
28224:   /* The 2-byte case */
28225:   p++;
28226:   b = *p;
28227:   /* b: p1 (unmasked) */
28228:   if (!(b&0x80))
28229:   {
28230:     /* Values between 128 and 16383 */
28231:     a &= 0x7f;
28232:     a = a<<7;
28233:     *v = a | b;
28234:     return 2;
28235:   }
28236: 
28237:   /* The 3-byte case */
28238:   p++;
28239:   a = a<<14;
28240:   a |= *p;
28241:   /* a: p0<<14 | p2 (unmasked) */
28242:   if (!(a&0x80))
28243:   {
28244:     /* Values between 16384 and 2097151 */
28245:     a &= (0x7f<<14)|(0x7f);
28246:     b &= 0x7f;
28247:     b = b<<7;
28248:     *v = a | b;
28249:     return 3;
28250:   }
28251: 
28252:   /* A 32-bit varint is used to store size information in btrees.
28253:   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
28254:   ** A 3-byte varint is sufficient, for example, to record the size
28255:   ** of a 1048569-byte BLOB or string.
28256:   **
28257:   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
28258:   ** rare larger cases can be handled by the slower 64-bit varint
28259:   ** routine.
28260:   */
28261: #if 1
28262:   {
28263:     u64 v64;
28264:     u8 n;
28265: 
28266:     p -= 2;
28267:     n = sqlite3GetVarint(p, &v64);
28268:     assert( n>3 && n<=9 );
28269:     if( (v64 & SQLITE_MAX_U32)!=v64 ){
28270:       *v = 0xffffffff;
28271:     }else{
28272:       *v = (u32)v64;
28273:     }
28274:     return n;
28275:   }
28276: 
28277: #else
28278:   /* For following code (kept for historical record only) shows an
28279:   ** unrolling for the 3- and 4-byte varint cases.  This code is
28280:   ** slightly faster, but it is also larger and much harder to test.
28281:   */
28282:   p++;
28283:   b = b<<14;
28284:   b |= *p;
28285:   /* b: p1<<14 | p3 (unmasked) */
28286:   if (!(b&0x80))
28287:   {
28288:     /* Values between 2097152 and 268435455 */
28289:     b &= (0x7f<<14)|(0x7f);
28290:     a &= (0x7f<<14)|(0x7f);
28291:     a = a<<7;
28292:     *v = a | b;
28293:     return 4;
28294:   }
28295: 
28296:   p++;
28297:   a = a<<14;
28298:   a |= *p;
28299:   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28300:   if (!(a&0x80))
28301:   {
28302:     /* Values  between 268435456 and 34359738367 */
28303:     a &= SLOT_4_2_0;
28304:     b &= SLOT_4_2_0;
28305:     b = b<<7;
28306:     *v = a | b;
28307:     return 5;
28308:   }
28309: 
28310:   /* We can only reach this point when reading a corrupt database
28311:   ** file.  In that case we are not in any hurry.  Use the (relatively
28312:   ** slow) general-purpose sqlite3GetVarint() routine to extract the
28313:   ** value. */
28314:   {
28315:     u64 v64;
28316:     u8 n;
28317: 
28318:     p -= 4;
28319:     n = sqlite3GetVarint(p, &v64);
28320:     assert( n>5 && n<=9 );
28321:     *v = (u32)v64;
28322:     return n;
28323:   }
28324: #endif
28325: }
28326: 
28327: /*
28328: ** Return the number of bytes that will be needed to store the given
28329: ** 64-bit integer.
28330: */
28331: SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
28332:   int i;
28333:   for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
28334:   return i;
28335: }
28336: 
28337: 
28338: /*
28339: ** Read or write a four-byte big-endian integer value.
28340: */
28341: SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
28342: #if SQLITE_BYTEORDER==4321
28343:   u32 x;
28344:   memcpy(&x,p,4);
28345:   return x;
28346: #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28347:     && defined(__GNUC__) && GCC_VERSION>=4003000
28348:   u32 x;
28349:   memcpy(&x,p,4);
28350:   return __builtin_bswap32(x);
28351: #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28352:     && defined(_MSC_VER) && _MSC_VER>=1300
28353:   u32 x;
28354:   memcpy(&x,p,4);
28355:   return _byteswap_ulong(x);
28356: #else
28357:   testcase( p[0]&0x80 );
28358:   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
28359: #endif
28360: }
28361: SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
28362: #if SQLITE_BYTEORDER==4321
28363:   memcpy(p,&v,4);
28364: #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28365:     && defined(__GNUC__) && GCC_VERSION>=4003000
28366:   u32 x = __builtin_bswap32(v);
28367:   memcpy(p,&x,4);
28368: #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28369:     && defined(_MSC_VER) && _MSC_VER>=1300
28370:   u32 x = _byteswap_ulong(v);
28371:   memcpy(p,&x,4);
28372: #else
28373:   p[0] = (u8)(v>>24);
28374:   p[1] = (u8)(v>>16);
28375:   p[2] = (u8)(v>>8);
28376:   p[3] = (u8)v;
28377: #endif
28378: }
28379: 
28380: 
28381: 
28382: /*
28383: ** Translate a single byte of Hex into an integer.
28384: ** This routine only works if h really is a valid hexadecimal
28385: ** character:  0..9a..fA..F
28386: */
28387: SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
28388:   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
28389: #ifdef SQLITE_ASCII
28390:   h += 9*(1&(h>>6));
28391: #endif
28392: #ifdef SQLITE_EBCDIC
28393:   h += 9*(1&~(h>>4));
28394: #endif
28395:   return (u8)(h & 0xf);
28396: }
28397: 
28398: #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
28399: /*
28400: ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
28401: ** value.  Return a pointer to its binary value.  Space to hold the
28402: ** binary value has been obtained from malloc and must be freed by
28403: ** the calling routine.
28404: */
28405: SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
28406:   char *zBlob;
28407:   int i;
28408: 
28409:   zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
28410:   n--;
28411:   if( zBlob ){
28412:     for(i=0; i<n; i+=2){
28413:       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
28414:     }
28415:     zBlob[i/2] = 0;
28416:   }
28417:   return zBlob;
28418: }
28419: #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
28420: 
28421: /*
28422: ** Log an error that is an API call on a connection pointer that should
28423: ** not have been used.  The "type" of connection pointer is given as the
28424: ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
28425: */
28426: static void logBadConnection(const char *zType){
28427:   sqlite3_log(SQLITE_MISUSE, 
28428:      "API call with %s database connection pointer",
28429:      zType
28430:   );
28431: }
28432: 
28433: /*
28434: ** Check to make sure we have a valid db pointer.  This test is not
28435: ** foolproof but it does provide some measure of protection against
28436: ** misuse of the interface such as passing in db pointers that are
28437: ** NULL or which have been previously closed.  If this routine returns
28438: ** 1 it means that the db pointer is valid and 0 if it should not be
28439: ** dereferenced for any reason.  The calling function should invoke
28440: ** SQLITE_MISUSE immediately.
28441: **
28442: ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
28443: ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
28444: ** open properly and is not fit for general use but which can be
28445: ** used as an argument to sqlite3_errmsg() or sqlite3_close().
28446: */
28447: SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
28448:   u32 magic;
28449:   if( db==0 ){
28450:     logBadConnection("NULL");
28451:     return 0;
28452:   }
28453:   magic = db->magic;
28454:   if( magic!=SQLITE_MAGIC_OPEN ){
28455:     if( sqlite3SafetyCheckSickOrOk(db) ){
28456:       testcase( sqlite3GlobalConfig.xLog!=0 );
28457:       logBadConnection("unopened");
28458:     }
28459:     return 0;
28460:   }else{
28461:     return 1;
28462:   }
28463: }
28464: SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
28465:   u32 magic;
28466:   magic = db->magic;
28467:   if( magic!=SQLITE_MAGIC_SICK &&
28468:       magic!=SQLITE_MAGIC_OPEN &&
28469:       magic!=SQLITE_MAGIC_BUSY ){
28470:     testcase( sqlite3GlobalConfig.xLog!=0 );
28471:     logBadConnection("invalid");
28472:     return 0;
28473:   }else{
28474:     return 1;
28475:   }
28476: }
28477: 
28478: /*
28479: ** Attempt to add, substract, or multiply the 64-bit signed value iB against
28480: ** the other 64-bit signed integer at *pA and store the result in *pA.
28481: ** Return 0 on success.  Or if the operation would have resulted in an
28482: ** overflow, leave *pA unchanged and return 1.
28483: */
28484: SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
28485:   i64 iA = *pA;
28486:   testcase( iA==0 ); testcase( iA==1 );
28487:   testcase( iB==-1 ); testcase( iB==0 );
28488:   if( iB>=0 ){
28489:     testcase( iA>0 && LARGEST_INT64 - iA == iB );
28490:     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
28491:     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
28492:   }else{
28493:     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
28494:     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
28495:     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
28496:   }
28497:   *pA += iB;
28498:   return 0; 
28499: }
28500: SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
28501:   testcase( iB==SMALLEST_INT64+1 );
28502:   if( iB==SMALLEST_INT64 ){
28503:     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
28504:     if( (*pA)>=0 ) return 1;
28505:     *pA -= iB;
28506:     return 0;
28507:   }else{
28508:     return sqlite3AddInt64(pA, -iB);
28509:   }
28510: }
28511: #define TWOPOWER32 (((i64)1)<<32)
28512: #define TWOPOWER31 (((i64)1)<<31)
28513: SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
28514:   i64 iA = *pA;
28515:   i64 iA1, iA0, iB1, iB0, r;
28516: 
28517:   iA1 = iA/TWOPOWER32;
28518:   iA0 = iA % TWOPOWER32;
28519:   iB1 = iB/TWOPOWER32;
28520:   iB0 = iB % TWOPOWER32;
28521:   if( iA1==0 ){
28522:     if( iB1==0 ){
28523:       *pA *= iB;
28524:       return 0;
28525:     }
28526:     r = iA0*iB1;
28527:   }else if( iB1==0 ){
28528:     r = iA1*iB0;
28529:   }else{
28530:     /* If both iA1 and iB1 are non-zero, overflow will result */
28531:     return 1;
28532:   }
28533:   testcase( r==(-TWOPOWER31)-1 );
28534:   testcase( r==(-TWOPOWER31) );
28535:   testcase( r==TWOPOWER31 );
28536:   testcase( r==TWOPOWER31-1 );
28537:   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
28538:   r *= TWOPOWER32;
28539:   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
28540:   *pA = r;
28541:   return 0;
28542: }
28543: 
28544: /*
28545: ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
28546: ** if the integer has a value of -2147483648, return +2147483647
28547: */
28548: SQLITE_PRIVATE int sqlite3AbsInt32(int x){
28549:   if( x>=0 ) return x;
28550:   if( x==(int)0x80000000 ) return 0x7fffffff;
28551:   return -x;
28552: }
28553: 
28554: #ifdef SQLITE_ENABLE_8_3_NAMES
28555: /*
28556: ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
28557: ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
28558: ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
28559: ** three characters, then shorten the suffix on z[] to be the last three
28560: ** characters of the original suffix.
28561: **
28562: ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
28563: ** do the suffix shortening regardless of URI parameter.
28564: **
28565: ** Examples:
28566: **
28567: **     test.db-journal    =>   test.nal
28568: **     test.db-wal        =>   test.wal
28569: **     test.db-shm        =>   test.shm
28570: **     test.db-mj7f3319fa =>   test.9fa
28571: */
28572: SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
28573: #if SQLITE_ENABLE_8_3_NAMES<2
28574:   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
28575: #endif
28576:   {
28577:     int i, sz;
28578:     sz = sqlite3Strlen30(z);
28579:     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
28580:     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
28581:   }
28582: }
28583: #endif
28584: 
28585: /* 
28586: ** Find (an approximate) sum of two LogEst values.  This computation is
28587: ** not a simple "+" operator because LogEst is stored as a logarithmic
28588: ** value.
28589: ** 
28590: */
28591: SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
28592:   static const unsigned char x[] = {
28593:      10, 10,                         /* 0,1 */
28594:       9, 9,                          /* 2,3 */
28595:       8, 8,                          /* 4,5 */
28596:       7, 7, 7,                       /* 6,7,8 */
28597:       6, 6, 6,                       /* 9,10,11 */
28598:       5, 5, 5,                       /* 12-14 */
28599:       4, 4, 4, 4,                    /* 15-18 */
28600:       3, 3, 3, 3, 3, 3,              /* 19-24 */
28601:       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
28602:   };
28603:   if( a>=b ){
28604:     if( a>b+49 ) return a;
28605:     if( a>b+31 ) return a+1;
28606:     return a+x[a-b];
28607:   }else{
28608:     if( b>a+49 ) return b;
28609:     if( b>a+31 ) return b+1;
28610:     return b+x[b-a];
28611:   }
28612: }
28613: 
28614: /*
28615: ** Convert an integer into a LogEst.  In other words, compute an
28616: ** approximation for 10*log2(x).
28617: */
28618: SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
28619:   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
28620:   LogEst y = 40;
28621:   if( x<8 ){
28622:     if( x<2 ) return 0;
28623:     while( x<8 ){  y -= 10; x <<= 1; }
28624:   }else{
28625:     while( x>255 ){ y += 40; x >>= 4; }  /*OPTIMIZATION-IF-TRUE*/
28626:     while( x>15 ){  y += 10; x >>= 1; }
28627:   }
28628:   return a[x&7] + y - 10;
28629: }
28630: 
28631: #ifndef SQLITE_OMIT_VIRTUALTABLE
28632: /*
28633: ** Convert a double into a LogEst
28634: ** In other words, compute an approximation for 10*log2(x).
28635: */
28636: SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
28637:   u64 a;
28638:   LogEst e;
28639:   assert( sizeof(x)==8 && sizeof(a)==8 );
28640:   if( x<=1 ) return 0;
28641:   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
28642:   memcpy(&a, &x, 8);
28643:   e = (a>>52) - 1022;
28644:   return e*10;
28645: }
28646: #endif /* SQLITE_OMIT_VIRTUALTABLE */
28647: 
28648: #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28649:     defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
28650:     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28651: /*
28652: ** Convert a LogEst into an integer.
28653: **
28654: ** Note that this routine is only used when one or more of various
28655: ** non-standard compile-time options is enabled.
28656: */
28657: SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
28658:   u64 n;
28659:   n = x%10;
28660:   x /= 10;
28661:   if( n>=5 ) n -= 2;
28662:   else if( n>=1 ) n -= 1;
28663: #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28664:     defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28665:   if( x>60 ) return (u64)LARGEST_INT64;
28666: #else
28667:   /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
28668:   ** possible to this routine is 310, resulting in a maximum x of 31 */
28669:   assert( x<=60 );
28670: #endif
28671:   return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
28672: }
28673: #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
28674: 
28675: /************** End of util.c ************************************************/
28676: /************** Begin file hash.c ********************************************/
28677: /*
28678: ** 2001 September 22
28679: **
28680: ** The author disclaims copyright to this source code.  In place of
28681: ** a legal notice, here is a blessing:
28682: **
28683: **    May you do good and not evil.
28684: **    May you find forgiveness for yourself and forgive others.
28685: **    May you share freely, never taking more than you give.
28686: **
28687: *************************************************************************
28688: ** This is the implementation of generic hash-tables
28689: ** used in SQLite.
28690: */
28691: /* #include "sqliteInt.h" */
28692: /* #include <assert.h> */
28693: 
28694: /* Turn bulk memory into a hash table object by initializing the
28695: ** fields of the Hash structure.
28696: **
28697: ** "pNew" is a pointer to the hash table that is to be initialized.
28698: */
28699: SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
28700:   assert( pNew!=0 );
28701:   pNew->first = 0;
28702:   pNew->count = 0;
28703:   pNew->htsize = 0;
28704:   pNew->ht = 0;
28705: }
28706: 
28707: /* Remove all entries from a hash table.  Reclaim all memory.
28708: ** Call this routine to delete a hash table or to reset a hash table
28709: ** to the empty state.
28710: */
28711: SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
28712:   HashElem *elem;         /* For looping over all elements of the table */
28713: 
28714:   assert( pH!=0 );
28715:   elem = pH->first;
28716:   pH->first = 0;
28717:   sqlite3_free(pH->ht);
28718:   pH->ht = 0;
28719:   pH->htsize = 0;
28720:   while( elem ){
28721:     HashElem *next_elem = elem->next;
28722:     sqlite3_free(elem);
28723:     elem = next_elem;
28724:   }
28725:   pH->count = 0;
28726: }
28727: 
28728: /*
28729: ** The hashing function.
28730: */
28731: static unsigned int strHash(const char *z){
28732:   unsigned int h = 0;
28733:   unsigned char c;
28734:   while( (c = (unsigned char)*z++)!=0 ){     /*OPTIMIZATION-IF-TRUE*/
28735:     h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
28736:   }
28737:   return h;
28738: }
28739: 
28740: 
28741: /* Link pNew element into the hash table pH.  If pEntry!=0 then also
28742: ** insert pNew into the pEntry hash bucket.
28743: */
28744: static void insertElement(
28745:   Hash *pH,              /* The complete hash table */
28746:   struct _ht *pEntry,    /* The entry into which pNew is inserted */
28747:   HashElem *pNew         /* The element to be inserted */
28748: ){
28749:   HashElem *pHead;       /* First element already in pEntry */
28750:   if( pEntry ){
28751:     pHead = pEntry->count ? pEntry->chain : 0;
28752:     pEntry->count++;
28753:     pEntry->chain = pNew;
28754:   }else{
28755:     pHead = 0;
28756:   }
28757:   if( pHead ){
28758:     pNew->next = pHead;
28759:     pNew->prev = pHead->prev;
28760:     if( pHead->prev ){ pHead->prev->next = pNew; }
28761:     else             { pH->first = pNew; }
28762:     pHead->prev = pNew;
28763:   }else{
28764:     pNew->next = pH->first;
28765:     if( pH->first ){ pH->first->prev = pNew; }
28766:     pNew->prev = 0;
28767:     pH->first = pNew;
28768:   }
28769: }
28770: 
28771: 
28772: /* Resize the hash table so that it cantains "new_size" buckets.
28773: **
28774: ** The hash table might fail to resize if sqlite3_malloc() fails or
28775: ** if the new size is the same as the prior size.
28776: ** Return TRUE if the resize occurs and false if not.
28777: */
28778: static int rehash(Hash *pH, unsigned int new_size){
28779:   struct _ht *new_ht;            /* The new hash table */
28780:   HashElem *elem, *next_elem;    /* For looping over existing elements */
28781: 
28782: #if SQLITE_MALLOC_SOFT_LIMIT>0
28783:   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
28784:     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
28785:   }
28786:   if( new_size==pH->htsize ) return 0;
28787: #endif
28788: 
28789:   /* The inability to allocates space for a larger hash table is
28790:   ** a performance hit but it is not a fatal error.  So mark the
28791:   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
28792:   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
28793:   ** only zeroes the requested number of bytes whereas this module will
28794:   ** use the actual amount of space allocated for the hash table (which
28795:   ** may be larger than the requested amount).
28796:   */
28797:   sqlite3BeginBenignMalloc();
28798:   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
28799:   sqlite3EndBenignMalloc();
28800: 
28801:   if( new_ht==0 ) return 0;
28802:   sqlite3_free(pH->ht);
28803:   pH->ht = new_ht;
28804:   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
28805:   memset(new_ht, 0, new_size*sizeof(struct _ht));
28806:   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
28807:     unsigned int h = strHash(elem->pKey) % new_size;
28808:     next_elem = elem->next;
28809:     insertElement(pH, &new_ht[h], elem);
28810:   }
28811:   return 1;
28812: }
28813: 
28814: /* This function (for internal use only) locates an element in an
28815: ** hash table that matches the given key.  The hash for this key is
28816: ** also computed and returned in the *pH parameter.
28817: */
28818: static HashElem *findElementWithHash(
28819:   const Hash *pH,     /* The pH to be searched */
28820:   const char *pKey,   /* The key we are searching for */
28821:   unsigned int *pHash /* Write the hash value here */
28822: ){
28823:   HashElem *elem;                /* Used to loop thru the element list */
28824:   int count;                     /* Number of elements left to test */
28825:   unsigned int h;                /* The computed hash */
28826: 
28827:   if( pH->ht ){   /*OPTIMIZATION-IF-TRUE*/
28828:     struct _ht *pEntry;
28829:     h = strHash(pKey) % pH->htsize;
28830:     pEntry = &pH->ht[h];
28831:     elem = pEntry->chain;
28832:     count = pEntry->count;
28833:   }else{
28834:     h = 0;
28835:     elem = pH->first;
28836:     count = pH->count;
28837:   }
28838:   *pHash = h;
28839:   while( count-- ){
28840:     assert( elem!=0 );
28841:     if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ 
28842:       return elem;
28843:     }
28844:     elem = elem->next;
28845:   }
28846:   return 0;
28847: }
28848: 
28849: /* Remove a single entry from the hash table given a pointer to that
28850: ** element and a hash on the element's key.
28851: */
28852: static void removeElementGivenHash(
28853:   Hash *pH,         /* The pH containing "elem" */
28854:   HashElem* elem,   /* The element to be removed from the pH */
28855:   unsigned int h    /* Hash value for the element */
28856: ){
28857:   struct _ht *pEntry;
28858:   if( elem->prev ){
28859:     elem->prev->next = elem->next; 
28860:   }else{
28861:     pH->first = elem->next;
28862:   }
28863:   if( elem->next ){
28864:     elem->next->prev = elem->prev;
28865:   }
28866:   if( pH->ht ){
28867:     pEntry = &pH->ht[h];
28868:     if( pEntry->chain==elem ){
28869:       pEntry->chain = elem->next;
28870:     }
28871:     pEntry->count--;
28872:     assert( pEntry->count>=0 );
28873:   }
28874:   sqlite3_free( elem );
28875:   pH->count--;
28876:   if( pH->count==0 ){
28877:     assert( pH->first==0 );
28878:     assert( pH->count==0 );
28879:     sqlite3HashClear(pH);
28880:   }
28881: }
28882: 
28883: /* Attempt to locate an element of the hash table pH with a key
28884: ** that matches pKey.  Return the data for this element if it is
28885: ** found, or NULL if there is no match.
28886: */
28887: SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
28888:   HashElem *elem;    /* The element that matches key */
28889:   unsigned int h;    /* A hash on key */
28890: 
28891:   assert( pH!=0 );
28892:   assert( pKey!=0 );
28893:   elem = findElementWithHash(pH, pKey, &h);
28894:   return elem ? elem->data : 0;
28895: }
28896: 
28897: /* Insert an element into the hash table pH.  The key is pKey
28898: ** and the data is "data".
28899: **
28900: ** If no element exists with a matching key, then a new
28901: ** element is created and NULL is returned.
28902: **
28903: ** If another element already exists with the same key, then the
28904: ** new data replaces the old data and the old data is returned.
28905: ** The key is not copied in this instance.  If a malloc fails, then
28906: ** the new data is returned and the hash table is unchanged.
28907: **
28908: ** If the "data" parameter to this function is NULL, then the
28909: ** element corresponding to "key" is removed from the hash table.
28910: */
28911: SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
28912:   unsigned int h;       /* the hash of the key modulo hash table size */
28913:   HashElem *elem;       /* Used to loop thru the element list */
28914:   HashElem *new_elem;   /* New element added to the pH */
28915: 
28916:   assert( pH!=0 );
28917:   assert( pKey!=0 );
28918:   elem = findElementWithHash(pH,pKey,&h);
28919:   if( elem ){
28920:     void *old_data = elem->data;
28921:     if( data==0 ){
28922:       removeElementGivenHash(pH,elem,h);
28923:     }else{
28924:       elem->data = data;
28925:       elem->pKey = pKey;
28926:     }
28927:     return old_data;
28928:   }
28929:   if( data==0 ) return 0;
28930:   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
28931:   if( new_elem==0 ) return data;
28932:   new_elem->pKey = pKey;
28933:   new_elem->data = data;
28934:   pH->count++;
28935:   if( pH->count>=10 && pH->count > 2*pH->htsize ){
28936:     if( rehash(pH, pH->count*2) ){
28937:       assert( pH->htsize>0 );
28938:       h = strHash(pKey) % pH->htsize;
28939:     }
28940:   }
28941:   insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
28942:   return 0;
28943: }
28944: 
28945: /************** End of hash.c ************************************************/
28946: /************** Begin file opcodes.c *****************************************/
28947: /* Automatically generated.  Do not edit */
28948: /* See the tool/mkopcodec.tcl script for details. */
28949: #if !defined(SQLITE_OMIT_EXPLAIN) \
28950:  || defined(VDBE_PROFILE) \
28951:  || defined(SQLITE_DEBUG)
28952: #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
28953: # define OpHelp(X) "\0" X
28954: #else
28955: # define OpHelp(X)
28956: #endif
28957: SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
28958:  static const char *const azName[] = {
28959:     /*   0 */ "Savepoint"        OpHelp(""),
28960:     /*   1 */ "AutoCommit"       OpHelp(""),
28961:     /*   2 */ "Transaction"      OpHelp(""),
28962:     /*   3 */ "SorterNext"       OpHelp(""),
28963:     /*   4 */ "PrevIfOpen"       OpHelp(""),
28964:     /*   5 */ "NextIfOpen"       OpHelp(""),
28965:     /*   6 */ "Prev"             OpHelp(""),
28966:     /*   7 */ "Next"             OpHelp(""),
28967:     /*   8 */ "Checkpoint"       OpHelp(""),
28968:     /*   9 */ "JournalMode"      OpHelp(""),
28969:     /*  10 */ "Vacuum"           OpHelp(""),
28970:     /*  11 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
28971:     /*  12 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
28972:     /*  13 */ "Goto"             OpHelp(""),
28973:     /*  14 */ "Gosub"            OpHelp(""),
28974:     /*  15 */ "InitCoroutine"    OpHelp(""),
28975:     /*  16 */ "Yield"            OpHelp(""),
28976:     /*  17 */ "MustBeInt"        OpHelp(""),
28977:     /*  18 */ "Jump"             OpHelp(""),
28978:     /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
28979:     /*  20 */ "Once"             OpHelp(""),
28980:     /*  21 */ "If"               OpHelp(""),
28981:     /*  22 */ "IfNot"            OpHelp(""),
28982:     /*  23 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
28983:     /*  24 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
28984:     /*  25 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
28985:     /*  26 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
28986:     /*  27 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
28987:     /*  28 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
28988:     /*  29 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
28989:     /*  30 */ "NotFound"         OpHelp("key=r[P3@P4]"),
28990:     /*  31 */ "Found"            OpHelp("key=r[P3@P4]"),
28991:     /*  32 */ "SeekRowid"        OpHelp("intkey=r[P3]"),
28992:     /*  33 */ "NotExists"        OpHelp("intkey=r[P3]"),
28993:     /*  34 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
28994:     /*  35 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
28995:     /*  36 */ "Ne"               OpHelp("IF r[P3]!=r[P1]"),
28996:     /*  37 */ "Eq"               OpHelp("IF r[P3]==r[P1]"),
28997:     /*  38 */ "Gt"               OpHelp("IF r[P3]>r[P1]"),
28998:     /*  39 */ "Le"               OpHelp("IF r[P3]<=r[P1]"),
28999:     /*  40 */ "Lt"               OpHelp("IF r[P3]<r[P1]"),
29000:     /*  41 */ "Ge"               OpHelp("IF r[P3]>=r[P1]"),
29001:     /*  42 */ "Last"             OpHelp(""),
29002:     /*  43 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
29003:     /*  44 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
29004:     /*  45 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
29005:     /*  46 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
29006:     /*  47 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
29007:     /*  48 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
29008:     /*  49 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
29009:     /*  50 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
29010:     /*  51 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
29011:     /*  52 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
29012:     /*  53 */ "SorterSort"       OpHelp(""),
29013:     /*  54 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
29014:     /*  55 */ "Sort"             OpHelp(""),
29015:     /*  56 */ "Rewind"           OpHelp(""),
29016:     /*  57 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
29017:     /*  58 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
29018:     /*  59 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
29019:     /*  60 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
29020:     /*  61 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
29021:     /*  62 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
29022:     /*  63 */ "Program"          OpHelp(""),
29023:     /*  64 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
29024:     /*  65 */ "IfPos"            OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
29025:     /*  66 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
29026:     /*  67 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
29027:     /*  68 */ "IncrVacuum"       OpHelp(""),
29028:     /*  69 */ "VNext"            OpHelp(""),
29029:     /*  70 */ "Init"             OpHelp("Start at P2"),
29030:     /*  71 */ "Return"           OpHelp(""),
29031:     /*  72 */ "EndCoroutine"     OpHelp(""),
29032:     /*  73 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
29033:     /*  74 */ "Halt"             OpHelp(""),
29034:     /*  75 */ "Integer"          OpHelp("r[P2]=P1"),
29035:     /*  76 */ "Int64"            OpHelp("r[P2]=P4"),
29036:     /*  77 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
29037:     /*  78 */ "Null"             OpHelp("r[P2..P3]=NULL"),
29038:     /*  79 */ "SoftNull"         OpHelp("r[P1]=NULL"),
29039:     /*  80 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
29040:     /*  81 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
29041:     /*  82 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
29042:     /*  83 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
29043:     /*  84 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
29044:     /*  85 */ "IntCopy"          OpHelp("r[P2]=r[P1]"),
29045:     /*  86 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
29046:     /*  87 */ "CollSeq"          OpHelp(""),
29047:     /*  88 */ "Function0"        OpHelp("r[P3]=func(r[P2@P5])"),
29048:     /*  89 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
29049:     /*  90 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
29050:     /*  91 */ "RealAffinity"     OpHelp(""),
29051:     /*  92 */ "Cast"             OpHelp("affinity(r[P1])"),
29052:     /*  93 */ "Permutation"      OpHelp(""),
29053:     /*  94 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
29054:     /*  95 */ "Column"           OpHelp("r[P3]=PX"),
29055:     /*  96 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
29056:     /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
29057:     /*  98 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
29058:     /*  99 */ "Count"            OpHelp("r[P2]=count()"),
29059:     /* 100 */ "ReadCookie"       OpHelp(""),
29060:     /* 101 */ "SetCookie"        OpHelp(""),
29061:     /* 102 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
29062:     /* 103 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
29063:     /* 104 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
29064:     /* 105 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
29065:     /* 106 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
29066:     /* 107 */ "SorterOpen"       OpHelp(""),
29067:     /* 108 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
29068:     /* 109 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
29069:     /* 110 */ "Close"            OpHelp(""),
29070:     /* 111 */ "ColumnsUsed"      OpHelp(""),
29071:     /* 112 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
29072:     /* 113 */ "NewRowid"         OpHelp("r[P2]=rowid"),
29073:     /* 114 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
29074:     /* 115 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
29075:     /* 116 */ "Delete"           OpHelp(""),
29076:     /* 117 */ "ResetCount"       OpHelp(""),
29077:     /* 118 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
29078:     /* 119 */ "SorterData"       OpHelp("r[P2]=data"),
29079:     /* 120 */ "RowKey"           OpHelp("r[P2]=key"),
29080:     /* 121 */ "RowData"          OpHelp("r[P2]=data"),
29081:     /* 122 */ "Rowid"            OpHelp("r[P2]=rowid"),
29082:     /* 123 */ "NullRow"          OpHelp(""),
29083:     /* 124 */ "SorterInsert"     OpHelp(""),
29084:     /* 125 */ "IdxInsert"        OpHelp("key=r[P2]"),
29085:     /* 126 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
29086:     /* 127 */ "Seek"             OpHelp("Move P3 to P1.rowid"),
29087:     /* 128 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
29088:     /* 129 */ "Destroy"          OpHelp(""),
29089:     /* 130 */ "Clear"            OpHelp(""),
29090:     /* 131 */ "ResetSorter"      OpHelp(""),
29091:     /* 132 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
29092:     /* 133 */ "Real"             OpHelp("r[P2]=P4"),
29093:     /* 134 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
29094:     /* 135 */ "ParseSchema"      OpHelp(""),
29095:     /* 136 */ "LoadAnalysis"     OpHelp(""),
29096:     /* 137 */ "DropTable"        OpHelp(""),
29097:     /* 138 */ "DropIndex"        OpHelp(""),
29098:     /* 139 */ "DropTrigger"      OpHelp(""),
29099:     /* 140 */ "IntegrityCk"      OpHelp(""),
29100:     /* 141 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
29101:     /* 142 */ "Param"            OpHelp(""),
29102:     /* 143 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
29103:     /* 144 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
29104:     /* 145 */ "OffsetLimit"      OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
29105:     /* 146 */ "AggStep0"         OpHelp("accum=r[P3] step(r[P2@P5])"),
29106:     /* 147 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
29107:     /* 148 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
29108:     /* 149 */ "Expire"           OpHelp(""),
29109:     /* 150 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
29110:     /* 151 */ "VBegin"           OpHelp(""),
29111:     /* 152 */ "VCreate"          OpHelp(""),
29112:     /* 153 */ "VDestroy"         OpHelp(""),
29113:     /* 154 */ "VOpen"            OpHelp(""),
29114:     /* 155 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
29115:     /* 156 */ "VRename"          OpHelp(""),
29116:     /* 157 */ "Pagecount"        OpHelp(""),
29117:     /* 158 */ "MaxPgcnt"         OpHelp(""),
29118:     /* 159 */ "CursorHint"       OpHelp(""),
29119:     /* 160 */ "Noop"             OpHelp(""),
29120:     /* 161 */ "Explain"          OpHelp(""),
29121:   };
29122:   return azName[i];
29123: }
29124: #endif
29125: 
29126: /************** End of opcodes.c *********************************************/
29127: /************** Begin file os_unix.c *****************************************/
29128: /*
29129: ** 2004 May 22
29130: **
29131: ** The author disclaims copyright to this source code.  In place of
29132: ** a legal notice, here is a blessing:
29133: **
29134: **    May you do good and not evil.
29135: **    May you find forgiveness for yourself and forgive others.
29136: **    May you share freely, never taking more than you give.
29137: **
29138: ******************************************************************************
29139: **
29140: ** This file contains the VFS implementation for unix-like operating systems
29141: ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
29142: **
29143: ** There are actually several different VFS implementations in this file.
29144: ** The differences are in the way that file locking is done.  The default
29145: ** implementation uses Posix Advisory Locks.  Alternative implementations
29146: ** use flock(), dot-files, various proprietary locking schemas, or simply
29147: ** skip locking all together.
29148: **
29149: ** This source file is organized into divisions where the logic for various
29150: ** subfunctions is contained within the appropriate division.  PLEASE
29151: ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
29152: ** in the correct division and should be clearly labeled.
29153: **
29154: ** The layout of divisions is as follows:
29155: **
29156: **   *  General-purpose declarations and utility functions.
29157: **   *  Unique file ID logic used by VxWorks.
29158: **   *  Various locking primitive implementations (all except proxy locking):
29159: **      + for Posix Advisory Locks
29160: **      + for no-op locks
29161: **      + for dot-file locks
29162: **      + for flock() locking
29163: **      + for named semaphore locks (VxWorks only)
29164: **      + for AFP filesystem locks (MacOSX only)
29165: **   *  sqlite3_file methods not associated with locking.
29166: **   *  Definitions of sqlite3_io_methods objects for all locking
29167: **      methods plus "finder" functions for each locking method.
29168: **   *  sqlite3_vfs method implementations.
29169: **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
29170: **   *  Definitions of sqlite3_vfs objects for all locking methods
29171: **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
29172: */
29173: /* #include "sqliteInt.h" */
29174: #if SQLITE_OS_UNIX              /* This file is used on unix only */
29175: 
29176: /*
29177: ** There are various methods for file locking used for concurrency
29178: ** control:
29179: **
29180: **   1. POSIX locking (the default),
29181: **   2. No locking,
29182: **   3. Dot-file locking,
29183: **   4. flock() locking,
29184: **   5. AFP locking (OSX only),
29185: **   6. Named POSIX semaphores (VXWorks only),
29186: **   7. proxy locking. (OSX only)
29187: **
29188: ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
29189: ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
29190: ** selection of the appropriate locking style based on the filesystem
29191: ** where the database is located.  
29192: */
29193: #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
29194: #  if defined(__APPLE__)
29195: #    define SQLITE_ENABLE_LOCKING_STYLE 1
29196: #  else
29197: #    define SQLITE_ENABLE_LOCKING_STYLE 0
29198: #  endif
29199: #endif
29200: 
29201: /* Use pread() and pwrite() if they are available */
29202: #if defined(__APPLE__)
29203: # define HAVE_PREAD 1
29204: # define HAVE_PWRITE 1
29205: #endif
29206: #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
29207: # undef USE_PREAD
29208: # define USE_PREAD64 1
29209: #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
29210: # undef USE_PREAD64
29211: # define USE_PREAD 1
29212: #endif
29213: 
29214: /*
29215: ** standard include files.
29216: */
29217: #include <sys/types.h>
29218: #include <sys/stat.h>
29219: #include <fcntl.h>
29220: #include <unistd.h>
29221: /* #include <time.h> */
29222: #include <sys/time.h>
29223: #include <errno.h>
29224: #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29225: # include <sys/mman.h>
29226: #endif
29227: 
29228: #if SQLITE_ENABLE_LOCKING_STYLE
29229: # include <sys/ioctl.h>
29230: # include <sys/file.h>
29231: # include <sys/param.h>
29232: #endif /* SQLITE_ENABLE_LOCKING_STYLE */
29233: 
29234: #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
29235:                            (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
29236: #  if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
29237:        && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
29238: #    define HAVE_GETHOSTUUID 1
29239: #  else
29240: #    warning "gethostuuid() is disabled."
29241: #  endif
29242: #endif
29243: 
29244: 
29245: #if OS_VXWORKS
29246: /* # include <sys/ioctl.h> */
29247: # include <semaphore.h>
29248: # include <limits.h>
29249: #endif /* OS_VXWORKS */
29250: 
29251: #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29252: # include <sys/mount.h>
29253: #endif
29254: 
29255: #ifdef HAVE_UTIME
29256: # include <utime.h>
29257: #endif
29258: 
29259: /*
29260: ** Allowed values of unixFile.fsFlags
29261: */
29262: #define SQLITE_FSFLAGS_IS_MSDOS     0x1
29263: 
29264: /*
29265: ** If we are to be thread-safe, include the pthreads header and define
29266: ** the SQLITE_UNIX_THREADS macro.
29267: */
29268: #if SQLITE_THREADSAFE
29269: /* # include <pthread.h> */
29270: # define SQLITE_UNIX_THREADS 1
29271: #endif
29272: 
29273: /*
29274: ** Default permissions when creating a new file
29275: */
29276: #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
29277: # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
29278: #endif
29279: 
29280: /*
29281: ** Default permissions when creating auto proxy dir
29282: */
29283: #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29284: # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
29285: #endif
29286: 
29287: /*
29288: ** Maximum supported path-length.
29289: */
29290: #define MAX_PATHNAME 512
29291: 
29292: /*
29293: ** Maximum supported symbolic links
29294: */
29295: #define SQLITE_MAX_SYMLINKS 100
29296: 
29297: /* Always cast the getpid() return type for compatibility with
29298: ** kernel modules in VxWorks. */
29299: #define osGetpid(X) (pid_t)getpid()
29300: 
29301: /*
29302: ** Only set the lastErrno if the error code is a real error and not 
29303: ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
29304: */
29305: #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
29306: 
29307: /* Forward references */
29308: typedef struct unixShm unixShm;               /* Connection shared memory */
29309: typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
29310: typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
29311: typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
29312: 
29313: /*
29314: ** Sometimes, after a file handle is closed by SQLite, the file descriptor
29315: ** cannot be closed immediately. In these cases, instances of the following
29316: ** structure are used to store the file descriptor while waiting for an
29317: ** opportunity to either close or reuse it.
29318: */
29319: struct UnixUnusedFd {
29320:   int fd;                   /* File descriptor to close */
29321:   int flags;                /* Flags this file descriptor was opened with */
29322:   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
29323: };
29324: 
29325: /*
29326: ** The unixFile structure is subclass of sqlite3_file specific to the unix
29327: ** VFS implementations.
29328: */
29329: typedef struct unixFile unixFile;
29330: struct unixFile {
29331:   sqlite3_io_methods const *pMethod;  /* Always the first entry */
29332:   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
29333:   unixInodeInfo *pInode;              /* Info about locks on this inode */
29334:   int h;                              /* The file descriptor */
29335:   unsigned char eFileLock;            /* The type of lock held on this fd */
29336:   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
29337:   int lastErrno;                      /* The unix errno from last I/O error */
29338:   void *lockingContext;               /* Locking style specific state */
29339:   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
29340:   const char *zPath;                  /* Name of the file */
29341:   unixShm *pShm;                      /* Shared memory segment information */
29342:   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
29343: #if SQLITE_MAX_MMAP_SIZE>0
29344:   int nFetchOut;                      /* Number of outstanding xFetch refs */
29345:   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
29346:   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
29347:   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
29348:   void *pMapRegion;                   /* Memory mapped region */
29349: #endif
29350: #ifdef __QNXNTO__
29351:   int sectorSize;                     /* Device sector size */
29352:   int deviceCharacteristics;          /* Precomputed device characteristics */
29353: #endif
29354: #if SQLITE_ENABLE_LOCKING_STYLE
29355:   int openFlags;                      /* The flags specified at open() */
29356: #endif
29357: #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
29358:   unsigned fsFlags;                   /* cached details from statfs() */
29359: #endif
29360: #if OS_VXWORKS
29361:   struct vxworksFileId *pId;          /* Unique file ID */
29362: #endif
29363: #ifdef SQLITE_DEBUG
29364:   /* The next group of variables are used to track whether or not the
29365:   ** transaction counter in bytes 24-27 of database files are updated
29366:   ** whenever any part of the database changes.  An assertion fault will
29367:   ** occur if a file is updated without also updating the transaction
29368:   ** counter.  This test is made to avoid new problems similar to the
29369:   ** one described by ticket #3584. 
29370:   */
29371:   unsigned char transCntrChng;   /* True if the transaction counter changed */
29372:   unsigned char dbUpdate;        /* True if any part of database file changed */
29373:   unsigned char inNormalWrite;   /* True if in a normal write operation */
29374: 
29375: #endif
29376: 
29377: #ifdef SQLITE_TEST
29378:   /* In test mode, increase the size of this structure a bit so that 
29379:   ** it is larger than the struct CrashFile defined in test6.c.
29380:   */
29381:   char aPadding[32];
29382: #endif
29383: };
29384: 
29385: /* This variable holds the process id (pid) from when the xRandomness()
29386: ** method was called.  If xOpen() is called from a different process id,
29387: ** indicating that a fork() has occurred, the PRNG will be reset.
29388: */
29389: static pid_t randomnessPid = 0;
29390: 
29391: /*
29392: ** Allowed values for the unixFile.ctrlFlags bitmask:
29393: */
29394: #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
29395: #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
29396: #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
29397: #ifndef SQLITE_DISABLE_DIRSYNC
29398: # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
29399: #else
29400: # define UNIXFILE_DIRSYNC    0x00
29401: #endif
29402: #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29403: #define UNIXFILE_DELETE      0x20     /* Delete on close */
29404: #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
29405: #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
29406: 
29407: /*
29408: ** Include code that is common to all os_*.c files
29409: */
29410: /************** Include os_common.h in the middle of os_unix.c ***************/
29411: /************** Begin file os_common.h ***************************************/
29412: /*
29413: ** 2004 May 22
29414: **
29415: ** The author disclaims copyright to this source code.  In place of
29416: ** a legal notice, here is a blessing:
29417: **
29418: **    May you do good and not evil.
29419: **    May you find forgiveness for yourself and forgive others.
29420: **    May you share freely, never taking more than you give.
29421: **
29422: ******************************************************************************
29423: **
29424: ** This file contains macros and a little bit of code that is common to
29425: ** all of the platform-specific files (os_*.c) and is #included into those
29426: ** files.
29427: **
29428: ** This file should be #included by the os_*.c files only.  It is not a
29429: ** general purpose header file.
29430: */
29431: #ifndef _OS_COMMON_H_
29432: #define _OS_COMMON_H_
29433: 
29434: /*
29435: ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29436: ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29437: ** switch.  The following code should catch this problem at compile-time.
29438: */
29439: #ifdef MEMORY_DEBUG
29440: # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29441: #endif
29442: 
29443: /*
29444: ** Macros for performance tracing.  Normally turned off.  Only works
29445: ** on i486 hardware.
29446: */
29447: #ifdef SQLITE_PERFORMANCE_TRACE
29448: 
29449: /*
29450: ** hwtime.h contains inline assembler code for implementing
29451: ** high-performance timing routines.
29452: */
29453: /************** Include hwtime.h in the middle of os_common.h ****************/
29454: /************** Begin file hwtime.h ******************************************/
29455: /*
29456: ** 2008 May 27
29457: **
29458: ** The author disclaims copyright to this source code.  In place of
29459: ** a legal notice, here is a blessing:
29460: **
29461: **    May you do good and not evil.
29462: **    May you find forgiveness for yourself and forgive others.
29463: **    May you share freely, never taking more than you give.
29464: **
29465: ******************************************************************************
29466: **
29467: ** This file contains inline asm code for retrieving "high-performance"
29468: ** counters for x86 class CPUs.
29469: */
29470: #ifndef SQLITE_HWTIME_H
29471: #define SQLITE_HWTIME_H
29472: 
29473: /*
29474: ** The following routine only works on pentium-class (or newer) processors.
29475: ** It uses the RDTSC opcode to read the cycle count value out of the
29476: ** processor and returns that value.  This can be used for high-res
29477: ** profiling.
29478: */
29479: #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29480:       (defined(i386) || defined(__i386__) || defined(_M_IX86))
29481: 
29482:   #if defined(__GNUC__)
29483: 
29484:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29485:      unsigned int lo, hi;
29486:      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29487:      return (sqlite_uint64)hi << 32 | lo;
29488:   }
29489: 
29490:   #elif defined(_MSC_VER)
29491: 
29492:   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29493:      __asm {
29494:         rdtsc
29495:         ret       ; return value at EDX:EAX
29496:      }
29497:   }
29498: 
29499:   #endif
29500: 
29501: #elif (defined(__GNUC__) && defined(__x86_64__))
29502: 
29503:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29504:       unsigned long val;
29505:       __asm__ __volatile__ ("rdtsc" : "=A" (val));
29506:       return val;
29507:   }
29508:  
29509: #elif (defined(__GNUC__) && defined(__ppc__))
29510: 
29511:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29512:       unsigned long long retval;
29513:       unsigned long junk;
29514:       __asm__ __volatile__ ("\n\
29515:           1:      mftbu   %1\n\
29516:                   mftb    %L0\n\
29517:                   mftbu   %0\n\
29518:                   cmpw    %0,%1\n\
29519:                   bne     1b"
29520:                   : "=r" (retval), "=r" (junk));
29521:       return retval;
29522:   }
29523: 
29524: #else
29525: 
29526:   #error Need implementation of sqlite3Hwtime() for your platform.
29527: 
29528:   /*
29529:   ** To compile without implementing sqlite3Hwtime() for your platform,
29530:   ** you can remove the above #error and use the following
29531:   ** stub function.  You will lose timing support for many
29532:   ** of the debugging and testing utilities, but it should at
29533:   ** least compile and run.
29534:   */
29535: SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29536: 
29537: #endif
29538: 
29539: #endif /* !defined(SQLITE_HWTIME_H) */
29540: 
29541: /************** End of hwtime.h **********************************************/
29542: /************** Continuing where we left off in os_common.h ******************/
29543: 
29544: static sqlite_uint64 g_start;
29545: static sqlite_uint64 g_elapsed;
29546: #define TIMER_START       g_start=sqlite3Hwtime()
29547: #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
29548: #define TIMER_ELAPSED     g_elapsed
29549: #else
29550: #define TIMER_START
29551: #define TIMER_END
29552: #define TIMER_ELAPSED     ((sqlite_uint64)0)
29553: #endif
29554: 
29555: /*
29556: ** If we compile with the SQLITE_TEST macro set, then the following block
29557: ** of code will give us the ability to simulate a disk I/O error.  This
29558: ** is used for testing the I/O recovery logic.
29559: */
29560: #if defined(SQLITE_TEST)
29561: SQLITE_API extern int sqlite3_io_error_hit;
29562: SQLITE_API extern int sqlite3_io_error_hardhit;
29563: SQLITE_API extern int sqlite3_io_error_pending;
29564: SQLITE_API extern int sqlite3_io_error_persist;
29565: SQLITE_API extern int sqlite3_io_error_benign;
29566: SQLITE_API extern int sqlite3_diskfull_pending;
29567: SQLITE_API extern int sqlite3_diskfull;
29568: #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29569: #define SimulateIOError(CODE)  \
29570:   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29571:        || sqlite3_io_error_pending-- == 1 )  \
29572:               { local_ioerr(); CODE; }
29573: static void local_ioerr(){
29574:   IOTRACE(("IOERR\n"));
29575:   sqlite3_io_error_hit++;
29576:   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29577: }
29578: #define SimulateDiskfullError(CODE) \
29579:    if( sqlite3_diskfull_pending ){ \
29580:      if( sqlite3_diskfull_pending == 1 ){ \
29581:        local_ioerr(); \
29582:        sqlite3_diskfull = 1; \
29583:        sqlite3_io_error_hit = 1; \
29584:        CODE; \
29585:      }else{ \
29586:        sqlite3_diskfull_pending--; \
29587:      } \
29588:    }
29589: #else
29590: #define SimulateIOErrorBenign(X)
29591: #define SimulateIOError(A)
29592: #define SimulateDiskfullError(A)
29593: #endif /* defined(SQLITE_TEST) */
29594: 
29595: /*
29596: ** When testing, keep a count of the number of open files.
29597: */
29598: #if defined(SQLITE_TEST)
29599: SQLITE_API extern int sqlite3_open_file_count;
29600: #define OpenCounter(X)  sqlite3_open_file_count+=(X)
29601: #else
29602: #define OpenCounter(X)
29603: #endif /* defined(SQLITE_TEST) */
29604: 
29605: #endif /* !defined(_OS_COMMON_H_) */
29606: 
29607: /************** End of os_common.h *******************************************/
29608: /************** Continuing where we left off in os_unix.c ********************/
29609: 
29610: /*
29611: ** Define various macros that are missing from some systems.
29612: */
29613: #ifndef O_LARGEFILE
29614: # define O_LARGEFILE 0
29615: #endif
29616: #ifdef SQLITE_DISABLE_LFS
29617: # undef O_LARGEFILE
29618: # define O_LARGEFILE 0
29619: #endif
29620: #ifndef O_NOFOLLOW
29621: # define O_NOFOLLOW 0
29622: #endif
29623: #ifndef O_BINARY
29624: # define O_BINARY 0
29625: #endif
29626: 
29627: /*
29628: ** The threadid macro resolves to the thread-id or to 0.  Used for
29629: ** testing and debugging only.
29630: */
29631: #if SQLITE_THREADSAFE
29632: #define threadid pthread_self()
29633: #else
29634: #define threadid 0
29635: #endif
29636: 
29637: /*
29638: ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
29639: */
29640: #if !defined(HAVE_MREMAP)
29641: # if defined(__linux__) && defined(_GNU_SOURCE)
29642: #  define HAVE_MREMAP 1
29643: # else
29644: #  define HAVE_MREMAP 0
29645: # endif
29646: #endif
29647: 
29648: /*
29649: ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
29650: ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
29651: */
29652: #ifdef __ANDROID__
29653: # define lseek lseek64
29654: #endif
29655: 
29656: /*
29657: ** Different Unix systems declare open() in different ways.  Same use
29658: ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
29659: ** The difference is important when using a pointer to the function.
29660: **
29661: ** The safest way to deal with the problem is to always use this wrapper
29662: ** which always has the same well-defined interface.
29663: */
29664: static int posixOpen(const char *zFile, int flags, int mode){
29665:   return open(zFile, flags, mode);
29666: }
29667: 
29668: /* Forward reference */
29669: static int openDirectory(const char*, int*);
29670: static int unixGetpagesize(void);
29671: 
29672: /*
29673: ** Many system calls are accessed through pointer-to-functions so that
29674: ** they may be overridden at runtime to facilitate fault injection during
29675: ** testing and sandboxing.  The following array holds the names and pointers
29676: ** to all overrideable system calls.
29677: */
29678: static struct unix_syscall {
29679:   const char *zName;            /* Name of the system call */
29680:   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
29681:   sqlite3_syscall_ptr pDefault; /* Default value */
29682: } aSyscall[] = {
29683:   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
29684: #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
29685: 
29686:   { "close",        (sqlite3_syscall_ptr)close,      0  },
29687: #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
29688: 
29689:   { "access",       (sqlite3_syscall_ptr)access,     0  },
29690: #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
29691: 
29692:   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
29693: #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
29694: 
29695:   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
29696: #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
29697: 
29698: /*
29699: ** The DJGPP compiler environment looks mostly like Unix, but it
29700: ** lacks the fcntl() system call.  So redefine fcntl() to be something
29701: ** that always succeeds.  This means that locking does not occur under
29702: ** DJGPP.  But it is DOS - what did you expect?
29703: */
29704: #ifdef __DJGPP__
29705:   { "fstat",        0,                 0  },
29706: #define osFstat(a,b,c)    0
29707: #else     
29708:   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
29709: #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
29710: #endif
29711: 
29712:   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
29713: #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
29714: 
29715:   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
29716: #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
29717: 
29718:   { "read",         (sqlite3_syscall_ptr)read,       0  },
29719: #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
29720: 
29721: #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29722:   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
29723: #else
29724:   { "pread",        (sqlite3_syscall_ptr)0,          0  },
29725: #endif
29726: #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
29727: 
29728: #if defined(USE_PREAD64)
29729:   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
29730: #else
29731:   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
29732: #endif
29733: #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
29734: 
29735:   { "write",        (sqlite3_syscall_ptr)write,      0  },
29736: #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
29737: 
29738: #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29739:   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
29740: #else
29741:   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
29742: #endif
29743: #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
29744:                     aSyscall[12].pCurrent)
29745: 
29746: #if defined(USE_PREAD64)
29747:   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
29748: #else
29749:   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
29750: #endif
29751: #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off64_t))\
29752:                     aSyscall[13].pCurrent)
29753: 
29754:   { "fchmod",       (sqlite3_syscall_ptr)fchmod,          0  },
29755: #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
29756: 
29757: #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29758:   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
29759: #else
29760:   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
29761: #endif
29762: #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
29763: 
29764:   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
29765: #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
29766: 
29767:   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
29768: #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
29769: 
29770:   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
29771: #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
29772: 
29773:   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
29774: #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
29775: 
29776: #if defined(HAVE_FCHOWN)
29777:   { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
29778: #else
29779:   { "fchown",       (sqlite3_syscall_ptr)0,               0 },
29780: #endif
29781: #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
29782: 
29783:   { "geteuid",      (sqlite3_syscall_ptr)geteuid,         0 },
29784: #define osGeteuid   ((uid_t(*)(void))aSyscall[21].pCurrent)
29785: 
29786: #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29787:   { "mmap",         (sqlite3_syscall_ptr)mmap,            0 },
29788: #else
29789:   { "mmap",         (sqlite3_syscall_ptr)0,               0 },
29790: #endif
29791: #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
29792: 
29793: #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29794:   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
29795: #else
29796:   { "munmap",       (sqlite3_syscall_ptr)0,               0 },
29797: #endif
29798: #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
29799: 
29800: #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
29801:   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
29802: #else
29803:   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
29804: #endif
29805: #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
29806: 
29807: #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29808:   { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
29809: #else
29810:   { "getpagesize",  (sqlite3_syscall_ptr)0,               0 },
29811: #endif
29812: #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
29813: 
29814: #if defined(HAVE_READLINK)
29815:   { "readlink",     (sqlite3_syscall_ptr)readlink,        0 },
29816: #else
29817:   { "readlink",     (sqlite3_syscall_ptr)0,               0 },
29818: #endif
29819: #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
29820: 
29821: #if defined(HAVE_LSTAT)
29822:   { "lstat",         (sqlite3_syscall_ptr)lstat,          0 },
29823: #else
29824:   { "lstat",         (sqlite3_syscall_ptr)0,              0 },
29825: #endif
29826: #define osLstat      ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
29827: 
29828: }; /* End of the overrideable system calls */
29829: 
29830: 
29831: /*
29832: ** On some systems, calls to fchown() will trigger a message in a security
29833: ** log if they come from non-root processes.  So avoid calling fchown() if
29834: ** we are not running as root.
29835: */
29836: static int robustFchown(int fd, uid_t uid, gid_t gid){
29837: #if defined(HAVE_FCHOWN)
29838:   return osGeteuid() ? 0 : osFchown(fd,uid,gid);
29839: #else
29840:   return 0;
29841: #endif
29842: }
29843: 
29844: /*
29845: ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
29846: ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
29847: ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
29848: ** system call named zName.
29849: */
29850: static int unixSetSystemCall(
29851:   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
29852:   const char *zName,            /* Name of system call to override */
29853:   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
29854: ){
29855:   unsigned int i;
29856:   int rc = SQLITE_NOTFOUND;
29857: 
29858:   UNUSED_PARAMETER(pNotUsed);
29859:   if( zName==0 ){
29860:     /* If no zName is given, restore all system calls to their default
29861:     ** settings and return NULL
29862:     */
29863:     rc = SQLITE_OK;
29864:     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29865:       if( aSyscall[i].pDefault ){
29866:         aSyscall[i].pCurrent = aSyscall[i].pDefault;
29867:       }
29868:     }
29869:   }else{
29870:     /* If zName is specified, operate on only the one system call
29871:     ** specified.
29872:     */
29873:     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29874:       if( strcmp(zName, aSyscall[i].zName)==0 ){
29875:         if( aSyscall[i].pDefault==0 ){
29876:           aSyscall[i].pDefault = aSyscall[i].pCurrent;
29877:         }
29878:         rc = SQLITE_OK;
29879:         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
29880:         aSyscall[i].pCurrent = pNewFunc;
29881:         break;
29882:       }
29883:     }
29884:   }
29885:   return rc;
29886: }
29887: 
29888: /*
29889: ** Return the value of a system call.  Return NULL if zName is not a
29890: ** recognized system call name.  NULL is also returned if the system call
29891: ** is currently undefined.
29892: */
29893: static sqlite3_syscall_ptr unixGetSystemCall(
29894:   sqlite3_vfs *pNotUsed,
29895:   const char *zName
29896: ){
29897:   unsigned int i;
29898: 
29899:   UNUSED_PARAMETER(pNotUsed);
29900:   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29901:     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
29902:   }
29903:   return 0;
29904: }
29905: 
29906: /*
29907: ** Return the name of the first system call after zName.  If zName==NULL
29908: ** then return the name of the first system call.  Return NULL if zName
29909: ** is the last system call or if zName is not the name of a valid
29910: ** system call.
29911: */
29912: static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
29913:   int i = -1;
29914: 
29915:   UNUSED_PARAMETER(p);
29916:   if( zName ){
29917:     for(i=0; i<ArraySize(aSyscall)-1; i++){
29918:       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
29919:     }
29920:   }
29921:   for(i++; i<ArraySize(aSyscall); i++){
29922:     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
29923:   }
29924:   return 0;
29925: }
29926: 
29927: /*
29928: ** Do not accept any file descriptor less than this value, in order to avoid
29929: ** opening database file using file descriptors that are commonly used for 
29930: ** standard input, output, and error.
29931: */
29932: #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
29933: # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
29934: #endif
29935: 
29936: /*
29937: ** Invoke open().  Do so multiple times, until it either succeeds or
29938: ** fails for some reason other than EINTR.
29939: **
29940: ** If the file creation mode "m" is 0 then set it to the default for
29941: ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
29942: ** 0644) as modified by the system umask.  If m is not 0, then
29943: ** make the file creation mode be exactly m ignoring the umask.
29944: **
29945: ** The m parameter will be non-zero only when creating -wal, -journal,
29946: ** and -shm files.  We want those files to have *exactly* the same
29947: ** permissions as their original database, unadulterated by the umask.
29948: ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
29949: ** transaction crashes and leaves behind hot journals, then any
29950: ** process that is able to write to the database will also be able to
29951: ** recover the hot journals.
29952: */
29953: static int robust_open(const char *z, int f, mode_t m){
29954:   int fd;
29955:   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
29956:   while(1){
29957: #if defined(O_CLOEXEC)
29958:     fd = osOpen(z,f|O_CLOEXEC,m2);
29959: #else
29960:     fd = osOpen(z,f,m2);
29961: #endif
29962:     if( fd<0 ){
29963:       if( errno==EINTR ) continue;
29964:       break;
29965:     }
29966:     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
29967:     osClose(fd);
29968:     sqlite3_log(SQLITE_WARNING, 
29969:                 "attempt to open \"%s\" as file descriptor %d", z, fd);
29970:     fd = -1;
29971:     if( osOpen("/dev/null", f, m)<0 ) break;
29972:   }
29973:   if( fd>=0 ){
29974:     if( m!=0 ){
29975:       struct stat statbuf;
29976:       if( osFstat(fd, &statbuf)==0 
29977:        && statbuf.st_size==0
29978:        && (statbuf.st_mode&0777)!=m 
29979:       ){
29980:         osFchmod(fd, m);
29981:       }
29982:     }
29983: #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
29984:     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29985: #endif
29986:   }
29987:   return fd;
29988: }
29989: 
29990: /*
29991: ** Helper functions to obtain and relinquish the global mutex. The
29992: ** global mutex is used to protect the unixInodeInfo and
29993: ** vxworksFileId objects used by this file, all of which may be 
29994: ** shared by multiple threads.
29995: **
29996: ** Function unixMutexHeld() is used to assert() that the global mutex 
29997: ** is held when required. This function is only used as part of assert() 
29998: ** statements. e.g.
29999: **
30000: **   unixEnterMutex()
30001: **     assert( unixMutexHeld() );
30002: **   unixEnterLeave()
30003: */
30004: static void unixEnterMutex(void){
30005:   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30006: }
30007: static void unixLeaveMutex(void){
30008:   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30009: }
30010: #ifdef SQLITE_DEBUG
30011: static int unixMutexHeld(void) {
30012:   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
30013: }
30014: #endif
30015: 
30016: 
30017: #ifdef SQLITE_HAVE_OS_TRACE
30018: /*
30019: ** Helper function for printing out trace information from debugging
30020: ** binaries. This returns the string representation of the supplied
30021: ** integer lock-type.
30022: */
30023: static const char *azFileLock(int eFileLock){
30024:   switch( eFileLock ){
30025:     case NO_LOCK: return "NONE";
30026:     case SHARED_LOCK: return "SHARED";
30027:     case RESERVED_LOCK: return "RESERVED";
30028:     case PENDING_LOCK: return "PENDING";
30029:     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
30030:   }
30031:   return "ERROR";
30032: }
30033: #endif
30034: 
30035: #ifdef SQLITE_LOCK_TRACE
30036: /*
30037: ** Print out information about all locking operations.
30038: **
30039: ** This routine is used for troubleshooting locks on multithreaded
30040: ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
30041: ** command-line option on the compiler.  This code is normally
30042: ** turned off.
30043: */
30044: static int lockTrace(int fd, int op, struct flock *p){
30045:   char *zOpName, *zType;
30046:   int s;
30047:   int savedErrno;
30048:   if( op==F_GETLK ){
30049:     zOpName = "GETLK";
30050:   }else if( op==F_SETLK ){
30051:     zOpName = "SETLK";
30052:   }else{
30053:     s = osFcntl(fd, op, p);
30054:     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
30055:     return s;
30056:   }
30057:   if( p->l_type==F_RDLCK ){
30058:     zType = "RDLCK";
30059:   }else if( p->l_type==F_WRLCK ){
30060:     zType = "WRLCK";
30061:   }else if( p->l_type==F_UNLCK ){
30062:     zType = "UNLCK";
30063:   }else{
30064:     assert( 0 );
30065:   }
30066:   assert( p->l_whence==SEEK_SET );
30067:   s = osFcntl(fd, op, p);
30068:   savedErrno = errno;
30069:   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
30070:      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
30071:      (int)p->l_pid, s);
30072:   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
30073:     struct flock l2;
30074:     l2 = *p;
30075:     osFcntl(fd, F_GETLK, &l2);
30076:     if( l2.l_type==F_RDLCK ){
30077:       zType = "RDLCK";
30078:     }else if( l2.l_type==F_WRLCK ){
30079:       zType = "WRLCK";
30080:     }else if( l2.l_type==F_UNLCK ){
30081:       zType = "UNLCK";
30082:     }else{
30083:       assert( 0 );
30084:     }
30085:     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
30086:        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
30087:   }
30088:   errno = savedErrno;
30089:   return s;
30090: }
30091: #undef osFcntl
30092: #define osFcntl lockTrace
30093: #endif /* SQLITE_LOCK_TRACE */
30094: 
30095: /*
30096: ** Retry ftruncate() calls that fail due to EINTR
30097: **
30098: ** All calls to ftruncate() within this file should be made through
30099: ** this wrapper.  On the Android platform, bypassing the logic below
30100: ** could lead to a corrupt database.
30101: */
30102: static int robust_ftruncate(int h, sqlite3_int64 sz){
30103:   int rc;
30104: #ifdef __ANDROID__
30105:   /* On Android, ftruncate() always uses 32-bit offsets, even if 
30106:   ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
30107:   ** truncate a file to any size larger than 2GiB. Silently ignore any
30108:   ** such attempts.  */
30109:   if( sz>(sqlite3_int64)0x7FFFFFFF ){
30110:     rc = SQLITE_OK;
30111:   }else
30112: #endif
30113:   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
30114:   return rc;
30115: }
30116: 
30117: /*
30118: ** This routine translates a standard POSIX errno code into something
30119: ** useful to the clients of the sqlite3 functions.  Specifically, it is
30120: ** intended to translate a variety of "try again" errors into SQLITE_BUSY
30121: ** and a variety of "please close the file descriptor NOW" errors into 
30122: ** SQLITE_IOERR
30123: ** 
30124: ** Errors during initialization of locks, or file system support for locks,
30125: ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
30126: */
30127: static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
30128:   assert( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
30129:           (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
30130:           (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
30131:           (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
30132:   switch (posixError) {
30133:   case EACCES: 
30134:   case EAGAIN:
30135:   case ETIMEDOUT:
30136:   case EBUSY:
30137:   case EINTR:
30138:   case ENOLCK:  
30139:     /* random NFS retry error, unless during file system support 
30140:      * introspection, in which it actually means what it says */
30141:     return SQLITE_BUSY;
30142:     
30143:   case EPERM: 
30144:     return SQLITE_PERM;
30145:     
30146:   default: 
30147:     return sqliteIOErr;
30148:   }
30149: }
30150: 
30151: 
30152: /******************************************************************************
30153: ****************** Begin Unique File ID Utility Used By VxWorks ***************
30154: **
30155: ** On most versions of unix, we can get a unique ID for a file by concatenating
30156: ** the device number and the inode number.  But this does not work on VxWorks.
30157: ** On VxWorks, a unique file id must be based on the canonical filename.
30158: **
30159: ** A pointer to an instance of the following structure can be used as a
30160: ** unique file ID in VxWorks.  Each instance of this structure contains
30161: ** a copy of the canonical filename.  There is also a reference count.  
30162: ** The structure is reclaimed when the number of pointers to it drops to
30163: ** zero.
30164: **
30165: ** There are never very many files open at one time and lookups are not
30166: ** a performance-critical path, so it is sufficient to put these
30167: ** structures on a linked list.
30168: */
30169: struct vxworksFileId {
30170:   struct vxworksFileId *pNext;  /* Next in a list of them all */
30171:   int nRef;                     /* Number of references to this one */
30172:   int nName;                    /* Length of the zCanonicalName[] string */
30173:   char *zCanonicalName;         /* Canonical filename */
30174: };
30175: 
30176: #if OS_VXWORKS
30177: /* 
30178: ** All unique filenames are held on a linked list headed by this
30179: ** variable:
30180: */
30181: static struct vxworksFileId *vxworksFileList = 0;
30182: 
30183: /*
30184: ** Simplify a filename into its canonical form
30185: ** by making the following changes:
30186: **
30187: **  * removing any trailing and duplicate /
30188: **  * convert /./ into just /
30189: **  * convert /A/../ where A is any simple name into just /
30190: **
30191: ** Changes are made in-place.  Return the new name length.
30192: **
30193: ** The original filename is in z[0..n-1].  Return the number of
30194: ** characters in the simplified name.
30195: */
30196: static int vxworksSimplifyName(char *z, int n){
30197:   int i, j;
30198:   while( n>1 && z[n-1]=='/' ){ n--; }
30199:   for(i=j=0; i<n; i++){
30200:     if( z[i]=='/' ){
30201:       if( z[i+1]=='/' ) continue;
30202:       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
30203:         i += 1;
30204:         continue;
30205:       }
30206:       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
30207:         while( j>0 && z[j-1]!='/' ){ j--; }
30208:         if( j>0 ){ j--; }
30209:         i += 2;
30210:         continue;
30211:       }
30212:     }
30213:     z[j++] = z[i];
30214:   }
30215:   z[j] = 0;
30216:   return j;
30217: }
30218: 
30219: /*
30220: ** Find a unique file ID for the given absolute pathname.  Return
30221: ** a pointer to the vxworksFileId object.  This pointer is the unique
30222: ** file ID.
30223: **
30224: ** The nRef field of the vxworksFileId object is incremented before
30225: ** the object is returned.  A new vxworksFileId object is created
30226: ** and added to the global list if necessary.
30227: **
30228: ** If a memory allocation error occurs, return NULL.
30229: */
30230: static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
30231:   struct vxworksFileId *pNew;         /* search key and new file ID */
30232:   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
30233:   int n;                              /* Length of zAbsoluteName string */
30234: 
30235:   assert( zAbsoluteName[0]=='/' );
30236:   n = (int)strlen(zAbsoluteName);
30237:   pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
30238:   if( pNew==0 ) return 0;
30239:   pNew->zCanonicalName = (char*)&pNew[1];
30240:   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
30241:   n = vxworksSimplifyName(pNew->zCanonicalName, n);
30242: 
30243:   /* Search for an existing entry that matching the canonical name.
30244:   ** If found, increment the reference count and return a pointer to
30245:   ** the existing file ID.
30246:   */
30247:   unixEnterMutex();
30248:   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
30249:     if( pCandidate->nName==n 
30250:      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
30251:     ){
30252:        sqlite3_free(pNew);
30253:        pCandidate->nRef++;
30254:        unixLeaveMutex();
30255:        return pCandidate;
30256:     }
30257:   }
30258: 
30259:   /* No match was found.  We will make a new file ID */
30260:   pNew->nRef = 1;
30261:   pNew->nName = n;
30262:   pNew->pNext = vxworksFileList;
30263:   vxworksFileList = pNew;
30264:   unixLeaveMutex();
30265:   return pNew;
30266: }
30267: 
30268: /*
30269: ** Decrement the reference count on a vxworksFileId object.  Free
30270: ** the object when the reference count reaches zero.
30271: */
30272: static void vxworksReleaseFileId(struct vxworksFileId *pId){
30273:   unixEnterMutex();
30274:   assert( pId->nRef>0 );
30275:   pId->nRef--;
30276:   if( pId->nRef==0 ){
30277:     struct vxworksFileId **pp;
30278:     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
30279:     assert( *pp==pId );
30280:     *pp = pId->pNext;
30281:     sqlite3_free(pId);
30282:   }
30283:   unixLeaveMutex();
30284: }
30285: #endif /* OS_VXWORKS */
30286: /*************** End of Unique File ID Utility Used By VxWorks ****************
30287: ******************************************************************************/
30288: 
30289: 
30290: /******************************************************************************
30291: *************************** Posix Advisory Locking ****************************
30292: **
30293: ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
30294: ** section 6.5.2.2 lines 483 through 490 specify that when a process
30295: ** sets or clears a lock, that operation overrides any prior locks set
30296: ** by the same process.  It does not explicitly say so, but this implies
30297: ** that it overrides locks set by the same process using a different
30298: ** file descriptor.  Consider this test case:
30299: **
30300: **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
30301: **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
30302: **
30303: ** Suppose ./file1 and ./file2 are really the same file (because
30304: ** one is a hard or symbolic link to the other) then if you set
30305: ** an exclusive lock on fd1, then try to get an exclusive lock
30306: ** on fd2, it works.  I would have expected the second lock to
30307: ** fail since there was already a lock on the file due to fd1.
30308: ** But not so.  Since both locks came from the same process, the
30309: ** second overrides the first, even though they were on different
30310: ** file descriptors opened on different file names.
30311: **
30312: ** This means that we cannot use POSIX locks to synchronize file access
30313: ** among competing threads of the same process.  POSIX locks will work fine
30314: ** to synchronize access for threads in separate processes, but not
30315: ** threads within the same process.
30316: **
30317: ** To work around the problem, SQLite has to manage file locks internally
30318: ** on its own.  Whenever a new database is opened, we have to find the
30319: ** specific inode of the database file (the inode is determined by the
30320: ** st_dev and st_ino fields of the stat structure that fstat() fills in)
30321: ** and check for locks already existing on that inode.  When locks are
30322: ** created or removed, we have to look at our own internal record of the
30323: ** locks to see if another thread has previously set a lock on that same
30324: ** inode.
30325: **
30326: ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
30327: ** For VxWorks, we have to use the alternative unique ID system based on
30328: ** canonical filename and implemented in the previous division.)
30329: **
30330: ** The sqlite3_file structure for POSIX is no longer just an integer file
30331: ** descriptor.  It is now a structure that holds the integer file
30332: ** descriptor and a pointer to a structure that describes the internal
30333: ** locks on the corresponding inode.  There is one locking structure
30334: ** per inode, so if the same inode is opened twice, both unixFile structures
30335: ** point to the same locking structure.  The locking structure keeps
30336: ** a reference count (so we will know when to delete it) and a "cnt"
30337: ** field that tells us its internal lock status.  cnt==0 means the
30338: ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
30339: ** cnt>0 means there are cnt shared locks on the file.
30340: **
30341: ** Any attempt to lock or unlock a file first checks the locking
30342: ** structure.  The fcntl() system call is only invoked to set a 
30343: ** POSIX lock if the internal lock structure transitions between
30344: ** a locked and an unlocked state.
30345: **
30346: ** But wait:  there are yet more problems with POSIX advisory locks.
30347: **
30348: ** If you close a file descriptor that points to a file that has locks,
30349: ** all locks on that file that are owned by the current process are
30350: ** released.  To work around this problem, each unixInodeInfo object
30351: ** maintains a count of the number of pending locks on tha inode.
30352: ** When an attempt is made to close an unixFile, if there are
30353: ** other unixFile open on the same inode that are holding locks, the call
30354: ** to close() the file descriptor is deferred until all of the locks clear.
30355: ** The unixInodeInfo structure keeps a list of file descriptors that need to
30356: ** be closed and that list is walked (and cleared) when the last lock
30357: ** clears.
30358: **
30359: ** Yet another problem:  LinuxThreads do not play well with posix locks.
30360: **
30361: ** Many older versions of linux use the LinuxThreads library which is
30362: ** not posix compliant.  Under LinuxThreads, a lock created by thread
30363: ** A cannot be modified or overridden by a different thread B.
30364: ** Only thread A can modify the lock.  Locking behavior is correct
30365: ** if the appliation uses the newer Native Posix Thread Library (NPTL)
30366: ** on linux - with NPTL a lock created by thread A can override locks
30367: ** in thread B.  But there is no way to know at compile-time which
30368: ** threading library is being used.  So there is no way to know at
30369: ** compile-time whether or not thread A can override locks on thread B.
30370: ** One has to do a run-time check to discover the behavior of the
30371: ** current process.
30372: **
30373: ** SQLite used to support LinuxThreads.  But support for LinuxThreads
30374: ** was dropped beginning with version 3.7.0.  SQLite will still work with
30375: ** LinuxThreads provided that (1) there is no more than one connection 
30376: ** per database file in the same process and (2) database connections
30377: ** do not move across threads.
30378: */
30379: 
30380: /*
30381: ** An instance of the following structure serves as the key used
30382: ** to locate a particular unixInodeInfo object.
30383: */
30384: struct unixFileId {
30385:   dev_t dev;                  /* Device number */
30386: #if OS_VXWORKS
30387:   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
30388: #else
30389:   ino_t ino;                  /* Inode number */
30390: #endif
30391: };
30392: 
30393: /*
30394: ** An instance of the following structure is allocated for each open
30395: ** inode.  Or, on LinuxThreads, there is one of these structures for
30396: ** each inode opened by each thread.
30397: **
30398: ** A single inode can have multiple file descriptors, so each unixFile
30399: ** structure contains a pointer to an instance of this object and this
30400: ** object keeps a count of the number of unixFile pointing to it.
30401: */
30402: struct unixInodeInfo {
30403:   struct unixFileId fileId;       /* The lookup key */
30404:   int nShared;                    /* Number of SHARED locks held */
30405:   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
30406:   unsigned char bProcessLock;     /* An exclusive process lock is held */
30407:   int nRef;                       /* Number of pointers to this structure */
30408:   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
30409:   int nLock;                      /* Number of outstanding file locks */
30410:   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
30411:   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
30412:   unixInodeInfo *pPrev;           /*    .... doubly linked */
30413: #if SQLITE_ENABLE_LOCKING_STYLE
30414:   unsigned long long sharedByte;  /* for AFP simulated shared lock */
30415: #endif
30416: #if OS_VXWORKS
30417:   sem_t *pSem;                    /* Named POSIX semaphore */
30418:   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
30419: #endif
30420: };
30421: 
30422: /*
30423: ** A lists of all unixInodeInfo objects.
30424: */
30425: static unixInodeInfo *inodeList = 0;
30426: 
30427: /*
30428: **
30429: ** This function - unixLogErrorAtLine(), is only ever called via the macro
30430: ** unixLogError().
30431: **
30432: ** It is invoked after an error occurs in an OS function and errno has been
30433: ** set. It logs a message using sqlite3_log() containing the current value of
30434: ** errno and, if possible, the human-readable equivalent from strerror() or
30435: ** strerror_r().
30436: **
30437: ** The first argument passed to the macro should be the error code that
30438: ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
30439: ** The two subsequent arguments should be the name of the OS function that
30440: ** failed (e.g. "unlink", "open") and the associated file-system path,
30441: ** if any.
30442: */
30443: #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
30444: static int unixLogErrorAtLine(
30445:   int errcode,                    /* SQLite error code */
30446:   const char *zFunc,              /* Name of OS function that failed */
30447:   const char *zPath,              /* File path associated with error */
30448:   int iLine                       /* Source line number where error occurred */
30449: ){
30450:   char *zErr;                     /* Message from strerror() or equivalent */
30451:   int iErrno = errno;             /* Saved syscall error number */
30452: 
30453:   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
30454:   ** the strerror() function to obtain the human-readable error message
30455:   ** equivalent to errno. Otherwise, use strerror_r().
30456:   */ 
30457: #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
30458:   char aErr[80];
30459:   memset(aErr, 0, sizeof(aErr));
30460:   zErr = aErr;
30461: 
30462:   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
30463:   ** assume that the system provides the GNU version of strerror_r() that
30464:   ** returns a pointer to a buffer containing the error message. That pointer 
30465:   ** may point to aErr[], or it may point to some static storage somewhere. 
30466:   ** Otherwise, assume that the system provides the POSIX version of 
30467:   ** strerror_r(), which always writes an error message into aErr[].
30468:   **
30469:   ** If the code incorrectly assumes that it is the POSIX version that is
30470:   ** available, the error message will often be an empty string. Not a
30471:   ** huge problem. Incorrectly concluding that the GNU version is available 
30472:   ** could lead to a segfault though.
30473:   */
30474: #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
30475:   zErr = 
30476: # endif
30477:   strerror_r(iErrno, aErr, sizeof(aErr)-1);
30478: 
30479: #elif SQLITE_THREADSAFE
30480:   /* This is a threadsafe build, but strerror_r() is not available. */
30481:   zErr = "";
30482: #else
30483:   /* Non-threadsafe build, use strerror(). */
30484:   zErr = strerror(iErrno);
30485: #endif
30486: 
30487:   if( zPath==0 ) zPath = "";
30488:   sqlite3_log(errcode,
30489:       "os_unix.c:%d: (%d) %s(%s) - %s",
30490:       iLine, iErrno, zFunc, zPath, zErr
30491:   );
30492: 
30493:   return errcode;
30494: }
30495: 
30496: /*
30497: ** Close a file descriptor.
30498: **
30499: ** We assume that close() almost always works, since it is only in a
30500: ** very sick application or on a very sick platform that it might fail.
30501: ** If it does fail, simply leak the file descriptor, but do log the
30502: ** error.
30503: **
30504: ** Note that it is not safe to retry close() after EINTR since the
30505: ** file descriptor might have already been reused by another thread.
30506: ** So we don't even try to recover from an EINTR.  Just log the error
30507: ** and move on.
30508: */
30509: static void robust_close(unixFile *pFile, int h, int lineno){
30510:   if( osClose(h) ){
30511:     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
30512:                        pFile ? pFile->zPath : 0, lineno);
30513:   }
30514: }
30515: 
30516: /*
30517: ** Set the pFile->lastErrno.  Do this in a subroutine as that provides
30518: ** a convenient place to set a breakpoint.
30519: */
30520: static void storeLastErrno(unixFile *pFile, int error){
30521:   pFile->lastErrno = error;
30522: }
30523: 
30524: /*
30525: ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
30526: */ 
30527: static void closePendingFds(unixFile *pFile){
30528:   unixInodeInfo *pInode = pFile->pInode;
30529:   UnixUnusedFd *p;
30530:   UnixUnusedFd *pNext;
30531:   for(p=pInode->pUnused; p; p=pNext){
30532:     pNext = p->pNext;
30533:     robust_close(pFile, p->fd, __LINE__);
30534:     sqlite3_free(p);
30535:   }
30536:   pInode->pUnused = 0;
30537: }
30538: 
30539: /*
30540: ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
30541: **
30542: ** The mutex entered using the unixEnterMutex() function must be held
30543: ** when this function is called.
30544: */
30545: static void releaseInodeInfo(unixFile *pFile){
30546:   unixInodeInfo *pInode = pFile->pInode;
30547:   assert( unixMutexHeld() );
30548:   if( ALWAYS(pInode) ){
30549:     pInode->nRef--;
30550:     if( pInode->nRef==0 ){
30551:       assert( pInode->pShmNode==0 );
30552:       closePendingFds(pFile);
30553:       if( pInode->pPrev ){
30554:         assert( pInode->pPrev->pNext==pInode );
30555:         pInode->pPrev->pNext = pInode->pNext;
30556:       }else{
30557:         assert( inodeList==pInode );
30558:         inodeList = pInode->pNext;
30559:       }
30560:       if( pInode->pNext ){
30561:         assert( pInode->pNext->pPrev==pInode );
30562:         pInode->pNext->pPrev = pInode->pPrev;
30563:       }
30564:       sqlite3_free(pInode);
30565:     }
30566:   }
30567: }
30568: 
30569: /*
30570: ** Given a file descriptor, locate the unixInodeInfo object that
30571: ** describes that file descriptor.  Create a new one if necessary.  The
30572: ** return value might be uninitialized if an error occurs.
30573: **
30574: ** The mutex entered using the unixEnterMutex() function must be held
30575: ** when this function is called.
30576: **
30577: ** Return an appropriate error code.
30578: */
30579: static int findInodeInfo(
30580:   unixFile *pFile,               /* Unix file with file desc used in the key */
30581:   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
30582: ){
30583:   int rc;                        /* System call return code */
30584:   int fd;                        /* The file descriptor for pFile */
30585:   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
30586:   struct stat statbuf;           /* Low-level file information */
30587:   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
30588: 
30589:   assert( unixMutexHeld() );
30590: 
30591:   /* Get low-level information about the file that we can used to
30592:   ** create a unique name for the file.
30593:   */
30594:   fd = pFile->h;
30595:   rc = osFstat(fd, &statbuf);
30596:   if( rc!=0 ){
30597:     storeLastErrno(pFile, errno);
30598: #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
30599:     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
30600: #endif
30601:     return SQLITE_IOERR;
30602:   }
30603: 
30604: #ifdef __APPLE__
30605:   /* On OS X on an msdos filesystem, the inode number is reported
30606:   ** incorrectly for zero-size files.  See ticket #3260.  To work
30607:   ** around this problem (we consider it a bug in OS X, not SQLite)
30608:   ** we always increase the file size to 1 by writing a single byte
30609:   ** prior to accessing the inode number.  The one byte written is
30610:   ** an ASCII 'S' character which also happens to be the first byte
30611:   ** in the header of every SQLite database.  In this way, if there
30612:   ** is a race condition such that another thread has already populated
30613:   ** the first page of the database, no damage is done.
30614:   */
30615:   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
30616:     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
30617:     if( rc!=1 ){
30618:       storeLastErrno(pFile, errno);
30619:       return SQLITE_IOERR;
30620:     }
30621:     rc = osFstat(fd, &statbuf);
30622:     if( rc!=0 ){
30623:       storeLastErrno(pFile, errno);
30624:       return SQLITE_IOERR;
30625:     }
30626:   }
30627: #endif
30628: 
30629:   memset(&fileId, 0, sizeof(fileId));
30630:   fileId.dev = statbuf.st_dev;
30631: #if OS_VXWORKS
30632:   fileId.pId = pFile->pId;
30633: #else
30634:   fileId.ino = statbuf.st_ino;
30635: #endif
30636:   pInode = inodeList;
30637:   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
30638:     pInode = pInode->pNext;
30639:   }
30640:   if( pInode==0 ){
30641:     pInode = sqlite3_malloc64( sizeof(*pInode) );
30642:     if( pInode==0 ){
30643:       return SQLITE_NOMEM_BKPT;
30644:     }
30645:     memset(pInode, 0, sizeof(*pInode));
30646:     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
30647:     pInode->nRef = 1;
30648:     pInode->pNext = inodeList;
30649:     pInode->pPrev = 0;
30650:     if( inodeList ) inodeList->pPrev = pInode;
30651:     inodeList = pInode;
30652:   }else{
30653:     pInode->nRef++;
30654:   }
30655:   *ppInode = pInode;
30656:   return SQLITE_OK;
30657: }
30658: 
30659: /*
30660: ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
30661: */
30662: static int fileHasMoved(unixFile *pFile){
30663: #if OS_VXWORKS
30664:   return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
30665: #else
30666:   struct stat buf;
30667:   return pFile->pInode!=0 &&
30668:       (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
30669: #endif
30670: }
30671: 
30672: 
30673: /*
30674: ** Check a unixFile that is a database.  Verify the following:
30675: **
30676: ** (1) There is exactly one hard link on the file
30677: ** (2) The file is not a symbolic link
30678: ** (3) The file has not been renamed or unlinked
30679: **
30680: ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
30681: */
30682: static void verifyDbFile(unixFile *pFile){
30683:   struct stat buf;
30684:   int rc;
30685: 
30686:   /* These verifications occurs for the main database only */
30687:   if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
30688: 
30689:   rc = osFstat(pFile->h, &buf);
30690:   if( rc!=0 ){
30691:     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
30692:     return;
30693:   }
30694:   if( buf.st_nlink==0 ){
30695:     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
30696:     return;
30697:   }
30698:   if( buf.st_nlink>1 ){
30699:     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
30700:     return;
30701:   }
30702:   if( fileHasMoved(pFile) ){
30703:     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
30704:     return;
30705:   }
30706: }
30707: 
30708: 
30709: /*
30710: ** This routine checks if there is a RESERVED lock held on the specified
30711: ** file by this or any other process. If such a lock is held, set *pResOut
30712: ** to a non-zero value otherwise *pResOut is set to zero.  The return value
30713: ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30714: */
30715: static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
30716:   int rc = SQLITE_OK;
30717:   int reserved = 0;
30718:   unixFile *pFile = (unixFile*)id;
30719: 
30720:   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30721: 
30722:   assert( pFile );
30723:   assert( pFile->eFileLock<=SHARED_LOCK );
30724:   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
30725: 
30726:   /* Check if a thread in this process holds such a lock */
30727:   if( pFile->pInode->eFileLock>SHARED_LOCK ){
30728:     reserved = 1;
30729:   }
30730: 
30731:   /* Otherwise see if some other process holds it.
30732:   */
30733: #ifndef __DJGPP__
30734:   if( !reserved && !pFile->pInode->bProcessLock ){
30735:     struct flock lock;
30736:     lock.l_whence = SEEK_SET;
30737:     lock.l_start = RESERVED_BYTE;
30738:     lock.l_len = 1;
30739:     lock.l_type = F_WRLCK;
30740:     if( osFcntl(pFile->h, F_GETLK, &lock) ){
30741:       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
30742:       storeLastErrno(pFile, errno);
30743:     } else if( lock.l_type!=F_UNLCK ){
30744:       reserved = 1;
30745:     }
30746:   }
30747: #endif
30748:   
30749:   unixLeaveMutex();
30750:   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
30751: 
30752:   *pResOut = reserved;
30753:   return rc;
30754: }
30755: 
30756: /*
30757: ** Attempt to set a system-lock on the file pFile.  The lock is 
30758: ** described by pLock.
30759: **
30760: ** If the pFile was opened read/write from unix-excl, then the only lock
30761: ** ever obtained is an exclusive lock, and it is obtained exactly once
30762: ** the first time any lock is attempted.  All subsequent system locking
30763: ** operations become no-ops.  Locking operations still happen internally,
30764: ** in order to coordinate access between separate database connections
30765: ** within this process, but all of that is handled in memory and the
30766: ** operating system does not participate.
30767: **
30768: ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
30769: ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
30770: ** and is read-only.
30771: **
30772: ** Zero is returned if the call completes successfully, or -1 if a call
30773: ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
30774: */
30775: static int unixFileLock(unixFile *pFile, struct flock *pLock){
30776:   int rc;
30777:   unixInodeInfo *pInode = pFile->pInode;
30778:   assert( unixMutexHeld() );
30779:   assert( pInode!=0 );
30780:   if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
30781:     if( pInode->bProcessLock==0 ){
30782:       struct flock lock;
30783:       assert( pInode->nLock==0 );
30784:       lock.l_whence = SEEK_SET;
30785:       lock.l_start = SHARED_FIRST;
30786:       lock.l_len = SHARED_SIZE;
30787:       lock.l_type = F_WRLCK;
30788:       rc = osFcntl(pFile->h, F_SETLK, &lock);
30789:       if( rc<0 ) return rc;
30790:       pInode->bProcessLock = 1;
30791:       pInode->nLock++;
30792:     }else{
30793:       rc = 0;
30794:     }
30795:   }else{
30796:     rc = osFcntl(pFile->h, F_SETLK, pLock);
30797:   }
30798:   return rc;
30799: }
30800: 
30801: /*
30802: ** Lock the file with the lock specified by parameter eFileLock - one
30803: ** of the following:
30804: **
30805: **     (1) SHARED_LOCK
30806: **     (2) RESERVED_LOCK
30807: **     (3) PENDING_LOCK
30808: **     (4) EXCLUSIVE_LOCK
30809: **
30810: ** Sometimes when requesting one lock state, additional lock states
30811: ** are inserted in between.  The locking might fail on one of the later
30812: ** transitions leaving the lock state different from what it started but
30813: ** still short of its goal.  The following chart shows the allowed
30814: ** transitions and the inserted intermediate states:
30815: **
30816: **    UNLOCKED -> SHARED
30817: **    SHARED -> RESERVED
30818: **    SHARED -> (PENDING) -> EXCLUSIVE
30819: **    RESERVED -> (PENDING) -> EXCLUSIVE
30820: **    PENDING -> EXCLUSIVE
30821: **
30822: ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30823: ** routine to lower a locking level.
30824: */
30825: static int unixLock(sqlite3_file *id, int eFileLock){
30826:   /* The following describes the implementation of the various locks and
30827:   ** lock transitions in terms of the POSIX advisory shared and exclusive
30828:   ** lock primitives (called read-locks and write-locks below, to avoid
30829:   ** confusion with SQLite lock names). The algorithms are complicated
30830:   ** slightly in order to be compatible with Windows95 systems simultaneously
30831:   ** accessing the same database file, in case that is ever required.
30832:   **
30833:   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
30834:   ** byte', each single bytes at well known offsets, and the 'shared byte
30835:   ** range', a range of 510 bytes at a well known offset.
30836:   **
30837:   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
30838:   ** byte'.  If this is successful, 'shared byte range' is read-locked
30839:   ** and the lock on the 'pending byte' released.  (Legacy note:  When
30840:   ** SQLite was first developed, Windows95 systems were still very common,
30841:   ** and Widnows95 lacks a shared-lock capability.  So on Windows95, a
30842:   ** single randomly selected by from the 'shared byte range' is locked.
30843:   ** Windows95 is now pretty much extinct, but this work-around for the
30844:   ** lack of shared-locks on Windows95 lives on, for backwards
30845:   ** compatibility.)
30846:   **
30847:   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
30848:   ** A RESERVED lock is implemented by grabbing a write-lock on the
30849:   ** 'reserved byte'. 
30850:   **
30851:   ** A process may only obtain a PENDING lock after it has obtained a
30852:   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
30853:   ** on the 'pending byte'. This ensures that no new SHARED locks can be
30854:   ** obtained, but existing SHARED locks are allowed to persist. A process
30855:   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
30856:   ** This property is used by the algorithm for rolling back a journal file
30857:   ** after a crash.
30858:   **
30859:   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
30860:   ** implemented by obtaining a write-lock on the entire 'shared byte
30861:   ** range'. Since all other locks require a read-lock on one of the bytes
30862:   ** within this range, this ensures that no other locks are held on the
30863:   ** database. 
30864:   */
30865:   int rc = SQLITE_OK;
30866:   unixFile *pFile = (unixFile*)id;
30867:   unixInodeInfo *pInode;
30868:   struct flock lock;
30869:   int tErrno = 0;
30870: 
30871:   assert( pFile );
30872:   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
30873:       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
30874:       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
30875:       osGetpid(0)));
30876: 
30877:   /* If there is already a lock of this type or more restrictive on the
30878:   ** unixFile, do nothing. Don't use the end_lock: exit path, as
30879:   ** unixEnterMutex() hasn't been called yet.
30880:   */
30881:   if( pFile->eFileLock>=eFileLock ){
30882:     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
30883:             azFileLock(eFileLock)));
30884:     return SQLITE_OK;
30885:   }
30886: 
30887:   /* Make sure the locking sequence is correct.
30888:   **  (1) We never move from unlocked to anything higher than shared lock.
30889:   **  (2) SQLite never explicitly requests a pendig lock.
30890:   **  (3) A shared lock is always held when a reserve lock is requested.
30891:   */
30892:   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
30893:   assert( eFileLock!=PENDING_LOCK );
30894:   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
30895: 
30896:   /* This mutex is needed because pFile->pInode is shared across threads
30897:   */
30898:   unixEnterMutex();
30899:   pInode = pFile->pInode;
30900: 
30901:   /* If some thread using this PID has a lock via a different unixFile*
30902:   ** handle that precludes the requested lock, return BUSY.
30903:   */
30904:   if( (pFile->eFileLock!=pInode->eFileLock && 
30905:           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
30906:   ){
30907:     rc = SQLITE_BUSY;
30908:     goto end_lock;
30909:   }
30910: 
30911:   /* If a SHARED lock is requested, and some thread using this PID already
30912:   ** has a SHARED or RESERVED lock, then increment reference counts and
30913:   ** return SQLITE_OK.
30914:   */
30915:   if( eFileLock==SHARED_LOCK && 
30916:       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
30917:     assert( eFileLock==SHARED_LOCK );
30918:     assert( pFile->eFileLock==0 );
30919:     assert( pInode->nShared>0 );
30920:     pFile->eFileLock = SHARED_LOCK;
30921:     pInode->nShared++;
30922:     pInode->nLock++;
30923:     goto end_lock;
30924:   }
30925: 
30926: 
30927:   /* A PENDING lock is needed before acquiring a SHARED lock and before
30928:   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
30929:   ** be released.
30930:   */
30931:   lock.l_len = 1L;
30932:   lock.l_whence = SEEK_SET;
30933:   if( eFileLock==SHARED_LOCK 
30934:       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
30935:   ){
30936:     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
30937:     lock.l_start = PENDING_BYTE;
30938:     if( unixFileLock(pFile, &lock) ){
30939:       tErrno = errno;
30940:       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
30941:       if( rc!=SQLITE_BUSY ){
30942:         storeLastErrno(pFile, tErrno);
30943:       }
30944:       goto end_lock;
30945:     }
30946:   }
30947: 
30948: 
30949:   /* If control gets to this point, then actually go ahead and make
30950:   ** operating system calls for the specified lock.
30951:   */
30952:   if( eFileLock==SHARED_LOCK ){
30953:     assert( pInode->nShared==0 );
30954:     assert( pInode->eFileLock==0 );
30955:     assert( rc==SQLITE_OK );
30956: 
30957:     /* Now get the read-lock */
30958:     lock.l_start = SHARED_FIRST;
30959:     lock.l_len = SHARED_SIZE;
30960:     if( unixFileLock(pFile, &lock) ){
30961:       tErrno = errno;
30962:       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
30963:     }
30964: 
30965:     /* Drop the temporary PENDING lock */
30966:     lock.l_start = PENDING_BYTE;
30967:     lock.l_len = 1L;
30968:     lock.l_type = F_UNLCK;
30969:     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
30970:       /* This could happen with a network mount */
30971:       tErrno = errno;
30972:       rc = SQLITE_IOERR_UNLOCK; 
30973:     }
30974: 
30975:     if( rc ){
30976:       if( rc!=SQLITE_BUSY ){
30977:         storeLastErrno(pFile, tErrno);
30978:       }
30979:       goto end_lock;
30980:     }else{
30981:       pFile->eFileLock = SHARED_LOCK;
30982:       pInode->nLock++;
30983:       pInode->nShared = 1;
30984:     }
30985:   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
30986:     /* We are trying for an exclusive lock but another thread in this
30987:     ** same process is still holding a shared lock. */
30988:     rc = SQLITE_BUSY;
30989:   }else{
30990:     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
30991:     ** assumed that there is a SHARED or greater lock on the file
30992:     ** already.
30993:     */
30994:     assert( 0!=pFile->eFileLock );
30995:     lock.l_type = F_WRLCK;
30996: 
30997:     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
30998:     if( eFileLock==RESERVED_LOCK ){
30999:       lock.l_start = RESERVED_BYTE;
31000:       lock.l_len = 1L;
31001:     }else{
31002:       lock.l_start = SHARED_FIRST;
31003:       lock.l_len = SHARED_SIZE;
31004:     }
31005: 
31006:     if( unixFileLock(pFile, &lock) ){
31007:       tErrno = errno;
31008:       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31009:       if( rc!=SQLITE_BUSY ){
31010:         storeLastErrno(pFile, tErrno);
31011:       }
31012:     }
31013:   }
31014:   
31015: 
31016: #ifdef SQLITE_DEBUG
31017:   /* Set up the transaction-counter change checking flags when
31018:   ** transitioning from a SHARED to a RESERVED lock.  The change
31019:   ** from SHARED to RESERVED marks the beginning of a normal
31020:   ** write operation (not a hot journal rollback).
31021:   */
31022:   if( rc==SQLITE_OK
31023:    && pFile->eFileLock<=SHARED_LOCK
31024:    && eFileLock==RESERVED_LOCK
31025:   ){
31026:     pFile->transCntrChng = 0;
31027:     pFile->dbUpdate = 0;
31028:     pFile->inNormalWrite = 1;
31029:   }
31030: #endif
31031: 
31032: 
31033:   if( rc==SQLITE_OK ){
31034:     pFile->eFileLock = eFileLock;
31035:     pInode->eFileLock = eFileLock;
31036:   }else if( eFileLock==EXCLUSIVE_LOCK ){
31037:     pFile->eFileLock = PENDING_LOCK;
31038:     pInode->eFileLock = PENDING_LOCK;
31039:   }
31040: 
31041: end_lock:
31042:   unixLeaveMutex();
31043:   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
31044:       rc==SQLITE_OK ? "ok" : "failed"));
31045:   return rc;
31046: }
31047: 
31048: /*
31049: ** Add the file descriptor used by file handle pFile to the corresponding
31050: ** pUnused list.
31051: */
31052: static void setPendingFd(unixFile *pFile){
31053:   unixInodeInfo *pInode = pFile->pInode;
31054:   UnixUnusedFd *p = pFile->pUnused;
31055:   p->pNext = pInode->pUnused;
31056:   pInode->pUnused = p;
31057:   pFile->h = -1;
31058:   pFile->pUnused = 0;
31059: }
31060: 
31061: /*
31062: ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31063: ** must be either NO_LOCK or SHARED_LOCK.
31064: **
31065: ** If the locking level of the file descriptor is already at or below
31066: ** the requested locking level, this routine is a no-op.
31067: ** 
31068: ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
31069: ** the byte range is divided into 2 parts and the first part is unlocked then
31070: ** set to a read lock, then the other part is simply unlocked.  This works 
31071: ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
31072: ** remove the write lock on a region when a read lock is set.
31073: */
31074: static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
31075:   unixFile *pFile = (unixFile*)id;
31076:   unixInodeInfo *pInode;
31077:   struct flock lock;
31078:   int rc = SQLITE_OK;
31079: 
31080:   assert( pFile );
31081:   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
31082:       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
31083:       osGetpid(0)));
31084: 
31085:   assert( eFileLock<=SHARED_LOCK );
31086:   if( pFile->eFileLock<=eFileLock ){
31087:     return SQLITE_OK;
31088:   }
31089:   unixEnterMutex();
31090:   pInode = pFile->pInode;
31091:   assert( pInode->nShared!=0 );
31092:   if( pFile->eFileLock>SHARED_LOCK ){
31093:     assert( pInode->eFileLock==pFile->eFileLock );
31094: 
31095: #ifdef SQLITE_DEBUG
31096:     /* When reducing a lock such that other processes can start
31097:     ** reading the database file again, make sure that the
31098:     ** transaction counter was updated if any part of the database
31099:     ** file changed.  If the transaction counter is not updated,
31100:     ** other connections to the same file might not realize that
31101:     ** the file has changed and hence might not know to flush their
31102:     ** cache.  The use of a stale cache can lead to database corruption.
31103:     */
31104:     pFile->inNormalWrite = 0;
31105: #endif
31106: 
31107:     /* downgrading to a shared lock on NFS involves clearing the write lock
31108:     ** before establishing the readlock - to avoid a race condition we downgrade
31109:     ** the lock in 2 blocks, so that part of the range will be covered by a 
31110:     ** write lock until the rest is covered by a read lock:
31111:     **  1:   [WWWWW]
31112:     **  2:   [....W]
31113:     **  3:   [RRRRW]
31114:     **  4:   [RRRR.]
31115:     */
31116:     if( eFileLock==SHARED_LOCK ){
31117: #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
31118:       (void)handleNFSUnlock;
31119:       assert( handleNFSUnlock==0 );
31120: #endif
31121: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31122:       if( handleNFSUnlock ){
31123:         int tErrno;               /* Error code from system call errors */
31124:         off_t divSize = SHARED_SIZE - 1;
31125:         
31126:         lock.l_type = F_UNLCK;
31127:         lock.l_whence = SEEK_SET;
31128:         lock.l_start = SHARED_FIRST;
31129:         lock.l_len = divSize;
31130:         if( unixFileLock(pFile, &lock)==(-1) ){
31131:           tErrno = errno;
31132:           rc = SQLITE_IOERR_UNLOCK;
31133:           storeLastErrno(pFile, tErrno);
31134:           goto end_unlock;
31135:         }
31136:         lock.l_type = F_RDLCK;
31137:         lock.l_whence = SEEK_SET;
31138:         lock.l_start = SHARED_FIRST;
31139:         lock.l_len = divSize;
31140:         if( unixFileLock(pFile, &lock)==(-1) ){
31141:           tErrno = errno;
31142:           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
31143:           if( IS_LOCK_ERROR(rc) ){
31144:             storeLastErrno(pFile, tErrno);
31145:           }
31146:           goto end_unlock;
31147:         }
31148:         lock.l_type = F_UNLCK;
31149:         lock.l_whence = SEEK_SET;
31150:         lock.l_start = SHARED_FIRST+divSize;
31151:         lock.l_len = SHARED_SIZE-divSize;
31152:         if( unixFileLock(pFile, &lock)==(-1) ){
31153:           tErrno = errno;
31154:           rc = SQLITE_IOERR_UNLOCK;
31155:           storeLastErrno(pFile, tErrno);
31156:           goto end_unlock;
31157:         }
31158:       }else
31159: #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31160:       {
31161:         lock.l_type = F_RDLCK;
31162:         lock.l_whence = SEEK_SET;
31163:         lock.l_start = SHARED_FIRST;
31164:         lock.l_len = SHARED_SIZE;
31165:         if( unixFileLock(pFile, &lock) ){
31166:           /* In theory, the call to unixFileLock() cannot fail because another
31167:           ** process is holding an incompatible lock. If it does, this 
31168:           ** indicates that the other process is not following the locking
31169:           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
31170:           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
31171:           ** an assert to fail). */ 
31172:           rc = SQLITE_IOERR_RDLOCK;
31173:           storeLastErrno(pFile, errno);
31174:           goto end_unlock;
31175:         }
31176:       }
31177:     }
31178:     lock.l_type = F_UNLCK;
31179:     lock.l_whence = SEEK_SET;
31180:     lock.l_start = PENDING_BYTE;
31181:     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
31182:     if( unixFileLock(pFile, &lock)==0 ){
31183:       pInode->eFileLock = SHARED_LOCK;
31184:     }else{
31185:       rc = SQLITE_IOERR_UNLOCK;
31186:       storeLastErrno(pFile, errno);
31187:       goto end_unlock;
31188:     }
31189:   }
31190:   if( eFileLock==NO_LOCK ){
31191:     /* Decrement the shared lock counter.  Release the lock using an
31192:     ** OS call only when all threads in this same process have released
31193:     ** the lock.
31194:     */
31195:     pInode->nShared--;
31196:     if( pInode->nShared==0 ){
31197:       lock.l_type = F_UNLCK;
31198:       lock.l_whence = SEEK_SET;
31199:       lock.l_start = lock.l_len = 0L;
31200:       if( unixFileLock(pFile, &lock)==0 ){
31201:         pInode->eFileLock = NO_LOCK;
31202:       }else{
31203:         rc = SQLITE_IOERR_UNLOCK;
31204:         storeLastErrno(pFile, errno);
31205:         pInode->eFileLock = NO_LOCK;
31206:         pFile->eFileLock = NO_LOCK;
31207:       }
31208:     }
31209: 
31210:     /* Decrement the count of locks against this same file.  When the
31211:     ** count reaches zero, close any other file descriptors whose close
31212:     ** was deferred because of outstanding locks.
31213:     */
31214:     pInode->nLock--;
31215:     assert( pInode->nLock>=0 );
31216:     if( pInode->nLock==0 ){
31217:       closePendingFds(pFile);
31218:     }
31219:   }
31220: 
31221: end_unlock:
31222:   unixLeaveMutex();
31223:   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
31224:   return rc;
31225: }
31226: 
31227: /*
31228: ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31229: ** must be either NO_LOCK or SHARED_LOCK.
31230: **
31231: ** If the locking level of the file descriptor is already at or below
31232: ** the requested locking level, this routine is a no-op.
31233: */
31234: static int unixUnlock(sqlite3_file *id, int eFileLock){
31235: #if SQLITE_MAX_MMAP_SIZE>0
31236:   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
31237: #endif
31238:   return posixUnlock(id, eFileLock, 0);
31239: }
31240: 
31241: #if SQLITE_MAX_MMAP_SIZE>0
31242: static int unixMapfile(unixFile *pFd, i64 nByte);
31243: static void unixUnmapfile(unixFile *pFd);
31244: #endif
31245: 
31246: /*
31247: ** This function performs the parts of the "close file" operation 
31248: ** common to all locking schemes. It closes the directory and file
31249: ** handles, if they are valid, and sets all fields of the unixFile
31250: ** structure to 0.
31251: **
31252: ** It is *not* necessary to hold the mutex when this routine is called,
31253: ** even on VxWorks.  A mutex will be acquired on VxWorks by the
31254: ** vxworksReleaseFileId() routine.
31255: */
31256: static int closeUnixFile(sqlite3_file *id){
31257:   unixFile *pFile = (unixFile*)id;
31258: #if SQLITE_MAX_MMAP_SIZE>0
31259:   unixUnmapfile(pFile);
31260: #endif
31261:   if( pFile->h>=0 ){
31262:     robust_close(pFile, pFile->h, __LINE__);
31263:     pFile->h = -1;
31264:   }
31265: #if OS_VXWORKS
31266:   if( pFile->pId ){
31267:     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31268:       osUnlink(pFile->pId->zCanonicalName);
31269:     }
31270:     vxworksReleaseFileId(pFile->pId);
31271:     pFile->pId = 0;
31272:   }
31273: #endif
31274: #ifdef SQLITE_UNLINK_AFTER_CLOSE
31275:   if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31276:     osUnlink(pFile->zPath);
31277:     sqlite3_free(*(char**)&pFile->zPath);
31278:     pFile->zPath = 0;
31279:   }
31280: #endif
31281:   OSTRACE(("CLOSE   %-3d\n", pFile->h));
31282:   OpenCounter(-1);
31283:   sqlite3_free(pFile->pUnused);
31284:   memset(pFile, 0, sizeof(unixFile));
31285:   return SQLITE_OK;
31286: }
31287: 
31288: /*
31289: ** Close a file.
31290: */
31291: static int unixClose(sqlite3_file *id){
31292:   int rc = SQLITE_OK;
31293:   unixFile *pFile = (unixFile *)id;
31294:   verifyDbFile(pFile);
31295:   unixUnlock(id, NO_LOCK);
31296:   unixEnterMutex();
31297: 
31298:   /* unixFile.pInode is always valid here. Otherwise, a different close
31299:   ** routine (e.g. nolockClose()) would be called instead.
31300:   */
31301:   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
31302:   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
31303:     /* If there are outstanding locks, do not actually close the file just
31304:     ** yet because that would clear those locks.  Instead, add the file
31305:     ** descriptor to pInode->pUnused list.  It will be automatically closed 
31306:     ** when the last lock is cleared.
31307:     */
31308:     setPendingFd(pFile);
31309:   }
31310:   releaseInodeInfo(pFile);
31311:   rc = closeUnixFile(id);
31312:   unixLeaveMutex();
31313:   return rc;
31314: }
31315: 
31316: /************** End of the posix advisory lock implementation *****************
31317: ******************************************************************************/
31318: 
31319: /******************************************************************************
31320: ****************************** No-op Locking **********************************
31321: **
31322: ** Of the various locking implementations available, this is by far the
31323: ** simplest:  locking is ignored.  No attempt is made to lock the database
31324: ** file for reading or writing.
31325: **
31326: ** This locking mode is appropriate for use on read-only databases
31327: ** (ex: databases that are burned into CD-ROM, for example.)  It can
31328: ** also be used if the application employs some external mechanism to
31329: ** prevent simultaneous access of the same database by two or more
31330: ** database connections.  But there is a serious risk of database
31331: ** corruption if this locking mode is used in situations where multiple
31332: ** database connections are accessing the same database file at the same
31333: ** time and one or more of those connections are writing.
31334: */
31335: 
31336: static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
31337:   UNUSED_PARAMETER(NotUsed);
31338:   *pResOut = 0;
31339:   return SQLITE_OK;
31340: }
31341: static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
31342:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
31343:   return SQLITE_OK;
31344: }
31345: static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
31346:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
31347:   return SQLITE_OK;
31348: }
31349: 
31350: /*
31351: ** Close the file.
31352: */
31353: static int nolockClose(sqlite3_file *id) {
31354:   return closeUnixFile(id);
31355: }
31356: 
31357: /******************* End of the no-op lock implementation *********************
31358: ******************************************************************************/
31359: 
31360: /******************************************************************************
31361: ************************* Begin dot-file Locking ******************************
31362: **
31363: ** The dotfile locking implementation uses the existence of separate lock
31364: ** files (really a directory) to control access to the database.  This works
31365: ** on just about every filesystem imaginable.  But there are serious downsides:
31366: **
31367: **    (1)  There is zero concurrency.  A single reader blocks all other
31368: **         connections from reading or writing the database.
31369: **
31370: **    (2)  An application crash or power loss can leave stale lock files
31371: **         sitting around that need to be cleared manually.
31372: **
31373: ** Nevertheless, a dotlock is an appropriate locking mode for use if no
31374: ** other locking strategy is available.
31375: **
31376: ** Dotfile locking works by creating a subdirectory in the same directory as
31377: ** the database and with the same name but with a ".lock" extension added.
31378: ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
31379: ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
31380: */
31381: 
31382: /*
31383: ** The file suffix added to the data base filename in order to create the
31384: ** lock directory.
31385: */
31386: #define DOTLOCK_SUFFIX ".lock"
31387: 
31388: /*
31389: ** This routine checks if there is a RESERVED lock held on the specified
31390: ** file by this or any other process. If such a lock is held, set *pResOut
31391: ** to a non-zero value otherwise *pResOut is set to zero.  The return value
31392: ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31393: **
31394: ** In dotfile locking, either a lock exists or it does not.  So in this
31395: ** variation of CheckReservedLock(), *pResOut is set to true if any lock
31396: ** is held on the file and false if the file is unlocked.
31397: */
31398: static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
31399:   int rc = SQLITE_OK;
31400:   int reserved = 0;
31401:   unixFile *pFile = (unixFile*)id;
31402: 
31403:   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31404:   
31405:   assert( pFile );
31406:   reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
31407:   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
31408:   *pResOut = reserved;
31409:   return rc;
31410: }
31411: 
31412: /*
31413: ** Lock the file with the lock specified by parameter eFileLock - one
31414: ** of the following:
31415: **
31416: **     (1) SHARED_LOCK
31417: **     (2) RESERVED_LOCK
31418: **     (3) PENDING_LOCK
31419: **     (4) EXCLUSIVE_LOCK
31420: **
31421: ** Sometimes when requesting one lock state, additional lock states
31422: ** are inserted in between.  The locking might fail on one of the later
31423: ** transitions leaving the lock state different from what it started but
31424: ** still short of its goal.  The following chart shows the allowed
31425: ** transitions and the inserted intermediate states:
31426: **
31427: **    UNLOCKED -> SHARED
31428: **    SHARED -> RESERVED
31429: **    SHARED -> (PENDING) -> EXCLUSIVE
31430: **    RESERVED -> (PENDING) -> EXCLUSIVE
31431: **    PENDING -> EXCLUSIVE
31432: **
31433: ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31434: ** routine to lower a locking level.
31435: **
31436: ** With dotfile locking, we really only support state (4): EXCLUSIVE.
31437: ** But we track the other locking levels internally.
31438: */
31439: static int dotlockLock(sqlite3_file *id, int eFileLock) {
31440:   unixFile *pFile = (unixFile*)id;
31441:   char *zLockFile = (char *)pFile->lockingContext;
31442:   int rc = SQLITE_OK;
31443: 
31444: 
31445:   /* If we have any lock, then the lock file already exists.  All we have
31446:   ** to do is adjust our internal record of the lock level.
31447:   */
31448:   if( pFile->eFileLock > NO_LOCK ){
31449:     pFile->eFileLock = eFileLock;
31450:     /* Always update the timestamp on the old file */
31451: #ifdef HAVE_UTIME
31452:     utime(zLockFile, NULL);
31453: #else
31454:     utimes(zLockFile, NULL);
31455: #endif
31456:     return SQLITE_OK;
31457:   }
31458:   
31459:   /* grab an exclusive lock */
31460:   rc = osMkdir(zLockFile, 0777);
31461:   if( rc<0 ){
31462:     /* failed to open/create the lock directory */
31463:     int tErrno = errno;
31464:     if( EEXIST == tErrno ){
31465:       rc = SQLITE_BUSY;
31466:     } else {
31467:       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31468:       if( rc!=SQLITE_BUSY ){
31469:         storeLastErrno(pFile, tErrno);
31470:       }
31471:     }
31472:     return rc;
31473:   } 
31474:   
31475:   /* got it, set the type and return ok */
31476:   pFile->eFileLock = eFileLock;
31477:   return rc;
31478: }
31479: 
31480: /*
31481: ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31482: ** must be either NO_LOCK or SHARED_LOCK.
31483: **
31484: ** If the locking level of the file descriptor is already at or below
31485: ** the requested locking level, this routine is a no-op.
31486: **
31487: ** When the locking level reaches NO_LOCK, delete the lock file.
31488: */
31489: static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
31490:   unixFile *pFile = (unixFile*)id;
31491:   char *zLockFile = (char *)pFile->lockingContext;
31492:   int rc;
31493: 
31494:   assert( pFile );
31495:   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
31496:            pFile->eFileLock, osGetpid(0)));
31497:   assert( eFileLock<=SHARED_LOCK );
31498:   
31499:   /* no-op if possible */
31500:   if( pFile->eFileLock==eFileLock ){
31501:     return SQLITE_OK;
31502:   }
31503: 
31504:   /* To downgrade to shared, simply update our internal notion of the
31505:   ** lock state.  No need to mess with the file on disk.
31506:   */
31507:   if( eFileLock==SHARED_LOCK ){
31508:     pFile->eFileLock = SHARED_LOCK;
31509:     return SQLITE_OK;
31510:   }
31511:   
31512:   /* To fully unlock the database, delete the lock file */
31513:   assert( eFileLock==NO_LOCK );
31514:   rc = osRmdir(zLockFile);
31515:   if( rc<0 ){
31516:     int tErrno = errno;
31517:     if( tErrno==ENOENT ){
31518:       rc = SQLITE_OK;
31519:     }else{
31520:       rc = SQLITE_IOERR_UNLOCK;
31521:       storeLastErrno(pFile, tErrno);
31522:     }
31523:     return rc; 
31524:   }
31525:   pFile->eFileLock = NO_LOCK;
31526:   return SQLITE_OK;
31527: }
31528: 
31529: /*
31530: ** Close a file.  Make sure the lock has been released before closing.
31531: */
31532: static int dotlockClose(sqlite3_file *id) {
31533:   unixFile *pFile = (unixFile*)id;
31534:   assert( id!=0 );
31535:   dotlockUnlock(id, NO_LOCK);
31536:   sqlite3_free(pFile->lockingContext);
31537:   return closeUnixFile(id);
31538: }
31539: /****************** End of the dot-file lock implementation *******************
31540: ******************************************************************************/
31541: 
31542: /******************************************************************************
31543: ************************** Begin flock Locking ********************************
31544: **
31545: ** Use the flock() system call to do file locking.
31546: **
31547: ** flock() locking is like dot-file locking in that the various
31548: ** fine-grain locking levels supported by SQLite are collapsed into
31549: ** a single exclusive lock.  In other words, SHARED, RESERVED, and
31550: ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
31551: ** still works when you do this, but concurrency is reduced since
31552: ** only a single process can be reading the database at a time.
31553: **
31554: ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
31555: */
31556: #if SQLITE_ENABLE_LOCKING_STYLE
31557: 
31558: /*
31559: ** Retry flock() calls that fail with EINTR
31560: */
31561: #ifdef EINTR
31562: static int robust_flock(int fd, int op){
31563:   int rc;
31564:   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
31565:   return rc;
31566: }
31567: #else
31568: # define robust_flock(a,b) flock(a,b)
31569: #endif
31570:      
31571: 
31572: /*
31573: ** This routine checks if there is a RESERVED lock held on the specified
31574: ** file by this or any other process. If such a lock is held, set *pResOut
31575: ** to a non-zero value otherwise *pResOut is set to zero.  The return value
31576: ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31577: */
31578: static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
31579:   int rc = SQLITE_OK;
31580:   int reserved = 0;
31581:   unixFile *pFile = (unixFile*)id;
31582:   
31583:   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31584:   
31585:   assert( pFile );
31586:   
31587:   /* Check if a thread in this process holds such a lock */
31588:   if( pFile->eFileLock>SHARED_LOCK ){
31589:     reserved = 1;
31590:   }
31591:   
31592:   /* Otherwise see if some other process holds it. */
31593:   if( !reserved ){
31594:     /* attempt to get the lock */
31595:     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
31596:     if( !lrc ){
31597:       /* got the lock, unlock it */
31598:       lrc = robust_flock(pFile->h, LOCK_UN);
31599:       if ( lrc ) {
31600:         int tErrno = errno;
31601:         /* unlock failed with an error */
31602:         lrc = SQLITE_IOERR_UNLOCK; 
31603:         storeLastErrno(pFile, tErrno);
31604:         rc = lrc;
31605:       }
31606:     } else {
31607:       int tErrno = errno;
31608:       reserved = 1;
31609:       /* someone else might have it reserved */
31610:       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
31611:       if( IS_LOCK_ERROR(lrc) ){
31612:         storeLastErrno(pFile, tErrno);
31613:         rc = lrc;
31614:       }
31615:     }
31616:   }
31617:   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
31618: 
31619: #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31620:   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31621:     rc = SQLITE_OK;
31622:     reserved=1;
31623:   }
31624: #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31625:   *pResOut = reserved;
31626:   return rc;
31627: }
31628: 
31629: /*
31630: ** Lock the file with the lock specified by parameter eFileLock - one
31631: ** of the following:
31632: **
31633: **     (1) SHARED_LOCK
31634: **     (2) RESERVED_LOCK
31635: **     (3) PENDING_LOCK
31636: **     (4) EXCLUSIVE_LOCK
31637: **
31638: ** Sometimes when requesting one lock state, additional lock states
31639: ** are inserted in between.  The locking might fail on one of the later
31640: ** transitions leaving the lock state different from what it started but
31641: ** still short of its goal.  The following chart shows the allowed
31642: ** transitions and the inserted intermediate states:
31643: **
31644: **    UNLOCKED -> SHARED
31645: **    SHARED -> RESERVED
31646: **    SHARED -> (PENDING) -> EXCLUSIVE
31647: **    RESERVED -> (PENDING) -> EXCLUSIVE
31648: **    PENDING -> EXCLUSIVE
31649: **
31650: ** flock() only really support EXCLUSIVE locks.  We track intermediate
31651: ** lock states in the sqlite3_file structure, but all locks SHARED or
31652: ** above are really EXCLUSIVE locks and exclude all other processes from
31653: ** access the file.
31654: **
31655: ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31656: ** routine to lower a locking level.
31657: */
31658: static int flockLock(sqlite3_file *id, int eFileLock) {
31659:   int rc = SQLITE_OK;
31660:   unixFile *pFile = (unixFile*)id;
31661: 
31662:   assert( pFile );
31663: 
31664:   /* if we already have a lock, it is exclusive.  
31665:   ** Just adjust level and punt on outta here. */
31666:   if (pFile->eFileLock > NO_LOCK) {
31667:     pFile->eFileLock = eFileLock;
31668:     return SQLITE_OK;
31669:   }
31670:   
31671:   /* grab an exclusive lock */
31672:   
31673:   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
31674:     int tErrno = errno;
31675:     /* didn't get, must be busy */
31676:     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
31677:     if( IS_LOCK_ERROR(rc) ){
31678:       storeLastErrno(pFile, tErrno);
31679:     }
31680:   } else {
31681:     /* got it, set the type and return ok */
31682:     pFile->eFileLock = eFileLock;
31683:   }
31684:   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
31685:            rc==SQLITE_OK ? "ok" : "failed"));
31686: #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31687:   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31688:     rc = SQLITE_BUSY;
31689:   }
31690: #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31691:   return rc;
31692: }
31693: 
31694: 
31695: /*
31696: ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31697: ** must be either NO_LOCK or SHARED_LOCK.
31698: **
31699: ** If the locking level of the file descriptor is already at or below
31700: ** the requested locking level, this routine is a no-op.
31701: */
31702: static int flockUnlock(sqlite3_file *id, int eFileLock) {
31703:   unixFile *pFile = (unixFile*)id;
31704:   
31705:   assert( pFile );
31706:   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
31707:            pFile->eFileLock, osGetpid(0)));
31708:   assert( eFileLock<=SHARED_LOCK );
31709:   
31710:   /* no-op if possible */
31711:   if( pFile->eFileLock==eFileLock ){
31712:     return SQLITE_OK;
31713:   }
31714:   
31715:   /* shared can just be set because we always have an exclusive */
31716:   if (eFileLock==SHARED_LOCK) {
31717:     pFile->eFileLock = eFileLock;
31718:     return SQLITE_OK;
31719:   }
31720:   
31721:   /* no, really, unlock. */
31722:   if( robust_flock(pFile->h, LOCK_UN) ){
31723: #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31724:     return SQLITE_OK;
31725: #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31726:     return SQLITE_IOERR_UNLOCK;
31727:   }else{
31728:     pFile->eFileLock = NO_LOCK;
31729:     return SQLITE_OK;
31730:   }
31731: }
31732: 
31733: /*
31734: ** Close a file.
31735: */
31736: static int flockClose(sqlite3_file *id) {
31737:   assert( id!=0 );
31738:   flockUnlock(id, NO_LOCK);
31739:   return closeUnixFile(id);
31740: }
31741: 
31742: #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
31743: 
31744: /******************* End of the flock lock implementation *********************
31745: ******************************************************************************/
31746: 
31747: /******************************************************************************
31748: ************************ Begin Named Semaphore Locking ************************
31749: **
31750: ** Named semaphore locking is only supported on VxWorks.
31751: **
31752: ** Semaphore locking is like dot-lock and flock in that it really only
31753: ** supports EXCLUSIVE locking.  Only a single process can read or write
31754: ** the database file at a time.  This reduces potential concurrency, but
31755: ** makes the lock implementation much easier.
31756: */
31757: #if OS_VXWORKS
31758: 
31759: /*
31760: ** This routine checks if there is a RESERVED lock held on the specified
31761: ** file by this or any other process. If such a lock is held, set *pResOut
31762: ** to a non-zero value otherwise *pResOut is set to zero.  The return value
31763: ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31764: */
31765: static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
31766:   int rc = SQLITE_OK;
31767:   int reserved = 0;
31768:   unixFile *pFile = (unixFile*)id;
31769: 
31770:   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
31771:   
31772:   assert( pFile );
31773: 
31774:   /* Check if a thread in this process holds such a lock */
31775:   if( pFile->eFileLock>SHARED_LOCK ){
31776:     reserved = 1;
31777:   }
31778:   
31779:   /* Otherwise see if some other process holds it. */
31780:   if( !reserved ){
31781:     sem_t *pSem = pFile->pInode->pSem;
31782: 
31783:     if( sem_trywait(pSem)==-1 ){
31784:       int tErrno = errno;
31785:       if( EAGAIN != tErrno ){
31786:         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
31787:         storeLastErrno(pFile, tErrno);
31788:       } else {
31789:         /* someone else has the lock when we are in NO_LOCK */
31790:         reserved = (pFile->eFileLock < SHARED_LOCK);
31791:       }
31792:     }else{
31793:       /* we could have it if we want it */
31794:       sem_post(pSem);
31795:     }
31796:   }
31797:   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
31798: 
31799:   *pResOut = reserved;
31800:   return rc;
31801: }
31802: 
31803: /*
31804: ** Lock the file with the lock specified by parameter eFileLock - one
31805: ** of the following:
31806: **
31807: **     (1) SHARED_LOCK
31808: **     (2) RESERVED_LOCK
31809: **     (3) PENDING_LOCK
31810: **     (4) EXCLUSIVE_LOCK
31811: **
31812: ** Sometimes when requesting one lock state, additional lock states
31813: ** are inserted in between.  The locking might fail on one of the later
31814: ** transitions leaving the lock state different from what it started but
31815: ** still short of its goal.  The following chart shows the allowed
31816: ** transitions and the inserted intermediate states:
31817: **
31818: **    UNLOCKED -> SHARED
31819: **    SHARED -> RESERVED
31820: **    SHARED -> (PENDING) -> EXCLUSIVE
31821: **    RESERVED -> (PENDING) -> EXCLUSIVE
31822: **    PENDING -> EXCLUSIVE
31823: **
31824: ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
31825: ** lock states in the sqlite3_file structure, but all locks SHARED or
31826: ** above are really EXCLUSIVE locks and exclude all other processes from
31827: ** access the file.
31828: **
31829: ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31830: ** routine to lower a locking level.
31831: */
31832: static int semXLock(sqlite3_file *id, int eFileLock) {
31833:   unixFile *pFile = (unixFile*)id;
31834:   sem_t *pSem = pFile->pInode->pSem;
31835:   int rc = SQLITE_OK;
31836: 
31837:   /* if we already have a lock, it is exclusive.  
31838:   ** Just adjust level and punt on outta here. */
31839:   if (pFile->eFileLock > NO_LOCK) {
31840:     pFile->eFileLock = eFileLock;
31841:     rc = SQLITE_OK;
31842:     goto sem_end_lock;
31843:   }
31844:   
31845:   /* lock semaphore now but bail out when already locked. */
31846:   if( sem_trywait(pSem)==-1 ){
31847:     rc = SQLITE_BUSY;
31848:     goto sem_end_lock;
31849:   }
31850: 
31851:   /* got it, set the type and return ok */
31852:   pFile->eFileLock = eFileLock;
31853: 
31854:  sem_end_lock:
31855:   return rc;
31856: }
31857: 
31858: /*
31859: ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31860: ** must be either NO_LOCK or SHARED_LOCK.
31861: **
31862: ** If the locking level of the file descriptor is already at or below
31863: ** the requested locking level, this routine is a no-op.
31864: */
31865: static int semXUnlock(sqlite3_file *id, int eFileLock) {
31866:   unixFile *pFile = (unixFile*)id;
31867:   sem_t *pSem = pFile->pInode->pSem;
31868: 
31869:   assert( pFile );
31870:   assert( pSem );
31871:   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
31872:            pFile->eFileLock, osGetpid(0)));
31873:   assert( eFileLock<=SHARED_LOCK );
31874:   
31875:   /* no-op if possible */
31876:   if( pFile->eFileLock==eFileLock ){
31877:     return SQLITE_OK;
31878:   }
31879:   
31880:   /* shared can just be set because we always have an exclusive */
31881:   if (eFileLock==SHARED_LOCK) {
31882:     pFile->eFileLock = eFileLock;
31883:     return SQLITE_OK;
31884:   }
31885:   
31886:   /* no, really unlock. */
31887:   if ( sem_post(pSem)==-1 ) {
31888:     int rc, tErrno = errno;
31889:     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
31890:     if( IS_LOCK_ERROR(rc) ){
31891:       storeLastErrno(pFile, tErrno);
31892:     }
31893:     return rc; 
31894:   }
31895:   pFile->eFileLock = NO_LOCK;
31896:   return SQLITE_OK;
31897: }
31898: 
31899: /*
31900:  ** Close a file.
31901:  */
31902: static int semXClose(sqlite3_file *id) {
31903:   if( id ){
31904:     unixFile *pFile = (unixFile*)id;
31905:     semXUnlock(id, NO_LOCK);
31906:     assert( pFile );
31907:     unixEnterMutex();
31908:     releaseInodeInfo(pFile);
31909:     unixLeaveMutex();
31910:     closeUnixFile(id);
31911:   }
31912:   return SQLITE_OK;
31913: }
31914: 
31915: #endif /* OS_VXWORKS */
31916: /*
31917: ** Named semaphore locking is only available on VxWorks.
31918: **
31919: *************** End of the named semaphore lock implementation ****************
31920: ******************************************************************************/
31921: 
31922: 
31923: /******************************************************************************
31924: *************************** Begin AFP Locking *********************************
31925: **
31926: ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
31927: ** on Apple Macintosh computers - both OS9 and OSX.
31928: **
31929: ** Third-party implementations of AFP are available.  But this code here
31930: ** only works on OSX.
31931: */
31932: 
31933: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31934: /*
31935: ** The afpLockingContext structure contains all afp lock specific state
31936: */
31937: typedef struct afpLockingContext afpLockingContext;
31938: struct afpLockingContext {
31939:   int reserved;
31940:   const char *dbPath;             /* Name of the open file */
31941: };
31942: 
31943: struct ByteRangeLockPB2
31944: {
31945:   unsigned long long offset;        /* offset to first byte to lock */
31946:   unsigned long long length;        /* nbr of bytes to lock */
31947:   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
31948:   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
31949:   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
31950:   int fd;                           /* file desc to assoc this lock with */
31951: };
31952: 
31953: #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
31954: 
31955: /*
31956: ** This is a utility for setting or clearing a bit-range lock on an
31957: ** AFP filesystem.
31958: ** 
31959: ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
31960: */
31961: static int afpSetLock(
31962:   const char *path,              /* Name of the file to be locked or unlocked */
31963:   unixFile *pFile,               /* Open file descriptor on path */
31964:   unsigned long long offset,     /* First byte to be locked */
31965:   unsigned long long length,     /* Number of bytes to lock */
31966:   int setLockFlag                /* True to set lock.  False to clear lock */
31967: ){
31968:   struct ByteRangeLockPB2 pb;
31969:   int err;
31970:   
31971:   pb.unLockFlag = setLockFlag ? 0 : 1;
31972:   pb.startEndFlag = 0;
31973:   pb.offset = offset;
31974:   pb.length = length; 
31975:   pb.fd = pFile->h;
31976:   
31977:   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
31978:     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
31979:     offset, length));
31980:   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
31981:   if ( err==-1 ) {
31982:     int rc;
31983:     int tErrno = errno;
31984:     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
31985:              path, tErrno, strerror(tErrno)));
31986: #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
31987:     rc = SQLITE_BUSY;
31988: #else
31989:     rc = sqliteErrorFromPosixError(tErrno,
31990:                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
31991: #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
31992:     if( IS_LOCK_ERROR(rc) ){
31993:       storeLastErrno(pFile, tErrno);
31994:     }
31995:     return rc;
31996:   } else {
31997:     return SQLITE_OK;
31998:   }
31999: }
32000: 
32001: /*
32002: ** This routine checks if there is a RESERVED lock held on the specified
32003: ** file by this or any other process. If such a lock is held, set *pResOut
32004: ** to a non-zero value otherwise *pResOut is set to zero.  The return value
32005: ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32006: */
32007: static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
32008:   int rc = SQLITE_OK;
32009:   int reserved = 0;
32010:   unixFile *pFile = (unixFile*)id;
32011:   afpLockingContext *context;
32012:   
32013:   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
32014:   
32015:   assert( pFile );
32016:   context = (afpLockingContext *) pFile->lockingContext;
32017:   if( context->reserved ){
32018:     *pResOut = 1;
32019:     return SQLITE_OK;
32020:   }
32021:   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
32022:   
32023:   /* Check if a thread in this process holds such a lock */
32024:   if( pFile->pInode->eFileLock>SHARED_LOCK ){
32025:     reserved = 1;
32026:   }
32027:   
32028:   /* Otherwise see if some other process holds it.
32029:    */
32030:   if( !reserved ){
32031:     /* lock the RESERVED byte */
32032:     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
32033:     if( SQLITE_OK==lrc ){
32034:       /* if we succeeded in taking the reserved lock, unlock it to restore
32035:       ** the original state */
32036:       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32037:     } else {
32038:       /* if we failed to get the lock then someone else must have it */
32039:       reserved = 1;
32040:     }
32041:     if( IS_LOCK_ERROR(lrc) ){
32042:       rc=lrc;
32043:     }
32044:   }
32045:   
32046:   unixLeaveMutex();
32047:   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
32048:   
32049:   *pResOut = reserved;
32050:   return rc;
32051: }
32052: 
32053: /*
32054: ** Lock the file with the lock specified by parameter eFileLock - one
32055: ** of the following:
32056: **
32057: **     (1) SHARED_LOCK
32058: **     (2) RESERVED_LOCK
32059: **     (3) PENDING_LOCK
32060: **     (4) EXCLUSIVE_LOCK
32061: **
32062: ** Sometimes when requesting one lock state, additional lock states
32063: ** are inserted in between.  The locking might fail on one of the later
32064: ** transitions leaving the lock state different from what it started but
32065: ** still short of its goal.  The following chart shows the allowed
32066: ** transitions and the inserted intermediate states:
32067: **
32068: **    UNLOCKED -> SHARED
32069: **    SHARED -> RESERVED
32070: **    SHARED -> (PENDING) -> EXCLUSIVE
32071: **    RESERVED -> (PENDING) -> EXCLUSIVE
32072: **    PENDING -> EXCLUSIVE
32073: **
32074: ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32075: ** routine to lower a locking level.
32076: */
32077: static int afpLock(sqlite3_file *id, int eFileLock){
32078:   int rc = SQLITE_OK;
32079:   unixFile *pFile = (unixFile*)id;
32080:   unixInodeInfo *pInode = pFile->pInode;
32081:   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32082:   
32083:   assert( pFile );
32084:   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
32085:            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
32086:            azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
32087: 
32088:   /* If there is already a lock of this type or more restrictive on the
32089:   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
32090:   ** unixEnterMutex() hasn't been called yet.
32091:   */
32092:   if( pFile->eFileLock>=eFileLock ){
32093:     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
32094:            azFileLock(eFileLock)));
32095:     return SQLITE_OK;
32096:   }
32097: 
32098:   /* Make sure the locking sequence is correct
32099:   **  (1) We never move from unlocked to anything higher than shared lock.
32100:   **  (2) SQLite never explicitly requests a pendig lock.
32101:   **  (3) A shared lock is always held when a reserve lock is requested.
32102:   */
32103:   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
32104:   assert( eFileLock!=PENDING_LOCK );
32105:   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
32106:   
32107:   /* This mutex is needed because pFile->pInode is shared across threads
32108:   */
32109:   unixEnterMutex();
32110:   pInode = pFile->pInode;
32111: 
32112:   /* If some thread using this PID has a lock via a different unixFile*
32113:   ** handle that precludes the requested lock, return BUSY.
32114:   */
32115:   if( (pFile->eFileLock!=pInode->eFileLock && 
32116:        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
32117:      ){
32118:     rc = SQLITE_BUSY;
32119:     goto afp_end_lock;
32120:   }
32121:   
32122:   /* If a SHARED lock is requested, and some thread using this PID already
32123:   ** has a SHARED or RESERVED lock, then increment reference counts and
32124:   ** return SQLITE_OK.
32125:   */
32126:   if( eFileLock==SHARED_LOCK && 
32127:      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
32128:     assert( eFileLock==SHARED_LOCK );
32129:     assert( pFile->eFileLock==0 );
32130:     assert( pInode->nShared>0 );
32131:     pFile->eFileLock = SHARED_LOCK;
32132:     pInode->nShared++;
32133:     pInode->nLock++;
32134:     goto afp_end_lock;
32135:   }
32136:     
32137:   /* A PENDING lock is needed before acquiring a SHARED lock and before
32138:   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
32139:   ** be released.
32140:   */
32141:   if( eFileLock==SHARED_LOCK 
32142:       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
32143:   ){
32144:     int failed;
32145:     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
32146:     if (failed) {
32147:       rc = failed;
32148:       goto afp_end_lock;
32149:     }
32150:   }
32151:   
32152:   /* If control gets to this point, then actually go ahead and make
32153:   ** operating system calls for the specified lock.
32154:   */
32155:   if( eFileLock==SHARED_LOCK ){
32156:     int lrc1, lrc2, lrc1Errno = 0;
32157:     long lk, mask;
32158:     
32159:     assert( pInode->nShared==0 );
32160:     assert( pInode->eFileLock==0 );
32161:         
32162:     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
32163:     /* Now get the read-lock SHARED_LOCK */
32164:     /* note that the quality of the randomness doesn't matter that much */
32165:     lk = random(); 
32166:     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
32167:     lrc1 = afpSetLock(context->dbPath, pFile, 
32168:           SHARED_FIRST+pInode->sharedByte, 1, 1);
32169:     if( IS_LOCK_ERROR(lrc1) ){
32170:       lrc1Errno = pFile->lastErrno;
32171:     }
32172:     /* Drop the temporary PENDING lock */
32173:     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32174:     
32175:     if( IS_LOCK_ERROR(lrc1) ) {
32176:       storeLastErrno(pFile, lrc1Errno);
32177:       rc = lrc1;
32178:       goto afp_end_lock;
32179:     } else if( IS_LOCK_ERROR(lrc2) ){
32180:       rc = lrc2;
32181:       goto afp_end_lock;
32182:     } else if( lrc1 != SQLITE_OK ) {
32183:       rc = lrc1;
32184:     } else {
32185:       pFile->eFileLock = SHARED_LOCK;
32186:       pInode->nLock++;
32187:       pInode->nShared = 1;
32188:     }
32189:   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
32190:     /* We are trying for an exclusive lock but another thread in this
32191:      ** same process is still holding a shared lock. */
32192:     rc = SQLITE_BUSY;
32193:   }else{
32194:     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
32195:     ** assumed that there is a SHARED or greater lock on the file
32196:     ** already.
32197:     */
32198:     int failed = 0;
32199:     assert( 0!=pFile->eFileLock );
32200:     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
32201:         /* Acquire a RESERVED lock */
32202:         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
32203:       if( !failed ){
32204:         context->reserved = 1;
32205:       }
32206:     }
32207:     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
32208:       /* Acquire an EXCLUSIVE lock */
32209:         
32210:       /* Remove the shared lock before trying the range.  we'll need to 
32211:       ** reestablish the shared lock if we can't get the  afpUnlock
32212:       */
32213:       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
32214:                          pInode->sharedByte, 1, 0)) ){
32215:         int failed2 = SQLITE_OK;
32216:         /* now attemmpt to get the exclusive lock range */
32217:         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
32218:                                SHARED_SIZE, 1);
32219:         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
32220:                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
32221:           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
32222:           ** a critical I/O error
32223:           */
32224:           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
32225:                SQLITE_IOERR_LOCK;
32226:           goto afp_end_lock;
32227:         } 
32228:       }else{
32229:         rc = failed; 
32230:       }
32231:     }
32232:     if( failed ){
32233:       rc = failed;
32234:     }
32235:   }
32236:   
32237:   if( rc==SQLITE_OK ){
32238:     pFile->eFileLock = eFileLock;
32239:     pInode->eFileLock = eFileLock;
32240:   }else if( eFileLock==EXCLUSIVE_LOCK ){
32241:     pFile->eFileLock = PENDING_LOCK;
32242:     pInode->eFileLock = PENDING_LOCK;
32243:   }
32244:   
32245: afp_end_lock:
32246:   unixLeaveMutex();
32247:   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
32248:          rc==SQLITE_OK ? "ok" : "failed"));
32249:   return rc;
32250: }
32251: 
32252: /*
32253: ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32254: ** must be either NO_LOCK or SHARED_LOCK.
32255: **
32256: ** If the locking level of the file descriptor is already at or below
32257: ** the requested locking level, this routine is a no-op.
32258: */
32259: static int afpUnlock(sqlite3_file *id, int eFileLock) {
32260:   int rc = SQLITE_OK;
32261:   unixFile *pFile = (unixFile*)id;
32262:   unixInodeInfo *pInode;
32263:   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32264:   int skipShared = 0;
32265: #ifdef SQLITE_TEST
32266:   int h = pFile->h;
32267: #endif
32268: 
32269:   assert( pFile );
32270:   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
32271:            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32272:            osGetpid(0)));
32273: 
32274:   assert( eFileLock<=SHARED_LOCK );
32275:   if( pFile->eFileLock<=eFileLock ){
32276:     return SQLITE_OK;
32277:   }
32278:   unixEnterMutex();
32279:   pInode = pFile->pInode;
32280:   assert( pInode->nShared!=0 );
32281:   if( pFile->eFileLock>SHARED_LOCK ){
32282:     assert( pInode->eFileLock==pFile->eFileLock );
32283:     SimulateIOErrorBenign(1);
32284:     SimulateIOError( h=(-1) )
32285:     SimulateIOErrorBenign(0);
32286:     
32287: #ifdef SQLITE_DEBUG
32288:     /* When reducing a lock such that other processes can start
32289:     ** reading the database file again, make sure that the
32290:     ** transaction counter was updated if any part of the database
32291:     ** file changed.  If the transaction counter is not updated,
32292:     ** other connections to the same file might not realize that
32293:     ** the file has changed and hence might not know to flush their
32294:     ** cache.  The use of a stale cache can lead to database corruption.
32295:     */
32296:     assert( pFile->inNormalWrite==0
32297:            || pFile->dbUpdate==0
32298:            || pFile->transCntrChng==1 );
32299:     pFile->inNormalWrite = 0;
32300: #endif
32301:     
32302:     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
32303:       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
32304:       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
32305:         /* only re-establish the shared lock if necessary */
32306:         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32307:         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
32308:       } else {
32309:         skipShared = 1;
32310:       }
32311:     }
32312:     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
32313:       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32314:     } 
32315:     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
32316:       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32317:       if( !rc ){ 
32318:         context->reserved = 0; 
32319:       }
32320:     }
32321:     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
32322:       pInode->eFileLock = SHARED_LOCK;
32323:     }
32324:   }
32325:   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
32326: 
32327:     /* Decrement the shared lock counter.  Release the lock using an
32328:     ** OS call only when all threads in this same process have released
32329:     ** the lock.
32330:     */
32331:     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32332:     pInode->nShared--;
32333:     if( pInode->nShared==0 ){
32334:       SimulateIOErrorBenign(1);
32335:       SimulateIOError( h=(-1) )
32336:       SimulateIOErrorBenign(0);
32337:       if( !skipShared ){
32338:         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
32339:       }
32340:       if( !rc ){
32341:         pInode->eFileLock = NO_LOCK;
32342:         pFile->eFileLock = NO_LOCK;
32343:       }
32344:     }
32345:     if( rc==SQLITE_OK ){
32346:       pInode->nLock--;
32347:       assert( pInode->nLock>=0 );
32348:       if( pInode->nLock==0 ){
32349:         closePendingFds(pFile);
32350:       }
32351:     }
32352:   }
32353:   
32354:   unixLeaveMutex();
32355:   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32356:   return rc;
32357: }
32358: 
32359: /*
32360: ** Close a file & cleanup AFP specific locking context 
32361: */
32362: static int afpClose(sqlite3_file *id) {
32363:   int rc = SQLITE_OK;
32364:   unixFile *pFile = (unixFile*)id;
32365:   assert( id!=0 );
32366:   afpUnlock(id, NO_LOCK);
32367:   unixEnterMutex();
32368:   if( pFile->pInode && pFile->pInode->nLock ){
32369:     /* If there are outstanding locks, do not actually close the file just
32370:     ** yet because that would clear those locks.  Instead, add the file
32371:     ** descriptor to pInode->aPending.  It will be automatically closed when
32372:     ** the last lock is cleared.
32373:     */
32374:     setPendingFd(pFile);
32375:   }
32376:   releaseInodeInfo(pFile);
32377:   sqlite3_free(pFile->lockingContext);
32378:   rc = closeUnixFile(id);
32379:   unixLeaveMutex();
32380:   return rc;
32381: }
32382: 
32383: #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32384: /*
32385: ** The code above is the AFP lock implementation.  The code is specific
32386: ** to MacOSX and does not work on other unix platforms.  No alternative
32387: ** is available.  If you don't compile for a mac, then the "unix-afp"
32388: ** VFS is not available.
32389: **
32390: ********************* End of the AFP lock implementation **********************
32391: ******************************************************************************/
32392: 
32393: /******************************************************************************
32394: *************************** Begin NFS Locking ********************************/
32395: 
32396: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32397: /*
32398:  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32399:  ** must be either NO_LOCK or SHARED_LOCK.
32400:  **
32401:  ** If the locking level of the file descriptor is already at or below
32402:  ** the requested locking level, this routine is a no-op.
32403:  */
32404: static int nfsUnlock(sqlite3_file *id, int eFileLock){
32405:   return posixUnlock(id, eFileLock, 1);
32406: }
32407: 
32408: #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32409: /*
32410: ** The code above is the NFS lock implementation.  The code is specific
32411: ** to MacOSX and does not work on other unix platforms.  No alternative
32412: ** is available.  
32413: **
32414: ********************* End of the NFS lock implementation **********************
32415: ******************************************************************************/
32416: 
32417: /******************************************************************************
32418: **************** Non-locking sqlite3_file methods *****************************
32419: **
32420: ** The next division contains implementations for all methods of the 
32421: ** sqlite3_file object other than the locking methods.  The locking
32422: ** methods were defined in divisions above (one locking method per
32423: ** division).  Those methods that are common to all locking modes
32424: ** are gather together into this division.
32425: */
32426: 
32427: /*
32428: ** Seek to the offset passed as the second argument, then read cnt 
32429: ** bytes into pBuf. Return the number of bytes actually read.
32430: **
32431: ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
32432: ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
32433: ** one system to another.  Since SQLite does not define USE_PREAD
32434: ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
32435: ** See tickets #2741 and #2681.
32436: **
32437: ** To avoid stomping the errno value on a failed read the lastErrno value
32438: ** is set before returning.
32439: */
32440: static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
32441:   int got;
32442:   int prior = 0;
32443: #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
32444:   i64 newOffset;
32445: #endif
32446:   TIMER_START;
32447:   assert( cnt==(cnt&0x1ffff) );
32448:   assert( id->h>2 );
32449:   do{
32450: #if defined(USE_PREAD)
32451:     got = osPread(id->h, pBuf, cnt, offset);
32452:     SimulateIOError( got = -1 );
32453: #elif defined(USE_PREAD64)
32454:     got = osPread64(id->h, pBuf, cnt, offset);
32455:     SimulateIOError( got = -1 );
32456: #else
32457:     newOffset = lseek(id->h, offset, SEEK_SET);
32458:     SimulateIOError( newOffset = -1 );
32459:     if( newOffset<0 ){
32460:       storeLastErrno((unixFile*)id, errno);
32461:       return -1;
32462:     }
32463:     got = osRead(id->h, pBuf, cnt);
32464: #endif
32465:     if( got==cnt ) break;
32466:     if( got<0 ){
32467:       if( errno==EINTR ){ got = 1; continue; }
32468:       prior = 0;
32469:       storeLastErrno((unixFile*)id,  errno);
32470:       break;
32471:     }else if( got>0 ){
32472:       cnt -= got;
32473:       offset += got;
32474:       prior += got;
32475:       pBuf = (void*)(got + (char*)pBuf);
32476:     }
32477:   }while( got>0 );
32478:   TIMER_END;
32479:   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
32480:             id->h, got+prior, offset-prior, TIMER_ELAPSED));
32481:   return got+prior;
32482: }
32483: 
32484: /*
32485: ** Read data from a file into a buffer.  Return SQLITE_OK if all
32486: ** bytes were read successfully and SQLITE_IOERR if anything goes
32487: ** wrong.
32488: */
32489: static int unixRead(
32490:   sqlite3_file *id, 
32491:   void *pBuf, 
32492:   int amt,
32493:   sqlite3_int64 offset
32494: ){
32495:   unixFile *pFile = (unixFile *)id;
32496:   int got;
32497:   assert( id );
32498:   assert( offset>=0 );
32499:   assert( amt>0 );
32500: 
32501:   /* If this is a database file (not a journal, master-journal or temp
32502:   ** file), the bytes in the locking range should never be read or written. */
32503: #if 0
32504:   assert( pFile->pUnused==0
32505:        || offset>=PENDING_BYTE+512
32506:        || offset+amt<=PENDING_BYTE 
32507:   );
32508: #endif
32509: 
32510: #if SQLITE_MAX_MMAP_SIZE>0
32511:   /* Deal with as much of this read request as possible by transfering
32512:   ** data from the memory mapping using memcpy().  */
32513:   if( offset<pFile->mmapSize ){
32514:     if( offset+amt <= pFile->mmapSize ){
32515:       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32516:       return SQLITE_OK;
32517:     }else{
32518:       int nCopy = pFile->mmapSize - offset;
32519:       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32520:       pBuf = &((u8 *)pBuf)[nCopy];
32521:       amt -= nCopy;
32522:       offset += nCopy;
32523:     }
32524:   }
32525: #endif
32526: 
32527:   got = seekAndRead(pFile, offset, pBuf, amt);
32528:   if( got==amt ){
32529:     return SQLITE_OK;
32530:   }else if( got<0 ){
32531:     /* lastErrno set by seekAndRead */
32532:     return SQLITE_IOERR_READ;
32533:   }else{
32534:     storeLastErrno(pFile, 0);   /* not a system error */
32535:     /* Unread parts of the buffer must be zero-filled */
32536:     memset(&((char*)pBuf)[got], 0, amt-got);
32537:     return SQLITE_IOERR_SHORT_READ;
32538:   }
32539: }
32540: 
32541: /*
32542: ** Attempt to seek the file-descriptor passed as the first argument to
32543: ** absolute offset iOff, then attempt to write nBuf bytes of data from
32544: ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
32545: ** return the actual number of bytes written (which may be less than
32546: ** nBuf).
32547: */
32548: static int seekAndWriteFd(
32549:   int fd,                         /* File descriptor to write to */
32550:   i64 iOff,                       /* File offset to begin writing at */
32551:   const void *pBuf,               /* Copy data from this buffer to the file */
32552:   int nBuf,                       /* Size of buffer pBuf in bytes */
32553:   int *piErrno                    /* OUT: Error number if error occurs */
32554: ){
32555:   int rc = 0;                     /* Value returned by system call */
32556: 
32557:   assert( nBuf==(nBuf&0x1ffff) );
32558:   assert( fd>2 );
32559:   assert( piErrno!=0 );
32560:   nBuf &= 0x1ffff;
32561:   TIMER_START;
32562: 
32563: #if defined(USE_PREAD)
32564:   do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
32565: #elif defined(USE_PREAD64)
32566:   do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
32567: #else
32568:   do{
32569:     i64 iSeek = lseek(fd, iOff, SEEK_SET);
32570:     SimulateIOError( iSeek = -1 );
32571:     if( iSeek<0 ){
32572:       rc = -1;
32573:       break;
32574:     }
32575:     rc = osWrite(fd, pBuf, nBuf);
32576:   }while( rc<0 && errno==EINTR );
32577: #endif
32578: 
32579:   TIMER_END;
32580:   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
32581: 
32582:   if( rc<0 ) *piErrno = errno;
32583:   return rc;
32584: }
32585: 
32586: 
32587: /*
32588: ** Seek to the offset in id->offset then read cnt bytes into pBuf.
32589: ** Return the number of bytes actually read.  Update the offset.
32590: **
32591: ** To avoid stomping the errno value on a failed write the lastErrno value
32592: ** is set before returning.
32593: */
32594: static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
32595:   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
32596: }
32597: 
32598: 
32599: /*
32600: ** Write data from a buffer into a file.  Return SQLITE_OK on success
32601: ** or some other error code on failure.
32602: */
32603: static int unixWrite(
32604:   sqlite3_file *id, 
32605:   const void *pBuf, 
32606:   int amt,
32607:   sqlite3_int64 offset 
32608: ){
32609:   unixFile *pFile = (unixFile*)id;
32610:   int wrote = 0;
32611:   assert( id );
32612:   assert( amt>0 );
32613: 
32614:   /* If this is a database file (not a journal, master-journal or temp
32615:   ** file), the bytes in the locking range should never be read or written. */
32616: #if 0
32617:   assert( pFile->pUnused==0
32618:        || offset>=PENDING_BYTE+512
32619:        || offset+amt<=PENDING_BYTE 
32620:   );
32621: #endif
32622: 
32623: #ifdef SQLITE_DEBUG
32624:   /* If we are doing a normal write to a database file (as opposed to
32625:   ** doing a hot-journal rollback or a write to some file other than a
32626:   ** normal database file) then record the fact that the database
32627:   ** has changed.  If the transaction counter is modified, record that
32628:   ** fact too.
32629:   */
32630:   if( pFile->inNormalWrite ){
32631:     pFile->dbUpdate = 1;  /* The database has been modified */
32632:     if( offset<=24 && offset+amt>=27 ){
32633:       int rc;
32634:       char oldCntr[4];
32635:       SimulateIOErrorBenign(1);
32636:       rc = seekAndRead(pFile, 24, oldCntr, 4);
32637:       SimulateIOErrorBenign(0);
32638:       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
32639:         pFile->transCntrChng = 1;  /* The transaction counter has changed */
32640:       }
32641:     }
32642:   }
32643: #endif
32644: 
32645: #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
32646:   /* Deal with as much of this write request as possible by transfering
32647:   ** data from the memory mapping using memcpy().  */
32648:   if( offset<pFile->mmapSize ){
32649:     if( offset+amt <= pFile->mmapSize ){
32650:       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32651:       return SQLITE_OK;
32652:     }else{
32653:       int nCopy = pFile->mmapSize - offset;
32654:       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32655:       pBuf = &((u8 *)pBuf)[nCopy];
32656:       amt -= nCopy;
32657:       offset += nCopy;
32658:     }
32659:   }
32660: #endif
32661:  
32662:   while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
32663:     amt -= wrote;
32664:     offset += wrote;
32665:     pBuf = &((char*)pBuf)[wrote];
32666:   }
32667:   SimulateIOError(( wrote=(-1), amt=1 ));
32668:   SimulateDiskfullError(( wrote=0, amt=1 ));
32669: 
32670:   if( amt>wrote ){
32671:     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
32672:       /* lastErrno set by seekAndWrite */
32673:       return SQLITE_IOERR_WRITE;
32674:     }else{
32675:       storeLastErrno(pFile, 0); /* not a system error */
32676:       return SQLITE_FULL;
32677:     }
32678:   }
32679: 
32680:   return SQLITE_OK;
32681: }
32682: 
32683: #ifdef SQLITE_TEST
32684: /*
32685: ** Count the number of fullsyncs and normal syncs.  This is used to test
32686: ** that syncs and fullsyncs are occurring at the right times.
32687: */
32688: SQLITE_API int sqlite3_sync_count = 0;
32689: SQLITE_API int sqlite3_fullsync_count = 0;
32690: #endif
32691: 
32692: /*
32693: ** We do not trust systems to provide a working fdatasync().  Some do.
32694: ** Others do no.  To be safe, we will stick with the (slightly slower)
32695: ** fsync(). If you know that your system does support fdatasync() correctly,
32696: ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
32697: */
32698: #if !defined(fdatasync) && !HAVE_FDATASYNC
32699: # define fdatasync fsync
32700: #endif
32701: 
32702: /*
32703: ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
32704: ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
32705: ** only available on Mac OS X.  But that could change.
32706: */
32707: #ifdef F_FULLFSYNC
32708: # define HAVE_FULLFSYNC 1
32709: #else
32710: # define HAVE_FULLFSYNC 0
32711: #endif
32712: 
32713: 
32714: /*
32715: ** The fsync() system call does not work as advertised on many
32716: ** unix systems.  The following procedure is an attempt to make
32717: ** it work better.
32718: **
32719: ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
32720: ** for testing when we want to run through the test suite quickly.
32721: ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
32722: ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
32723: ** or power failure will likely corrupt the database file.
32724: **
32725: ** SQLite sets the dataOnly flag if the size of the file is unchanged.
32726: ** The idea behind dataOnly is that it should only write the file content
32727: ** to disk, not the inode.  We only set dataOnly if the file size is 
32728: ** unchanged since the file size is part of the inode.  However, 
32729: ** Ted Ts'o tells us that fdatasync() will also write the inode if the
32730: ** file size has changed.  The only real difference between fdatasync()
32731: ** and fsync(), Ted tells us, is that fdatasync() will not flush the
32732: ** inode if the mtime or owner or other inode attributes have changed.
32733: ** We only care about the file size, not the other file attributes, so
32734: ** as far as SQLite is concerned, an fdatasync() is always adequate.
32735: ** So, we always use fdatasync() if it is available, regardless of
32736: ** the value of the dataOnly flag.
32737: */
32738: static int full_fsync(int fd, int fullSync, int dataOnly){
32739:   int rc;
32740: 
32741:   /* The following "ifdef/elif/else/" block has the same structure as
32742:   ** the one below. It is replicated here solely to avoid cluttering 
32743:   ** up the real code with the UNUSED_PARAMETER() macros.
32744:   */
32745: #ifdef SQLITE_NO_SYNC
32746:   UNUSED_PARAMETER(fd);
32747:   UNUSED_PARAMETER(fullSync);
32748:   UNUSED_PARAMETER(dataOnly);
32749: #elif HAVE_FULLFSYNC
32750:   UNUSED_PARAMETER(dataOnly);
32751: #else
32752:   UNUSED_PARAMETER(fullSync);
32753:   UNUSED_PARAMETER(dataOnly);
32754: #endif
32755: 
32756:   /* Record the number of times that we do a normal fsync() and 
32757:   ** FULLSYNC.  This is used during testing to verify that this procedure
32758:   ** gets called with the correct arguments.
32759:   */
32760: #ifdef SQLITE_TEST
32761:   if( fullSync ) sqlite3_fullsync_count++;
32762:   sqlite3_sync_count++;
32763: #endif
32764: 
32765:   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32766:   ** no-op.  But go ahead and call fstat() to validate the file
32767:   ** descriptor as we need a method to provoke a failure during
32768:   ** coverate testing.
32769:   */
32770: #ifdef SQLITE_NO_SYNC
32771:   {
32772:     struct stat buf;
32773:     rc = osFstat(fd, &buf);
32774:   }
32775: #elif HAVE_FULLFSYNC
32776:   if( fullSync ){
32777:     rc = osFcntl(fd, F_FULLFSYNC, 0);
32778:   }else{
32779:     rc = 1;
32780:   }
32781:   /* If the FULLFSYNC failed, fall back to attempting an fsync().
32782:   ** It shouldn't be possible for fullfsync to fail on the local 
32783:   ** file system (on OSX), so failure indicates that FULLFSYNC
32784:   ** isn't supported for this file system. So, attempt an fsync 
32785:   ** and (for now) ignore the overhead of a superfluous fcntl call.  
32786:   ** It'd be better to detect fullfsync support once and avoid 
32787:   ** the fcntl call every time sync is called.
32788:   */
32789:   if( rc ) rc = fsync(fd);
32790: 
32791: #elif defined(__APPLE__)
32792:   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
32793:   ** so currently we default to the macro that redefines fdatasync to fsync
32794:   */
32795:   rc = fsync(fd);
32796: #else 
32797:   rc = fdatasync(fd);
32798: #if OS_VXWORKS
32799:   if( rc==-1 && errno==ENOTSUP ){
32800:     rc = fsync(fd);
32801:   }
32802: #endif /* OS_VXWORKS */
32803: #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
32804: 
32805:   if( OS_VXWORKS && rc!= -1 ){
32806:     rc = 0;
32807:   }
32808:   return rc;
32809: }
32810: 
32811: /*
32812: ** Open a file descriptor to the directory containing file zFilename.
32813: ** If successful, *pFd is set to the opened file descriptor and
32814: ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
32815: ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
32816: ** value.
32817: **
32818: ** The directory file descriptor is used for only one thing - to
32819: ** fsync() a directory to make sure file creation and deletion events
32820: ** are flushed to disk.  Such fsyncs are not needed on newer
32821: ** journaling filesystems, but are required on older filesystems.
32822: **
32823: ** This routine can be overridden using the xSetSysCall interface.
32824: ** The ability to override this routine was added in support of the
32825: ** chromium sandbox.  Opening a directory is a security risk (we are
32826: ** told) so making it overrideable allows the chromium sandbox to
32827: ** replace this routine with a harmless no-op.  To make this routine
32828: ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
32829: ** *pFd set to a negative number.
32830: **
32831: ** If SQLITE_OK is returned, the caller is responsible for closing
32832: ** the file descriptor *pFd using close().
32833: */
32834: static int openDirectory(const char *zFilename, int *pFd){
32835:   int ii;
32836:   int fd = -1;
32837:   char zDirname[MAX_PATHNAME+1];
32838: 
32839:   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
32840:   for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
32841:   if( ii>0 ){
32842:     zDirname[ii] = '\0';
32843:   }else{
32844:     if( zDirname[0]!='/' ) zDirname[0] = '.';
32845:     zDirname[1] = 0;
32846:   }
32847:   fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
32848:   if( fd>=0 ){
32849:     OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
32850:   }
32851:   *pFd = fd;
32852:   if( fd>=0 ) return SQLITE_OK;
32853:   return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
32854: }
32855: 
32856: /*
32857: ** Make sure all writes to a particular file are committed to disk.
32858: **
32859: ** If dataOnly==0 then both the file itself and its metadata (file
32860: ** size, access time, etc) are synced.  If dataOnly!=0 then only the
32861: ** file data is synced.
32862: **
32863: ** Under Unix, also make sure that the directory entry for the file
32864: ** has been created by fsync-ing the directory that contains the file.
32865: ** If we do not do this and we encounter a power failure, the directory
32866: ** entry for the journal might not exist after we reboot.  The next
32867: ** SQLite to access the file will not know that the journal exists (because
32868: ** the directory entry for the journal was never created) and the transaction
32869: ** will not roll back - possibly leading to database corruption.
32870: */
32871: static int unixSync(sqlite3_file *id, int flags){
32872:   int rc;
32873:   unixFile *pFile = (unixFile*)id;
32874: 
32875:   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
32876:   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
32877: 
32878:   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32879:   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32880:       || (flags&0x0F)==SQLITE_SYNC_FULL
32881:   );
32882: 
32883:   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32884:   ** line is to test that doing so does not cause any problems.
32885:   */
32886:   SimulateDiskfullError( return SQLITE_FULL );
32887: 
32888:   assert( pFile );
32889:   OSTRACE(("SYNC    %-3d\n", pFile->h));
32890:   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
32891:   SimulateIOError( rc=1 );
32892:   if( rc ){
32893:     storeLastErrno(pFile, errno);
32894:     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
32895:   }
32896: 
32897:   /* Also fsync the directory containing the file if the DIRSYNC flag
32898:   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
32899:   ** are unable to fsync a directory, so ignore errors on the fsync.
32900:   */
32901:   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
32902:     int dirfd;
32903:     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
32904:             HAVE_FULLFSYNC, isFullsync));
32905:     rc = osOpenDirectory(pFile->zPath, &dirfd);
32906:     if( rc==SQLITE_OK ){
32907:       full_fsync(dirfd, 0, 0);
32908:       robust_close(pFile, dirfd, __LINE__);
32909:     }else{
32910:       assert( rc==SQLITE_CANTOPEN );
32911:       rc = SQLITE_OK;
32912:     }
32913:     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
32914:   }
32915:   return rc;
32916: }
32917: 
32918: /*
32919: ** Truncate an open file to a specified size
32920: */
32921: static int unixTruncate(sqlite3_file *id, i64 nByte){
32922:   unixFile *pFile = (unixFile *)id;
32923:   int rc;
32924:   assert( pFile );
32925:   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
32926: 
32927:   /* If the user has configured a chunk-size for this file, truncate the
32928:   ** file so that it consists of an integer number of chunks (i.e. the
32929:   ** actual file size after the operation may be larger than the requested
32930:   ** size).
32931:   */
32932:   if( pFile->szChunk>0 ){
32933:     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32934:   }
32935: 
32936:   rc = robust_ftruncate(pFile->h, nByte);
32937:   if( rc ){
32938:     storeLastErrno(pFile, errno);
32939:     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
32940:   }else{
32941: #ifdef SQLITE_DEBUG
32942:     /* If we are doing a normal write to a database file (as opposed to
32943:     ** doing a hot-journal rollback or a write to some file other than a
32944:     ** normal database file) and we truncate the file to zero length,
32945:     ** that effectively updates the change counter.  This might happen
32946:     ** when restoring a database using the backup API from a zero-length
32947:     ** source.
32948:     */
32949:     if( pFile->inNormalWrite && nByte==0 ){
32950:       pFile->transCntrChng = 1;
32951:     }
32952: #endif
32953: 
32954: #if SQLITE_MAX_MMAP_SIZE>0
32955:     /* If the file was just truncated to a size smaller than the currently
32956:     ** mapped region, reduce the effective mapping size as well. SQLite will
32957:     ** use read() and write() to access data beyond this point from now on.  
32958:     */
32959:     if( nByte<pFile->mmapSize ){
32960:       pFile->mmapSize = nByte;
32961:     }
32962: #endif
32963: 
32964:     return SQLITE_OK;
32965:   }
32966: }
32967: 
32968: /*
32969: ** Determine the current size of a file in bytes
32970: */
32971: static int unixFileSize(sqlite3_file *id, i64 *pSize){
32972:   int rc;
32973:   struct stat buf;
32974:   assert( id );
32975:   rc = osFstat(((unixFile*)id)->h, &buf);
32976:   SimulateIOError( rc=1 );
32977:   if( rc!=0 ){
32978:     storeLastErrno((unixFile*)id, errno);
32979:     return SQLITE_IOERR_FSTAT;
32980:   }
32981:   *pSize = buf.st_size;
32982: 
32983:   /* When opening a zero-size database, the findInodeInfo() procedure
32984:   ** writes a single byte into that file in order to work around a bug
32985:   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
32986:   ** layers, we need to report this file size as zero even though it is
32987:   ** really 1.   Ticket #3260.
32988:   */
32989:   if( *pSize==1 ) *pSize = 0;
32990: 
32991: 
32992:   return SQLITE_OK;
32993: }
32994: 
32995: #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32996: /*
32997: ** Handler for proxy-locking file-control verbs.  Defined below in the
32998: ** proxying locking division.
32999: */
33000: static int proxyFileControl(sqlite3_file*,int,void*);
33001: #endif
33002: 
33003: /* 
33004: ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
33005: ** file-control operation.  Enlarge the database to nBytes in size
33006: ** (rounded up to the next chunk-size).  If the database is already
33007: ** nBytes or larger, this routine is a no-op.
33008: */
33009: static int fcntlSizeHint(unixFile *pFile, i64 nByte){
33010:   if( pFile->szChunk>0 ){
33011:     i64 nSize;                    /* Required file size */
33012:     struct stat buf;              /* Used to hold return values of fstat() */
33013:    
33014:     if( osFstat(pFile->h, &buf) ){
33015:       return SQLITE_IOERR_FSTAT;
33016:     }
33017: 
33018:     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
33019:     if( nSize>(i64)buf.st_size ){
33020: 
33021: #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
33022:       /* The code below is handling the return value of osFallocate() 
33023:       ** correctly. posix_fallocate() is defined to "returns zero on success, 
33024:       ** or an error number on  failure". See the manpage for details. */
33025:       int err;
33026:       do{
33027:         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
33028:       }while( err==EINTR );
33029:       if( err ) return SQLITE_IOERR_WRITE;
33030: #else
33031:       /* If the OS does not have posix_fallocate(), fake it. Write a 
33032:       ** single byte to the last byte in each block that falls entirely
33033:       ** within the extended region. Then, if required, a single byte
33034:       ** at offset (nSize-1), to set the size of the file correctly.
33035:       ** This is a similar technique to that used by glibc on systems
33036:       ** that do not have a real fallocate() call.
33037:       */
33038:       int nBlk = buf.st_blksize;  /* File-system block size */
33039:       int nWrite = 0;             /* Number of bytes written by seekAndWrite */
33040:       i64 iWrite;                 /* Next offset to write to */
33041: 
33042:       iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
33043:       assert( iWrite>=buf.st_size );
33044:       assert( ((iWrite+1)%nBlk)==0 );
33045:       for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
33046:         if( iWrite>=nSize ) iWrite = nSize - 1;
33047:         nWrite = seekAndWrite(pFile, iWrite, "", 1);
33048:         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
33049:       }
33050: #endif
33051:     }
33052:   }
33053: 
33054: #if SQLITE_MAX_MMAP_SIZE>0
33055:   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
33056:     int rc;
33057:     if( pFile->szChunk<=0 ){
33058:       if( robust_ftruncate(pFile->h, nByte) ){
33059:         storeLastErrno(pFile, errno);
33060:         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
33061:       }
33062:     }
33063: 
33064:     rc = unixMapfile(pFile, nByte);
33065:     return rc;
33066:   }
33067: #endif
33068: 
33069:   return SQLITE_OK;
33070: }
33071: 
33072: /*
33073: ** If *pArg is initially negative then this is a query.  Set *pArg to
33074: ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33075: **
33076: ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33077: */
33078: static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
33079:   if( *pArg<0 ){
33080:     *pArg = (pFile->ctrlFlags & mask)!=0;
33081:   }else if( (*pArg)==0 ){
33082:     pFile->ctrlFlags &= ~mask;
33083:   }else{
33084:     pFile->ctrlFlags |= mask;
33085:   }
33086: }
33087: 
33088: /* Forward declaration */
33089: static int unixGetTempname(int nBuf, char *zBuf);
33090: 
33091: /*
33092: ** Information and control of an open file handle.
33093: */
33094: static int unixFileControl(sqlite3_file *id, int op, void *pArg){
33095:   unixFile *pFile = (unixFile*)id;
33096:   switch( op ){
33097:     case SQLITE_FCNTL_LOCKSTATE: {
33098:       *(int*)pArg = pFile->eFileLock;
33099:       return SQLITE_OK;
33100:     }
33101:     case SQLITE_FCNTL_LAST_ERRNO: {
33102:       *(int*)pArg = pFile->lastErrno;
33103:       return SQLITE_OK;
33104:     }
33105:     case SQLITE_FCNTL_CHUNK_SIZE: {
33106:       pFile->szChunk = *(int *)pArg;
33107:       return SQLITE_OK;
33108:     }
33109:     case SQLITE_FCNTL_SIZE_HINT: {
33110:       int rc;
33111:       SimulateIOErrorBenign(1);
33112:       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
33113:       SimulateIOErrorBenign(0);
33114:       return rc;
33115:     }
33116:     case SQLITE_FCNTL_PERSIST_WAL: {
33117:       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
33118:       return SQLITE_OK;
33119:     }
33120:     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
33121:       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
33122:       return SQLITE_OK;
33123:     }
33124:     case SQLITE_FCNTL_VFSNAME: {
33125:       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
33126:       return SQLITE_OK;
33127:     }
33128:     case SQLITE_FCNTL_TEMPFILENAME: {
33129:       char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
33130:       if( zTFile ){
33131:         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
33132:         *(char**)pArg = zTFile;
33133:       }
33134:       return SQLITE_OK;
33135:     }
33136:     case SQLITE_FCNTL_HAS_MOVED: {
33137:       *(int*)pArg = fileHasMoved(pFile);
33138:       return SQLITE_OK;
33139:     }
33140: #if SQLITE_MAX_MMAP_SIZE>0
33141:     case SQLITE_FCNTL_MMAP_SIZE: {
33142:       i64 newLimit = *(i64*)pArg;
33143:       int rc = SQLITE_OK;
33144:       if( newLimit>sqlite3GlobalConfig.mxMmap ){
33145:         newLimit = sqlite3GlobalConfig.mxMmap;
33146:       }
33147:       *(i64*)pArg = pFile->mmapSizeMax;
33148:       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
33149:         pFile->mmapSizeMax = newLimit;
33150:         if( pFile->mmapSize>0 ){
33151:           unixUnmapfile(pFile);
33152:           rc = unixMapfile(pFile, -1);
33153:         }
33154:       }
33155:       return rc;
33156:     }
33157: #endif
33158: #ifdef SQLITE_DEBUG
33159:     /* The pager calls this method to signal that it has done
33160:     ** a rollback and that the database is therefore unchanged and
33161:     ** it hence it is OK for the transaction change counter to be
33162:     ** unchanged.
33163:     */
33164:     case SQLITE_FCNTL_DB_UNCHANGED: {
33165:       ((unixFile*)id)->dbUpdate = 0;
33166:       return SQLITE_OK;
33167:     }
33168: #endif
33169: #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
33170:     case SQLITE_FCNTL_SET_LOCKPROXYFILE:
33171:     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
33172:       return proxyFileControl(id,op,pArg);
33173:     }
33174: #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
33175:   }
33176:   return SQLITE_NOTFOUND;
33177: }
33178: 
33179: /*
33180: ** Return the sector size in bytes of the underlying block device for
33181: ** the specified file. This is almost always 512 bytes, but may be
33182: ** larger for some devices.
33183: **
33184: ** SQLite code assumes this function cannot fail. It also assumes that
33185: ** if two files are created in the same file-system directory (i.e.
33186: ** a database and its journal file) that the sector size will be the
33187: ** same for both.
33188: */
33189: #ifndef __QNXNTO__ 
33190: static int unixSectorSize(sqlite3_file *NotUsed){
33191:   UNUSED_PARAMETER(NotUsed);
33192:   return SQLITE_DEFAULT_SECTOR_SIZE;
33193: }
33194: #endif
33195: 
33196: /*
33197: ** The following version of unixSectorSize() is optimized for QNX.
33198: */
33199: #ifdef __QNXNTO__
33200: #include <sys/dcmd_blk.h>
33201: #include <sys/statvfs.h>
33202: static int unixSectorSize(sqlite3_file *id){
33203:   unixFile *pFile = (unixFile*)id;
33204:   if( pFile->sectorSize == 0 ){
33205:     struct statvfs fsInfo;
33206:        
33207:     /* Set defaults for non-supported filesystems */
33208:     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33209:     pFile->deviceCharacteristics = 0;
33210:     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
33211:       return pFile->sectorSize;
33212:     }
33213: 
33214:     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
33215:       pFile->sectorSize = fsInfo.f_bsize;
33216:       pFile->deviceCharacteristics =
33217:         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
33218:         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33219:                                       ** the write succeeds */
33220:         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33221:                                       ** so it is ordered */
33222:         0;
33223:     }else if( strstr(fsInfo.f_basetype, "etfs") ){
33224:       pFile->sectorSize = fsInfo.f_bsize;
33225:       pFile->deviceCharacteristics =
33226:         /* etfs cluster size writes are atomic */
33227:         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
33228:         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33229:                                       ** the write succeeds */
33230:         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33231:                                       ** so it is ordered */
33232:         0;
33233:     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
33234:       pFile->sectorSize = fsInfo.f_bsize;
33235:       pFile->deviceCharacteristics =
33236:         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
33237:         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33238:                                       ** the write succeeds */
33239:         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33240:                                       ** so it is ordered */
33241:         0;
33242:     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
33243:       pFile->sectorSize = fsInfo.f_bsize;
33244:       pFile->deviceCharacteristics =
33245:         /* full bitset of atomics from max sector size and smaller */
33246:         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33247:         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33248:                                       ** so it is ordered */
33249:         0;
33250:     }else if( strstr(fsInfo.f_basetype, "dos") ){
33251:       pFile->sectorSize = fsInfo.f_bsize;
33252:       pFile->deviceCharacteristics =
33253:         /* full bitset of atomics from max sector size and smaller */
33254:         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33255:         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
33256:                                       ** so it is ordered */
33257:         0;
33258:     }else{
33259:       pFile->deviceCharacteristics =
33260:         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
33261:         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
33262:                                       ** the write succeeds */
33263:         0;
33264:     }
33265:   }
33266:   /* Last chance verification.  If the sector size isn't a multiple of 512
33267:   ** then it isn't valid.*/
33268:   if( pFile->sectorSize % 512 != 0 ){
33269:     pFile->deviceCharacteristics = 0;
33270:     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33271:   }
33272:   return pFile->sectorSize;
33273: }
33274: #endif /* __QNXNTO__ */
33275: 
33276: /*
33277: ** Return the device characteristics for the file.
33278: **
33279: ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
33280: ** However, that choice is controversial since technically the underlying
33281: ** file system does not always provide powersafe overwrites.  (In other
33282: ** words, after a power-loss event, parts of the file that were never
33283: ** written might end up being altered.)  However, non-PSOW behavior is very,
33284: ** very rare.  And asserting PSOW makes a large reduction in the amount
33285: ** of required I/O for journaling, since a lot of padding is eliminated.
33286: **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
33287: ** available to turn it off and URI query parameter available to turn it off.
33288: */
33289: static int unixDeviceCharacteristics(sqlite3_file *id){
33290:   unixFile *p = (unixFile*)id;
33291:   int rc = 0;
33292: #ifdef __QNXNTO__
33293:   if( p->sectorSize==0 ) unixSectorSize(id);
33294:   rc = p->deviceCharacteristics;
33295: #endif
33296:   if( p->ctrlFlags & UNIXFILE_PSOW ){
33297:     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
33298:   }
33299:   return rc;
33300: }
33301: 
33302: #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
33303: 
33304: /*
33305: ** Return the system page size.
33306: **
33307: ** This function should not be called directly by other code in this file. 
33308: ** Instead, it should be called via macro osGetpagesize().
33309: */
33310: static int unixGetpagesize(void){
33311: #if OS_VXWORKS
33312:   return 1024;
33313: #elif defined(_BSD_SOURCE)
33314:   return getpagesize();
33315: #else
33316:   return (int)sysconf(_SC_PAGESIZE);
33317: #endif
33318: }
33319: 
33320: #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
33321: 
33322: #ifndef SQLITE_OMIT_WAL
33323: 
33324: /*
33325: ** Object used to represent an shared memory buffer.  
33326: **
33327: ** When multiple threads all reference the same wal-index, each thread
33328: ** has its own unixShm object, but they all point to a single instance
33329: ** of this unixShmNode object.  In other words, each wal-index is opened
33330: ** only once per process.
33331: **
33332: ** Each unixShmNode object is connected to a single unixInodeInfo object.
33333: ** We could coalesce this object into unixInodeInfo, but that would mean
33334: ** every open file that does not use shared memory (in other words, most
33335: ** open files) would have to carry around this extra information.  So
33336: ** the unixInodeInfo object contains a pointer to this unixShmNode object
33337: ** and the unixShmNode object is created only when needed.
33338: **
33339: ** unixMutexHeld() must be true when creating or destroying
33340: ** this object or while reading or writing the following fields:
33341: **
33342: **      nRef
33343: **
33344: ** The following fields are read-only after the object is created:
33345: ** 
33346: **      fid
33347: **      zFilename
33348: **
33349: ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
33350: ** unixMutexHeld() is true when reading or writing any other field
33351: ** in this structure.
33352: */
33353: struct unixShmNode {
33354:   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
33355:   sqlite3_mutex *mutex;      /* Mutex to access this object */
33356:   char *zFilename;           /* Name of the mmapped file */
33357:   int h;                     /* Open file descriptor */
33358:   int szRegion;              /* Size of shared-memory regions */
33359:   u16 nRegion;               /* Size of array apRegion */
33360:   u8 isReadonly;             /* True if read-only */
33361:   char **apRegion;           /* Array of mapped shared-memory regions */
33362:   int nRef;                  /* Number of unixShm objects pointing to this */
33363:   unixShm *pFirst;           /* All unixShm objects pointing to this */
33364: #ifdef SQLITE_DEBUG
33365:   u8 exclMask;               /* Mask of exclusive locks held */
33366:   u8 sharedMask;             /* Mask of shared locks held */
33367:   u8 nextShmId;              /* Next available unixShm.id value */
33368: #endif
33369: };
33370: 
33371: /*
33372: ** Structure used internally by this VFS to record the state of an
33373: ** open shared memory connection.
33374: **
33375: ** The following fields are initialized when this object is created and
33376: ** are read-only thereafter:
33377: **
33378: **    unixShm.pFile
33379: **    unixShm.id
33380: **
33381: ** All other fields are read/write.  The unixShm.pFile->mutex must be held
33382: ** while accessing any read/write fields.
33383: */
33384: struct unixShm {
33385:   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
33386:   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
33387:   u8 hasMutex;               /* True if holding the unixShmNode mutex */
33388:   u8 id;                     /* Id of this connection within its unixShmNode */
33389:   u16 sharedMask;            /* Mask of shared locks held */
33390:   u16 exclMask;              /* Mask of exclusive locks held */
33391: };
33392: 
33393: /*
33394: ** Constants used for locking
33395: */
33396: #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
33397: #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33398: 
33399: /*
33400: ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
33401: **
33402: ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
33403: ** otherwise.
33404: */
33405: static int unixShmSystemLock(
33406:   unixFile *pFile,       /* Open connection to the WAL file */
33407:   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
33408:   int ofst,              /* First byte of the locking range */
33409:   int n                  /* Number of bytes to lock */
33410: ){
33411:   unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
33412:   struct flock f;        /* The posix advisory locking structure */
33413:   int rc = SQLITE_OK;    /* Result code form fcntl() */
33414: 
33415:   /* Access to the unixShmNode object is serialized by the caller */
33416:   pShmNode = pFile->pInode->pShmNode;
33417:   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
33418: 
33419:   /* Shared locks never span more than one byte */
33420:   assert( n==1 || lockType!=F_RDLCK );
33421: 
33422:   /* Locks are within range */
33423:   assert( n>=1 && n<=SQLITE_SHM_NLOCK );
33424: 
33425:   if( pShmNode->h>=0 ){
33426:     /* Initialize the locking parameters */
33427:     memset(&f, 0, sizeof(f));
33428:     f.l_type = lockType;
33429:     f.l_whence = SEEK_SET;
33430:     f.l_start = ofst;
33431:     f.l_len = n;
33432: 
33433:     rc = osFcntl(pShmNode->h, F_SETLK, &f);
33434:     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
33435:   }
33436: 
33437:   /* Update the global lock state and do debug tracing */
33438: #ifdef SQLITE_DEBUG
33439:   { u16 mask;
33440:   OSTRACE(("SHM-LOCK "));
33441:   mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
33442:   if( rc==SQLITE_OK ){
33443:     if( lockType==F_UNLCK ){
33444:       OSTRACE(("unlock %d ok", ofst));
33445:       pShmNode->exclMask &= ~mask;
33446:       pShmNode->sharedMask &= ~mask;
33447:     }else if( lockType==F_RDLCK ){
33448:       OSTRACE(("read-lock %d ok", ofst));
33449:       pShmNode->exclMask &= ~mask;
33450:       pShmNode->sharedMask |= mask;
33451:     }else{
33452:       assert( lockType==F_WRLCK );
33453:       OSTRACE(("write-lock %d ok", ofst));
33454:       pShmNode->exclMask |= mask;
33455:       pShmNode->sharedMask &= ~mask;
33456:     }
33457:   }else{
33458:     if( lockType==F_UNLCK ){
33459:       OSTRACE(("unlock %d failed", ofst));
33460:     }else if( lockType==F_RDLCK ){
33461:       OSTRACE(("read-lock failed"));
33462:     }else{
33463:       assert( lockType==F_WRLCK );
33464:       OSTRACE(("write-lock %d failed", ofst));
33465:     }
33466:   }
33467:   OSTRACE((" - afterwards %03x,%03x\n",
33468:            pShmNode->sharedMask, pShmNode->exclMask));
33469:   }
33470: #endif
33471: 
33472:   return rc;        
33473: }
33474: 
33475: /*
33476: ** Return the minimum number of 32KB shm regions that should be mapped at
33477: ** a time, assuming that each mapping must be an integer multiple of the
33478: ** current system page-size.
33479: **
33480: ** Usually, this is 1. The exception seems to be systems that are configured
33481: ** to use 64KB pages - in this case each mapping must cover at least two
33482: ** shm regions.
33483: */
33484: static int unixShmRegionPerMap(void){
33485:   int shmsz = 32*1024;            /* SHM region size */
33486:   int pgsz = osGetpagesize();   /* System page size */
33487:   assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
33488:   if( pgsz<shmsz ) return 1;
33489:   return pgsz/shmsz;
33490: }
33491: 
33492: /*
33493: ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
33494: **
33495: ** This is not a VFS shared-memory method; it is a utility function called
33496: ** by VFS shared-memory methods.
33497: */
33498: static void unixShmPurge(unixFile *pFd){
33499:   unixShmNode *p = pFd->pInode->pShmNode;
33500:   assert( unixMutexHeld() );
33501:   if( p && ALWAYS(p->nRef==0) ){
33502:     int nShmPerMap = unixShmRegionPerMap();
33503:     int i;
33504:     assert( p->pInode==pFd->pInode );
33505:     sqlite3_mutex_free(p->mutex);
33506:     for(i=0; i<p->nRegion; i+=nShmPerMap){
33507:       if( p->h>=0 ){
33508:         osMunmap(p->apRegion[i], p->szRegion);
33509:       }else{
33510:         sqlite3_free(p->apRegion[i]);
33511:       }
33512:     }
33513:     sqlite3_free(p->apRegion);
33514:     if( p->h>=0 ){
33515:       robust_close(pFd, p->h, __LINE__);
33516:       p->h = -1;
33517:     }
33518:     p->pInode->pShmNode = 0;
33519:     sqlite3_free(p);
33520:   }
33521: }
33522: 
33523: /*
33524: ** Open a shared-memory area associated with open database file pDbFd.  
33525: ** This particular implementation uses mmapped files.
33526: **
33527: ** The file used to implement shared-memory is in the same directory
33528: ** as the open database file and has the same name as the open database
33529: ** file with the "-shm" suffix added.  For example, if the database file
33530: ** is "/home/user1/config.db" then the file that is created and mmapped
33531: ** for shared memory will be called "/home/user1/config.db-shm".  
33532: **
33533: ** Another approach to is to use files in /dev/shm or /dev/tmp or an
33534: ** some other tmpfs mount. But if a file in a different directory
33535: ** from the database file is used, then differing access permissions
33536: ** or a chroot() might cause two different processes on the same
33537: ** database to end up using different files for shared memory - 
33538: ** meaning that their memory would not really be shared - resulting
33539: ** in database corruption.  Nevertheless, this tmpfs file usage
33540: ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
33541: ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
33542: ** option results in an incompatible build of SQLite;  builds of SQLite
33543: ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
33544: ** same database file at the same time, database corruption will likely
33545: ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
33546: ** "unsupported" and may go away in a future SQLite release.
33547: **
33548: ** When opening a new shared-memory file, if no other instances of that
33549: ** file are currently open, in this process or in other processes, then
33550: ** the file must be truncated to zero length or have its header cleared.
33551: **
33552: ** If the original database file (pDbFd) is using the "unix-excl" VFS
33553: ** that means that an exclusive lock is held on the database file and
33554: ** that no other processes are able to read or write the database.  In
33555: ** that case, we do not really need shared memory.  No shared memory
33556: ** file is created.  The shared memory will be simulated with heap memory.
33557: */
33558: static int unixOpenSharedMemory(unixFile *pDbFd){
33559:   struct unixShm *p = 0;          /* The connection to be opened */
33560:   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
33561:   int rc;                         /* Result code */
33562:   unixInodeInfo *pInode;          /* The inode of fd */
33563:   char *zShmFilename;             /* Name of the file used for SHM */
33564:   int nShmFilename;               /* Size of the SHM filename in bytes */
33565: 
33566:   /* Allocate space for the new unixShm object. */
33567:   p = sqlite3_malloc64( sizeof(*p) );
33568:   if( p==0 ) return SQLITE_NOMEM_BKPT;
33569:   memset(p, 0, sizeof(*p));
33570:   assert( pDbFd->pShm==0 );
33571: 
33572:   /* Check to see if a unixShmNode object already exists. Reuse an existing
33573:   ** one if present. Create a new one if necessary.
33574:   */
33575:   unixEnterMutex();
33576:   pInode = pDbFd->pInode;
33577:   pShmNode = pInode->pShmNode;
33578:   if( pShmNode==0 ){
33579:     struct stat sStat;                 /* fstat() info for database file */
33580: #ifndef SQLITE_SHM_DIRECTORY
33581:     const char *zBasePath = pDbFd->zPath;
33582: #endif
33583: 
33584:     /* Call fstat() to figure out the permissions on the database file. If
33585:     ** a new *-shm file is created, an attempt will be made to create it
33586:     ** with the same permissions.
33587:     */
33588:     if( osFstat(pDbFd->h, &sStat) ){
33589:       rc = SQLITE_IOERR_FSTAT;
33590:       goto shm_open_err;
33591:     }
33592: 
33593: #ifdef SQLITE_SHM_DIRECTORY
33594:     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
33595: #else
33596:     nShmFilename = 6 + (int)strlen(zBasePath);
33597: #endif
33598:     pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
33599:     if( pShmNode==0 ){
33600:       rc = SQLITE_NOMEM_BKPT;
33601:       goto shm_open_err;
33602:     }
33603:     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
33604:     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
33605: #ifdef SQLITE_SHM_DIRECTORY
33606:     sqlite3_snprintf(nShmFilename, zShmFilename, 
33607:                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
33608:                      (u32)sStat.st_ino, (u32)sStat.st_dev);
33609: #else
33610:     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
33611:     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
33612: #endif
33613:     pShmNode->h = -1;
33614:     pDbFd->pInode->pShmNode = pShmNode;
33615:     pShmNode->pInode = pDbFd->pInode;
33616:     if( sqlite3GlobalConfig.bCoreMutex ){
33617:       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33618:       if( pShmNode->mutex==0 ){
33619:         rc = SQLITE_NOMEM_BKPT;
33620:         goto shm_open_err;
33621:       }
33622:     }
33623: 
33624:     if( pInode->bProcessLock==0 ){
33625:       int openFlags = O_RDWR | O_CREAT;
33626:       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
33627:         openFlags = O_RDONLY;
33628:         pShmNode->isReadonly = 1;
33629:       }
33630:       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
33631:       if( pShmNode->h<0 ){
33632:         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
33633:         goto shm_open_err;
33634:       }
33635: 
33636:       /* If this process is running as root, make sure that the SHM file
33637:       ** is owned by the same user that owns the original database.  Otherwise,
33638:       ** the original owner will not be able to connect.
33639:       */
33640:       robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
33641:   
33642:       /* Check to see if another process is holding the dead-man switch.
33643:       ** If not, truncate the file to zero length. 
33644:       */
33645:       rc = SQLITE_OK;
33646:       if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
33647:         if( robust_ftruncate(pShmNode->h, 0) ){
33648:           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
33649:         }
33650:       }
33651:       if( rc==SQLITE_OK ){
33652:         rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
33653:       }
33654:       if( rc ) goto shm_open_err;
33655:     }
33656:   }
33657: 
33658:   /* Make the new connection a child of the unixShmNode */
33659:   p->pShmNode = pShmNode;
33660: #ifdef SQLITE_DEBUG
33661:   p->id = pShmNode->nextShmId++;
33662: #endif
33663:   pShmNode->nRef++;
33664:   pDbFd->pShm = p;
33665:   unixLeaveMutex();
33666: 
33667:   /* The reference count on pShmNode has already been incremented under
33668:   ** the cover of the unixEnterMutex() mutex and the pointer from the
33669:   ** new (struct unixShm) object to the pShmNode has been set. All that is
33670:   ** left to do is to link the new object into the linked list starting
33671:   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
33672:   ** mutex.
33673:   */
33674:   sqlite3_mutex_enter(pShmNode->mutex);
33675:   p->pNext = pShmNode->pFirst;
33676:   pShmNode->pFirst = p;
33677:   sqlite3_mutex_leave(pShmNode->mutex);
33678:   return SQLITE_OK;
33679: 
33680:   /* Jump here on any error */
33681: shm_open_err:
33682:   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
33683:   sqlite3_free(p);
33684:   unixLeaveMutex();
33685:   return rc;
33686: }
33687: 
33688: /*
33689: ** This function is called to obtain a pointer to region iRegion of the 
33690: ** shared-memory associated with the database file fd. Shared-memory regions 
33691: ** are numbered starting from zero. Each shared-memory region is szRegion 
33692: ** bytes in size.
33693: **
33694: ** If an error occurs, an error code is returned and *pp is set to NULL.
33695: **
33696: ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
33697: ** region has not been allocated (by any client, including one running in a
33698: ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
33699: ** bExtend is non-zero and the requested shared-memory region has not yet 
33700: ** been allocated, it is allocated by this function.
33701: **
33702: ** If the shared-memory region has already been allocated or is allocated by
33703: ** this call as described above, then it is mapped into this processes 
33704: ** address space (if it is not already), *pp is set to point to the mapped 
33705: ** memory and SQLITE_OK returned.
33706: */
33707: static int unixShmMap(
33708:   sqlite3_file *fd,               /* Handle open on database file */
33709:   int iRegion,                    /* Region to retrieve */
33710:   int szRegion,                   /* Size of regions */
33711:   int bExtend,                    /* True to extend file if necessary */
33712:   void volatile **pp              /* OUT: Mapped memory */
33713: ){
33714:   unixFile *pDbFd = (unixFile*)fd;
33715:   unixShm *p;
33716:   unixShmNode *pShmNode;
33717:   int rc = SQLITE_OK;
33718:   int nShmPerMap = unixShmRegionPerMap();
33719:   int nReqRegion;
33720: 
33721:   /* If the shared-memory file has not yet been opened, open it now. */
33722:   if( pDbFd->pShm==0 ){
33723:     rc = unixOpenSharedMemory(pDbFd);
33724:     if( rc!=SQLITE_OK ) return rc;
33725:   }
33726: 
33727:   p = pDbFd->pShm;
33728:   pShmNode = p->pShmNode;
33729:   sqlite3_mutex_enter(pShmNode->mutex);
33730:   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33731:   assert( pShmNode->pInode==pDbFd->pInode );
33732:   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33733:   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33734: 
33735:   /* Minimum number of regions required to be mapped. */
33736:   nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
33737: 
33738:   if( pShmNode->nRegion<nReqRegion ){
33739:     char **apNew;                      /* New apRegion[] array */
33740:     int nByte = nReqRegion*szRegion;   /* Minimum required file size */
33741:     struct stat sStat;                 /* Used by fstat() */
33742: 
33743:     pShmNode->szRegion = szRegion;
33744: 
33745:     if( pShmNode->h>=0 ){
33746:       /* The requested region is not mapped into this processes address space.
33747:       ** Check to see if it has been allocated (i.e. if the wal-index file is
33748:       ** large enough to contain the requested region).
33749:       */
33750:       if( osFstat(pShmNode->h, &sStat) ){
33751:         rc = SQLITE_IOERR_SHMSIZE;
33752:         goto shmpage_out;
33753:       }
33754:   
33755:       if( sStat.st_size<nByte ){
33756:         /* The requested memory region does not exist. If bExtend is set to
33757:         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
33758:         */
33759:         if( !bExtend ){
33760:           goto shmpage_out;
33761:         }
33762: 
33763:         /* Alternatively, if bExtend is true, extend the file. Do this by
33764:         ** writing a single byte to the end of each (OS) page being
33765:         ** allocated or extended. Technically, we need only write to the
33766:         ** last page in order to extend the file. But writing to all new
33767:         ** pages forces the OS to allocate them immediately, which reduces
33768:         ** the chances of SIGBUS while accessing the mapped region later on.
33769:         */
33770:         else{
33771:           static const int pgsz = 4096;
33772:           int iPg;
33773: 
33774:           /* Write to the last byte of each newly allocated or extended page */
33775:           assert( (nByte % pgsz)==0 );
33776:           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
33777:             int x = 0;
33778:             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
33779:               const char *zFile = pShmNode->zFilename;
33780:               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
33781:               goto shmpage_out;
33782:             }
33783:           }
33784:         }
33785:       }
33786:     }
33787: 
33788:     /* Map the requested memory region into this processes address space. */
33789:     apNew = (char **)sqlite3_realloc(
33790:         pShmNode->apRegion, nReqRegion*sizeof(char *)
33791:     );
33792:     if( !apNew ){
33793:       rc = SQLITE_IOERR_NOMEM_BKPT;
33794:       goto shmpage_out;
33795:     }
33796:     pShmNode->apRegion = apNew;
33797:     while( pShmNode->nRegion<nReqRegion ){
33798:       int nMap = szRegion*nShmPerMap;
33799:       int i;
33800:       void *pMem;
33801:       if( pShmNode->h>=0 ){
33802:         pMem = osMmap(0, nMap,
33803:             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
33804:             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
33805:         );
33806:         if( pMem==MAP_FAILED ){
33807:           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
33808:           goto shmpage_out;
33809:         }
33810:       }else{
33811:         pMem = sqlite3_malloc64(szRegion);
33812:         if( pMem==0 ){
33813:           rc = SQLITE_NOMEM_BKPT;
33814:           goto shmpage_out;
33815:         }
33816:         memset(pMem, 0, szRegion);
33817:       }
33818: 
33819:       for(i=0; i<nShmPerMap; i++){
33820:         pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
33821:       }
33822:       pShmNode->nRegion += nShmPerMap;
33823:     }
33824:   }
33825: 
33826: shmpage_out:
33827:   if( pShmNode->nRegion>iRegion ){
33828:     *pp = pShmNode->apRegion[iRegion];
33829:   }else{
33830:     *pp = 0;
33831:   }
33832:   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
33833:   sqlite3_mutex_leave(pShmNode->mutex);
33834:   return rc;
33835: }
33836: 
33837: /*
33838: ** Change the lock state for a shared-memory segment.
33839: **
33840: ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
33841: ** different here than in posix.  In xShmLock(), one can go from unlocked
33842: ** to shared and back or from unlocked to exclusive and back.  But one may
33843: ** not go from shared to exclusive or from exclusive to shared.
33844: */
33845: static int unixShmLock(
33846:   sqlite3_file *fd,          /* Database file holding the shared memory */
33847:   int ofst,                  /* First lock to acquire or release */
33848:   int n,                     /* Number of locks to acquire or release */
33849:   int flags                  /* What to do with the lock */
33850: ){
33851:   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
33852:   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
33853:   unixShm *pX;                          /* For looping over all siblings */
33854:   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
33855:   int rc = SQLITE_OK;                   /* Result code */
33856:   u16 mask;                             /* Mask of locks to take or release */
33857: 
33858:   assert( pShmNode==pDbFd->pInode->pShmNode );
33859:   assert( pShmNode->pInode==pDbFd->pInode );
33860:   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33861:   assert( n>=1 );
33862:   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33863:        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33864:        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33865:        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33866:   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33867:   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33868:   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33869: 
33870:   mask = (1<<(ofst+n)) - (1<<ofst);
33871:   assert( n>1 || mask==(1<<ofst) );
33872:   sqlite3_mutex_enter(pShmNode->mutex);
33873:   if( flags & SQLITE_SHM_UNLOCK ){
33874:     u16 allMask = 0; /* Mask of locks held by siblings */
33875: 
33876:     /* See if any siblings hold this same lock */
33877:     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33878:       if( pX==p ) continue;
33879:       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33880:       allMask |= pX->sharedMask;
33881:     }
33882: 
33883:     /* Unlock the system-level locks */
33884:     if( (mask & allMask)==0 ){
33885:       rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
33886:     }else{
33887:       rc = SQLITE_OK;
33888:     }
33889: 
33890:     /* Undo the local locks */
33891:     if( rc==SQLITE_OK ){
33892:       p->exclMask &= ~mask;
33893:       p->sharedMask &= ~mask;
33894:     } 
33895:   }else if( flags & SQLITE_SHM_SHARED ){
33896:     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
33897: 
33898:     /* Find out which shared locks are already held by sibling connections.
33899:     ** If any sibling already holds an exclusive lock, go ahead and return
33900:     ** SQLITE_BUSY.
33901:     */
33902:     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33903:       if( (pX->exclMask & mask)!=0 ){
33904:         rc = SQLITE_BUSY;
33905:         break;
33906:       }
33907:       allShared |= pX->sharedMask;
33908:     }
33909: 
33910:     /* Get shared locks at the system level, if necessary */
33911:     if( rc==SQLITE_OK ){
33912:       if( (allShared & mask)==0 ){
33913:         rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
33914:       }else{
33915:         rc = SQLITE_OK;
33916:       }
33917:     }
33918: 
33919:     /* Get the local shared locks */
33920:     if( rc==SQLITE_OK ){
33921:       p->sharedMask |= mask;
33922:     }
33923:   }else{
33924:     /* Make sure no sibling connections hold locks that will block this
33925:     ** lock.  If any do, return SQLITE_BUSY right away.
33926:     */
33927:     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33928:       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33929:         rc = SQLITE_BUSY;
33930:         break;
33931:       }
33932:     }
33933:   
33934:     /* Get the exclusive locks at the system level.  Then if successful
33935:     ** also mark the local connection as being locked.
33936:     */
33937:     if( rc==SQLITE_OK ){
33938:       rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
33939:       if( rc==SQLITE_OK ){
33940:         assert( (p->sharedMask & mask)==0 );
33941:         p->exclMask |= mask;
33942:       }
33943:     }
33944:   }
33945:   sqlite3_mutex_leave(pShmNode->mutex);
33946:   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
33947:            p->id, osGetpid(0), p->sharedMask, p->exclMask));
33948:   return rc;
33949: }
33950: 
33951: /*
33952: ** Implement a memory barrier or memory fence on shared memory.  
33953: **
33954: ** All loads and stores begun before the barrier must complete before
33955: ** any load or store begun after the barrier.
33956: */
33957: static void unixShmBarrier(
33958:   sqlite3_file *fd                /* Database file holding the shared memory */
33959: ){
33960:   UNUSED_PARAMETER(fd);
33961:   sqlite3MemoryBarrier();         /* compiler-defined memory barrier */
33962:   unixEnterMutex();               /* Also mutex, for redundancy */
33963:   unixLeaveMutex();
33964: }
33965: 
33966: /*
33967: ** Close a connection to shared-memory.  Delete the underlying 
33968: ** storage if deleteFlag is true.
33969: **
33970: ** If there is no shared memory associated with the connection then this
33971: ** routine is a harmless no-op.
33972: */
33973: static int unixShmUnmap(
33974:   sqlite3_file *fd,               /* The underlying database file */
33975:   int deleteFlag                  /* Delete shared-memory if true */
33976: ){
33977:   unixShm *p;                     /* The connection to be closed */
33978:   unixShmNode *pShmNode;          /* The underlying shared-memory file */
33979:   unixShm **pp;                   /* For looping over sibling connections */
33980:   unixFile *pDbFd;                /* The underlying database file */
33981: 
33982:   pDbFd = (unixFile*)fd;
33983:   p = pDbFd->pShm;
33984:   if( p==0 ) return SQLITE_OK;
33985:   pShmNode = p->pShmNode;
33986: 
33987:   assert( pShmNode==pDbFd->pInode->pShmNode );
33988:   assert( pShmNode->pInode==pDbFd->pInode );
33989: 
33990:   /* Remove connection p from the set of connections associated
33991:   ** with pShmNode */
33992:   sqlite3_mutex_enter(pShmNode->mutex);
33993:   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33994:   *pp = p->pNext;
33995: 
33996:   /* Free the connection p */
33997:   sqlite3_free(p);
33998:   pDbFd->pShm = 0;
33999:   sqlite3_mutex_leave(pShmNode->mutex);
34000: 
34001:   /* If pShmNode->nRef has reached 0, then close the underlying
34002:   ** shared-memory file, too */
34003:   unixEnterMutex();
34004:   assert( pShmNode->nRef>0 );
34005:   pShmNode->nRef--;
34006:   if( pShmNode->nRef==0 ){
34007:     if( deleteFlag && pShmNode->h>=0 ){
34008:       osUnlink(pShmNode->zFilename);
34009:     }
34010:     unixShmPurge(pDbFd);
34011:   }
34012:   unixLeaveMutex();
34013: 
34014:   return SQLITE_OK;
34015: }
34016: 
34017: 
34018: #else
34019: # define unixShmMap     0
34020: # define unixShmLock    0
34021: # define unixShmBarrier 0
34022: # define unixShmUnmap   0
34023: #endif /* #ifndef SQLITE_OMIT_WAL */
34024: 
34025: #if SQLITE_MAX_MMAP_SIZE>0
34026: /*
34027: ** If it is currently memory mapped, unmap file pFd.
34028: */
34029: static void unixUnmapfile(unixFile *pFd){
34030:   assert( pFd->nFetchOut==0 );
34031:   if( pFd->pMapRegion ){
34032:     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
34033:     pFd->pMapRegion = 0;
34034:     pFd->mmapSize = 0;
34035:     pFd->mmapSizeActual = 0;
34036:   }
34037: }
34038: 
34039: /*
34040: ** Attempt to set the size of the memory mapping maintained by file 
34041: ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
34042: **
34043: ** If successful, this function sets the following variables:
34044: **
34045: **       unixFile.pMapRegion
34046: **       unixFile.mmapSize
34047: **       unixFile.mmapSizeActual
34048: **
34049: ** If unsuccessful, an error message is logged via sqlite3_log() and
34050: ** the three variables above are zeroed. In this case SQLite should
34051: ** continue accessing the database using the xRead() and xWrite()
34052: ** methods.
34053: */
34054: static void unixRemapfile(
34055:   unixFile *pFd,                  /* File descriptor object */
34056:   i64 nNew                        /* Required mapping size */
34057: ){
34058:   const char *zErr = "mmap";
34059:   int h = pFd->h;                      /* File descriptor open on db file */
34060:   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
34061:   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
34062:   u8 *pNew = 0;                        /* Location of new mapping */
34063:   int flags = PROT_READ;               /* Flags to pass to mmap() */
34064: 
34065:   assert( pFd->nFetchOut==0 );
34066:   assert( nNew>pFd->mmapSize );
34067:   assert( nNew<=pFd->mmapSizeMax );
34068:   assert( nNew>0 );
34069:   assert( pFd->mmapSizeActual>=pFd->mmapSize );
34070:   assert( MAP_FAILED!=0 );
34071: 
34072: #ifdef SQLITE_MMAP_READWRITE
34073:   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
34074: #endif
34075: 
34076:   if( pOrig ){
34077: #if HAVE_MREMAP
34078:     i64 nReuse = pFd->mmapSize;
34079: #else
34080:     const int szSyspage = osGetpagesize();
34081:     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
34082: #endif
34083:     u8 *pReq = &pOrig[nReuse];
34084: 
34085:     /* Unmap any pages of the existing mapping that cannot be reused. */
34086:     if( nReuse!=nOrig ){
34087:       osMunmap(pReq, nOrig-nReuse);
34088:     }
34089: 
34090: #if HAVE_MREMAP
34091:     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
34092:     zErr = "mremap";
34093: #else
34094:     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
34095:     if( pNew!=MAP_FAILED ){
34096:       if( pNew!=pReq ){
34097:         osMunmap(pNew, nNew - nReuse);
34098:         pNew = 0;
34099:       }else{
34100:         pNew = pOrig;
34101:       }
34102:     }
34103: #endif
34104: 
34105:     /* The attempt to extend the existing mapping failed. Free it. */
34106:     if( pNew==MAP_FAILED || pNew==0 ){
34107:       osMunmap(pOrig, nReuse);
34108:     }
34109:   }
34110: 
34111:   /* If pNew is still NULL, try to create an entirely new mapping. */
34112:   if( pNew==0 ){
34113:     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
34114:   }
34115: 
34116:   if( pNew==MAP_FAILED ){
34117:     pNew = 0;
34118:     nNew = 0;
34119:     unixLogError(SQLITE_OK, zErr, pFd->zPath);
34120: 
34121:     /* If the mmap() above failed, assume that all subsequent mmap() calls
34122:     ** will probably fail too. Fall back to using xRead/xWrite exclusively
34123:     ** in this case.  */
34124:     pFd->mmapSizeMax = 0;
34125:   }
34126:   pFd->pMapRegion = (void *)pNew;
34127:   pFd->mmapSize = pFd->mmapSizeActual = nNew;
34128: }
34129: 
34130: /*
34131: ** Memory map or remap the file opened by file-descriptor pFd (if the file
34132: ** is already mapped, the existing mapping is replaced by the new). Or, if 
34133: ** there already exists a mapping for this file, and there are still 
34134: ** outstanding xFetch() references to it, this function is a no-op.
34135: **
34136: ** If parameter nByte is non-negative, then it is the requested size of 
34137: ** the mapping to create. Otherwise, if nByte is less than zero, then the 
34138: ** requested size is the size of the file on disk. The actual size of the
34139: ** created mapping is either the requested size or the value configured 
34140: ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
34141: **
34142: ** SQLITE_OK is returned if no error occurs (even if the mapping is not
34143: ** recreated as a result of outstanding references) or an SQLite error
34144: ** code otherwise.
34145: */
34146: static int unixMapfile(unixFile *pFd, i64 nMap){
34147:   assert( nMap>=0 || pFd->nFetchOut==0 );
34148:   assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34149:   if( pFd->nFetchOut>0 ) return SQLITE_OK;
34150: 
34151:   if( nMap<0 ){
34152:     struct stat statbuf;          /* Low-level file information */
34153:     if( osFstat(pFd->h, &statbuf) ){
34154:       return SQLITE_IOERR_FSTAT;
34155:     }
34156:     nMap = statbuf.st_size;
34157:   }
34158:   if( nMap>pFd->mmapSizeMax ){
34159:     nMap = pFd->mmapSizeMax;
34160:   }
34161: 
34162:   assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
34163:   if( nMap!=pFd->mmapSize ){
34164:     unixRemapfile(pFd, nMap);
34165:   }
34166: 
34167:   return SQLITE_OK;
34168: }
34169: #endif /* SQLITE_MAX_MMAP_SIZE>0 */
34170: 
34171: /*
34172: ** If possible, return a pointer to a mapping of file fd starting at offset
34173: ** iOff. The mapping must be valid for at least nAmt bytes.
34174: **
34175: ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34176: ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34177: ** Finally, if an error does occur, return an SQLite error code. The final
34178: ** value of *pp is undefined in this case.
34179: **
34180: ** If this function does return a pointer, the caller must eventually 
34181: ** release the reference by calling unixUnfetch().
34182: */
34183: static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34184: #if SQLITE_MAX_MMAP_SIZE>0
34185:   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
34186: #endif
34187:   *pp = 0;
34188: 
34189: #if SQLITE_MAX_MMAP_SIZE>0
34190:   if( pFd->mmapSizeMax>0 ){
34191:     if( pFd->pMapRegion==0 ){
34192:       int rc = unixMapfile(pFd, -1);
34193:       if( rc!=SQLITE_OK ) return rc;
34194:     }
34195:     if( pFd->mmapSize >= iOff+nAmt ){
34196:       *pp = &((u8 *)pFd->pMapRegion)[iOff];
34197:       pFd->nFetchOut++;
34198:     }
34199:   }
34200: #endif
34201:   return SQLITE_OK;
34202: }
34203: 
34204: /*
34205: ** If the third argument is non-NULL, then this function releases a 
34206: ** reference obtained by an earlier call to unixFetch(). The second
34207: ** argument passed to this function must be the same as the corresponding
34208: ** argument that was passed to the unixFetch() invocation. 
34209: **
34210: ** Or, if the third argument is NULL, then this function is being called 
34211: ** to inform the VFS layer that, according to POSIX, any existing mapping 
34212: ** may now be invalid and should be unmapped.
34213: */
34214: static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34215: #if SQLITE_MAX_MMAP_SIZE>0
34216:   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
34217:   UNUSED_PARAMETER(iOff);
34218: 
34219:   /* If p==0 (unmap the entire file) then there must be no outstanding 
34220:   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34221:   ** then there must be at least one outstanding.  */
34222:   assert( (p==0)==(pFd->nFetchOut==0) );
34223: 
34224:   /* If p!=0, it must match the iOff value. */
34225:   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34226: 
34227:   if( p ){
34228:     pFd->nFetchOut--;
34229:   }else{
34230:     unixUnmapfile(pFd);
34231:   }
34232: 
34233:   assert( pFd->nFetchOut>=0 );
34234: #else
34235:   UNUSED_PARAMETER(fd);
34236:   UNUSED_PARAMETER(p);
34237:   UNUSED_PARAMETER(iOff);
34238: #endif
34239:   return SQLITE_OK;
34240: }
34241: 
34242: /*
34243: ** Here ends the implementation of all sqlite3_file methods.
34244: **
34245: ********************** End sqlite3_file Methods *******************************
34246: ******************************************************************************/
34247: 
34248: /*
34249: ** This division contains definitions of sqlite3_io_methods objects that
34250: ** implement various file locking strategies.  It also contains definitions
34251: ** of "finder" functions.  A finder-function is used to locate the appropriate
34252: ** sqlite3_io_methods object for a particular database file.  The pAppData
34253: ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
34254: ** the correct finder-function for that VFS.
34255: **
34256: ** Most finder functions return a pointer to a fixed sqlite3_io_methods
34257: ** object.  The only interesting finder-function is autolockIoFinder, which
34258: ** looks at the filesystem type and tries to guess the best locking
34259: ** strategy from that.
34260: **
34261: ** For finder-function F, two objects are created:
34262: **
34263: **    (1) The real finder-function named "FImpt()".
34264: **
34265: **    (2) A constant pointer to this function named just "F".
34266: **
34267: **
34268: ** A pointer to the F pointer is used as the pAppData value for VFS
34269: ** objects.  We have to do this instead of letting pAppData point
34270: ** directly at the finder-function since C90 rules prevent a void*
34271: ** from be cast into a function pointer.
34272: **
34273: **
34274: ** Each instance of this macro generates two objects:
34275: **
34276: **   *  A constant sqlite3_io_methods object call METHOD that has locking
34277: **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
34278: **
34279: **   *  An I/O method finder function called FINDER that returns a pointer
34280: **      to the METHOD object in the previous bullet.
34281: */
34282: #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
34283: static const sqlite3_io_methods METHOD = {                                   \
34284:    VERSION,                    /* iVersion */                                \
34285:    CLOSE,                      /* xClose */                                  \
34286:    unixRead,                   /* xRead */                                   \
34287:    unixWrite,                  /* xWrite */                                  \
34288:    unixTruncate,               /* xTruncate */                               \
34289:    unixSync,                   /* xSync */                                   \
34290:    unixFileSize,               /* xFileSize */                               \
34291:    LOCK,                       /* xLock */                                   \
34292:    UNLOCK,                     /* xUnlock */                                 \
34293:    CKLOCK,                     /* xCheckReservedLock */                      \
34294:    unixFileControl,            /* xFileControl */                            \
34295:    unixSectorSize,             /* xSectorSize */                             \
34296:    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
34297:    SHMMAP,                     /* xShmMap */                                 \
34298:    unixShmLock,                /* xShmLock */                                \
34299:    unixShmBarrier,             /* xShmBarrier */                             \
34300:    unixShmUnmap,               /* xShmUnmap */                               \
34301:    unixFetch,                  /* xFetch */                                  \
34302:    unixUnfetch,                /* xUnfetch */                                \
34303: };                                                                           \
34304: static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
34305:   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
34306:   return &METHOD;                                                            \
34307: }                                                                            \
34308: static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
34309:     = FINDER##Impl;
34310: 
34311: /*
34312: ** Here are all of the sqlite3_io_methods objects for each of the
34313: ** locking strategies.  Functions that return pointers to these methods
34314: ** are also created.
34315: */
34316: IOMETHODS(
34317:   posixIoFinder,            /* Finder function name */
34318:   posixIoMethods,           /* sqlite3_io_methods object name */
34319:   3,                        /* shared memory and mmap are enabled */
34320:   unixClose,                /* xClose method */
34321:   unixLock,                 /* xLock method */
34322:   unixUnlock,               /* xUnlock method */
34323:   unixCheckReservedLock,    /* xCheckReservedLock method */
34324:   unixShmMap                /* xShmMap method */
34325: )
34326: IOMETHODS(
34327:   nolockIoFinder,           /* Finder function name */
34328:   nolockIoMethods,          /* sqlite3_io_methods object name */
34329:   3,                        /* shared memory is disabled */
34330:   nolockClose,              /* xClose method */
34331:   nolockLock,               /* xLock method */
34332:   nolockUnlock,             /* xUnlock method */
34333:   nolockCheckReservedLock,  /* xCheckReservedLock method */
34334:   0                         /* xShmMap method */
34335: )
34336: IOMETHODS(
34337:   dotlockIoFinder,          /* Finder function name */
34338:   dotlockIoMethods,         /* sqlite3_io_methods object name */
34339:   1,                        /* shared memory is disabled */
34340:   dotlockClose,             /* xClose method */
34341:   dotlockLock,              /* xLock method */
34342:   dotlockUnlock,            /* xUnlock method */
34343:   dotlockCheckReservedLock, /* xCheckReservedLock method */
34344:   0                         /* xShmMap method */
34345: )
34346: 
34347: #if SQLITE_ENABLE_LOCKING_STYLE
34348: IOMETHODS(
34349:   flockIoFinder,            /* Finder function name */
34350:   flockIoMethods,           /* sqlite3_io_methods object name */
34351:   1,                        /* shared memory is disabled */
34352:   flockClose,               /* xClose method */
34353:   flockLock,                /* xLock method */
34354:   flockUnlock,              /* xUnlock method */
34355:   flockCheckReservedLock,   /* xCheckReservedLock method */
34356:   0                         /* xShmMap method */
34357: )
34358: #endif
34359: 
34360: #if OS_VXWORKS
34361: IOMETHODS(
34362:   semIoFinder,              /* Finder function name */
34363:   semIoMethods,             /* sqlite3_io_methods object name */
34364:   1,                        /* shared memory is disabled */
34365:   semXClose,                /* xClose method */
34366:   semXLock,                 /* xLock method */
34367:   semXUnlock,               /* xUnlock method */
34368:   semXCheckReservedLock,    /* xCheckReservedLock method */
34369:   0                         /* xShmMap method */
34370: )
34371: #endif
34372: 
34373: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34374: IOMETHODS(
34375:   afpIoFinder,              /* Finder function name */
34376:   afpIoMethods,             /* sqlite3_io_methods object name */
34377:   1,                        /* shared memory is disabled */
34378:   afpClose,                 /* xClose method */
34379:   afpLock,                  /* xLock method */
34380:   afpUnlock,                /* xUnlock method */
34381:   afpCheckReservedLock,     /* xCheckReservedLock method */
34382:   0                         /* xShmMap method */
34383: )
34384: #endif
34385: 
34386: /*
34387: ** The proxy locking method is a "super-method" in the sense that it
34388: ** opens secondary file descriptors for the conch and lock files and
34389: ** it uses proxy, dot-file, AFP, and flock() locking methods on those
34390: ** secondary files.  For this reason, the division that implements
34391: ** proxy locking is located much further down in the file.  But we need
34392: ** to go ahead and define the sqlite3_io_methods and finder function
34393: ** for proxy locking here.  So we forward declare the I/O methods.
34394: */
34395: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34396: static int proxyClose(sqlite3_file*);
34397: static int proxyLock(sqlite3_file*, int);
34398: static int proxyUnlock(sqlite3_file*, int);
34399: static int proxyCheckReservedLock(sqlite3_file*, int*);
34400: IOMETHODS(
34401:   proxyIoFinder,            /* Finder function name */
34402:   proxyIoMethods,           /* sqlite3_io_methods object name */
34403:   1,                        /* shared memory is disabled */
34404:   proxyClose,               /* xClose method */
34405:   proxyLock,                /* xLock method */
34406:   proxyUnlock,              /* xUnlock method */
34407:   proxyCheckReservedLock,   /* xCheckReservedLock method */
34408:   0                         /* xShmMap method */
34409: )
34410: #endif
34411: 
34412: /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
34413: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34414: IOMETHODS(
34415:   nfsIoFinder,               /* Finder function name */
34416:   nfsIoMethods,              /* sqlite3_io_methods object name */
34417:   1,                         /* shared memory is disabled */
34418:   unixClose,                 /* xClose method */
34419:   unixLock,                  /* xLock method */
34420:   nfsUnlock,                 /* xUnlock method */
34421:   unixCheckReservedLock,     /* xCheckReservedLock method */
34422:   0                          /* xShmMap method */
34423: )
34424: #endif
34425: 
34426: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34427: /* 
34428: ** This "finder" function attempts to determine the best locking strategy 
34429: ** for the database file "filePath".  It then returns the sqlite3_io_methods
34430: ** object that implements that strategy.
34431: **
34432: ** This is for MacOSX only.
34433: */
34434: static const sqlite3_io_methods *autolockIoFinderImpl(
34435:   const char *filePath,    /* name of the database file */
34436:   unixFile *pNew           /* open file object for the database file */
34437: ){
34438:   static const struct Mapping {
34439:     const char *zFilesystem;              /* Filesystem type name */
34440:     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
34441:   } aMap[] = {
34442:     { "hfs",    &posixIoMethods },
34443:     { "ufs",    &posixIoMethods },
34444:     { "afpfs",  &afpIoMethods },
34445:     { "smbfs",  &afpIoMethods },
34446:     { "webdav", &nolockIoMethods },
34447:     { 0, 0 }
34448:   };
34449:   int i;
34450:   struct statfs fsInfo;
34451:   struct flock lockInfo;
34452: 
34453:   if( !filePath ){
34454:     /* If filePath==NULL that means we are dealing with a transient file
34455:     ** that does not need to be locked. */
34456:     return &nolockIoMethods;
34457:   }
34458:   if( statfs(filePath, &fsInfo) != -1 ){
34459:     if( fsInfo.f_flags & MNT_RDONLY ){
34460:       return &nolockIoMethods;
34461:     }
34462:     for(i=0; aMap[i].zFilesystem; i++){
34463:       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
34464:         return aMap[i].pMethods;
34465:       }
34466:     }
34467:   }
34468: 
34469:   /* Default case. Handles, amongst others, "nfs".
34470:   ** Test byte-range lock using fcntl(). If the call succeeds, 
34471:   ** assume that the file-system supports POSIX style locks. 
34472:   */
34473:   lockInfo.l_len = 1;
34474:   lockInfo.l_start = 0;
34475:   lockInfo.l_whence = SEEK_SET;
34476:   lockInfo.l_type = F_RDLCK;
34477:   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34478:     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
34479:       return &nfsIoMethods;
34480:     } else {
34481:       return &posixIoMethods;
34482:     }
34483:   }else{
34484:     return &dotlockIoMethods;
34485:   }
34486: }
34487: static const sqlite3_io_methods 
34488:   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
34489: 
34490: #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
34491: 
34492: #if OS_VXWORKS
34493: /*
34494: ** This "finder" function for VxWorks checks to see if posix advisory
34495: ** locking works.  If it does, then that is what is used.  If it does not
34496: ** work, then fallback to named semaphore locking.
34497: */
34498: static const sqlite3_io_methods *vxworksIoFinderImpl(
34499:   const char *filePath,    /* name of the database file */
34500:   unixFile *pNew           /* the open file object */
34501: ){
34502:   struct flock lockInfo;
34503: 
34504:   if( !filePath ){
34505:     /* If filePath==NULL that means we are dealing with a transient file
34506:     ** that does not need to be locked. */
34507:     return &nolockIoMethods;
34508:   }
34509: 
34510:   /* Test if fcntl() is supported and use POSIX style locks.
34511:   ** Otherwise fall back to the named semaphore method.
34512:   */
34513:   lockInfo.l_len = 1;
34514:   lockInfo.l_start = 0;
34515:   lockInfo.l_whence = SEEK_SET;
34516:   lockInfo.l_type = F_RDLCK;
34517:   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34518:     return &posixIoMethods;
34519:   }else{
34520:     return &semIoMethods;
34521:   }
34522: }
34523: static const sqlite3_io_methods 
34524:   *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
34525: 
34526: #endif /* OS_VXWORKS */
34527: 
34528: /*
34529: ** An abstract type for a pointer to an IO method finder function:
34530: */
34531: typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
34532: 
34533: 
34534: /****************************************************************************
34535: **************************** sqlite3_vfs methods ****************************
34536: **
34537: ** This division contains the implementation of methods on the
34538: ** sqlite3_vfs object.
34539: */
34540: 
34541: /*
34542: ** Initialize the contents of the unixFile structure pointed to by pId.
34543: */
34544: static int fillInUnixFile(
34545:   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
34546:   int h,                  /* Open file descriptor of file being opened */
34547:   sqlite3_file *pId,      /* Write to the unixFile structure here */
34548:   const char *zFilename,  /* Name of the file being opened */
34549:   int ctrlFlags           /* Zero or more UNIXFILE_* values */
34550: ){
34551:   const sqlite3_io_methods *pLockingStyle;
34552:   unixFile *pNew = (unixFile *)pId;
34553:   int rc = SQLITE_OK;
34554: 
34555:   assert( pNew->pInode==NULL );
34556: 
34557:   /* Usually the path zFilename should not be a relative pathname. The
34558:   ** exception is when opening the proxy "conch" file in builds that
34559:   ** include the special Apple locking styles.
34560:   */
34561: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34562:   assert( zFilename==0 || zFilename[0]=='/' 
34563:     || pVfs->pAppData==(void*)&autolockIoFinder );
34564: #else
34565:   assert( zFilename==0 || zFilename[0]=='/' );
34566: #endif
34567: 
34568:   /* No locking occurs in temporary files */
34569:   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
34570: 
34571:   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
34572:   pNew->h = h;
34573:   pNew->pVfs = pVfs;
34574:   pNew->zPath = zFilename;
34575:   pNew->ctrlFlags = (u8)ctrlFlags;
34576: #if SQLITE_MAX_MMAP_SIZE>0
34577:   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34578: #endif
34579:   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
34580:                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34581:     pNew->ctrlFlags |= UNIXFILE_PSOW;
34582:   }
34583:   if( strcmp(pVfs->zName,"unix-excl")==0 ){
34584:     pNew->ctrlFlags |= UNIXFILE_EXCL;
34585:   }
34586: 
34587: #if OS_VXWORKS
34588:   pNew->pId = vxworksFindFileId(zFilename);
34589:   if( pNew->pId==0 ){
34590:     ctrlFlags |= UNIXFILE_NOLOCK;
34591:     rc = SQLITE_NOMEM_BKPT;
34592:   }
34593: #endif
34594: 
34595:   if( ctrlFlags & UNIXFILE_NOLOCK ){
34596:     pLockingStyle = &nolockIoMethods;
34597:   }else{
34598:     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
34599: #if SQLITE_ENABLE_LOCKING_STYLE
34600:     /* Cache zFilename in the locking context (AFP and dotlock override) for
34601:     ** proxyLock activation is possible (remote proxy is based on db name)
34602:     ** zFilename remains valid until file is closed, to support */
34603:     pNew->lockingContext = (void*)zFilename;
34604: #endif
34605:   }
34606: 
34607:   if( pLockingStyle == &posixIoMethods
34608: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34609:     || pLockingStyle == &nfsIoMethods
34610: #endif
34611:   ){
34612:     unixEnterMutex();
34613:     rc = findInodeInfo(pNew, &pNew->pInode);
34614:     if( rc!=SQLITE_OK ){
34615:       /* If an error occurred in findInodeInfo(), close the file descriptor
34616:       ** immediately, before releasing the mutex. findInodeInfo() may fail
34617:       ** in two scenarios:
34618:       **
34619:       **   (a) A call to fstat() failed.
34620:       **   (b) A malloc failed.
34621:       **
34622:       ** Scenario (b) may only occur if the process is holding no other
34623:       ** file descriptors open on the same file. If there were other file
34624:       ** descriptors on this file, then no malloc would be required by
34625:       ** findInodeInfo(). If this is the case, it is quite safe to close
34626:       ** handle h - as it is guaranteed that no posix locks will be released
34627:       ** by doing so.
34628:       **
34629:       ** If scenario (a) caused the error then things are not so safe. The
34630:       ** implicit assumption here is that if fstat() fails, things are in
34631:       ** such bad shape that dropping a lock or two doesn't matter much.
34632:       */
34633:       robust_close(pNew, h, __LINE__);
34634:       h = -1;
34635:     }
34636:     unixLeaveMutex();
34637:   }
34638: 
34639: #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34640:   else if( pLockingStyle == &afpIoMethods ){
34641:     /* AFP locking uses the file path so it needs to be included in
34642:     ** the afpLockingContext.
34643:     */
34644:     afpLockingContext *pCtx;
34645:     pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
34646:     if( pCtx==0 ){
34647:       rc = SQLITE_NOMEM_BKPT;
34648:     }else{
34649:       /* NB: zFilename exists and remains valid until the file is closed
34650:       ** according to requirement F11141.  So we do not need to make a
34651:       ** copy of the filename. */
34652:       pCtx->dbPath = zFilename;
34653:       pCtx->reserved = 0;
34654:       srandomdev();
34655:       unixEnterMutex();
34656:       rc = findInodeInfo(pNew, &pNew->pInode);
34657:       if( rc!=SQLITE_OK ){
34658:         sqlite3_free(pNew->lockingContext);
34659:         robust_close(pNew, h, __LINE__);
34660:         h = -1;
34661:       }
34662:       unixLeaveMutex();        
34663:     }
34664:   }
34665: #endif
34666: 
34667:   else if( pLockingStyle == &dotlockIoMethods ){
34668:     /* Dotfile locking uses the file path so it needs to be included in
34669:     ** the dotlockLockingContext 
34670:     */
34671:     char *zLockFile;
34672:     int nFilename;
34673:     assert( zFilename!=0 );
34674:     nFilename = (int)strlen(zFilename) + 6;
34675:     zLockFile = (char *)sqlite3_malloc64(nFilename);
34676:     if( zLockFile==0 ){
34677:       rc = SQLITE_NOMEM_BKPT;
34678:     }else{
34679:       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
34680:     }
34681:     pNew->lockingContext = zLockFile;
34682:   }
34683: 
34684: #if OS_VXWORKS
34685:   else if( pLockingStyle == &semIoMethods ){
34686:     /* Named semaphore locking uses the file path so it needs to be
34687:     ** included in the semLockingContext
34688:     */
34689:     unixEnterMutex();
34690:     rc = findInodeInfo(pNew, &pNew->pInode);
34691:     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
34692:       char *zSemName = pNew->pInode->aSemName;
34693:       int n;
34694:       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
34695:                        pNew->pId->zCanonicalName);
34696:       for( n=1; zSemName[n]; n++ )
34697:         if( zSemName[n]=='/' ) zSemName[n] = '_';
34698:       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
34699:       if( pNew->pInode->pSem == SEM_FAILED ){
34700:         rc = SQLITE_NOMEM_BKPT;
34701:         pNew->pInode->aSemName[0] = '\0';
34702:       }
34703:     }
34704:     unixLeaveMutex();
34705:   }
34706: #endif
34707:   
34708:   storeLastErrno(pNew, 0);
34709: #if OS_VXWORKS
34710:   if( rc!=SQLITE_OK ){
34711:     if( h>=0 ) robust_close(pNew, h, __LINE__);
34712:     h = -1;
34713:     osUnlink(zFilename);
34714:     pNew->ctrlFlags |= UNIXFILE_DELETE;
34715:   }
34716: #endif
34717:   if( rc!=SQLITE_OK ){
34718:     if( h>=0 ) robust_close(pNew, h, __LINE__);
34719:   }else{
34720:     pNew->pMethod = pLockingStyle;
34721:     OpenCounter(+1);
34722:     verifyDbFile(pNew);
34723:   }
34724:   return rc;
34725: }
34726: 
34727: /*
34728: ** Return the name of a directory in which to put temporary files.
34729: ** If no suitable temporary file directory can be found, return NULL.
34730: */
34731: static const char *unixTempFileDir(void){
34732:   static const char *azDirs[] = {
34733:      0,
34734:      0,
34735:      "/var/tmp",
34736:      "/usr/tmp",
34737:      "/tmp",
34738:      "."
34739:   };
34740:   unsigned int i = 0;
34741:   struct stat buf;
34742:   const char *zDir = sqlite3_temp_directory;
34743: 
34744:   if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
34745:   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
34746:   while(1){
34747:     if( zDir!=0
34748:      && osStat(zDir, &buf)==0
34749:      && S_ISDIR(buf.st_mode)
34750:      && osAccess(zDir, 03)==0
34751:     ){
34752:       return zDir;
34753:     }
34754:     if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
34755:     zDir = azDirs[i++];
34756:   }
34757:   return 0;
34758: }
34759: 
34760: /*
34761: ** Create a temporary file name in zBuf.  zBuf must be allocated
34762: ** by the calling process and must be big enough to hold at least
34763: ** pVfs->mxPathname bytes.
34764: */
34765: static int unixGetTempname(int nBuf, char *zBuf){
34766:   const char *zDir;
34767:   int iLimit = 0;
34768: 
34769:   /* It's odd to simulate an io-error here, but really this is just
34770:   ** using the io-error infrastructure to test that SQLite handles this
34771:   ** function failing. 
34772:   */
34773:   zBuf[0] = 0;
34774:   SimulateIOError( return SQLITE_IOERR );
34775: 
34776:   zDir = unixTempFileDir();
34777:   if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
34778:   do{
34779:     u64 r;
34780:     sqlite3_randomness(sizeof(r), &r);
34781:     assert( nBuf>2 );
34782:     zBuf[nBuf-2] = 0;
34783:     sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
34784:                      zDir, r, 0);
34785:     if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
34786:   }while( osAccess(zBuf,0)==0 );
34787:   return SQLITE_OK;
34788: }
34789: 
34790: #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34791: /*
34792: ** Routine to transform a unixFile into a proxy-locking unixFile.
34793: ** Implementation in the proxy-lock division, but used by unixOpen()
34794: ** if SQLITE_PREFER_PROXY_LOCKING is defined.
34795: */
34796: static int proxyTransformUnixFile(unixFile*, const char*);
34797: #endif
34798: 
34799: /*
34800: ** Search for an unused file descriptor that was opened on the database 
34801: ** file (not a journal or master-journal file) identified by pathname
34802: ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
34803: ** argument to this function.
34804: **
34805: ** Such a file descriptor may exist if a database connection was closed
34806: ** but the associated file descriptor could not be closed because some
34807: ** other file descriptor open on the same file is holding a file-lock.
34808: ** Refer to comments in the unixClose() function and the lengthy comment
34809: ** describing "Posix Advisory Locking" at the start of this file for 
34810: ** further details. Also, ticket #4018.
34811: **
34812: ** If a suitable file descriptor is found, then it is returned. If no
34813: ** such file descriptor is located, -1 is returned.
34814: */
34815: static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
34816:   UnixUnusedFd *pUnused = 0;
34817: 
34818:   /* Do not search for an unused file descriptor on vxworks. Not because
34819:   ** vxworks would not benefit from the change (it might, we're not sure),
34820:   ** but because no way to test it is currently available. It is better 
34821:   ** not to risk breaking vxworks support for the sake of such an obscure 
34822:   ** feature.  */
34823: #if !OS_VXWORKS
34824:   struct stat sStat;                   /* Results of stat() call */
34825: 
34826:   /* A stat() call may fail for various reasons. If this happens, it is
34827:   ** almost certain that an open() call on the same path will also fail.
34828:   ** For this reason, if an error occurs in the stat() call here, it is
34829:   ** ignored and -1 is returned. The caller will try to open a new file
34830:   ** descriptor on the same path, fail, and return an error to SQLite.
34831:   **
34832:   ** Even if a subsequent open() call does succeed, the consequences of
34833:   ** not searching for a reusable file descriptor are not dire.  */
34834:   if( 0==osStat(zPath, &sStat) ){
34835:     unixInodeInfo *pInode;
34836: 
34837:     unixEnterMutex();
34838:     pInode = inodeList;
34839:     while( pInode && (pInode->fileId.dev!=sStat.st_dev
34840:                      || pInode->fileId.ino!=sStat.st_ino) ){
34841:        pInode = pInode->pNext;
34842:     }
34843:     if( pInode ){
34844:       UnixUnusedFd **pp;
34845:       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
34846:       pUnused = *pp;
34847:       if( pUnused ){
34848:         *pp = pUnused->pNext;
34849:       }
34850:     }
34851:     unixLeaveMutex();
34852:   }
34853: #endif    /* if !OS_VXWORKS */
34854:   return pUnused;
34855: }
34856: 
34857: /*
34858: ** This function is called by unixOpen() to determine the unix permissions
34859: ** to create new files with. If no error occurs, then SQLITE_OK is returned
34860: ** and a value suitable for passing as the third argument to open(2) is
34861: ** written to *pMode. If an IO error occurs, an SQLite error code is 
34862: ** returned and the value of *pMode is not modified.
34863: **
34864: ** In most cases, this routine sets *pMode to 0, which will become
34865: ** an indication to robust_open() to create the file using
34866: ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
34867: ** But if the file being opened is a WAL or regular journal file, then 
34868: ** this function queries the file-system for the permissions on the 
34869: ** corresponding database file and sets *pMode to this value. Whenever 
34870: ** possible, WAL and journal files are created using the same permissions 
34871: ** as the associated database file.
34872: **
34873: ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
34874: ** original filename is unavailable.  But 8_3_NAMES is only used for
34875: ** FAT filesystems and permissions do not matter there, so just use
34876: ** the default permissions.
34877: */
34878: static int findCreateFileMode(
34879:   const char *zPath,              /* Path of file (possibly) being created */
34880:   int flags,                      /* Flags passed as 4th argument to xOpen() */
34881:   mode_t *pMode,                  /* OUT: Permissions to open file with */
34882:   uid_t *pUid,                    /* OUT: uid to set on the file */
34883:   gid_t *pGid                     /* OUT: gid to set on the file */
34884: ){
34885:   int rc = SQLITE_OK;             /* Return Code */
34886:   *pMode = 0;
34887:   *pUid = 0;
34888:   *pGid = 0;
34889:   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
34890:     char zDb[MAX_PATHNAME+1];     /* Database file path */
34891:     int nDb;                      /* Number of valid bytes in zDb */
34892:     struct stat sStat;            /* Output of stat() on database file */
34893: 
34894:     /* zPath is a path to a WAL or journal file. The following block derives
34895:     ** the path to the associated database file from zPath. This block handles
34896:     ** the following naming conventions:
34897:     **
34898:     **   "<path to db>-journal"
34899:     **   "<path to db>-wal"
34900:     **   "<path to db>-journalNN"
34901:     **   "<path to db>-walNN"
34902:     **
34903:     ** where NN is a decimal number. The NN naming schemes are 
34904:     ** used by the test_multiplex.c module.
34905:     */
34906:     nDb = sqlite3Strlen30(zPath) - 1; 
34907:     while( zPath[nDb]!='-' ){
34908: #ifndef SQLITE_ENABLE_8_3_NAMES
34909:       /* In the normal case (8+3 filenames disabled) the journal filename
34910:       ** is guaranteed to contain a '-' character. */
34911:       assert( nDb>0 );
34912:       assert( sqlite3Isalnum(zPath[nDb]) );
34913: #else
34914:       /* If 8+3 names are possible, then the journal file might not contain
34915:       ** a '-' character.  So check for that case and return early. */
34916:       if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
34917: #endif
34918:       nDb--;
34919:     }
34920:     memcpy(zDb, zPath, nDb);
34921:     zDb[nDb] = '\0';
34922: 
34923:     if( 0==osStat(zDb, &sStat) ){
34924:       *pMode = sStat.st_mode & 0777;
34925:       *pUid = sStat.st_uid;
34926:       *pGid = sStat.st_gid;
34927:     }else{
34928:       rc = SQLITE_IOERR_FSTAT;
34929:     }
34930:   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
34931:     *pMode = 0600;
34932:   }
34933:   return rc;
34934: }
34935: 
34936: /*
34937: ** Open the file zPath.
34938: ** 
34939: ** Previously, the SQLite OS layer used three functions in place of this
34940: ** one:
34941: **
34942: **     sqlite3OsOpenReadWrite();
34943: **     sqlite3OsOpenReadOnly();
34944: **     sqlite3OsOpenExclusive();
34945: **
34946: ** These calls correspond to the following combinations of flags:
34947: **
34948: **     ReadWrite() ->     (READWRITE | CREATE)
34949: **     ReadOnly()  ->     (READONLY) 
34950: **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
34951: **
34952: ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
34953: ** true, the file was configured to be automatically deleted when the
34954: ** file handle closed. To achieve the same effect using this new 
34955: ** interface, add the DELETEONCLOSE flag to those specified above for 
34956: ** OpenExclusive().
34957: */
34958: static int unixOpen(
34959:   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
34960:   const char *zPath,           /* Pathname of file to be opened */
34961:   sqlite3_file *pFile,         /* The file descriptor to be filled in */
34962:   int flags,                   /* Input flags to control the opening */
34963:   int *pOutFlags               /* Output flags returned to SQLite core */
34964: ){
34965:   unixFile *p = (unixFile *)pFile;
34966:   int fd = -1;                   /* File descriptor returned by open() */
34967:   int openFlags = 0;             /* Flags to pass to open() */
34968:   int eType = flags&0xFFFFFF00;  /* Type of file to open */
34969:   int noLock;                    /* True to omit locking primitives */
34970:   int rc = SQLITE_OK;            /* Function Return Code */
34971:   int ctrlFlags = 0;             /* UNIXFILE_* flags */
34972: 
34973:   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
34974:   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
34975:   int isCreate     = (flags & SQLITE_OPEN_CREATE);
34976:   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
34977:   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
34978: #if SQLITE_ENABLE_LOCKING_STYLE
34979:   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
34980: #endif
34981: #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
34982:   struct statfs fsInfo;
34983: #endif
34984: 
34985:   /* If creating a master or main-file journal, this function will open
34986:   ** a file-descriptor on the directory too. The first time unixSync()
34987:   ** is called the directory file descriptor will be fsync()ed and close()d.
34988:   */
34989:   int syncDir = (isCreate && (
34990:         eType==SQLITE_OPEN_MASTER_JOURNAL 
34991:      || eType==SQLITE_OPEN_MAIN_JOURNAL 
34992:      || eType==SQLITE_OPEN_WAL
34993:   ));
34994: 
34995:   /* If argument zPath is a NULL pointer, this function is required to open
34996:   ** a temporary file. Use this buffer to store the file name in.
34997:   */
34998:   char zTmpname[MAX_PATHNAME+2];
34999:   const char *zName = zPath;
35000: 
35001:   /* Check the following statements are true: 
35002:   **
35003:   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
35004:   **   (b) if CREATE is set, then READWRITE must also be set, and
35005:   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
35006:   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
35007:   */
35008:   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35009:   assert(isCreate==0 || isReadWrite);
35010:   assert(isExclusive==0 || isCreate);
35011:   assert(isDelete==0 || isCreate);
35012: 
35013:   /* The main DB, main journal, WAL file and master journal are never 
35014:   ** automatically deleted. Nor are they ever temporary files.  */
35015:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35016:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35017:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35018:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35019: 
35020:   /* Assert that the upper layer has set one of the "file-type" flags. */
35021:   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
35022:        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
35023:        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
35024:        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35025:   );
35026: 
35027:   /* Detect a pid change and reset the PRNG.  There is a race condition
35028:   ** here such that two or more threads all trying to open databases at
35029:   ** the same instant might all reset the PRNG.  But multiple resets
35030:   ** are harmless.
35031:   */
35032:   if( randomnessPid!=osGetpid(0) ){
35033:     randomnessPid = osGetpid(0);
35034:     sqlite3_randomness(0,0);
35035:   }
35036: 
35037:   memset(p, 0, sizeof(unixFile));
35038: 
35039:   if( eType==SQLITE_OPEN_MAIN_DB ){
35040:     UnixUnusedFd *pUnused;
35041:     pUnused = findReusableFd(zName, flags);
35042:     if( pUnused ){
35043:       fd = pUnused->fd;
35044:     }else{
35045:       pUnused = sqlite3_malloc64(sizeof(*pUnused));
35046:       if( !pUnused ){
35047:         return SQLITE_NOMEM_BKPT;
35048:       }
35049:     }
35050:     p->pUnused = pUnused;
35051: 
35052:     /* Database filenames are double-zero terminated if they are not
35053:     ** URIs with parameters.  Hence, they can always be passed into
35054:     ** sqlite3_uri_parameter(). */
35055:     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
35056: 
35057:   }else if( !zName ){
35058:     /* If zName is NULL, the upper layer is requesting a temp file. */
35059:     assert(isDelete && !syncDir);
35060:     rc = unixGetTempname(pVfs->mxPathname, zTmpname);
35061:     if( rc!=SQLITE_OK ){
35062:       return rc;
35063:     }
35064:     zName = zTmpname;
35065: 
35066:     /* Generated temporary filenames are always double-zero terminated
35067:     ** for use by sqlite3_uri_parameter(). */
35068:     assert( zName[strlen(zName)+1]==0 );
35069:   }
35070: 
35071:   /* Determine the value of the flags parameter passed to POSIX function
35072:   ** open(). These must be calculated even if open() is not called, as
35073:   ** they may be stored as part of the file handle and used by the 
35074:   ** 'conch file' locking functions later on.  */
35075:   if( isReadonly )  openFlags |= O_RDONLY;
35076:   if( isReadWrite ) openFlags |= O_RDWR;
35077:   if( isCreate )    openFlags |= O_CREAT;
35078:   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
35079:   openFlags |= (O_LARGEFILE|O_BINARY);
35080: 
35081:   if( fd<0 ){
35082:     mode_t openMode;              /* Permissions to create file with */
35083:     uid_t uid;                    /* Userid for the file */
35084:     gid_t gid;                    /* Groupid for the file */
35085:     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
35086:     if( rc!=SQLITE_OK ){
35087:       assert( !p->pUnused );
35088:       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
35089:       return rc;
35090:     }
35091:     fd = robust_open(zName, openFlags, openMode);
35092:     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
35093:     assert( !isExclusive || (openFlags & O_CREAT)!=0 );
35094:     if( fd<0 && errno!=EISDIR && isReadWrite ){
35095:       /* Failed to open the file for read/write access. Try read-only. */
35096:       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
35097:       openFlags &= ~(O_RDWR|O_CREAT);
35098:       flags |= SQLITE_OPEN_READONLY;
35099:       openFlags |= O_RDONLY;
35100:       isReadonly = 1;
35101:       fd = robust_open(zName, openFlags, openMode);
35102:     }
35103:     if( fd<0 ){
35104:       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
35105:       goto open_finished;
35106:     }
35107: 
35108:     /* If this process is running as root and if creating a new rollback
35109:     ** journal or WAL file, set the ownership of the journal or WAL to be
35110:     ** the same as the original database.
35111:     */
35112:     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
35113:       robustFchown(fd, uid, gid);
35114:     }
35115:   }
35116:   assert( fd>=0 );
35117:   if( pOutFlags ){
35118:     *pOutFlags = flags;
35119:   }
35120: 
35121:   if( p->pUnused ){
35122:     p->pUnused->fd = fd;
35123:     p->pUnused->flags = flags;
35124:   }
35125: 
35126:   if( isDelete ){
35127: #if OS_VXWORKS
35128:     zPath = zName;
35129: #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
35130:     zPath = sqlite3_mprintf("%s", zName);
35131:     if( zPath==0 ){
35132:       robust_close(p, fd, __LINE__);
35133:       return SQLITE_NOMEM_BKPT;
35134:     }
35135: #else
35136:     osUnlink(zName);
35137: #endif
35138:   }
35139: #if SQLITE_ENABLE_LOCKING_STYLE
35140:   else{
35141:     p->openFlags = openFlags;
35142:   }
35143: #endif
35144:   
35145: #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
35146:   if( fstatfs(fd, &fsInfo) == -1 ){
35147:     storeLastErrno(p, errno);
35148:     robust_close(p, fd, __LINE__);
35149:     return SQLITE_IOERR_ACCESS;
35150:   }
35151:   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
35152:     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35153:   }
35154:   if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
35155:     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
35156:   }
35157: #endif
35158: 
35159:   /* Set up appropriate ctrlFlags */
35160:   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
35161:   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
35162:   noLock = eType!=SQLITE_OPEN_MAIN_DB;
35163:   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
35164:   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
35165:   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
35166: 
35167: #if SQLITE_ENABLE_LOCKING_STYLE
35168: #if SQLITE_PREFER_PROXY_LOCKING
35169:   isAutoProxy = 1;
35170: #endif
35171:   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
35172:     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
35173:     int useProxy = 0;
35174: 
35175:     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
35176:     ** never use proxy, NULL means use proxy for non-local files only.  */
35177:     if( envforce!=NULL ){
35178:       useProxy = atoi(envforce)>0;
35179:     }else{
35180:       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
35181:     }
35182:     if( useProxy ){
35183:       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35184:       if( rc==SQLITE_OK ){
35185:         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
35186:         if( rc!=SQLITE_OK ){
35187:           /* Use unixClose to clean up the resources added in fillInUnixFile 
35188:           ** and clear all the structure's references.  Specifically, 
35189:           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
35190:           */
35191:           unixClose(pFile);
35192:           return rc;
35193:         }
35194:       }
35195:       goto open_finished;
35196:     }
35197:   }
35198: #endif
35199:   
35200:   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
35201: 
35202: open_finished:
35203:   if( rc!=SQLITE_OK ){
35204:     sqlite3_free(p->pUnused);
35205:   }
35206:   return rc;
35207: }
35208: 
35209: 
35210: /*
35211: ** Delete the file at zPath. If the dirSync argument is true, fsync()
35212: ** the directory after deleting the file.
35213: */
35214: static int unixDelete(
35215:   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
35216:   const char *zPath,        /* Name of file to be deleted */
35217:   int dirSync               /* If true, fsync() directory after deleting file */
35218: ){
35219:   int rc = SQLITE_OK;
35220:   UNUSED_PARAMETER(NotUsed);
35221:   SimulateIOError(return SQLITE_IOERR_DELETE);
35222:   if( osUnlink(zPath)==(-1) ){
35223:     if( errno==ENOENT
35224: #if OS_VXWORKS
35225:         || osAccess(zPath,0)!=0
35226: #endif
35227:     ){
35228:       rc = SQLITE_IOERR_DELETE_NOENT;
35229:     }else{
35230:       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
35231:     }
35232:     return rc;
35233:   }
35234: #ifndef SQLITE_DISABLE_DIRSYNC
35235:   if( (dirSync & 1)!=0 ){
35236:     int fd;
35237:     rc = osOpenDirectory(zPath, &fd);
35238:     if( rc==SQLITE_OK ){
35239:       if( full_fsync(fd,0,0) ){
35240:         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
35241:       }
35242:       robust_close(0, fd, __LINE__);
35243:     }else{
35244:       assert( rc==SQLITE_CANTOPEN );
35245:       rc = SQLITE_OK;
35246:     }
35247:   }
35248: #endif
35249:   return rc;
35250: }
35251: 
35252: /*
35253: ** Test the existence of or access permissions of file zPath. The
35254: ** test performed depends on the value of flags:
35255: **
35256: **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
35257: **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
35258: **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
35259: **
35260: ** Otherwise return 0.
35261: */
35262: static int unixAccess(
35263:   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
35264:   const char *zPath,      /* Path of the file to examine */
35265:   int flags,              /* What do we want to learn about the zPath file? */
35266:   int *pResOut            /* Write result boolean here */
35267: ){
35268:   UNUSED_PARAMETER(NotUsed);
35269:   SimulateIOError( return SQLITE_IOERR_ACCESS; );
35270:   assert( pResOut!=0 );
35271: 
35272:   /* The spec says there are three possible values for flags.  But only
35273:   ** two of them are actually used */
35274:   assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
35275: 
35276:   if( flags==SQLITE_ACCESS_EXISTS ){
35277:     struct stat buf;
35278:     *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
35279:   }else{
35280:     *pResOut = osAccess(zPath, W_OK|R_OK)==0;
35281:   }
35282:   return SQLITE_OK;
35283: }
35284: 
35285: /*
35286: **
35287: */
35288: static int mkFullPathname(
35289:   const char *zPath,              /* Input path */
35290:   char *zOut,                     /* Output buffer */
35291:   int nOut                        /* Allocated size of buffer zOut */
35292: ){
35293:   int nPath = sqlite3Strlen30(zPath);
35294:   int iOff = 0;
35295:   if( zPath[0]!='/' ){
35296:     if( osGetcwd(zOut, nOut-2)==0 ){
35297:       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
35298:     }
35299:     iOff = sqlite3Strlen30(zOut);
35300:     zOut[iOff++] = '/';
35301:   }
35302:   if( (iOff+nPath+1)>nOut ){
35303:     /* SQLite assumes that xFullPathname() nul-terminates the output buffer
35304:     ** even if it returns an error.  */
35305:     zOut[iOff] = '\0';
35306:     return SQLITE_CANTOPEN_BKPT;
35307:   }
35308:   sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
35309:   return SQLITE_OK;
35310: }
35311: 
35312: /*
35313: ** Turn a relative pathname into a full pathname. The relative path
35314: ** is stored as a nul-terminated string in the buffer pointed to by
35315: ** zPath. 
35316: **
35317: ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
35318: ** (in this case, MAX_PATHNAME bytes). The full-path is written to
35319: ** this buffer before returning.
35320: */
35321: static int unixFullPathname(
35322:   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35323:   const char *zPath,            /* Possibly relative input path */
35324:   int nOut,                     /* Size of output buffer in bytes */
35325:   char *zOut                    /* Output buffer */
35326: ){
35327: #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
35328:   return mkFullPathname(zPath, zOut, nOut);
35329: #else
35330:   int rc = SQLITE_OK;
35331:   int nByte;
35332:   int nLink = 1;                /* Number of symbolic links followed so far */
35333:   const char *zIn = zPath;      /* Input path for each iteration of loop */
35334:   char *zDel = 0;
35335: 
35336:   assert( pVfs->mxPathname==MAX_PATHNAME );
35337:   UNUSED_PARAMETER(pVfs);
35338: 
35339:   /* It's odd to simulate an io-error here, but really this is just
35340:   ** using the io-error infrastructure to test that SQLite handles this
35341:   ** function failing. This function could fail if, for example, the
35342:   ** current working directory has been unlinked.
35343:   */
35344:   SimulateIOError( return SQLITE_ERROR );
35345: 
35346:   do {
35347: 
35348:     /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
35349:     ** link, or false otherwise.  */
35350:     int bLink = 0;
35351:     struct stat buf;
35352:     if( osLstat(zIn, &buf)!=0 ){
35353:       if( errno!=ENOENT ){
35354:         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
35355:       }
35356:     }else{
35357:       bLink = S_ISLNK(buf.st_mode);
35358:     }
35359: 
35360:     if( bLink ){
35361:       if( zDel==0 ){
35362:         zDel = sqlite3_malloc(nOut);
35363:         if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
35364:       }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
35365:         rc = SQLITE_CANTOPEN_BKPT;
35366:       }
35367: 
35368:       if( rc==SQLITE_OK ){
35369:         nByte = osReadlink(zIn, zDel, nOut-1);
35370:         if( nByte<0 ){
35371:           rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
35372:         }else{
35373:           if( zDel[0]!='/' ){
35374:             int n;
35375:             for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
35376:             if( nByte+n+1>nOut ){
35377:               rc = SQLITE_CANTOPEN_BKPT;
35378:             }else{
35379:               memmove(&zDel[n], zDel, nByte+1);
35380:               memcpy(zDel, zIn, n);
35381:               nByte += n;
35382:             }
35383:           }
35384:           zDel[nByte] = '\0';
35385:         }
35386:       }
35387: 
35388:       zIn = zDel;
35389:     }
35390: 
35391:     assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
35392:     if( rc==SQLITE_OK && zIn!=zOut ){
35393:       rc = mkFullPathname(zIn, zOut, nOut);
35394:     }
35395:     if( bLink==0 ) break;
35396:     zIn = zOut;
35397:   }while( rc==SQLITE_OK );
35398: 
35399:   sqlite3_free(zDel);
35400:   return rc;
35401: #endif   /* HAVE_READLINK && HAVE_LSTAT */
35402: }
35403: 
35404: 
35405: #ifndef SQLITE_OMIT_LOAD_EXTENSION
35406: /*
35407: ** Interfaces for opening a shared library, finding entry points
35408: ** within the shared library, and closing the shared library.
35409: */
35410: #include <dlfcn.h>
35411: static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
35412:   UNUSED_PARAMETER(NotUsed);
35413:   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
35414: }
35415: 
35416: /*
35417: ** SQLite calls this function immediately after a call to unixDlSym() or
35418: ** unixDlOpen() fails (returns a null pointer). If a more detailed error
35419: ** message is available, it is written to zBufOut. If no error message
35420: ** is available, zBufOut is left unmodified and SQLite uses a default
35421: ** error message.
35422: */
35423: static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
35424:   const char *zErr;
35425:   UNUSED_PARAMETER(NotUsed);
35426:   unixEnterMutex();
35427:   zErr = dlerror();
35428:   if( zErr ){
35429:     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
35430:   }
35431:   unixLeaveMutex();
35432: }
35433: static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
35434:   /* 
35435:   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
35436:   ** cast into a pointer to a function.  And yet the library dlsym() routine
35437:   ** returns a void* which is really a pointer to a function.  So how do we
35438:   ** use dlsym() with -pedantic-errors?
35439:   **
35440:   ** Variable x below is defined to be a pointer to a function taking
35441:   ** parameters void* and const char* and returning a pointer to a function.
35442:   ** We initialize x by assigning it a pointer to the dlsym() function.
35443:   ** (That assignment requires a cast.)  Then we call the function that
35444:   ** x points to.  
35445:   **
35446:   ** This work-around is unlikely to work correctly on any system where
35447:   ** you really cannot cast a function pointer into void*.  But then, on the
35448:   ** other hand, dlsym() will not work on such a system either, so we have
35449:   ** not really lost anything.
35450:   */
35451:   void (*(*x)(void*,const char*))(void);
35452:   UNUSED_PARAMETER(NotUsed);
35453:   x = (void(*(*)(void*,const char*))(void))dlsym;
35454:   return (*x)(p, zSym);
35455: }
35456: static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
35457:   UNUSED_PARAMETER(NotUsed);
35458:   dlclose(pHandle);
35459: }
35460: #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35461:   #define unixDlOpen  0
35462:   #define unixDlError 0
35463:   #define unixDlSym   0
35464:   #define unixDlClose 0
35465: #endif
35466: 
35467: /*
35468: ** Write nBuf bytes of random data to the supplied buffer zBuf.
35469: */
35470: static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
35471:   UNUSED_PARAMETER(NotUsed);
35472:   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
35473: 
35474:   /* We have to initialize zBuf to prevent valgrind from reporting
35475:   ** errors.  The reports issued by valgrind are incorrect - we would
35476:   ** prefer that the randomness be increased by making use of the
35477:   ** uninitialized space in zBuf - but valgrind errors tend to worry
35478:   ** some users.  Rather than argue, it seems easier just to initialize
35479:   ** the whole array and silence valgrind, even if that means less randomness
35480:   ** in the random seed.
35481:   **
35482:   ** When testing, initializing zBuf[] to zero is all we do.  That means
35483:   ** that we always use the same random number sequence.  This makes the
35484:   ** tests repeatable.
35485:   */
35486:   memset(zBuf, 0, nBuf);
35487:   randomnessPid = osGetpid(0);  
35488: #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
35489:   {
35490:     int fd, got;
35491:     fd = robust_open("/dev/urandom", O_RDONLY, 0);
35492:     if( fd<0 ){
35493:       time_t t;
35494:       time(&t);
35495:       memcpy(zBuf, &t, sizeof(t));
35496:       memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
35497:       assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
35498:       nBuf = sizeof(t) + sizeof(randomnessPid);
35499:     }else{
35500:       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
35501:       robust_close(0, fd, __LINE__);
35502:     }
35503:   }
35504: #endif
35505:   return nBuf;
35506: }
35507: 
35508: 
35509: /*
35510: ** Sleep for a little while.  Return the amount of time slept.
35511: ** The argument is the number of microseconds we want to sleep.
35512: ** The return value is the number of microseconds of sleep actually
35513: ** requested from the underlying operating system, a number which
35514: ** might be greater than or equal to the argument, but not less
35515: ** than the argument.
35516: */
35517: static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
35518: #if OS_VXWORKS
35519:   struct timespec sp;
35520: 
35521:   sp.tv_sec = microseconds / 1000000;
35522:   sp.tv_nsec = (microseconds % 1000000) * 1000;
35523:   nanosleep(&sp, NULL);
35524:   UNUSED_PARAMETER(NotUsed);
35525:   return microseconds;
35526: #elif defined(HAVE_USLEEP) && HAVE_USLEEP
35527:   usleep(microseconds);
35528:   UNUSED_PARAMETER(NotUsed);
35529:   return microseconds;
35530: #else
35531:   int seconds = (microseconds+999999)/1000000;
35532:   sleep(seconds);
35533:   UNUSED_PARAMETER(NotUsed);
35534:   return seconds*1000000;
35535: #endif
35536: }
35537: 
35538: /*
35539: ** The following variable, if set to a non-zero value, is interpreted as
35540: ** the number of seconds since 1970 and is used to set the result of
35541: ** sqlite3OsCurrentTime() during testing.
35542: */
35543: #ifdef SQLITE_TEST
35544: SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
35545: #endif
35546: 
35547: /*
35548: ** Find the current time (in Universal Coordinated Time).  Write into *piNow
35549: ** the current time and date as a Julian Day number times 86_400_000.  In
35550: ** other words, write into *piNow the number of milliseconds since the Julian
35551: ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35552: ** proleptic Gregorian calendar.
35553: **
35554: ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
35555: ** cannot be found.
35556: */
35557: static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
35558:   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35559:   int rc = SQLITE_OK;
35560: #if defined(NO_GETTOD)
35561:   time_t t;
35562:   time(&t);
35563:   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
35564: #elif OS_VXWORKS
35565:   struct timespec sNow;
35566:   clock_gettime(CLOCK_REALTIME, &sNow);
35567:   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
35568: #else
35569:   struct timeval sNow;
35570:   (void)gettimeofday(&sNow, 0);  /* Cannot fail given valid arguments */
35571:   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
35572: #endif
35573: 
35574: #ifdef SQLITE_TEST
35575:   if( sqlite3_current_time ){
35576:     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35577:   }
35578: #endif
35579:   UNUSED_PARAMETER(NotUsed);
35580:   return rc;
35581: }
35582: 
35583: #ifndef SQLITE_OMIT_DEPRECATED
35584: /*
35585: ** Find the current time (in Universal Coordinated Time).  Write the
35586: ** current time and date as a Julian Day number into *prNow and
35587: ** return 0.  Return 1 if the time and date cannot be found.
35588: */
35589: static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
35590:   sqlite3_int64 i = 0;
35591:   int rc;
35592:   UNUSED_PARAMETER(NotUsed);
35593:   rc = unixCurrentTimeInt64(0, &i);
35594:   *prNow = i/86400000.0;
35595:   return rc;
35596: }
35597: #else
35598: # define unixCurrentTime 0
35599: #endif
35600: 
35601: /*
35602: ** The xGetLastError() method is designed to return a better
35603: ** low-level error message when operating-system problems come up
35604: ** during SQLite operation.  Only the integer return code is currently
35605: ** used.
35606: */
35607: static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
35608:   UNUSED_PARAMETER(NotUsed);
35609:   UNUSED_PARAMETER(NotUsed2);
35610:   UNUSED_PARAMETER(NotUsed3);
35611:   return errno;
35612: }
35613: 
35614: 
35615: /*
35616: ************************ End of sqlite3_vfs methods ***************************
35617: ******************************************************************************/
35618: 
35619: /******************************************************************************
35620: ************************** Begin Proxy Locking ********************************
35621: **
35622: ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
35623: ** other locking methods on secondary lock files.  Proxy locking is a
35624: ** meta-layer over top of the primitive locking implemented above.  For
35625: ** this reason, the division that implements of proxy locking is deferred
35626: ** until late in the file (here) after all of the other I/O methods have
35627: ** been defined - so that the primitive locking methods are available
35628: ** as services to help with the implementation of proxy locking.
35629: **
35630: ****
35631: **
35632: ** The default locking schemes in SQLite use byte-range locks on the
35633: ** database file to coordinate safe, concurrent access by multiple readers
35634: ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
35635: ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
35636: ** as POSIX read & write locks over fixed set of locations (via fsctl),
35637: ** on AFP and SMB only exclusive byte-range locks are available via fsctl
35638: ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
35639: ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
35640: ** address in the shared range is taken for a SHARED lock, the entire
35641: ** shared range is taken for an EXCLUSIVE lock):
35642: **
35643: **      PENDING_BYTE        0x40000000
35644: **      RESERVED_BYTE       0x40000001
35645: **      SHARED_RANGE        0x40000002 -> 0x40000200
35646: **
35647: ** This works well on the local file system, but shows a nearly 100x
35648: ** slowdown in read performance on AFP because the AFP client disables
35649: ** the read cache when byte-range locks are present.  Enabling the read
35650: ** cache exposes a cache coherency problem that is present on all OS X
35651: ** supported network file systems.  NFS and AFP both observe the
35652: ** close-to-open semantics for ensuring cache coherency
35653: ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
35654: ** address the requirements for concurrent database access by multiple
35655: ** readers and writers
35656: ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
35657: **
35658: ** To address the performance and cache coherency issues, proxy file locking
35659: ** changes the way database access is controlled by limiting access to a
35660: ** single host at a time and moving file locks off of the database file
35661: ** and onto a proxy file on the local file system.  
35662: **
35663: **
35664: ** Using proxy locks
35665: ** -----------------
35666: **
35667: ** C APIs
35668: **
35669: **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
35670: **                       <proxy_path> | ":auto:");
35671: **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
35672: **                       &<proxy_path>);
35673: **
35674: **
35675: ** SQL pragmas
35676: **
35677: **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
35678: **  PRAGMA [database.]lock_proxy_file
35679: **
35680: ** Specifying ":auto:" means that if there is a conch file with a matching
35681: ** host ID in it, the proxy path in the conch file will be used, otherwise
35682: ** a proxy path based on the user's temp dir
35683: ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
35684: ** actual proxy file name is generated from the name and path of the
35685: ** database file.  For example:
35686: **
35687: **       For database path "/Users/me/foo.db" 
35688: **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
35689: **
35690: ** Once a lock proxy is configured for a database connection, it can not
35691: ** be removed, however it may be switched to a different proxy path via
35692: ** the above APIs (assuming the conch file is not being held by another
35693: ** connection or process). 
35694: **
35695: **
35696: ** How proxy locking works
35697: ** -----------------------
35698: **
35699: ** Proxy file locking relies primarily on two new supporting files: 
35700: **
35701: **   *  conch file to limit access to the database file to a single host
35702: **      at a time
35703: **
35704: **   *  proxy file to act as a proxy for the advisory locks normally
35705: **      taken on the database
35706: **
35707: ** The conch file - to use a proxy file, sqlite must first "hold the conch"
35708: ** by taking an sqlite-style shared lock on the conch file, reading the
35709: ** contents and comparing the host's unique host ID (see below) and lock
35710: ** proxy path against the values stored in the conch.  The conch file is
35711: ** stored in the same directory as the database file and the file name
35712: ** is patterned after the database file name as ".<databasename>-conch".
35713: ** If the conch file does not exist, or its contents do not match the
35714: ** host ID and/or proxy path, then the lock is escalated to an exclusive
35715: ** lock and the conch file contents is updated with the host ID and proxy
35716: ** path and the lock is downgraded to a shared lock again.  If the conch
35717: ** is held by another process (with a shared lock), the exclusive lock
35718: ** will fail and SQLITE_BUSY is returned.
35719: **
35720: ** The proxy file - a single-byte file used for all advisory file locks
35721: ** normally taken on the database file.   This allows for safe sharing
35722: ** of the database file for multiple readers and writers on the same
35723: ** host (the conch ensures that they all use the same local lock file).
35724: **
35725: ** Requesting the lock proxy does not immediately take the conch, it is
35726: ** only taken when the first request to lock database file is made.  
35727: ** This matches the semantics of the traditional locking behavior, where
35728: ** opening a connection to a database file does not take a lock on it.
35729: ** The shared lock and an open file descriptor are maintained until 
35730: ** the connection to the database is closed. 
35731: **
35732: ** The proxy file and the lock file are never deleted so they only need
35733: ** to be created the first time they are used.
35734: **
35735: ** Configuration options
35736: ** ---------------------
35737: **
35738: **  SQLITE_PREFER_PROXY_LOCKING
35739: **
35740: **       Database files accessed on non-local file systems are
35741: **       automatically configured for proxy locking, lock files are
35742: **       named automatically using the same logic as
35743: **       PRAGMA lock_proxy_file=":auto:"
35744: **    
35745: **  SQLITE_PROXY_DEBUG
35746: **
35747: **       Enables the logging of error messages during host id file
35748: **       retrieval and creation
35749: **
35750: **  LOCKPROXYDIR
35751: **
35752: **       Overrides the default directory used for lock proxy files that
35753: **       are named automatically via the ":auto:" setting
35754: **
35755: **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
35756: **
35757: **       Permissions to use when creating a directory for storing the
35758: **       lock proxy files, only used when LOCKPROXYDIR is not set.
35759: **    
35760: **    
35761: ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
35762: ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
35763: ** force proxy locking to be used for every database file opened, and 0
35764: ** will force automatic proxy locking to be disabled for all database
35765: ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
35766: ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
35767: */
35768: 
35769: /*
35770: ** Proxy locking is only available on MacOSX 
35771: */
35772: #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35773: 
35774: /*
35775: ** The proxyLockingContext has the path and file structures for the remote 
35776: ** and local proxy files in it
35777: */
35778: typedef struct proxyLockingContext proxyLockingContext;
35779: struct proxyLockingContext {
35780:   unixFile *conchFile;         /* Open conch file */
35781:   char *conchFilePath;         /* Name of the conch file */
35782:   unixFile *lockProxy;         /* Open proxy lock file */
35783:   char *lockProxyPath;         /* Name of the proxy lock file */
35784:   char *dbPath;                /* Name of the open file */
35785:   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
35786:   int nFails;                  /* Number of conch taking failures */
35787:   void *oldLockingContext;     /* Original lockingcontext to restore on close */
35788:   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
35789: };
35790: 
35791: /* 
35792: ** The proxy lock file path for the database at dbPath is written into lPath, 
35793: ** which must point to valid, writable memory large enough for a maxLen length
35794: ** file path. 
35795: */
35796: static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
35797:   int len;
35798:   int dbLen;
35799:   int i;
35800: 
35801: #ifdef LOCKPROXYDIR
35802:   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
35803: #else
35804: # ifdef _CS_DARWIN_USER_TEMP_DIR
35805:   {
35806:     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
35807:       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
35808:                lPath, errno, osGetpid(0)));
35809:       return SQLITE_IOERR_LOCK;
35810:     }
35811:     len = strlcat(lPath, "sqliteplocks", maxLen);    
35812:   }
35813: # else
35814:   len = strlcpy(lPath, "/tmp/", maxLen);
35815: # endif
35816: #endif
35817: 
35818:   if( lPath[len-1]!='/' ){
35819:     len = strlcat(lPath, "/", maxLen);
35820:   }
35821:   
35822:   /* transform the db path to a unique cache name */
35823:   dbLen = (int)strlen(dbPath);
35824:   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
35825:     char c = dbPath[i];
35826:     lPath[i+len] = (c=='/')?'_':c;
35827:   }
35828:   lPath[i+len]='\0';
35829:   strlcat(lPath, ":auto:", maxLen);
35830:   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
35831:   return SQLITE_OK;
35832: }
35833: 
35834: /* 
35835:  ** Creates the lock file and any missing directories in lockPath
35836:  */
35837: static int proxyCreateLockPath(const char *lockPath){
35838:   int i, len;
35839:   char buf[MAXPATHLEN];
35840:   int start = 0;
35841:   
35842:   assert(lockPath!=NULL);
35843:   /* try to create all the intermediate directories */
35844:   len = (int)strlen(lockPath);
35845:   buf[0] = lockPath[0];
35846:   for( i=1; i<len; i++ ){
35847:     if( lockPath[i] == '/' && (i - start > 0) ){
35848:       /* only mkdir if leaf dir != "." or "/" or ".." */
35849:       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
35850:          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
35851:         buf[i]='\0';
35852:         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
35853:           int err=errno;
35854:           if( err!=EEXIST ) {
35855:             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
35856:                      "'%s' proxy lock path=%s pid=%d\n",
35857:                      buf, strerror(err), lockPath, osGetpid(0)));
35858:             return err;
35859:           }
35860:         }
35861:       }
35862:       start=i+1;
35863:     }
35864:     buf[i] = lockPath[i];
35865:   }
35866:   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
35867:   return 0;
35868: }
35869: 
35870: /*
35871: ** Create a new VFS file descriptor (stored in memory obtained from
35872: ** sqlite3_malloc) and open the file named "path" in the file descriptor.
35873: **
35874: ** The caller is responsible not only for closing the file descriptor
35875: ** but also for freeing the memory associated with the file descriptor.
35876: */
35877: static int proxyCreateUnixFile(
35878:     const char *path,        /* path for the new unixFile */
35879:     unixFile **ppFile,       /* unixFile created and returned by ref */
35880:     int islockfile           /* if non zero missing dirs will be created */
35881: ) {
35882:   int fd = -1;
35883:   unixFile *pNew;
35884:   int rc = SQLITE_OK;
35885:   int openFlags = O_RDWR | O_CREAT;
35886:   sqlite3_vfs dummyVfs;
35887:   int terrno = 0;
35888:   UnixUnusedFd *pUnused = NULL;
35889: 
35890:   /* 1. first try to open/create the file
35891:   ** 2. if that fails, and this is a lock file (not-conch), try creating
35892:   ** the parent directories and then try again.
35893:   ** 3. if that fails, try to open the file read-only
35894:   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
35895:   */
35896:   pUnused = findReusableFd(path, openFlags);
35897:   if( pUnused ){
35898:     fd = pUnused->fd;
35899:   }else{
35900:     pUnused = sqlite3_malloc64(sizeof(*pUnused));
35901:     if( !pUnused ){
35902:       return SQLITE_NOMEM_BKPT;
35903:     }
35904:   }
35905:   if( fd<0 ){
35906:     fd = robust_open(path, openFlags, 0);
35907:     terrno = errno;
35908:     if( fd<0 && errno==ENOENT && islockfile ){
35909:       if( proxyCreateLockPath(path) == SQLITE_OK ){
35910:         fd = robust_open(path, openFlags, 0);
35911:       }
35912:     }
35913:   }
35914:   if( fd<0 ){
35915:     openFlags = O_RDONLY;
35916:     fd = robust_open(path, openFlags, 0);
35917:     terrno = errno;
35918:   }
35919:   if( fd<0 ){
35920:     if( islockfile ){
35921:       return SQLITE_BUSY;
35922:     }
35923:     switch (terrno) {
35924:       case EACCES:
35925:         return SQLITE_PERM;
35926:       case EIO: 
35927:         return SQLITE_IOERR_LOCK; /* even though it is the conch */
35928:       default:
35929:         return SQLITE_CANTOPEN_BKPT;
35930:     }
35931:   }
35932:   
35933:   pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
35934:   if( pNew==NULL ){
35935:     rc = SQLITE_NOMEM_BKPT;
35936:     goto end_create_proxy;
35937:   }
35938:   memset(pNew, 0, sizeof(unixFile));
35939:   pNew->openFlags = openFlags;
35940:   memset(&dummyVfs, 0, sizeof(dummyVfs));
35941:   dummyVfs.pAppData = (void*)&autolockIoFinder;
35942:   dummyVfs.zName = "dummy";
35943:   pUnused->fd = fd;
35944:   pUnused->flags = openFlags;
35945:   pNew->pUnused = pUnused;
35946:   
35947:   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
35948:   if( rc==SQLITE_OK ){
35949:     *ppFile = pNew;
35950:     return SQLITE_OK;
35951:   }
35952: end_create_proxy:    
35953:   robust_close(pNew, fd, __LINE__);
35954:   sqlite3_free(pNew);
35955:   sqlite3_free(pUnused);
35956:   return rc;
35957: }
35958: 
35959: #ifdef SQLITE_TEST
35960: /* simulate multiple hosts by creating unique hostid file paths */
35961: SQLITE_API int sqlite3_hostid_num = 0;
35962: #endif
35963: 
35964: #define PROXY_HOSTIDLEN    16  /* conch file host id length */
35965: 
35966: #ifdef HAVE_GETHOSTUUID
35967: /* Not always defined in the headers as it ought to be */
35968: extern int gethostuuid(uuid_t id, const struct timespec *wait);
35969: #endif
35970: 
35971: /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
35972: ** bytes of writable memory.
35973: */
35974: static int proxyGetHostID(unsigned char *pHostID, int *pError){
35975:   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
35976:   memset(pHostID, 0, PROXY_HOSTIDLEN);
35977: #ifdef HAVE_GETHOSTUUID
35978:   {
35979:     struct timespec timeout = {1, 0}; /* 1 sec timeout */
35980:     if( gethostuuid(pHostID, &timeout) ){
35981:       int err = errno;
35982:       if( pError ){
35983:         *pError = err;
35984:       }
35985:       return SQLITE_IOERR;
35986:     }
35987:   }
35988: #else
35989:   UNUSED_PARAMETER(pError);
35990: #endif
35991: #ifdef SQLITE_TEST
35992:   /* simulate multiple hosts by creating unique hostid file paths */
35993:   if( sqlite3_hostid_num != 0){
35994:     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
35995:   }
35996: #endif
35997:   
35998:   return SQLITE_OK;
35999: }
36000: 
36001: /* The conch file contains the header, host id and lock file path
36002:  */
36003: #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
36004: #define PROXY_HEADERLEN    1   /* conch file header length */
36005: #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
36006: #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
36007: 
36008: /* 
36009: ** Takes an open conch file, copies the contents to a new path and then moves 
36010: ** it back.  The newly created file's file descriptor is assigned to the
36011: ** conch file structure and finally the original conch file descriptor is 
36012: ** closed.  Returns zero if successful.
36013: */
36014: static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
36015:   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
36016:   unixFile *conchFile = pCtx->conchFile;
36017:   char tPath[MAXPATHLEN];
36018:   char buf[PROXY_MAXCONCHLEN];
36019:   char *cPath = pCtx->conchFilePath;
36020:   size_t readLen = 0;
36021:   size_t pathLen = 0;
36022:   char errmsg[64] = "";
36023:   int fd = -1;
36024:   int rc = -1;
36025:   UNUSED_PARAMETER(myHostID);
36026: 
36027:   /* create a new path by replace the trailing '-conch' with '-break' */
36028:   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
36029:   if( pathLen>MAXPATHLEN || pathLen<6 || 
36030:      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
36031:     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
36032:     goto end_breaklock;
36033:   }
36034:   /* read the conch content */
36035:   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
36036:   if( readLen<PROXY_PATHINDEX ){
36037:     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
36038:     goto end_breaklock;
36039:   }
36040:   /* write it out to the temporary break file */
36041:   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
36042:   if( fd<0 ){
36043:     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
36044:     goto end_breaklock;
36045:   }
36046:   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
36047:     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
36048:     goto end_breaklock;
36049:   }
36050:   if( rename(tPath, cPath) ){
36051:     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
36052:     goto end_breaklock;
36053:   }
36054:   rc = 0;
36055:   fprintf(stderr, "broke stale lock on %s\n", cPath);
36056:   robust_close(pFile, conchFile->h, __LINE__);
36057:   conchFile->h = fd;
36058:   conchFile->openFlags = O_RDWR | O_CREAT;
36059: 
36060: end_breaklock:
36061:   if( rc ){
36062:     if( fd>=0 ){
36063:       osUnlink(tPath);
36064:       robust_close(pFile, fd, __LINE__);
36065:     }
36066:     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
36067:   }
36068:   return rc;
36069: }
36070: 
36071: /* Take the requested lock on the conch file and break a stale lock if the 
36072: ** host id matches.
36073: */
36074: static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
36075:   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
36076:   unixFile *conchFile = pCtx->conchFile;
36077:   int rc = SQLITE_OK;
36078:   int nTries = 0;
36079:   struct timespec conchModTime;
36080:   
36081:   memset(&conchModTime, 0, sizeof(conchModTime));
36082:   do {
36083:     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36084:     nTries ++;
36085:     if( rc==SQLITE_BUSY ){
36086:       /* If the lock failed (busy):
36087:        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
36088:        * 2nd try: fail if the mod time changed or host id is different, wait 
36089:        *           10 sec and try again
36090:        * 3rd try: break the lock unless the mod time has changed.
36091:        */
36092:       struct stat buf;
36093:       if( osFstat(conchFile->h, &buf) ){
36094:         storeLastErrno(pFile, errno);
36095:         return SQLITE_IOERR_LOCK;
36096:       }
36097:       
36098:       if( nTries==1 ){
36099:         conchModTime = buf.st_mtimespec;
36100:         usleep(500000); /* wait 0.5 sec and try the lock again*/
36101:         continue;  
36102:       }
36103: 
36104:       assert( nTries>1 );
36105:       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
36106:          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
36107:         return SQLITE_BUSY;
36108:       }
36109:       
36110:       if( nTries==2 ){  
36111:         char tBuf[PROXY_MAXCONCHLEN];
36112:         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
36113:         if( len<0 ){
36114:           storeLastErrno(pFile, errno);
36115:           return SQLITE_IOERR_LOCK;
36116:         }
36117:         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
36118:           /* don't break the lock if the host id doesn't match */
36119:           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
36120:             return SQLITE_BUSY;
36121:           }
36122:         }else{
36123:           /* don't break the lock on short read or a version mismatch */
36124:           return SQLITE_BUSY;
36125:         }
36126:         usleep(10000000); /* wait 10 sec and try the lock again */
36127:         continue; 
36128:       }
36129:       
36130:       assert( nTries==3 );
36131:       if( 0==proxyBreakConchLock(pFile, myHostID) ){
36132:         rc = SQLITE_OK;
36133:         if( lockType==EXCLUSIVE_LOCK ){
36134:           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
36135:         }
36136:         if( !rc ){
36137:           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
36138:         }
36139:       }
36140:     }
36141:   } while( rc==SQLITE_BUSY && nTries<3 );
36142:   
36143:   return rc;
36144: }
36145: 
36146: /* Takes the conch by taking a shared lock and read the contents conch, if 
36147: ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
36148: ** lockPath means that the lockPath in the conch file will be used if the 
36149: ** host IDs match, or a new lock path will be generated automatically 
36150: ** and written to the conch file.
36151: */
36152: static int proxyTakeConch(unixFile *pFile){
36153:   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
36154:   
36155:   if( pCtx->conchHeld!=0 ){
36156:     return SQLITE_OK;
36157:   }else{
36158:     unixFile *conchFile = pCtx->conchFile;
36159:     uuid_t myHostID;
36160:     int pError = 0;
36161:     char readBuf[PROXY_MAXCONCHLEN];
36162:     char lockPath[MAXPATHLEN];
36163:     char *tempLockPath = NULL;
36164:     int rc = SQLITE_OK;
36165:     int createConch = 0;
36166:     int hostIdMatch = 0;
36167:     int readLen = 0;
36168:     int tryOldLockPath = 0;
36169:     int forceNewLockPath = 0;
36170:     
36171:     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
36172:              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36173:              osGetpid(0)));
36174: 
36175:     rc = proxyGetHostID(myHostID, &pError);
36176:     if( (rc&0xff)==SQLITE_IOERR ){
36177:       storeLastErrno(pFile, pError);
36178:       goto end_takeconch;
36179:     }
36180:     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
36181:     if( rc!=SQLITE_OK ){
36182:       goto end_takeconch;
36183:     }
36184:     /* read the existing conch file */
36185:     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
36186:     if( readLen<0 ){
36187:       /* I/O error: lastErrno set by seekAndRead */
36188:       storeLastErrno(pFile, conchFile->lastErrno);
36189:       rc = SQLITE_IOERR_READ;
36190:       goto end_takeconch;
36191:     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
36192:              readBuf[0]!=(char)PROXY_CONCHVERSION ){
36193:       /* a short read or version format mismatch means we need to create a new 
36194:       ** conch file. 
36195:       */
36196:       createConch = 1;
36197:     }
36198:     /* if the host id matches and the lock path already exists in the conch
36199:     ** we'll try to use the path there, if we can't open that path, we'll 
36200:     ** retry with a new auto-generated path 
36201:     */
36202:     do { /* in case we need to try again for an :auto: named lock file */
36203: 
36204:       if( !createConch && !forceNewLockPath ){
36205:         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
36206:                                   PROXY_HOSTIDLEN);
36207:         /* if the conch has data compare the contents */
36208:         if( !pCtx->lockProxyPath ){
36209:           /* for auto-named local lock file, just check the host ID and we'll
36210:            ** use the local lock file path that's already in there
36211:            */
36212:           if( hostIdMatch ){
36213:             size_t pathLen = (readLen - PROXY_PATHINDEX);
36214:             
36215:             if( pathLen>=MAXPATHLEN ){
36216:               pathLen=MAXPATHLEN-1;
36217:             }
36218:             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
36219:             lockPath[pathLen] = 0;
36220:             tempLockPath = lockPath;
36221:             tryOldLockPath = 1;
36222:             /* create a copy of the lock path if the conch is taken */
36223:             goto end_takeconch;
36224:           }
36225:         }else if( hostIdMatch
36226:                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
36227:                            readLen-PROXY_PATHINDEX)
36228:         ){
36229:           /* conch host and lock path match */
36230:           goto end_takeconch; 
36231:         }
36232:       }
36233:       
36234:       /* if the conch isn't writable and doesn't match, we can't take it */
36235:       if( (conchFile->openFlags&O_RDWR) == 0 ){
36236:         rc = SQLITE_BUSY;
36237:         goto end_takeconch;
36238:       }
36239:       
36240:       /* either the conch didn't match or we need to create a new one */
36241:       if( !pCtx->lockProxyPath ){
36242:         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
36243:         tempLockPath = lockPath;
36244:         /* create a copy of the lock path _only_ if the conch is taken */
36245:       }
36246:       
36247:       /* update conch with host and path (this will fail if other process
36248:       ** has a shared lock already), if the host id matches, use the big
36249:       ** stick.
36250:       */
36251:       futimes(conchFile->h, NULL);
36252:       if( hostIdMatch && !createConch ){
36253:         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
36254:           /* We are trying for an exclusive lock but another thread in this
36255:            ** same process is still holding a shared lock. */
36256:           rc = SQLITE_BUSY;
36257:         } else {          
36258:           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36259:         }
36260:       }else{
36261:         rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
36262:       }
36263:       if( rc==SQLITE_OK ){
36264:         char writeBuffer[PROXY_MAXCONCHLEN];
36265:         int writeSize = 0;
36266:         
36267:         writeBuffer[0] = (char)PROXY_CONCHVERSION;
36268:         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
36269:         if( pCtx->lockProxyPath!=NULL ){
36270:           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
36271:                   MAXPATHLEN);
36272:         }else{
36273:           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
36274:         }
36275:         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
36276:         robust_ftruncate(conchFile->h, writeSize);
36277:         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
36278:         full_fsync(conchFile->h,0,0);
36279:         /* If we created a new conch file (not just updated the contents of a 
36280:          ** valid conch file), try to match the permissions of the database 
36281:          */
36282:         if( rc==SQLITE_OK && createConch ){
36283:           struct stat buf;
36284:           int err = osFstat(pFile->h, &buf);
36285:           if( err==0 ){
36286:             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
36287:                                         S_IROTH|S_IWOTH);
36288:             /* try to match the database file R/W permissions, ignore failure */
36289: #ifndef SQLITE_PROXY_DEBUG
36290:             osFchmod(conchFile->h, cmode);
36291: #else
36292:             do{
36293:               rc = osFchmod(conchFile->h, cmode);
36294:             }while( rc==(-1) && errno==EINTR );
36295:             if( rc!=0 ){
36296:               int code = errno;
36297:               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
36298:                       cmode, code, strerror(code));
36299:             } else {
36300:               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
36301:             }
36302:           }else{
36303:             int code = errno;
36304:             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
36305:                     err, code, strerror(code));
36306: #endif
36307:           }
36308:         }
36309:       }
36310:       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
36311:       
36312:     end_takeconch:
36313:       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
36314:       if( rc==SQLITE_OK && pFile->openFlags ){
36315:         int fd;
36316:         if( pFile->h>=0 ){
36317:           robust_close(pFile, pFile->h, __LINE__);
36318:         }
36319:         pFile->h = -1;
36320:         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
36321:         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
36322:         if( fd>=0 ){
36323:           pFile->h = fd;
36324:         }else{
36325:           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
36326:            during locking */
36327:         }
36328:       }
36329:       if( rc==SQLITE_OK && !pCtx->lockProxy ){
36330:         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
36331:         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
36332:         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
36333:           /* we couldn't create the proxy lock file with the old lock file path
36334:            ** so try again via auto-naming 
36335:            */
36336:           forceNewLockPath = 1;
36337:           tryOldLockPath = 0;
36338:           continue; /* go back to the do {} while start point, try again */
36339:         }
36340:       }
36341:       if( rc==SQLITE_OK ){
36342:         /* Need to make a copy of path if we extracted the value
36343:          ** from the conch file or the path was allocated on the stack
36344:          */
36345:         if( tempLockPath ){
36346:           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
36347:           if( !pCtx->lockProxyPath ){
36348:             rc = SQLITE_NOMEM_BKPT;
36349:           }
36350:         }
36351:       }
36352:       if( rc==SQLITE_OK ){
36353:         pCtx->conchHeld = 1;
36354:         
36355:         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
36356:           afpLockingContext *afpCtx;
36357:           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
36358:           afpCtx->dbPath = pCtx->lockProxyPath;
36359:         }
36360:       } else {
36361:         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36362:       }
36363:       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
36364:                rc==SQLITE_OK?"ok":"failed"));
36365:       return rc;
36366:     } while (1); /* in case we need to retry the :auto: lock file - 
36367:                  ** we should never get here except via the 'continue' call. */
36368:   }
36369: }
36370: 
36371: /*
36372: ** If pFile holds a lock on a conch file, then release that lock.
36373: */
36374: static int proxyReleaseConch(unixFile *pFile){
36375:   int rc = SQLITE_OK;         /* Subroutine return code */
36376:   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
36377:   unixFile *conchFile;        /* Name of the conch file */
36378: 
36379:   pCtx = (proxyLockingContext *)pFile->lockingContext;
36380:   conchFile = pCtx->conchFile;
36381:   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
36382:            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
36383:            osGetpid(0)));
36384:   if( pCtx->conchHeld>0 ){
36385:     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36386:   }
36387:   pCtx->conchHeld = 0;
36388:   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
36389:            (rc==SQLITE_OK ? "ok" : "failed")));
36390:   return rc;
36391: }
36392: 
36393: /*
36394: ** Given the name of a database file, compute the name of its conch file.
36395: ** Store the conch filename in memory obtained from sqlite3_malloc64().
36396: ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
36397: ** or SQLITE_NOMEM if unable to obtain memory.
36398: **
36399: ** The caller is responsible for ensuring that the allocated memory
36400: ** space is eventually freed.
36401: **
36402: ** *pConchPath is set to NULL if a memory allocation error occurs.
36403: */
36404: static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
36405:   int i;                        /* Loop counter */
36406:   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
36407:   char *conchPath;              /* buffer in which to construct conch name */
36408: 
36409:   /* Allocate space for the conch filename and initialize the name to
36410:   ** the name of the original database file. */  
36411:   *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
36412:   if( conchPath==0 ){
36413:     return SQLITE_NOMEM_BKPT;
36414:   }
36415:   memcpy(conchPath, dbPath, len+1);
36416:   
36417:   /* now insert a "." before the last / character */
36418:   for( i=(len-1); i>=0; i-- ){
36419:     if( conchPath[i]=='/' ){
36420:       i++;
36421:       break;
36422:     }
36423:   }
36424:   conchPath[i]='.';
36425:   while ( i<len ){
36426:     conchPath[i+1]=dbPath[i];
36427:     i++;
36428:   }
36429: 
36430:   /* append the "-conch" suffix to the file */
36431:   memcpy(&conchPath[i+1], "-conch", 7);
36432:   assert( (int)strlen(conchPath) == len+7 );
36433: 
36434:   return SQLITE_OK;
36435: }
36436: 
36437: 
36438: /* Takes a fully configured proxy locking-style unix file and switches
36439: ** the local lock file path 
36440: */
36441: static int switchLockProxyPath(unixFile *pFile, const char *path) {
36442:   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36443:   char *oldPath = pCtx->lockProxyPath;
36444:   int rc = SQLITE_OK;
36445: 
36446:   if( pFile->eFileLock!=NO_LOCK ){
36447:     return SQLITE_BUSY;
36448:   }  
36449: 
36450:   /* nothing to do if the path is NULL, :auto: or matches the existing path */
36451:   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
36452:     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
36453:     return SQLITE_OK;
36454:   }else{
36455:     unixFile *lockProxy = pCtx->lockProxy;
36456:     pCtx->lockProxy=NULL;
36457:     pCtx->conchHeld = 0;
36458:     if( lockProxy!=NULL ){
36459:       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
36460:       if( rc ) return rc;
36461:       sqlite3_free(lockProxy);
36462:     }
36463:     sqlite3_free(oldPath);
36464:     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
36465:   }
36466:   
36467:   return rc;
36468: }
36469: 
36470: /*
36471: ** pFile is a file that has been opened by a prior xOpen call.  dbPath
36472: ** is a string buffer at least MAXPATHLEN+1 characters in size.
36473: **
36474: ** This routine find the filename associated with pFile and writes it
36475: ** int dbPath.
36476: */
36477: static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
36478: #if defined(__APPLE__)
36479:   if( pFile->pMethod == &afpIoMethods ){
36480:     /* afp style keeps a reference to the db path in the filePath field 
36481:     ** of the struct */
36482:     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36483:     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
36484:             MAXPATHLEN);
36485:   } else
36486: #endif
36487:   if( pFile->pMethod == &dotlockIoMethods ){
36488:     /* dot lock style uses the locking context to store the dot lock
36489:     ** file path */
36490:     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
36491:     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
36492:   }else{
36493:     /* all other styles use the locking context to store the db file path */
36494:     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36495:     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
36496:   }
36497:   return SQLITE_OK;
36498: }
36499: 
36500: /*
36501: ** Takes an already filled in unix file and alters it so all file locking 
36502: ** will be performed on the local proxy lock file.  The following fields
36503: ** are preserved in the locking context so that they can be restored and 
36504: ** the unix structure properly cleaned up at close time:
36505: **  ->lockingContext
36506: **  ->pMethod
36507: */
36508: static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
36509:   proxyLockingContext *pCtx;
36510:   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
36511:   char *lockPath=NULL;
36512:   int rc = SQLITE_OK;
36513:   
36514:   if( pFile->eFileLock!=NO_LOCK ){
36515:     return SQLITE_BUSY;
36516:   }
36517:   proxyGetDbPathForUnixFile(pFile, dbPath);
36518:   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
36519:     lockPath=NULL;
36520:   }else{
36521:     lockPath=(char *)path;
36522:   }
36523:   
36524:   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
36525:            (lockPath ? lockPath : ":auto:"), osGetpid(0)));
36526: 
36527:   pCtx = sqlite3_malloc64( sizeof(*pCtx) );
36528:   if( pCtx==0 ){
36529:     return SQLITE_NOMEM_BKPT;
36530:   }
36531:   memset(pCtx, 0, sizeof(*pCtx));
36532: 
36533:   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
36534:   if( rc==SQLITE_OK ){
36535:     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
36536:     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
36537:       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
36538:       ** (c) the file system is read-only, then enable no-locking access.
36539:       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
36540:       ** that openFlags will have only one of O_RDONLY or O_RDWR.
36541:       */
36542:       struct statfs fsInfo;
36543:       struct stat conchInfo;
36544:       int goLockless = 0;
36545: 
36546:       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
36547:         int err = errno;
36548:         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
36549:           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
36550:         }
36551:       }
36552:       if( goLockless ){
36553:         pCtx->conchHeld = -1; /* read only FS/ lockless */
36554:         rc = SQLITE_OK;
36555:       }
36556:     }
36557:   }  
36558:   if( rc==SQLITE_OK && lockPath ){
36559:     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
36560:   }
36561: 
36562:   if( rc==SQLITE_OK ){
36563:     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
36564:     if( pCtx->dbPath==NULL ){
36565:       rc = SQLITE_NOMEM_BKPT;
36566:     }
36567:   }
36568:   if( rc==SQLITE_OK ){
36569:     /* all memory is allocated, proxys are created and assigned, 
36570:     ** switch the locking context and pMethod then return.
36571:     */
36572:     pCtx->oldLockingContext = pFile->lockingContext;
36573:     pFile->lockingContext = pCtx;
36574:     pCtx->pOldMethod = pFile->pMethod;
36575:     pFile->pMethod = &proxyIoMethods;
36576:   }else{
36577:     if( pCtx->conchFile ){ 
36578:       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
36579:       sqlite3_free(pCtx->conchFile);
36580:     }
36581:     sqlite3DbFree(0, pCtx->lockProxyPath);
36582:     sqlite3_free(pCtx->conchFilePath); 
36583:     sqlite3_free(pCtx);
36584:   }
36585:   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
36586:            (rc==SQLITE_OK ? "ok" : "failed")));
36587:   return rc;
36588: }
36589: 
36590: 
36591: /*
36592: ** This routine handles sqlite3_file_control() calls that are specific
36593: ** to proxy locking.
36594: */
36595: static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
36596:   switch( op ){
36597:     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
36598:       unixFile *pFile = (unixFile*)id;
36599:       if( pFile->pMethod == &proxyIoMethods ){
36600:         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36601:         proxyTakeConch(pFile);
36602:         if( pCtx->lockProxyPath ){
36603:           *(const char **)pArg = pCtx->lockProxyPath;
36604:         }else{
36605:           *(const char **)pArg = ":auto: (not held)";
36606:         }
36607:       } else {
36608:         *(const char **)pArg = NULL;
36609:       }
36610:       return SQLITE_OK;
36611:     }
36612:     case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
36613:       unixFile *pFile = (unixFile*)id;
36614:       int rc = SQLITE_OK;
36615:       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
36616:       if( pArg==NULL || (const char *)pArg==0 ){
36617:         if( isProxyStyle ){
36618:           /* turn off proxy locking - not supported.  If support is added for
36619:           ** switching proxy locking mode off then it will need to fail if
36620:           ** the journal mode is WAL mode. 
36621:           */
36622:           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
36623:         }else{
36624:           /* turn off proxy locking - already off - NOOP */
36625:           rc = SQLITE_OK;
36626:         }
36627:       }else{
36628:         const char *proxyPath = (const char *)pArg;
36629:         if( isProxyStyle ){
36630:           proxyLockingContext *pCtx = 
36631:             (proxyLockingContext*)pFile->lockingContext;
36632:           if( !strcmp(pArg, ":auto:") 
36633:            || (pCtx->lockProxyPath &&
36634:                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
36635:           ){
36636:             rc = SQLITE_OK;
36637:           }else{
36638:             rc = switchLockProxyPath(pFile, proxyPath);
36639:           }
36640:         }else{
36641:           /* turn on proxy file locking */
36642:           rc = proxyTransformUnixFile(pFile, proxyPath);
36643:         }
36644:       }
36645:       return rc;
36646:     }
36647:     default: {
36648:       assert( 0 );  /* The call assures that only valid opcodes are sent */
36649:     }
36650:   }
36651:   /*NOTREACHED*/
36652:   return SQLITE_ERROR;
36653: }
36654: 
36655: /*
36656: ** Within this division (the proxying locking implementation) the procedures
36657: ** above this point are all utilities.  The lock-related methods of the
36658: ** proxy-locking sqlite3_io_method object follow.
36659: */
36660: 
36661: 
36662: /*
36663: ** This routine checks if there is a RESERVED lock held on the specified
36664: ** file by this or any other process. If such a lock is held, set *pResOut
36665: ** to a non-zero value otherwise *pResOut is set to zero.  The return value
36666: ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
36667: */
36668: static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
36669:   unixFile *pFile = (unixFile*)id;
36670:   int rc = proxyTakeConch(pFile);
36671:   if( rc==SQLITE_OK ){
36672:     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36673:     if( pCtx->conchHeld>0 ){
36674:       unixFile *proxy = pCtx->lockProxy;
36675:       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
36676:     }else{ /* conchHeld < 0 is lockless */
36677:       pResOut=0;
36678:     }
36679:   }
36680:   return rc;
36681: }
36682: 
36683: /*
36684: ** Lock the file with the lock specified by parameter eFileLock - one
36685: ** of the following:
36686: **
36687: **     (1) SHARED_LOCK
36688: **     (2) RESERVED_LOCK
36689: **     (3) PENDING_LOCK
36690: **     (4) EXCLUSIVE_LOCK
36691: **
36692: ** Sometimes when requesting one lock state, additional lock states
36693: ** are inserted in between.  The locking might fail on one of the later
36694: ** transitions leaving the lock state different from what it started but
36695: ** still short of its goal.  The following chart shows the allowed
36696: ** transitions and the inserted intermediate states:
36697: **
36698: **    UNLOCKED -> SHARED
36699: **    SHARED -> RESERVED
36700: **    SHARED -> (PENDING) -> EXCLUSIVE
36701: **    RESERVED -> (PENDING) -> EXCLUSIVE
36702: **    PENDING -> EXCLUSIVE
36703: **
36704: ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
36705: ** routine to lower a locking level.
36706: */
36707: static int proxyLock(sqlite3_file *id, int eFileLock) {
36708:   unixFile *pFile = (unixFile*)id;
36709:   int rc = proxyTakeConch(pFile);
36710:   if( rc==SQLITE_OK ){
36711:     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36712:     if( pCtx->conchHeld>0 ){
36713:       unixFile *proxy = pCtx->lockProxy;
36714:       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
36715:       pFile->eFileLock = proxy->eFileLock;
36716:     }else{
36717:       /* conchHeld < 0 is lockless */
36718:     }
36719:   }
36720:   return rc;
36721: }
36722: 
36723: 
36724: /*
36725: ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
36726: ** must be either NO_LOCK or SHARED_LOCK.
36727: **
36728: ** If the locking level of the file descriptor is already at or below
36729: ** the requested locking level, this routine is a no-op.
36730: */
36731: static int proxyUnlock(sqlite3_file *id, int eFileLock) {
36732:   unixFile *pFile = (unixFile*)id;
36733:   int rc = proxyTakeConch(pFile);
36734:   if( rc==SQLITE_OK ){
36735:     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36736:     if( pCtx->conchHeld>0 ){
36737:       unixFile *proxy = pCtx->lockProxy;
36738:       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
36739:       pFile->eFileLock = proxy->eFileLock;
36740:     }else{
36741:       /* conchHeld < 0 is lockless */
36742:     }
36743:   }
36744:   return rc;
36745: }
36746: 
36747: /*
36748: ** Close a file that uses proxy locks.
36749: */
36750: static int proxyClose(sqlite3_file *id) {
36751:   if( ALWAYS(id) ){
36752:     unixFile *pFile = (unixFile*)id;
36753:     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36754:     unixFile *lockProxy = pCtx->lockProxy;
36755:     unixFile *conchFile = pCtx->conchFile;
36756:     int rc = SQLITE_OK;
36757:     
36758:     if( lockProxy ){
36759:       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
36760:       if( rc ) return rc;
36761:       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
36762:       if( rc ) return rc;
36763:       sqlite3_free(lockProxy);
36764:       pCtx->lockProxy = 0;
36765:     }
36766:     if( conchFile ){
36767:       if( pCtx->conchHeld ){
36768:         rc = proxyReleaseConch(pFile);
36769:         if( rc ) return rc;
36770:       }
36771:       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
36772:       if( rc ) return rc;
36773:       sqlite3_free(conchFile);
36774:     }
36775:     sqlite3DbFree(0, pCtx->lockProxyPath);
36776:     sqlite3_free(pCtx->conchFilePath);
36777:     sqlite3DbFree(0, pCtx->dbPath);
36778:     /* restore the original locking context and pMethod then close it */
36779:     pFile->lockingContext = pCtx->oldLockingContext;
36780:     pFile->pMethod = pCtx->pOldMethod;
36781:     sqlite3_free(pCtx);
36782:     return pFile->pMethod->xClose(id);
36783:   }
36784:   return SQLITE_OK;
36785: }
36786: 
36787: 
36788: 
36789: #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
36790: /*
36791: ** The proxy locking style is intended for use with AFP filesystems.
36792: ** And since AFP is only supported on MacOSX, the proxy locking is also
36793: ** restricted to MacOSX.
36794: ** 
36795: **
36796: ******************* End of the proxy lock implementation **********************
36797: ******************************************************************************/
36798: 
36799: /*
36800: ** Initialize the operating system interface.
36801: **
36802: ** This routine registers all VFS implementations for unix-like operating
36803: ** systems.  This routine, and the sqlite3_os_end() routine that follows,
36804: ** should be the only routines in this file that are visible from other
36805: ** files.
36806: **
36807: ** This routine is called once during SQLite initialization and by a
36808: ** single thread.  The memory allocation and mutex subsystems have not
36809: ** necessarily been initialized when this routine is called, and so they
36810: ** should not be used.
36811: */
36812: SQLITE_API int sqlite3_os_init(void){ 
36813:   /* 
36814:   ** The following macro defines an initializer for an sqlite3_vfs object.
36815:   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
36816:   ** to the "finder" function.  (pAppData is a pointer to a pointer because
36817:   ** silly C90 rules prohibit a void* from being cast to a function pointer
36818:   ** and so we have to go through the intermediate pointer to avoid problems
36819:   ** when compiling with -pedantic-errors on GCC.)
36820:   **
36821:   ** The FINDER parameter to this macro is the name of the pointer to the
36822:   ** finder-function.  The finder-function returns a pointer to the
36823:   ** sqlite_io_methods object that implements the desired locking
36824:   ** behaviors.  See the division above that contains the IOMETHODS
36825:   ** macro for addition information on finder-functions.
36826:   **
36827:   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
36828:   ** object.  But the "autolockIoFinder" available on MacOSX does a little
36829:   ** more than that; it looks at the filesystem type that hosts the 
36830:   ** database file and tries to choose an locking method appropriate for
36831:   ** that filesystem time.
36832:   */
36833:   #define UNIXVFS(VFSNAME, FINDER) {                        \
36834:     3,                    /* iVersion */                    \
36835:     sizeof(unixFile),     /* szOsFile */                    \
36836:     MAX_PATHNAME,         /* mxPathname */                  \
36837:     0,                    /* pNext */                       \
36838:     VFSNAME,              /* zName */                       \
36839:     (void*)&FINDER,       /* pAppData */                    \
36840:     unixOpen,             /* xOpen */                       \
36841:     unixDelete,           /* xDelete */                     \
36842:     unixAccess,           /* xAccess */                     \
36843:     unixFullPathname,     /* xFullPathname */               \
36844:     unixDlOpen,           /* xDlOpen */                     \
36845:     unixDlError,          /* xDlError */                    \
36846:     unixDlSym,            /* xDlSym */                      \
36847:     unixDlClose,          /* xDlClose */                    \
36848:     unixRandomness,       /* xRandomness */                 \
36849:     unixSleep,            /* xSleep */                      \
36850:     unixCurrentTime,      /* xCurrentTime */                \
36851:     unixGetLastError,     /* xGetLastError */               \
36852:     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
36853:     unixSetSystemCall,    /* xSetSystemCall */              \
36854:     unixGetSystemCall,    /* xGetSystemCall */              \
36855:     unixNextSystemCall,   /* xNextSystemCall */             \
36856:   }
36857: 
36858:   /*
36859:   ** All default VFSes for unix are contained in the following array.
36860:   **
36861:   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
36862:   ** by the SQLite core when the VFS is registered.  So the following
36863:   ** array cannot be const.
36864:   */
36865:   static sqlite3_vfs aVfs[] = {
36866: #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36867:     UNIXVFS("unix",          autolockIoFinder ),
36868: #elif OS_VXWORKS
36869:     UNIXVFS("unix",          vxworksIoFinder ),
36870: #else
36871:     UNIXVFS("unix",          posixIoFinder ),
36872: #endif
36873:     UNIXVFS("unix-none",     nolockIoFinder ),
36874:     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
36875:     UNIXVFS("unix-excl",     posixIoFinder ),
36876: #if OS_VXWORKS
36877:     UNIXVFS("unix-namedsem", semIoFinder ),
36878: #endif
36879: #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
36880:     UNIXVFS("unix-posix",    posixIoFinder ),
36881: #endif
36882: #if SQLITE_ENABLE_LOCKING_STYLE
36883:     UNIXVFS("unix-flock",    flockIoFinder ),
36884: #endif
36885: #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36886:     UNIXVFS("unix-afp",      afpIoFinder ),
36887:     UNIXVFS("unix-nfs",      nfsIoFinder ),
36888:     UNIXVFS("unix-proxy",    proxyIoFinder ),
36889: #endif
36890:   };
36891:   unsigned int i;          /* Loop counter */
36892: 
36893:   /* Double-check that the aSyscall[] array has been constructed
36894:   ** correctly.  See ticket [bb3a86e890c8e96ab] */
36895:   assert( ArraySize(aSyscall)==28 );
36896: 
36897:   /* Register all VFSes defined in the aVfs[] array */
36898:   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
36899:     sqlite3_vfs_register(&aVfs[i], i==0);
36900:   }
36901:   return SQLITE_OK; 
36902: }
36903: 
36904: /*
36905: ** Shutdown the operating system interface.
36906: **
36907: ** Some operating systems might need to do some cleanup in this routine,
36908: ** to release dynamically allocated objects.  But not on unix.
36909: ** This routine is a no-op for unix.
36910: */
36911: SQLITE_API int sqlite3_os_end(void){ 
36912:   return SQLITE_OK; 
36913: }
36914:  
36915: #endif /* SQLITE_OS_UNIX */
36916: 
36917: /************** End of os_unix.c *********************************************/
36918: /************** Begin file os_win.c ******************************************/
36919: /*
36920: ** 2004 May 22
36921: **
36922: ** The author disclaims copyright to this source code.  In place of
36923: ** a legal notice, here is a blessing:
36924: **
36925: **    May you do good and not evil.
36926: **    May you find forgiveness for yourself and forgive others.
36927: **    May you share freely, never taking more than you give.
36928: **
36929: ******************************************************************************
36930: **
36931: ** This file contains code that is specific to Windows.
36932: */
36933: /* #include "sqliteInt.h" */
36934: #if SQLITE_OS_WIN               /* This file is used for Windows only */
36935: 
36936: /*
36937: ** Include code that is common to all os_*.c files
36938: */
36939: /************** Include os_common.h in the middle of os_win.c ****************/
36940: /************** Begin file os_common.h ***************************************/
36941: /*
36942: ** 2004 May 22
36943: **
36944: ** The author disclaims copyright to this source code.  In place of
36945: ** a legal notice, here is a blessing:
36946: **
36947: **    May you do good and not evil.
36948: **    May you find forgiveness for yourself and forgive others.
36949: **    May you share freely, never taking more than you give.
36950: **
36951: ******************************************************************************
36952: **
36953: ** This file contains macros and a little bit of code that is common to
36954: ** all of the platform-specific files (os_*.c) and is #included into those
36955: ** files.
36956: **
36957: ** This file should be #included by the os_*.c files only.  It is not a
36958: ** general purpose header file.
36959: */
36960: #ifndef _OS_COMMON_H_
36961: #define _OS_COMMON_H_
36962: 
36963: /*
36964: ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
36965: ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
36966: ** switch.  The following code should catch this problem at compile-time.
36967: */
36968: #ifdef MEMORY_DEBUG
36969: # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
36970: #endif
36971: 
36972: /*
36973: ** Macros for performance tracing.  Normally turned off.  Only works
36974: ** on i486 hardware.
36975: */
36976: #ifdef SQLITE_PERFORMANCE_TRACE
36977: 
36978: /*
36979: ** hwtime.h contains inline assembler code for implementing
36980: ** high-performance timing routines.
36981: */
36982: /************** Include hwtime.h in the middle of os_common.h ****************/
36983: /************** Begin file hwtime.h ******************************************/
36984: /*
36985: ** 2008 May 27
36986: **
36987: ** The author disclaims copyright to this source code.  In place of
36988: ** a legal notice, here is a blessing:
36989: **
36990: **    May you do good and not evil.
36991: **    May you find forgiveness for yourself and forgive others.
36992: **    May you share freely, never taking more than you give.
36993: **
36994: ******************************************************************************
36995: **
36996: ** This file contains inline asm code for retrieving "high-performance"
36997: ** counters for x86 class CPUs.
36998: */
36999: #ifndef SQLITE_HWTIME_H
37000: #define SQLITE_HWTIME_H
37001: 
37002: /*
37003: ** The following routine only works on pentium-class (or newer) processors.
37004: ** It uses the RDTSC opcode to read the cycle count value out of the
37005: ** processor and returns that value.  This can be used for high-res
37006: ** profiling.
37007: */
37008: #if (defined(__GNUC__) || defined(_MSC_VER)) && \
37009:       (defined(i386) || defined(__i386__) || defined(_M_IX86))
37010: 
37011:   #if defined(__GNUC__)
37012: 
37013:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
37014:      unsigned int lo, hi;
37015:      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
37016:      return (sqlite_uint64)hi << 32 | lo;
37017:   }
37018: 
37019:   #elif defined(_MSC_VER)
37020: 
37021:   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
37022:      __asm {
37023:         rdtsc
37024:         ret       ; return value at EDX:EAX
37025:      }
37026:   }
37027: 
37028:   #endif
37029: 
37030: #elif (defined(__GNUC__) && defined(__x86_64__))
37031: 
37032:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
37033:       unsigned long val;
37034:       __asm__ __volatile__ ("rdtsc" : "=A" (val));
37035:       return val;
37036:   }
37037:  
37038: #elif (defined(__GNUC__) && defined(__ppc__))
37039: 
37040:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
37041:       unsigned long long retval;
37042:       unsigned long junk;
37043:       __asm__ __volatile__ ("\n\
37044:           1:      mftbu   %1\n\
37045:                   mftb    %L0\n\
37046:                   mftbu   %0\n\
37047:                   cmpw    %0,%1\n\
37048:                   bne     1b"
37049:                   : "=r" (retval), "=r" (junk));
37050:       return retval;
37051:   }
37052: 
37053: #else
37054: 
37055:   #error Need implementation of sqlite3Hwtime() for your platform.
37056: 
37057:   /*
37058:   ** To compile without implementing sqlite3Hwtime() for your platform,
37059:   ** you can remove the above #error and use the following
37060:   ** stub function.  You will lose timing support for many
37061:   ** of the debugging and testing utilities, but it should at
37062:   ** least compile and run.
37063:   */
37064: SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
37065: 
37066: #endif
37067: 
37068: #endif /* !defined(SQLITE_HWTIME_H) */
37069: 
37070: /************** End of hwtime.h **********************************************/
37071: /************** Continuing where we left off in os_common.h ******************/
37072: 
37073: static sqlite_uint64 g_start;
37074: static sqlite_uint64 g_elapsed;
37075: #define TIMER_START       g_start=sqlite3Hwtime()
37076: #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
37077: #define TIMER_ELAPSED     g_elapsed
37078: #else
37079: #define TIMER_START
37080: #define TIMER_END
37081: #define TIMER_ELAPSED     ((sqlite_uint64)0)
37082: #endif
37083: 
37084: /*
37085: ** If we compile with the SQLITE_TEST macro set, then the following block
37086: ** of code will give us the ability to simulate a disk I/O error.  This
37087: ** is used for testing the I/O recovery logic.
37088: */
37089: #if defined(SQLITE_TEST)
37090: SQLITE_API extern int sqlite3_io_error_hit;
37091: SQLITE_API extern int sqlite3_io_error_hardhit;
37092: SQLITE_API extern int sqlite3_io_error_pending;
37093: SQLITE_API extern int sqlite3_io_error_persist;
37094: SQLITE_API extern int sqlite3_io_error_benign;
37095: SQLITE_API extern int sqlite3_diskfull_pending;
37096: SQLITE_API extern int sqlite3_diskfull;
37097: #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
37098: #define SimulateIOError(CODE)  \
37099:   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
37100:        || sqlite3_io_error_pending-- == 1 )  \
37101:               { local_ioerr(); CODE; }
37102: static void local_ioerr(){
37103:   IOTRACE(("IOERR\n"));
37104:   sqlite3_io_error_hit++;
37105:   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
37106: }
37107: #define SimulateDiskfullError(CODE) \
37108:    if( sqlite3_diskfull_pending ){ \
37109:      if( sqlite3_diskfull_pending == 1 ){ \
37110:        local_ioerr(); \
37111:        sqlite3_diskfull = 1; \
37112:        sqlite3_io_error_hit = 1; \
37113:        CODE; \
37114:      }else{ \
37115:        sqlite3_diskfull_pending--; \
37116:      } \
37117:    }
37118: #else
37119: #define SimulateIOErrorBenign(X)
37120: #define SimulateIOError(A)
37121: #define SimulateDiskfullError(A)
37122: #endif /* defined(SQLITE_TEST) */
37123: 
37124: /*
37125: ** When testing, keep a count of the number of open files.
37126: */
37127: #if defined(SQLITE_TEST)
37128: SQLITE_API extern int sqlite3_open_file_count;
37129: #define OpenCounter(X)  sqlite3_open_file_count+=(X)
37130: #else
37131: #define OpenCounter(X)
37132: #endif /* defined(SQLITE_TEST) */
37133: 
37134: #endif /* !defined(_OS_COMMON_H_) */
37135: 
37136: /************** End of os_common.h *******************************************/
37137: /************** Continuing where we left off in os_win.c *********************/
37138: 
37139: /*
37140: ** Include the header file for the Windows VFS.
37141: */
37142: /* #include "os_win.h" */
37143: 
37144: /*
37145: ** Compiling and using WAL mode requires several APIs that are only
37146: ** available in Windows platforms based on the NT kernel.
37147: */
37148: #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
37149: #  error "WAL mode requires support from the Windows NT kernel, compile\
37150:  with SQLITE_OMIT_WAL."
37151: #endif
37152: 
37153: #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
37154: #  error "Memory mapped files require support from the Windows NT kernel,\
37155:  compile with SQLITE_MAX_MMAP_SIZE=0."
37156: #endif
37157: 
37158: /*
37159: ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
37160: ** based on the sub-platform)?
37161: */
37162: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
37163: #  define SQLITE_WIN32_HAS_ANSI
37164: #endif
37165: 
37166: /*
37167: ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
37168: ** based on the sub-platform)?
37169: */
37170: #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
37171:     !defined(SQLITE_WIN32_NO_WIDE)
37172: #  define SQLITE_WIN32_HAS_WIDE
37173: #endif
37174: 
37175: /*
37176: ** Make sure at least one set of Win32 APIs is available.
37177: */
37178: #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
37179: #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
37180:  must be defined."
37181: #endif
37182: 
37183: /*
37184: ** Define the required Windows SDK version constants if they are not
37185: ** already available.
37186: */
37187: #ifndef NTDDI_WIN8
37188: #  define NTDDI_WIN8                        0x06020000
37189: #endif
37190: 
37191: #ifndef NTDDI_WINBLUE
37192: #  define NTDDI_WINBLUE                     0x06030000
37193: #endif
37194: 
37195: #ifndef NTDDI_WINTHRESHOLD
37196: #  define NTDDI_WINTHRESHOLD                0x06040000
37197: #endif
37198: 
37199: /*
37200: ** Check to see if the GetVersionEx[AW] functions are deprecated on the
37201: ** target system.  GetVersionEx was first deprecated in Win8.1.
37202: */
37203: #ifndef SQLITE_WIN32_GETVERSIONEX
37204: #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
37205: #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
37206: #  else
37207: #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
37208: #  endif
37209: #endif
37210: 
37211: /*
37212: ** Check to see if the CreateFileMappingA function is supported on the
37213: ** target system.  It is unavailable when using "mincore.lib" on Win10.
37214: ** When compiling for Windows 10, always assume "mincore.lib" is in use.
37215: */
37216: #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
37217: #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
37218: #    define SQLITE_WIN32_CREATEFILEMAPPINGA   0
37219: #  else
37220: #    define SQLITE_WIN32_CREATEFILEMAPPINGA   1
37221: #  endif
37222: #endif
37223: 
37224: /*
37225: ** This constant should already be defined (in the "WinDef.h" SDK file).
37226: */
37227: #ifndef MAX_PATH
37228: #  define MAX_PATH                      (260)
37229: #endif
37230: 
37231: /*
37232: ** Maximum pathname length (in chars) for Win32.  This should normally be
37233: ** MAX_PATH.
37234: */
37235: #ifndef SQLITE_WIN32_MAX_PATH_CHARS
37236: #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
37237: #endif
37238: 
37239: /*
37240: ** This constant should already be defined (in the "WinNT.h" SDK file).
37241: */
37242: #ifndef UNICODE_STRING_MAX_CHARS
37243: #  define UNICODE_STRING_MAX_CHARS      (32767)
37244: #endif
37245: 
37246: /*
37247: ** Maximum pathname length (in chars) for WinNT.  This should normally be
37248: ** UNICODE_STRING_MAX_CHARS.
37249: */
37250: #ifndef SQLITE_WINNT_MAX_PATH_CHARS
37251: #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
37252: #endif
37253: 
37254: /*
37255: ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
37256: ** characters, so we allocate 4 bytes per character assuming worst-case of
37257: ** 4-bytes-per-character for UTF8.
37258: */
37259: #ifndef SQLITE_WIN32_MAX_PATH_BYTES
37260: #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
37261: #endif
37262: 
37263: /*
37264: ** Maximum pathname length (in bytes) for WinNT.  This should normally be
37265: ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
37266: */
37267: #ifndef SQLITE_WINNT_MAX_PATH_BYTES
37268: #  define SQLITE_WINNT_MAX_PATH_BYTES   \
37269:                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
37270: #endif
37271: 
37272: /*
37273: ** Maximum error message length (in chars) for WinRT.
37274: */
37275: #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
37276: #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
37277: #endif
37278: 
37279: /*
37280: ** Returns non-zero if the character should be treated as a directory
37281: ** separator.
37282: */
37283: #ifndef winIsDirSep
37284: #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
37285: #endif
37286: 
37287: /*
37288: ** This macro is used when a local variable is set to a value that is
37289: ** [sometimes] not used by the code (e.g. via conditional compilation).
37290: */
37291: #ifndef UNUSED_VARIABLE_VALUE
37292: #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
37293: #endif
37294: 
37295: /*
37296: ** Returns the character that should be used as the directory separator.
37297: */
37298: #ifndef winGetDirSep
37299: #  define winGetDirSep()                '\\'
37300: #endif
37301: 
37302: /*
37303: ** Do we need to manually define the Win32 file mapping APIs for use with WAL
37304: ** mode or memory mapped files (e.g. these APIs are available in the Windows
37305: ** CE SDK; however, they are not present in the header file)?
37306: */
37307: #if SQLITE_WIN32_FILEMAPPING_API && \
37308:         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37309: /*
37310: ** Two of the file mapping APIs are different under WinRT.  Figure out which
37311: ** set we need.
37312: */
37313: #if SQLITE_OS_WINRT
37314: WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
37315:         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
37316: 
37317: WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
37318: #else
37319: #if defined(SQLITE_WIN32_HAS_ANSI)
37320: WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
37321:         DWORD, DWORD, DWORD, LPCSTR);
37322: #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
37323: 
37324: #if defined(SQLITE_WIN32_HAS_WIDE)
37325: WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
37326:         DWORD, DWORD, DWORD, LPCWSTR);
37327: #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
37328: 
37329: WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
37330: #endif /* SQLITE_OS_WINRT */
37331: 
37332: /*
37333: ** These file mapping APIs are common to both Win32 and WinRT.
37334: */
37335: 
37336: WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
37337: WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
37338: #endif /* SQLITE_WIN32_FILEMAPPING_API */
37339: 
37340: /*
37341: ** Some Microsoft compilers lack this definition.
37342: */
37343: #ifndef INVALID_FILE_ATTRIBUTES
37344: # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
37345: #endif
37346: 
37347: #ifndef FILE_FLAG_MASK
37348: # define FILE_FLAG_MASK          (0xFF3C0000)
37349: #endif
37350: 
37351: #ifndef FILE_ATTRIBUTE_MASK
37352: # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
37353: #endif
37354: 
37355: #ifndef SQLITE_OMIT_WAL
37356: /* Forward references to structures used for WAL */
37357: typedef struct winShm winShm;           /* A connection to shared-memory */
37358: typedef struct winShmNode winShmNode;   /* A region of shared-memory */
37359: #endif
37360: 
37361: /*
37362: ** WinCE lacks native support for file locking so we have to fake it
37363: ** with some code of our own.
37364: */
37365: #if SQLITE_OS_WINCE
37366: typedef struct winceLock {
37367:   int nReaders;       /* Number of reader locks obtained */
37368:   BOOL bPending;      /* Indicates a pending lock has been obtained */
37369:   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
37370:   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
37371: } winceLock;
37372: #endif
37373: 
37374: /*
37375: ** The winFile structure is a subclass of sqlite3_file* specific to the win32
37376: ** portability layer.
37377: */
37378: typedef struct winFile winFile;
37379: struct winFile {
37380:   const sqlite3_io_methods *pMethod; /*** Must be first ***/
37381:   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
37382:   HANDLE h;               /* Handle for accessing the file */
37383:   u8 locktype;            /* Type of lock currently held on this file */
37384:   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
37385:   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
37386:   DWORD lastErrno;        /* The Windows errno from the last I/O error */
37387: #ifndef SQLITE_OMIT_WAL
37388:   winShm *pShm;           /* Instance of shared memory on this file */
37389: #endif
37390:   const char *zPath;      /* Full pathname of this file */
37391:   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
37392: #if SQLITE_OS_WINCE
37393:   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
37394:   HANDLE hMutex;          /* Mutex used to control access to shared lock */
37395:   HANDLE hShared;         /* Shared memory segment used for locking */
37396:   winceLock local;        /* Locks obtained by this instance of winFile */
37397:   winceLock *shared;      /* Global shared lock memory for the file  */
37398: #endif
37399: #if SQLITE_MAX_MMAP_SIZE>0
37400:   int nFetchOut;                /* Number of outstanding xFetch references */
37401:   HANDLE hMap;                  /* Handle for accessing memory mapping */
37402:   void *pMapRegion;             /* Area memory mapped */
37403:   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
37404:   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
37405:   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
37406: #endif
37407: };
37408: 
37409: /*
37410: ** The winVfsAppData structure is used for the pAppData member for all of the
37411: ** Win32 VFS variants.
37412: */
37413: typedef struct winVfsAppData winVfsAppData;
37414: struct winVfsAppData {
37415:   const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
37416:   void *pAppData;                    /* The extra pAppData, if any. */
37417:   BOOL bNoLock;                      /* Non-zero if locking is disabled. */
37418: };
37419: 
37420: /*
37421: ** Allowed values for winFile.ctrlFlags
37422: */
37423: #define WINFILE_RDONLY          0x02   /* Connection is read only */
37424: #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
37425: #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
37426: 
37427: /*
37428:  * The size of the buffer used by sqlite3_win32_write_debug().
37429:  */
37430: #ifndef SQLITE_WIN32_DBG_BUF_SIZE
37431: #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
37432: #endif
37433: 
37434: /*
37435:  * The value used with sqlite3_win32_set_directory() to specify that
37436:  * the data directory should be changed.
37437:  */
37438: #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
37439: #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
37440: #endif
37441: 
37442: /*
37443:  * The value used with sqlite3_win32_set_directory() to specify that
37444:  * the temporary directory should be changed.
37445:  */
37446: #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
37447: #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
37448: #endif
37449: 
37450: /*
37451:  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
37452:  * various Win32 API heap functions instead of our own.
37453:  */
37454: #ifdef SQLITE_WIN32_MALLOC
37455: 
37456: /*
37457:  * If this is non-zero, an isolated heap will be created by the native Win32
37458:  * allocator subsystem; otherwise, the default process heap will be used.  This
37459:  * setting has no effect when compiling for WinRT.  By default, this is enabled
37460:  * and an isolated heap will be created to store all allocated data.
37461:  *
37462:  ******************************************************************************
37463:  * WARNING: It is important to note that when this setting is non-zero and the
37464:  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
37465:  *          function), all data that was allocated using the isolated heap will
37466:  *          be freed immediately and any attempt to access any of that freed
37467:  *          data will almost certainly result in an immediate access violation.
37468:  ******************************************************************************
37469:  */
37470: #ifndef SQLITE_WIN32_HEAP_CREATE
37471: #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
37472: #endif
37473: 
37474: /*
37475:  * This is cache size used in the calculation of the initial size of the
37476:  * Win32-specific heap.  It cannot be negative.
37477:  */
37478: #ifndef SQLITE_WIN32_CACHE_SIZE
37479: #  if SQLITE_DEFAULT_CACHE_SIZE>=0
37480: #    define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
37481: #  else
37482: #    define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
37483: #  endif
37484: #endif
37485: 
37486: /*
37487:  * The initial size of the Win32-specific heap.  This value may be zero.
37488:  */
37489: #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
37490: #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
37491:                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
37492: #endif
37493: 
37494: /*
37495:  * The maximum size of the Win32-specific heap.  This value may be zero.
37496:  */
37497: #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
37498: #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
37499: #endif
37500: 
37501: /*
37502:  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
37503:  * zero for the default behavior.
37504:  */
37505: #ifndef SQLITE_WIN32_HEAP_FLAGS
37506: #  define SQLITE_WIN32_HEAP_FLAGS     (0)
37507: #endif
37508: 
37509: 
37510: /*
37511: ** The winMemData structure stores information required by the Win32-specific
37512: ** sqlite3_mem_methods implementation.
37513: */
37514: typedef struct winMemData winMemData;
37515: struct winMemData {
37516: #ifndef NDEBUG
37517:   u32 magic1;   /* Magic number to detect structure corruption. */
37518: #endif
37519:   HANDLE hHeap; /* The handle to our heap. */
37520:   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
37521: #ifndef NDEBUG
37522:   u32 magic2;   /* Magic number to detect structure corruption. */
37523: #endif
37524: };
37525: 
37526: #ifndef NDEBUG
37527: #define WINMEM_MAGIC1     0x42b2830b
37528: #define WINMEM_MAGIC2     0xbd4d7cf4
37529: #endif
37530: 
37531: static struct winMemData win_mem_data = {
37532: #ifndef NDEBUG
37533:   WINMEM_MAGIC1,
37534: #endif
37535:   NULL, FALSE
37536: #ifndef NDEBUG
37537:   ,WINMEM_MAGIC2
37538: #endif
37539: };
37540: 
37541: #ifndef NDEBUG
37542: #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
37543: #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
37544: #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
37545: #else
37546: #define winMemAssertMagic()
37547: #endif
37548: 
37549: #define winMemGetDataPtr()  &win_mem_data
37550: #define winMemGetHeap()     win_mem_data.hHeap
37551: #define winMemGetOwned()    win_mem_data.bOwned
37552: 
37553: static void *winMemMalloc(int nBytes);
37554: static void winMemFree(void *pPrior);
37555: static void *winMemRealloc(void *pPrior, int nBytes);
37556: static int winMemSize(void *p);
37557: static int winMemRoundup(int n);
37558: static int winMemInit(void *pAppData);
37559: static void winMemShutdown(void *pAppData);
37560: 
37561: SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
37562: #endif /* SQLITE_WIN32_MALLOC */
37563: 
37564: /*
37565: ** The following variable is (normally) set once and never changes
37566: ** thereafter.  It records whether the operating system is Win9x
37567: ** or WinNT.
37568: **
37569: ** 0:   Operating system unknown.
37570: ** 1:   Operating system is Win9x.
37571: ** 2:   Operating system is WinNT.
37572: **
37573: ** In order to facilitate testing on a WinNT system, the test fixture
37574: ** can manually set this value to 1 to emulate Win98 behavior.
37575: */
37576: #ifdef SQLITE_TEST
37577: SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37578: #else
37579: static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37580: #endif
37581: 
37582: #ifndef SYSCALL
37583: #  define SYSCALL sqlite3_syscall_ptr
37584: #endif
37585: 
37586: /*
37587: ** This function is not available on Windows CE or WinRT.
37588:  */
37589: 
37590: #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
37591: #  define osAreFileApisANSI()       1
37592: #endif
37593: 
37594: /*
37595: ** Many system calls are accessed through pointer-to-functions so that
37596: ** they may be overridden at runtime to facilitate fault injection during
37597: ** testing and sandboxing.  The following array holds the names and pointers
37598: ** to all overrideable system calls.
37599: */
37600: static struct win_syscall {
37601:   const char *zName;            /* Name of the system call */
37602:   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
37603:   sqlite3_syscall_ptr pDefault; /* Default value */
37604: } aSyscall[] = {
37605: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37606:   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
37607: #else
37608:   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
37609: #endif
37610: 
37611: #ifndef osAreFileApisANSI
37612: #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
37613: #endif
37614: 
37615: #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37616:   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
37617: #else
37618:   { "CharLowerW",              (SYSCALL)0,                       0 },
37619: #endif
37620: 
37621: #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
37622: 
37623: #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37624:   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
37625: #else
37626:   { "CharUpperW",              (SYSCALL)0,                       0 },
37627: #endif
37628: 
37629: #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
37630: 
37631:   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
37632: 
37633: #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
37634: 
37635: #if defined(SQLITE_WIN32_HAS_ANSI)
37636:   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
37637: #else
37638:   { "CreateFileA",             (SYSCALL)0,                       0 },
37639: #endif
37640: 
37641: #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
37642:         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
37643: 
37644: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37645:   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
37646: #else
37647:   { "CreateFileW",             (SYSCALL)0,                       0 },
37648: #endif
37649: 
37650: #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
37651:         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
37652: 
37653: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
37654:         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
37655:         SQLITE_WIN32_CREATEFILEMAPPINGA
37656:   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
37657: #else
37658:   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
37659: #endif
37660: 
37661: #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37662:         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
37663: 
37664: #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37665:         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
37666:   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
37667: #else
37668:   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
37669: #endif
37670: 
37671: #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37672:         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
37673: 
37674: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37675:   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
37676: #else
37677:   { "CreateMutexW",            (SYSCALL)0,                       0 },
37678: #endif
37679: 
37680: #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
37681:         LPCWSTR))aSyscall[8].pCurrent)
37682: 
37683: #if defined(SQLITE_WIN32_HAS_ANSI)
37684:   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
37685: #else
37686:   { "DeleteFileA",             (SYSCALL)0,                       0 },
37687: #endif
37688: 
37689: #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
37690: 
37691: #if defined(SQLITE_WIN32_HAS_WIDE)
37692:   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
37693: #else
37694:   { "DeleteFileW",             (SYSCALL)0,                       0 },
37695: #endif
37696: 
37697: #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
37698: 
37699: #if SQLITE_OS_WINCE
37700:   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
37701: #else
37702:   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
37703: #endif
37704: 
37705: #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37706:         LPFILETIME))aSyscall[11].pCurrent)
37707: 
37708: #if SQLITE_OS_WINCE
37709:   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
37710: #else
37711:   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
37712: #endif
37713: 
37714: #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37715:         LPSYSTEMTIME))aSyscall[12].pCurrent)
37716: 
37717:   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
37718: 
37719: #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
37720: 
37721: #if defined(SQLITE_WIN32_HAS_ANSI)
37722:   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
37723: #else
37724:   { "FormatMessageA",          (SYSCALL)0,                       0 },
37725: #endif
37726: 
37727: #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
37728:         DWORD,va_list*))aSyscall[14].pCurrent)
37729: 
37730: #if defined(SQLITE_WIN32_HAS_WIDE)
37731:   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
37732: #else
37733:   { "FormatMessageW",          (SYSCALL)0,                       0 },
37734: #endif
37735: 
37736: #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
37737:         DWORD,va_list*))aSyscall[15].pCurrent)
37738: 
37739: #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37740:   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
37741: #else
37742:   { "FreeLibrary",             (SYSCALL)0,                       0 },
37743: #endif
37744: 
37745: #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
37746: 
37747:   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
37748: 
37749: #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
37750: 
37751: #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37752:   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
37753: #else
37754:   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
37755: #endif
37756: 
37757: #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
37758:         LPDWORD))aSyscall[18].pCurrent)
37759: 
37760: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37761:   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
37762: #else
37763:   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
37764: #endif
37765: 
37766: #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
37767:         LPDWORD))aSyscall[19].pCurrent)
37768: 
37769: #if defined(SQLITE_WIN32_HAS_ANSI)
37770:   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
37771: #else
37772:   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
37773: #endif
37774: 
37775: #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
37776: 
37777: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37778:   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
37779: #else
37780:   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
37781: #endif
37782: 
37783: #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
37784: 
37785: #if defined(SQLITE_WIN32_HAS_WIDE)
37786:   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
37787: #else
37788:   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
37789: #endif
37790: 
37791: #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
37792:         LPVOID))aSyscall[22].pCurrent)
37793: 
37794: #if !SQLITE_OS_WINRT
37795:   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
37796: #else
37797:   { "GetFileSize",             (SYSCALL)0,                       0 },
37798: #endif
37799: 
37800: #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
37801: 
37802: #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37803:   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
37804: #else
37805:   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
37806: #endif
37807: 
37808: #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
37809:         LPSTR*))aSyscall[24].pCurrent)
37810: 
37811: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37812:   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
37813: #else
37814:   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
37815: #endif
37816: 
37817: #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
37818:         LPWSTR*))aSyscall[25].pCurrent)
37819: 
37820:   { "GetLastError",            (SYSCALL)GetLastError,            0 },
37821: 
37822: #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
37823: 
37824: #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37825: #if SQLITE_OS_WINCE
37826:   /* The GetProcAddressA() routine is only available on Windows CE. */
37827:   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
37828: #else
37829:   /* All other Windows platforms expect GetProcAddress() to take
37830:   ** an ANSI string regardless of the _UNICODE setting */
37831:   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
37832: #endif
37833: #else
37834:   { "GetProcAddressA",         (SYSCALL)0,                       0 },
37835: #endif
37836: 
37837: #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
37838:         LPCSTR))aSyscall[27].pCurrent)
37839: 
37840: #if !SQLITE_OS_WINRT
37841:   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
37842: #else
37843:   { "GetSystemInfo",           (SYSCALL)0,                       0 },
37844: #endif
37845: 
37846: #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
37847: 
37848:   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
37849: 
37850: #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
37851: 
37852: #if !SQLITE_OS_WINCE
37853:   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
37854: #else
37855:   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
37856: #endif
37857: 
37858: #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
37859:         LPFILETIME))aSyscall[30].pCurrent)
37860: 
37861: #if defined(SQLITE_WIN32_HAS_ANSI)
37862:   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
37863: #else
37864:   { "GetTempPathA",            (SYSCALL)0,                       0 },
37865: #endif
37866: 
37867: #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
37868: 
37869: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37870:   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
37871: #else
37872:   { "GetTempPathW",            (SYSCALL)0,                       0 },
37873: #endif
37874: 
37875: #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
37876: 
37877: #if !SQLITE_OS_WINRT
37878:   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
37879: #else
37880:   { "GetTickCount",            (SYSCALL)0,                       0 },
37881: #endif
37882: 
37883: #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
37884: 
37885: #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
37886:   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
37887: #else
37888:   { "GetVersionExA",           (SYSCALL)0,                       0 },
37889: #endif
37890: 
37891: #define osGetVersionExA ((BOOL(WINAPI*)( \
37892:         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
37893: 
37894: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37895:         SQLITE_WIN32_GETVERSIONEX
37896:   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
37897: #else
37898:   { "GetVersionExW",           (SYSCALL)0,                       0 },
37899: #endif
37900: 
37901: #define osGetVersionExW ((BOOL(WINAPI*)( \
37902:         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
37903: 
37904:   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
37905: 
37906: #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
37907:         SIZE_T))aSyscall[36].pCurrent)
37908: 
37909: #if !SQLITE_OS_WINRT
37910:   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
37911: #else
37912:   { "HeapCreate",              (SYSCALL)0,                       0 },
37913: #endif
37914: 
37915: #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
37916:         SIZE_T))aSyscall[37].pCurrent)
37917: 
37918: #if !SQLITE_OS_WINRT
37919:   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
37920: #else
37921:   { "HeapDestroy",             (SYSCALL)0,                       0 },
37922: #endif
37923: 
37924: #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
37925: 
37926:   { "HeapFree",                (SYSCALL)HeapFree,                0 },
37927: 
37928: #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
37929: 
37930:   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
37931: 
37932: #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
37933:         SIZE_T))aSyscall[40].pCurrent)
37934: 
37935:   { "HeapSize",                (SYSCALL)HeapSize,                0 },
37936: 
37937: #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
37938:         LPCVOID))aSyscall[41].pCurrent)
37939: 
37940: #if !SQLITE_OS_WINRT
37941:   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
37942: #else
37943:   { "HeapValidate",            (SYSCALL)0,                       0 },
37944: #endif
37945: 
37946: #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
37947:         LPCVOID))aSyscall[42].pCurrent)
37948: 
37949: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37950:   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
37951: #else
37952:   { "HeapCompact",             (SYSCALL)0,                       0 },
37953: #endif
37954: 
37955: #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
37956: 
37957: #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
37958:   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
37959: #else
37960:   { "LoadLibraryA",            (SYSCALL)0,                       0 },
37961: #endif
37962: 
37963: #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
37964: 
37965: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37966:         !defined(SQLITE_OMIT_LOAD_EXTENSION)
37967:   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
37968: #else
37969:   { "LoadLibraryW",            (SYSCALL)0,                       0 },
37970: #endif
37971: 
37972: #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
37973: 
37974: #if !SQLITE_OS_WINRT
37975:   { "LocalFree",               (SYSCALL)LocalFree,               0 },
37976: #else
37977:   { "LocalFree",               (SYSCALL)0,                       0 },
37978: #endif
37979: 
37980: #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
37981: 
37982: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37983:   { "LockFile",                (SYSCALL)LockFile,                0 },
37984: #else
37985:   { "LockFile",                (SYSCALL)0,                       0 },
37986: #endif
37987: 
37988: #ifndef osLockFile
37989: #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
37990:         DWORD))aSyscall[47].pCurrent)
37991: #endif
37992: 
37993: #if !SQLITE_OS_WINCE
37994:   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
37995: #else
37996:   { "LockFileEx",              (SYSCALL)0,                       0 },
37997: #endif
37998: 
37999: #ifndef osLockFileEx
38000: #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
38001:         LPOVERLAPPED))aSyscall[48].pCurrent)
38002: #endif
38003: 
38004: #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
38005:         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
38006:   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
38007: #else
38008:   { "MapViewOfFile",           (SYSCALL)0,                       0 },
38009: #endif
38010: 
38011: #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38012:         SIZE_T))aSyscall[49].pCurrent)
38013: 
38014:   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
38015: 
38016: #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
38017:         int))aSyscall[50].pCurrent)
38018: 
38019:   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
38020: 
38021: #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
38022:         LARGE_INTEGER*))aSyscall[51].pCurrent)
38023: 
38024:   { "ReadFile",                (SYSCALL)ReadFile,                0 },
38025: 
38026: #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
38027:         LPOVERLAPPED))aSyscall[52].pCurrent)
38028: 
38029:   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
38030: 
38031: #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
38032: 
38033: #if !SQLITE_OS_WINRT
38034:   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
38035: #else
38036:   { "SetFilePointer",          (SYSCALL)0,                       0 },
38037: #endif
38038: 
38039: #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
38040:         DWORD))aSyscall[54].pCurrent)
38041: 
38042: #if !SQLITE_OS_WINRT
38043:   { "Sleep",                   (SYSCALL)Sleep,                   0 },
38044: #else
38045:   { "Sleep",                   (SYSCALL)0,                       0 },
38046: #endif
38047: 
38048: #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
38049: 
38050:   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
38051: 
38052: #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
38053:         LPFILETIME))aSyscall[56].pCurrent)
38054: 
38055: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38056:   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
38057: #else
38058:   { "UnlockFile",              (SYSCALL)0,                       0 },
38059: #endif
38060: 
38061: #ifndef osUnlockFile
38062: #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38063:         DWORD))aSyscall[57].pCurrent)
38064: #endif
38065: 
38066: #if !SQLITE_OS_WINCE
38067:   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
38068: #else
38069:   { "UnlockFileEx",            (SYSCALL)0,                       0 },
38070: #endif
38071: 
38072: #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
38073:         LPOVERLAPPED))aSyscall[58].pCurrent)
38074: 
38075: #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
38076:   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
38077: #else
38078:   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
38079: #endif
38080: 
38081: #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
38082: 
38083:   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
38084: 
38085: #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
38086:         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
38087: 
38088:   { "WriteFile",               (SYSCALL)WriteFile,               0 },
38089: 
38090: #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
38091:         LPOVERLAPPED))aSyscall[61].pCurrent)
38092: 
38093: #if SQLITE_OS_WINRT
38094:   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
38095: #else
38096:   { "CreateEventExW",          (SYSCALL)0,                       0 },
38097: #endif
38098: 
38099: #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
38100:         DWORD,DWORD))aSyscall[62].pCurrent)
38101: 
38102: #if !SQLITE_OS_WINRT
38103:   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
38104: #else
38105:   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
38106: #endif
38107: 
38108: #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
38109:         DWORD))aSyscall[63].pCurrent)
38110: 
38111: #if !SQLITE_OS_WINCE
38112:   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
38113: #else
38114:   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
38115: #endif
38116: 
38117: #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
38118:         BOOL))aSyscall[64].pCurrent)
38119: 
38120: #if SQLITE_OS_WINRT
38121:   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
38122: #else
38123:   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
38124: #endif
38125: 
38126: #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
38127:         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
38128: 
38129: #if SQLITE_OS_WINRT
38130:   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
38131: #else
38132:   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
38133: #endif
38134: 
38135: #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
38136:         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
38137: 
38138: #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38139:   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
38140: #else
38141:   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
38142: #endif
38143: 
38144: #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
38145:         SIZE_T))aSyscall[67].pCurrent)
38146: 
38147: #if SQLITE_OS_WINRT
38148:   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
38149: #else
38150:   { "CreateFile2",             (SYSCALL)0,                       0 },
38151: #endif
38152: 
38153: #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
38154:         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
38155: 
38156: #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
38157:   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
38158: #else
38159:   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
38160: #endif
38161: 
38162: #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
38163:         DWORD))aSyscall[69].pCurrent)
38164: 
38165: #if SQLITE_OS_WINRT
38166:   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
38167: #else
38168:   { "GetTickCount64",          (SYSCALL)0,                       0 },
38169: #endif
38170: 
38171: #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
38172: 
38173: #if SQLITE_OS_WINRT
38174:   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
38175: #else
38176:   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
38177: #endif
38178: 
38179: #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
38180:         LPSYSTEM_INFO))aSyscall[71].pCurrent)
38181: 
38182: #if defined(SQLITE_WIN32_HAS_ANSI)
38183:   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
38184: #else
38185:   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
38186: #endif
38187: 
38188: #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
38189: 
38190: #if defined(SQLITE_WIN32_HAS_WIDE)
38191:   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
38192: #else
38193:   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
38194: #endif
38195: 
38196: #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
38197: 
38198:   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
38199: 
38200: #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
38201: 
38202: #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
38203:   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
38204: #else
38205:   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
38206: #endif
38207: 
38208: #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
38209:         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
38210: 
38211: /*
38212: ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
38213: **       is really just a macro that uses a compiler intrinsic (e.g. x64).
38214: **       So do not try to make this is into a redefinable interface.
38215: */
38216: #if defined(InterlockedCompareExchange)
38217:   { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
38218: 
38219: #define osInterlockedCompareExchange InterlockedCompareExchange
38220: #else
38221:   { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
38222: 
38223: #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
38224:         SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
38225: #endif /* defined(InterlockedCompareExchange) */
38226: 
38227: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38228:   { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
38229: #else
38230:   { "UuidCreate",               (SYSCALL)0,                      0 },
38231: #endif
38232: 
38233: #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
38234: 
38235: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38236:   { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
38237: #else
38238:   { "UuidCreateSequential",     (SYSCALL)0,                      0 },
38239: #endif
38240: 
38241: #define osUuidCreateSequential \
38242:         ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
38243: 
38244: #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
38245:   { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
38246: #else
38247:   { "FlushViewOfFile",          (SYSCALL)0,                      0 },
38248: #endif
38249: 
38250: #define osFlushViewOfFile \
38251:         ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
38252: 
38253: }; /* End of the overrideable system calls */
38254: 
38255: /*
38256: ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
38257: ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
38258: ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
38259: ** system call named zName.
38260: */
38261: static int winSetSystemCall(
38262:   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
38263:   const char *zName,            /* Name of system call to override */
38264:   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
38265: ){
38266:   unsigned int i;
38267:   int rc = SQLITE_NOTFOUND;
38268: 
38269:   UNUSED_PARAMETER(pNotUsed);
38270:   if( zName==0 ){
38271:     /* If no zName is given, restore all system calls to their default
38272:     ** settings and return NULL
38273:     */
38274:     rc = SQLITE_OK;
38275:     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38276:       if( aSyscall[i].pDefault ){
38277:         aSyscall[i].pCurrent = aSyscall[i].pDefault;
38278:       }
38279:     }
38280:   }else{
38281:     /* If zName is specified, operate on only the one system call
38282:     ** specified.
38283:     */
38284:     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38285:       if( strcmp(zName, aSyscall[i].zName)==0 ){
38286:         if( aSyscall[i].pDefault==0 ){
38287:           aSyscall[i].pDefault = aSyscall[i].pCurrent;
38288:         }
38289:         rc = SQLITE_OK;
38290:         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
38291:         aSyscall[i].pCurrent = pNewFunc;
38292:         break;
38293:       }
38294:     }
38295:   }
38296:   return rc;
38297: }
38298: 
38299: /*
38300: ** Return the value of a system call.  Return NULL if zName is not a
38301: ** recognized system call name.  NULL is also returned if the system call
38302: ** is currently undefined.
38303: */
38304: static sqlite3_syscall_ptr winGetSystemCall(
38305:   sqlite3_vfs *pNotUsed,
38306:   const char *zName
38307: ){
38308:   unsigned int i;
38309: 
38310:   UNUSED_PARAMETER(pNotUsed);
38311:   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38312:     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
38313:   }
38314:   return 0;
38315: }
38316: 
38317: /*
38318: ** Return the name of the first system call after zName.  If zName==NULL
38319: ** then return the name of the first system call.  Return NULL if zName
38320: ** is the last system call or if zName is not the name of a valid
38321: ** system call.
38322: */
38323: static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
38324:   int i = -1;
38325: 
38326:   UNUSED_PARAMETER(p);
38327:   if( zName ){
38328:     for(i=0; i<ArraySize(aSyscall)-1; i++){
38329:       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
38330:     }
38331:   }
38332:   for(i++; i<ArraySize(aSyscall); i++){
38333:     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
38334:   }
38335:   return 0;
38336: }
38337: 
38338: #ifdef SQLITE_WIN32_MALLOC
38339: /*
38340: ** If a Win32 native heap has been configured, this function will attempt to
38341: ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
38342: ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
38343: ** "pnLargest" argument, if non-zero, will be used to return the size of the
38344: ** largest committed free block in the heap, in bytes.
38345: */
38346: SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
38347:   int rc = SQLITE_OK;
38348:   UINT nLargest = 0;
38349:   HANDLE hHeap;
38350: 
38351:   winMemAssertMagic();
38352:   hHeap = winMemGetHeap();
38353:   assert( hHeap!=0 );
38354:   assert( hHeap!=INVALID_HANDLE_VALUE );
38355: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38356:   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38357: #endif
38358: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38359:   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
38360:     DWORD lastErrno = osGetLastError();
38361:     if( lastErrno==NO_ERROR ){
38362:       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
38363:                   (void*)hHeap);
38364:       rc = SQLITE_NOMEM_BKPT;
38365:     }else{
38366:       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
38367:                   osGetLastError(), (void*)hHeap);
38368:       rc = SQLITE_ERROR;
38369:     }
38370:   }
38371: #else
38372:   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
38373:               (void*)hHeap);
38374:   rc = SQLITE_NOTFOUND;
38375: #endif
38376:   if( pnLargest ) *pnLargest = nLargest;
38377:   return rc;
38378: }
38379: 
38380: /*
38381: ** If a Win32 native heap has been configured, this function will attempt to
38382: ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
38383: ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
38384: ** be returned and no changes will be made to the Win32 native heap.
38385: */
38386: SQLITE_API int sqlite3_win32_reset_heap(){
38387:   int rc;
38388:   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
38389:   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
38390:   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
38391:   MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
38392:   sqlite3_mutex_enter(pMaster);
38393:   sqlite3_mutex_enter(pMem);
38394:   winMemAssertMagic();
38395:   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
38396:     /*
38397:     ** At this point, there should be no outstanding memory allocations on
38398:     ** the heap.  Also, since both the master and memsys locks are currently
38399:     ** being held by us, no other function (i.e. from another thread) should
38400:     ** be able to even access the heap.  Attempt to destroy and recreate our
38401:     ** isolated Win32 native heap now.
38402:     */
38403:     assert( winMemGetHeap()!=NULL );
38404:     assert( winMemGetOwned() );
38405:     assert( sqlite3_memory_used()==0 );
38406:     winMemShutdown(winMemGetDataPtr());
38407:     assert( winMemGetHeap()==NULL );
38408:     assert( !winMemGetOwned() );
38409:     assert( sqlite3_memory_used()==0 );
38410:     rc = winMemInit(winMemGetDataPtr());
38411:     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
38412:     assert( rc!=SQLITE_OK || winMemGetOwned() );
38413:     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
38414:   }else{
38415:     /*
38416:     ** The Win32 native heap cannot be modified because it may be in use.
38417:     */
38418:     rc = SQLITE_BUSY;
38419:   }
38420:   sqlite3_mutex_leave(pMem);
38421:   sqlite3_mutex_leave(pMaster);
38422:   return rc;
38423: }
38424: #endif /* SQLITE_WIN32_MALLOC */
38425: 
38426: /*
38427: ** This function outputs the specified (ANSI) string to the Win32 debugger
38428: ** (if available).
38429: */
38430: 
38431: SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
38432:   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
38433:   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
38434:   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
38435:   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
38436: #ifdef SQLITE_ENABLE_API_ARMOR
38437:   if( !zBuf ){
38438:     (void)SQLITE_MISUSE_BKPT;
38439:     return;
38440:   }
38441: #endif
38442: #if defined(SQLITE_WIN32_HAS_ANSI)
38443:   if( nMin>0 ){
38444:     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38445:     memcpy(zDbgBuf, zBuf, nMin);
38446:     osOutputDebugStringA(zDbgBuf);
38447:   }else{
38448:     osOutputDebugStringA(zBuf);
38449:   }
38450: #elif defined(SQLITE_WIN32_HAS_WIDE)
38451:   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38452:   if ( osMultiByteToWideChar(
38453:           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
38454:           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
38455:     return;
38456:   }
38457:   osOutputDebugStringW((LPCWSTR)zDbgBuf);
38458: #else
38459:   if( nMin>0 ){
38460:     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38461:     memcpy(zDbgBuf, zBuf, nMin);
38462:     fprintf(stderr, "%s", zDbgBuf);
38463:   }else{
38464:     fprintf(stderr, "%s", zBuf);
38465:   }
38466: #endif
38467: }
38468: 
38469: /*
38470: ** The following routine suspends the current thread for at least ms
38471: ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
38472: */
38473: #if SQLITE_OS_WINRT
38474: static HANDLE sleepObj = NULL;
38475: #endif
38476: 
38477: SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
38478: #if SQLITE_OS_WINRT
38479:   if ( sleepObj==NULL ){
38480:     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
38481:                                 SYNCHRONIZE);
38482:   }
38483:   assert( sleepObj!=NULL );
38484:   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
38485: #else
38486:   osSleep(milliseconds);
38487: #endif
38488: }
38489: 
38490: #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
38491:         SQLITE_THREADSAFE>0
38492: SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
38493:   DWORD rc;
38494:   while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
38495:                                        TRUE))==WAIT_IO_COMPLETION ){}
38496:   return rc;
38497: }
38498: #endif
38499: 
38500: /*
38501: ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
38502: ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
38503: **
38504: ** Here is an interesting observation:  Win95, Win98, and WinME lack
38505: ** the LockFileEx() API.  But we can still statically link against that
38506: ** API as long as we don't call it when running Win95/98/ME.  A call to
38507: ** this routine is used to determine if the host is Win95/98/ME or
38508: ** WinNT/2K/XP so that we will know whether or not we can safely call
38509: ** the LockFileEx() API.
38510: */
38511: 
38512: #if !SQLITE_WIN32_GETVERSIONEX
38513: # define osIsNT()  (1)
38514: #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
38515: # define osIsNT()  (1)
38516: #elif !defined(SQLITE_WIN32_HAS_WIDE)
38517: # define osIsNT()  (0)
38518: #else
38519: # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
38520: #endif
38521: 
38522: /*
38523: ** This function determines if the machine is running a version of Windows
38524: ** based on the NT kernel.
38525: */
38526: SQLITE_API int sqlite3_win32_is_nt(void){
38527: #if SQLITE_OS_WINRT
38528:   /*
38529:   ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
38530:   **       kernel.
38531:   */
38532:   return 1;
38533: #elif SQLITE_WIN32_GETVERSIONEX
38534:   if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
38535: #if defined(SQLITE_WIN32_HAS_ANSI)
38536:     OSVERSIONINFOA sInfo;
38537:     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38538:     osGetVersionExA(&sInfo);
38539:     osInterlockedCompareExchange(&sqlite3_os_type,
38540:         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38541: #elif defined(SQLITE_WIN32_HAS_WIDE)
38542:     OSVERSIONINFOW sInfo;
38543:     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38544:     osGetVersionExW(&sInfo);
38545:     osInterlockedCompareExchange(&sqlite3_os_type,
38546:         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38547: #endif
38548:   }
38549:   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38550: #elif SQLITE_TEST
38551:   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38552: #else
38553:   /*
38554:   ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
38555:   **       deprecated are always assumed to be based on the NT kernel.
38556:   */
38557:   return 1;
38558: #endif
38559: }
38560: 
38561: #ifdef SQLITE_WIN32_MALLOC
38562: /*
38563: ** Allocate nBytes of memory.
38564: */
38565: static void *winMemMalloc(int nBytes){
38566:   HANDLE hHeap;
38567:   void *p;
38568: 
38569:   winMemAssertMagic();
38570:   hHeap = winMemGetHeap();
38571:   assert( hHeap!=0 );
38572:   assert( hHeap!=INVALID_HANDLE_VALUE );
38573: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38574:   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38575: #endif
38576:   assert( nBytes>=0 );
38577:   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38578:   if( !p ){
38579:     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
38580:                 nBytes, osGetLastError(), (void*)hHeap);
38581:   }
38582:   return p;
38583: }
38584: 
38585: /*
38586: ** Free memory.
38587: */
38588: static void winMemFree(void *pPrior){
38589:   HANDLE hHeap;
38590: 
38591:   winMemAssertMagic();
38592:   hHeap = winMemGetHeap();
38593:   assert( hHeap!=0 );
38594:   assert( hHeap!=INVALID_HANDLE_VALUE );
38595: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38596:   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38597: #endif
38598:   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
38599:   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
38600:     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
38601:                 pPrior, osGetLastError(), (void*)hHeap);
38602:   }
38603: }
38604: 
38605: /*
38606: ** Change the size of an existing memory allocation
38607: */
38608: static void *winMemRealloc(void *pPrior, int nBytes){
38609:   HANDLE hHeap;
38610:   void *p;
38611: 
38612:   winMemAssertMagic();
38613:   hHeap = winMemGetHeap();
38614:   assert( hHeap!=0 );
38615:   assert( hHeap!=INVALID_HANDLE_VALUE );
38616: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38617:   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38618: #endif
38619:   assert( nBytes>=0 );
38620:   if( !pPrior ){
38621:     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38622:   }else{
38623:     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
38624:   }
38625:   if( !p ){
38626:     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
38627:                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
38628:                 (void*)hHeap);
38629:   }
38630:   return p;
38631: }
38632: 
38633: /*
38634: ** Return the size of an outstanding allocation, in bytes.
38635: */
38636: static int winMemSize(void *p){
38637:   HANDLE hHeap;
38638:   SIZE_T n;
38639: 
38640:   winMemAssertMagic();
38641:   hHeap = winMemGetHeap();
38642:   assert( hHeap!=0 );
38643:   assert( hHeap!=INVALID_HANDLE_VALUE );
38644: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38645:   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
38646: #endif
38647:   if( !p ) return 0;
38648:   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
38649:   if( n==(SIZE_T)-1 ){
38650:     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
38651:                 p, osGetLastError(), (void*)hHeap);
38652:     return 0;
38653:   }
38654:   return (int)n;
38655: }
38656: 
38657: /*
38658: ** Round up a request size to the next valid allocation size.
38659: */
38660: static int winMemRoundup(int n){
38661:   return n;
38662: }
38663: 
38664: /*
38665: ** Initialize this module.
38666: */
38667: static int winMemInit(void *pAppData){
38668:   winMemData *pWinMemData = (winMemData *)pAppData;
38669: 
38670:   if( !pWinMemData ) return SQLITE_ERROR;
38671:   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38672:   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38673: 
38674: #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
38675:   if( !pWinMemData->hHeap ){
38676:     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
38677:     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
38678:     if( dwMaximumSize==0 ){
38679:       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
38680:     }else if( dwInitialSize>dwMaximumSize ){
38681:       dwInitialSize = dwMaximumSize;
38682:     }
38683:     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
38684:                                       dwInitialSize, dwMaximumSize);
38685:     if( !pWinMemData->hHeap ){
38686:       sqlite3_log(SQLITE_NOMEM,
38687:           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
38688:           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
38689:           dwMaximumSize);
38690:       return SQLITE_NOMEM_BKPT;
38691:     }
38692:     pWinMemData->bOwned = TRUE;
38693:     assert( pWinMemData->bOwned );
38694:   }
38695: #else
38696:   pWinMemData->hHeap = osGetProcessHeap();
38697:   if( !pWinMemData->hHeap ){
38698:     sqlite3_log(SQLITE_NOMEM,
38699:         "failed to GetProcessHeap (%lu)", osGetLastError());
38700:     return SQLITE_NOMEM_BKPT;
38701:   }
38702:   pWinMemData->bOwned = FALSE;
38703:   assert( !pWinMemData->bOwned );
38704: #endif
38705:   assert( pWinMemData->hHeap!=0 );
38706:   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38707: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38708:   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38709: #endif
38710:   return SQLITE_OK;
38711: }
38712: 
38713: /*
38714: ** Deinitialize this module.
38715: */
38716: static void winMemShutdown(void *pAppData){
38717:   winMemData *pWinMemData = (winMemData *)pAppData;
38718: 
38719:   if( !pWinMemData ) return;
38720:   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38721:   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38722: 
38723:   if( pWinMemData->hHeap ){
38724:     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38725: #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38726:     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38727: #endif
38728:     if( pWinMemData->bOwned ){
38729:       if( !osHeapDestroy(pWinMemData->hHeap) ){
38730:         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
38731:                     osGetLastError(), (void*)pWinMemData->hHeap);
38732:       }
38733:       pWinMemData->bOwned = FALSE;
38734:     }
38735:     pWinMemData->hHeap = NULL;
38736:   }
38737: }
38738: 
38739: /*
38740: ** Populate the low-level memory allocation function pointers in
38741: ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
38742: ** arguments specify the block of memory to manage.
38743: **
38744: ** This routine is only called by sqlite3_config(), and therefore
38745: ** is not required to be threadsafe (it is not).
38746: */
38747: SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
38748:   static const sqlite3_mem_methods winMemMethods = {
38749:     winMemMalloc,
38750:     winMemFree,
38751:     winMemRealloc,
38752:     winMemSize,
38753:     winMemRoundup,
38754:     winMemInit,
38755:     winMemShutdown,
38756:     &win_mem_data
38757:   };
38758:   return &winMemMethods;
38759: }
38760: 
38761: SQLITE_PRIVATE void sqlite3MemSetDefault(void){
38762:   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
38763: }
38764: #endif /* SQLITE_WIN32_MALLOC */
38765: 
38766: /*
38767: ** Convert a UTF-8 string to Microsoft Unicode.
38768: **
38769: ** Space to hold the returned string is obtained from sqlite3_malloc().
38770: */
38771: static LPWSTR winUtf8ToUnicode(const char *zText){
38772:   int nChar;
38773:   LPWSTR zWideText;
38774: 
38775:   nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
38776:   if( nChar==0 ){
38777:     return 0;
38778:   }
38779:   zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
38780:   if( zWideText==0 ){
38781:     return 0;
38782:   }
38783:   nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
38784:                                 nChar);
38785:   if( nChar==0 ){
38786:     sqlite3_free(zWideText);
38787:     zWideText = 0;
38788:   }
38789:   return zWideText;
38790: }
38791: 
38792: /*
38793: ** Convert a Microsoft Unicode string to UTF-8.
38794: **
38795: ** Space to hold the returned string is obtained from sqlite3_malloc().
38796: */
38797: static char *winUnicodeToUtf8(LPCWSTR zWideText){
38798:   int nByte;
38799:   char *zText;
38800: 
38801:   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
38802:   if( nByte == 0 ){
38803:     return 0;
38804:   }
38805:   zText = sqlite3MallocZero( nByte );
38806:   if( zText==0 ){
38807:     return 0;
38808:   }
38809:   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
38810:                                 0, 0);
38811:   if( nByte == 0 ){
38812:     sqlite3_free(zText);
38813:     zText = 0;
38814:   }
38815:   return zText;
38816: }
38817: 
38818: /*
38819: ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
38820: ** code page.
38821: **
38822: ** Space to hold the returned string is obtained from sqlite3_malloc().
38823: */
38824: static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
38825:   int nByte;
38826:   LPWSTR zMbcsText;
38827:   int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38828: 
38829:   nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
38830:                                 0)*sizeof(WCHAR);
38831:   if( nByte==0 ){
38832:     return 0;
38833:   }
38834:   zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
38835:   if( zMbcsText==0 ){
38836:     return 0;
38837:   }
38838:   nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
38839:                                 nByte);
38840:   if( nByte==0 ){
38841:     sqlite3_free(zMbcsText);
38842:     zMbcsText = 0;
38843:   }
38844:   return zMbcsText;
38845: }
38846: 
38847: /*
38848: ** Convert a Microsoft Unicode string to a multi-byte character string,
38849: ** using the ANSI or OEM code page.
38850: **
38851: ** Space to hold the returned string is obtained from sqlite3_malloc().
38852: */
38853: static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
38854:   int nByte;
38855:   char *zText;
38856:   int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38857: 
38858:   nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
38859:   if( nByte == 0 ){
38860:     return 0;
38861:   }
38862:   zText = sqlite3MallocZero( nByte );
38863:   if( zText==0 ){
38864:     return 0;
38865:   }
38866:   nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
38867:                                 nByte, 0, 0);
38868:   if( nByte == 0 ){
38869:     sqlite3_free(zText);
38870:     zText = 0;
38871:   }
38872:   return zText;
38873: }
38874: 
38875: /*
38876: ** Convert a multi-byte character string to UTF-8.
38877: **
38878: ** Space to hold the returned string is obtained from sqlite3_malloc().
38879: */
38880: static char *winMbcsToUtf8(const char *zText, int useAnsi){
38881:   char *zTextUtf8;
38882:   LPWSTR zTmpWide;
38883: 
38884:   zTmpWide = winMbcsToUnicode(zText, useAnsi);
38885:   if( zTmpWide==0 ){
38886:     return 0;
38887:   }
38888:   zTextUtf8 = winUnicodeToUtf8(zTmpWide);
38889:   sqlite3_free(zTmpWide);
38890:   return zTextUtf8;
38891: }
38892: 
38893: /*
38894: ** Convert a UTF-8 string to a multi-byte character string.
38895: **
38896: ** Space to hold the returned string is obtained from sqlite3_malloc().
38897: */
38898: static char *winUtf8ToMbcs(const char *zText, int useAnsi){
38899:   char *zTextMbcs;
38900:   LPWSTR zTmpWide;
38901: 
38902:   zTmpWide = winUtf8ToUnicode(zText);
38903:   if( zTmpWide==0 ){
38904:     return 0;
38905:   }
38906:   zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
38907:   sqlite3_free(zTmpWide);
38908:   return zTextMbcs;
38909: }
38910: 
38911: /*
38912: ** This is a public wrapper for the winUtf8ToUnicode() function.
38913: */
38914: SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
38915: #ifdef SQLITE_ENABLE_API_ARMOR
38916:   if( !zText ){
38917:     (void)SQLITE_MISUSE_BKPT;
38918:     return 0;
38919:   }
38920: #endif
38921: #ifndef SQLITE_OMIT_AUTOINIT
38922:   if( sqlite3_initialize() ) return 0;
38923: #endif
38924:   return winUtf8ToUnicode(zText);
38925: }
38926: 
38927: /*
38928: ** This is a public wrapper for the winUnicodeToUtf8() function.
38929: */
38930: SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
38931: #ifdef SQLITE_ENABLE_API_ARMOR
38932:   if( !zWideText ){
38933:     (void)SQLITE_MISUSE_BKPT;
38934:     return 0;
38935:   }
38936: #endif
38937: #ifndef SQLITE_OMIT_AUTOINIT
38938:   if( sqlite3_initialize() ) return 0;
38939: #endif
38940:   return winUnicodeToUtf8(zWideText);
38941: }
38942: 
38943: /*
38944: ** This is a public wrapper for the winMbcsToUtf8() function.
38945: */
38946: SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
38947: #ifdef SQLITE_ENABLE_API_ARMOR
38948:   if( !zText ){
38949:     (void)SQLITE_MISUSE_BKPT;
38950:     return 0;
38951:   }
38952: #endif
38953: #ifndef SQLITE_OMIT_AUTOINIT
38954:   if( sqlite3_initialize() ) return 0;
38955: #endif
38956:   return winMbcsToUtf8(zText, osAreFileApisANSI());
38957: }
38958: 
38959: /*
38960: ** This is a public wrapper for the winMbcsToUtf8() function.
38961: */
38962: SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
38963: #ifdef SQLITE_ENABLE_API_ARMOR
38964:   if( !zText ){
38965:     (void)SQLITE_MISUSE_BKPT;
38966:     return 0;
38967:   }
38968: #endif
38969: #ifndef SQLITE_OMIT_AUTOINIT
38970:   if( sqlite3_initialize() ) return 0;
38971: #endif
38972:   return winMbcsToUtf8(zText, useAnsi);
38973: }
38974: 
38975: /*
38976: ** This is a public wrapper for the winUtf8ToMbcs() function.
38977: */
38978: SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
38979: #ifdef SQLITE_ENABLE_API_ARMOR
38980:   if( !zText ){
38981:     (void)SQLITE_MISUSE_BKPT;
38982:     return 0;
38983:   }
38984: #endif
38985: #ifndef SQLITE_OMIT_AUTOINIT
38986:   if( sqlite3_initialize() ) return 0;
38987: #endif
38988:   return winUtf8ToMbcs(zText, osAreFileApisANSI());
38989: }
38990: 
38991: /*
38992: ** This is a public wrapper for the winUtf8ToMbcs() function.
38993: */
38994: SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
38995: #ifdef SQLITE_ENABLE_API_ARMOR
38996:   if( !zText ){
38997:     (void)SQLITE_MISUSE_BKPT;
38998:     return 0;
38999:   }
39000: #endif
39001: #ifndef SQLITE_OMIT_AUTOINIT
39002:   if( sqlite3_initialize() ) return 0;
39003: #endif
39004:   return winUtf8ToMbcs(zText, useAnsi);
39005: }
39006: 
39007: /*
39008: ** This function sets the data directory or the temporary directory based on
39009: ** the provided arguments.  The type argument must be 1 in order to set the
39010: ** data directory or 2 in order to set the temporary directory.  The zValue
39011: ** argument is the name of the directory to use.  The return value will be
39012: ** SQLITE_OK if successful.
39013: */
39014: SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
39015:   char **ppDirectory = 0;
39016: #ifndef SQLITE_OMIT_AUTOINIT
39017:   int rc = sqlite3_initialize();
39018:   if( rc ) return rc;
39019: #endif
39020:   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
39021:     ppDirectory = &sqlite3_data_directory;
39022:   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
39023:     ppDirectory = &sqlite3_temp_directory;
39024:   }
39025:   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
39026:           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
39027:   );
39028:   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
39029:   if( ppDirectory ){
39030:     char *zValueUtf8 = 0;
39031:     if( zValue && zValue[0] ){
39032:       zValueUtf8 = winUnicodeToUtf8(zValue);
39033:       if ( zValueUtf8==0 ){
39034:         return SQLITE_NOMEM_BKPT;
39035:       }
39036:     }
39037:     sqlite3_free(*ppDirectory);
39038:     *ppDirectory = zValueUtf8;
39039:     return SQLITE_OK;
39040:   }
39041:   return SQLITE_ERROR;
39042: }
39043: 
39044: /*
39045: ** The return value of winGetLastErrorMsg
39046: ** is zero if the error message fits in the buffer, or non-zero
39047: ** otherwise (if the message was truncated).
39048: */
39049: static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
39050:   /* FormatMessage returns 0 on failure.  Otherwise it
39051:   ** returns the number of TCHARs written to the output
39052:   ** buffer, excluding the terminating null char.
39053:   */
39054:   DWORD dwLen = 0;
39055:   char *zOut = 0;
39056: 
39057:   if( osIsNT() ){
39058: #if SQLITE_OS_WINRT
39059:     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
39060:     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
39061:                              FORMAT_MESSAGE_IGNORE_INSERTS,
39062:                              NULL,
39063:                              lastErrno,
39064:                              0,
39065:                              zTempWide,
39066:                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
39067:                              0);
39068: #else
39069:     LPWSTR zTempWide = NULL;
39070:     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39071:                              FORMAT_MESSAGE_FROM_SYSTEM |
39072:                              FORMAT_MESSAGE_IGNORE_INSERTS,
39073:                              NULL,
39074:                              lastErrno,
39075:                              0,
39076:                              (LPWSTR) &zTempWide,
39077:                              0,
39078:                              0);
39079: #endif
39080:     if( dwLen > 0 ){
39081:       /* allocate a buffer and convert to UTF8 */
39082:       sqlite3BeginBenignMalloc();
39083:       zOut = winUnicodeToUtf8(zTempWide);
39084:       sqlite3EndBenignMalloc();
39085: #if !SQLITE_OS_WINRT
39086:       /* free the system buffer allocated by FormatMessage */
39087:       osLocalFree(zTempWide);
39088: #endif
39089:     }
39090:   }
39091: #ifdef SQLITE_WIN32_HAS_ANSI
39092:   else{
39093:     char *zTemp = NULL;
39094:     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
39095:                              FORMAT_MESSAGE_FROM_SYSTEM |
39096:                              FORMAT_MESSAGE_IGNORE_INSERTS,
39097:                              NULL,
39098:                              lastErrno,
39099:                              0,
39100:                              (LPSTR) &zTemp,
39101:                              0,
39102:                              0);
39103:     if( dwLen > 0 ){
39104:       /* allocate a buffer and convert to UTF8 */
39105:       sqlite3BeginBenignMalloc();
39106:       zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
39107:       sqlite3EndBenignMalloc();
39108:       /* free the system buffer allocated by FormatMessage */
39109:       osLocalFree(zTemp);
39110:     }
39111:   }
39112: #endif
39113:   if( 0 == dwLen ){
39114:     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
39115:   }else{
39116:     /* copy a maximum of nBuf chars to output buffer */
39117:     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
39118:     /* free the UTF8 buffer */
39119:     sqlite3_free(zOut);
39120:   }
39121:   return 0;
39122: }
39123: 
39124: /*
39125: **
39126: ** This function - winLogErrorAtLine() - is only ever called via the macro
39127: ** winLogError().
39128: **
39129: ** This routine is invoked after an error occurs in an OS function.
39130: ** It logs a message using sqlite3_log() containing the current value of
39131: ** error code and, if possible, the human-readable equivalent from
39132: ** FormatMessage.
39133: **
39134: ** The first argument passed to the macro should be the error code that
39135: ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
39136: ** The two subsequent arguments should be the name of the OS function that
39137: ** failed and the associated file-system path, if any.
39138: */
39139: #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
39140: static int winLogErrorAtLine(
39141:   int errcode,                    /* SQLite error code */
39142:   DWORD lastErrno,                /* Win32 last error */
39143:   const char *zFunc,              /* Name of OS function that failed */
39144:   const char *zPath,              /* File path associated with error */
39145:   int iLine                       /* Source line number where error occurred */
39146: ){
39147:   char zMsg[500];                 /* Human readable error text */
39148:   int i;                          /* Loop counter */
39149: 
39150:   zMsg[0] = 0;
39151:   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
39152:   assert( errcode!=SQLITE_OK );
39153:   if( zPath==0 ) zPath = "";
39154:   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
39155:   zMsg[i] = 0;
39156:   sqlite3_log(errcode,
39157:       "os_win.c:%d: (%lu) %s(%s) - %s",
39158:       iLine, lastErrno, zFunc, zPath, zMsg
39159:   );
39160: 
39161:   return errcode;
39162: }
39163: 
39164: /*
39165: ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
39166: ** will be retried following a locking error - probably caused by
39167: ** antivirus software.  Also the initial delay before the first retry.
39168: ** The delay increases linearly with each retry.
39169: */
39170: #ifndef SQLITE_WIN32_IOERR_RETRY
39171: # define SQLITE_WIN32_IOERR_RETRY 10
39172: #endif
39173: #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
39174: # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
39175: #endif
39176: static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
39177: static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
39178: 
39179: /*
39180: ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
39181: ** error code obtained via GetLastError() is eligible to be retried.  It
39182: ** must accept the error code DWORD as its only argument and should return
39183: ** non-zero if the error code is transient in nature and the operation
39184: ** responsible for generating the original error might succeed upon being
39185: ** retried.  The argument to this macro should be a variable.
39186: **
39187: ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
39188: ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
39189: ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
39190: ** may be used to include additional error codes in the set that should
39191: ** result in the failing I/O operation being retried by the caller.  If
39192: ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
39193: ** identical to those of the "winIoerrCanRetry1" macro.
39194: */
39195: #if !defined(winIoerrCanRetry1)
39196: #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
39197:                               ((a)==ERROR_SHARING_VIOLATION)    || \
39198:                               ((a)==ERROR_LOCK_VIOLATION)       || \
39199:                               ((a)==ERROR_DEV_NOT_EXIST)        || \
39200:                               ((a)==ERROR_NETNAME_DELETED)      || \
39201:                               ((a)==ERROR_SEM_TIMEOUT)          || \
39202:                               ((a)==ERROR_NETWORK_UNREACHABLE))
39203: #endif
39204: 
39205: /*
39206: ** If a ReadFile() or WriteFile() error occurs, invoke this routine
39207: ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
39208: ** to give up with an error.
39209: */
39210: static int winRetryIoerr(int *pnRetry, DWORD *pError){
39211:   DWORD e = osGetLastError();
39212:   if( *pnRetry>=winIoerrRetry ){
39213:     if( pError ){
39214:       *pError = e;
39215:     }
39216:     return 0;
39217:   }
39218:   if( winIoerrCanRetry1(e) ){
39219:     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39220:     ++*pnRetry;
39221:     return 1;
39222:   }
39223: #if defined(winIoerrCanRetry2)
39224:   else if( winIoerrCanRetry2(e) ){
39225:     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
39226:     ++*pnRetry;
39227:     return 1;
39228:   }
39229: #endif
39230:   if( pError ){
39231:     *pError = e;
39232:   }
39233:   return 0;
39234: }
39235: 
39236: /*
39237: ** Log a I/O error retry episode.
39238: */
39239: static void winLogIoerr(int nRetry, int lineno){
39240:   if( nRetry ){
39241:     sqlite3_log(SQLITE_NOTICE,
39242:       "delayed %dms for lock/sharing conflict at line %d",
39243:       winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
39244:     );
39245:   }
39246: }
39247: 
39248: /*
39249: ** This #if does not rely on the SQLITE_OS_WINCE define because the
39250: ** corresponding section in "date.c" cannot use it.
39251: */
39252: #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
39253:     (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
39254: /*
39255: ** The MSVC CRT on Windows CE may not have a localtime() function.
39256: ** So define a substitute.
39257: */
39258: /* #  include <time.h> */
39259: struct tm *__cdecl localtime(const time_t *t)
39260: {
39261:   static struct tm y;
39262:   FILETIME uTm, lTm;
39263:   SYSTEMTIME pTm;
39264:   sqlite3_int64 t64;
39265:   t64 = *t;
39266:   t64 = (t64 + 11644473600)*10000000;
39267:   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
39268:   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
39269:   osFileTimeToLocalFileTime(&uTm,&lTm);
39270:   osFileTimeToSystemTime(&lTm,&pTm);
39271:   y.tm_year = pTm.wYear - 1900;
39272:   y.tm_mon = pTm.wMonth - 1;
39273:   y.tm_wday = pTm.wDayOfWeek;
39274:   y.tm_mday = pTm.wDay;
39275:   y.tm_hour = pTm.wHour;
39276:   y.tm_min = pTm.wMinute;
39277:   y.tm_sec = pTm.wSecond;
39278:   return &y;
39279: }
39280: #endif
39281: 
39282: #if SQLITE_OS_WINCE
39283: /*************************************************************************
39284: ** This section contains code for WinCE only.
39285: */
39286: #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
39287: 
39288: /*
39289: ** Acquire a lock on the handle h
39290: */
39291: static void winceMutexAcquire(HANDLE h){
39292:    DWORD dwErr;
39293:    do {
39294:      dwErr = osWaitForSingleObject(h, INFINITE);
39295:    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
39296: }
39297: /*
39298: ** Release a lock acquired by winceMutexAcquire()
39299: */
39300: #define winceMutexRelease(h) ReleaseMutex(h)
39301: 
39302: /*
39303: ** Create the mutex and shared memory used for locking in the file
39304: ** descriptor pFile
39305: */
39306: static int winceCreateLock(const char *zFilename, winFile *pFile){
39307:   LPWSTR zTok;
39308:   LPWSTR zName;
39309:   DWORD lastErrno;
39310:   BOOL bLogged = FALSE;
39311:   BOOL bInit = TRUE;
39312: 
39313:   zName = winUtf8ToUnicode(zFilename);
39314:   if( zName==0 ){
39315:     /* out of memory */
39316:     return SQLITE_IOERR_NOMEM_BKPT;
39317:   }
39318: 
39319:   /* Initialize the local lockdata */
39320:   memset(&pFile->local, 0, sizeof(pFile->local));
39321: 
39322:   /* Replace the backslashes from the filename and lowercase it
39323:   ** to derive a mutex name. */
39324:   zTok = osCharLowerW(zName);
39325:   for (;*zTok;zTok++){
39326:     if (*zTok == '\\') *zTok = '_';
39327:   }
39328: 
39329:   /* Create/open the named mutex */
39330:   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
39331:   if (!pFile->hMutex){
39332:     pFile->lastErrno = osGetLastError();
39333:     sqlite3_free(zName);
39334:     return winLogError(SQLITE_IOERR, pFile->lastErrno,
39335:                        "winceCreateLock1", zFilename);
39336:   }
39337: 
39338:   /* Acquire the mutex before continuing */
39339:   winceMutexAcquire(pFile->hMutex);
39340: 
39341:   /* Since the names of named mutexes, semaphores, file mappings etc are
39342:   ** case-sensitive, take advantage of that by uppercasing the mutex name
39343:   ** and using that as the shared filemapping name.
39344:   */
39345:   osCharUpperW(zName);
39346:   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
39347:                                         PAGE_READWRITE, 0, sizeof(winceLock),
39348:                                         zName);
39349: 
39350:   /* Set a flag that indicates we're the first to create the memory so it
39351:   ** must be zero-initialized */
39352:   lastErrno = osGetLastError();
39353:   if (lastErrno == ERROR_ALREADY_EXISTS){
39354:     bInit = FALSE;
39355:   }
39356: 
39357:   sqlite3_free(zName);
39358: 
39359:   /* If we succeeded in making the shared memory handle, map it. */
39360:   if( pFile->hShared ){
39361:     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
39362:              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
39363:     /* If mapping failed, close the shared memory handle and erase it */
39364:     if( !pFile->shared ){
39365:       pFile->lastErrno = osGetLastError();
39366:       winLogError(SQLITE_IOERR, pFile->lastErrno,
39367:                   "winceCreateLock2", zFilename);
39368:       bLogged = TRUE;
39369:       osCloseHandle(pFile->hShared);
39370:       pFile->hShared = NULL;
39371:     }
39372:   }
39373: 
39374:   /* If shared memory could not be created, then close the mutex and fail */
39375:   if( pFile->hShared==NULL ){
39376:     if( !bLogged ){
39377:       pFile->lastErrno = lastErrno;
39378:       winLogError(SQLITE_IOERR, pFile->lastErrno,
39379:                   "winceCreateLock3", zFilename);
39380:       bLogged = TRUE;
39381:     }
39382:     winceMutexRelease(pFile->hMutex);
39383:     osCloseHandle(pFile->hMutex);
39384:     pFile->hMutex = NULL;
39385:     return SQLITE_IOERR;
39386:   }
39387: 
39388:   /* Initialize the shared memory if we're supposed to */
39389:   if( bInit ){
39390:     memset(pFile->shared, 0, sizeof(winceLock));
39391:   }
39392: 
39393:   winceMutexRelease(pFile->hMutex);
39394:   return SQLITE_OK;
39395: }
39396: 
39397: /*
39398: ** Destroy the part of winFile that deals with wince locks
39399: */
39400: static void winceDestroyLock(winFile *pFile){
39401:   if (pFile->hMutex){
39402:     /* Acquire the mutex */
39403:     winceMutexAcquire(pFile->hMutex);
39404: 
39405:     /* The following blocks should probably assert in debug mode, but they
39406:        are to cleanup in case any locks remained open */
39407:     if (pFile->local.nReaders){
39408:       pFile->shared->nReaders --;
39409:     }
39410:     if (pFile->local.bReserved){
39411:       pFile->shared->bReserved = FALSE;
39412:     }
39413:     if (pFile->local.bPending){
39414:       pFile->shared->bPending = FALSE;
39415:     }
39416:     if (pFile->local.bExclusive){
39417:       pFile->shared->bExclusive = FALSE;
39418:     }
39419: 
39420:     /* De-reference and close our copy of the shared memory handle */
39421:     osUnmapViewOfFile(pFile->shared);
39422:     osCloseHandle(pFile->hShared);
39423: 
39424:     /* Done with the mutex */
39425:     winceMutexRelease(pFile->hMutex);
39426:     osCloseHandle(pFile->hMutex);
39427:     pFile->hMutex = NULL;
39428:   }
39429: }
39430: 
39431: /*
39432: ** An implementation of the LockFile() API of Windows for CE
39433: */
39434: static BOOL winceLockFile(
39435:   LPHANDLE phFile,
39436:   DWORD dwFileOffsetLow,
39437:   DWORD dwFileOffsetHigh,
39438:   DWORD nNumberOfBytesToLockLow,
39439:   DWORD nNumberOfBytesToLockHigh
39440: ){
39441:   winFile *pFile = HANDLE_TO_WINFILE(phFile);
39442:   BOOL bReturn = FALSE;
39443: 
39444:   UNUSED_PARAMETER(dwFileOffsetHigh);
39445:   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
39446: 
39447:   if (!pFile->hMutex) return TRUE;
39448:   winceMutexAcquire(pFile->hMutex);
39449: 
39450:   /* Wanting an exclusive lock? */
39451:   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
39452:        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
39453:     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
39454:        pFile->shared->bExclusive = TRUE;
39455:        pFile->local.bExclusive = TRUE;
39456:        bReturn = TRUE;
39457:     }
39458:   }
39459: 
39460:   /* Want a read-only lock? */
39461:   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
39462:            nNumberOfBytesToLockLow == 1){
39463:     if (pFile->shared->bExclusive == 0){
39464:       pFile->local.nReaders ++;
39465:       if (pFile->local.nReaders == 1){
39466:         pFile->shared->nReaders ++;
39467:       }
39468:       bReturn = TRUE;
39469:     }
39470:   }
39471: 
39472:   /* Want a pending lock? */
39473:   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39474:            && nNumberOfBytesToLockLow == 1){
39475:     /* If no pending lock has been acquired, then acquire it */
39476:     if (pFile->shared->bPending == 0) {
39477:       pFile->shared->bPending = TRUE;
39478:       pFile->local.bPending = TRUE;
39479:       bReturn = TRUE;
39480:     }
39481:   }
39482: 
39483:   /* Want a reserved lock? */
39484:   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39485:            && nNumberOfBytesToLockLow == 1){
39486:     if (pFile->shared->bReserved == 0) {
39487:       pFile->shared->bReserved = TRUE;
39488:       pFile->local.bReserved = TRUE;
39489:       bReturn = TRUE;
39490:     }
39491:   }
39492: 
39493:   winceMutexRelease(pFile->hMutex);
39494:   return bReturn;
39495: }
39496: 
39497: /*
39498: ** An implementation of the UnlockFile API of Windows for CE
39499: */
39500: static BOOL winceUnlockFile(
39501:   LPHANDLE phFile,
39502:   DWORD dwFileOffsetLow,
39503:   DWORD dwFileOffsetHigh,
39504:   DWORD nNumberOfBytesToUnlockLow,
39505:   DWORD nNumberOfBytesToUnlockHigh
39506: ){
39507:   winFile *pFile = HANDLE_TO_WINFILE(phFile);
39508:   BOOL bReturn = FALSE;
39509: 
39510:   UNUSED_PARAMETER(dwFileOffsetHigh);
39511:   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
39512: 
39513:   if (!pFile->hMutex) return TRUE;
39514:   winceMutexAcquire(pFile->hMutex);
39515: 
39516:   /* Releasing a reader lock or an exclusive lock */
39517:   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
39518:     /* Did we have an exclusive lock? */
39519:     if (pFile->local.bExclusive){
39520:       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
39521:       pFile->local.bExclusive = FALSE;
39522:       pFile->shared->bExclusive = FALSE;
39523:       bReturn = TRUE;
39524:     }
39525: 
39526:     /* Did we just have a reader lock? */
39527:     else if (pFile->local.nReaders){
39528:       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
39529:              || nNumberOfBytesToUnlockLow == 1);
39530:       pFile->local.nReaders --;
39531:       if (pFile->local.nReaders == 0)
39532:       {
39533:         pFile->shared->nReaders --;
39534:       }
39535:       bReturn = TRUE;
39536:     }
39537:   }
39538: 
39539:   /* Releasing a pending lock */
39540:   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39541:            && nNumberOfBytesToUnlockLow == 1){
39542:     if (pFile->local.bPending){
39543:       pFile->local.bPending = FALSE;
39544:       pFile->shared->bPending = FALSE;
39545:       bReturn = TRUE;
39546:     }
39547:   }
39548:   /* Releasing a reserved lock */
39549:   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39550:            && nNumberOfBytesToUnlockLow == 1){
39551:     if (pFile->local.bReserved) {
39552:       pFile->local.bReserved = FALSE;
39553:       pFile->shared->bReserved = FALSE;
39554:       bReturn = TRUE;
39555:     }
39556:   }
39557: 
39558:   winceMutexRelease(pFile->hMutex);
39559:   return bReturn;
39560: }
39561: /*
39562: ** End of the special code for wince
39563: *****************************************************************************/
39564: #endif /* SQLITE_OS_WINCE */
39565: 
39566: /*
39567: ** Lock a file region.
39568: */
39569: static BOOL winLockFile(
39570:   LPHANDLE phFile,
39571:   DWORD flags,
39572:   DWORD offsetLow,
39573:   DWORD offsetHigh,
39574:   DWORD numBytesLow,
39575:   DWORD numBytesHigh
39576: ){
39577: #if SQLITE_OS_WINCE
39578:   /*
39579:   ** NOTE: Windows CE is handled differently here due its lack of the Win32
39580:   **       API LockFile.
39581:   */
39582:   return winceLockFile(phFile, offsetLow, offsetHigh,
39583:                        numBytesLow, numBytesHigh);
39584: #else
39585:   if( osIsNT() ){
39586:     OVERLAPPED ovlp;
39587:     memset(&ovlp, 0, sizeof(OVERLAPPED));
39588:     ovlp.Offset = offsetLow;
39589:     ovlp.OffsetHigh = offsetHigh;
39590:     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
39591:   }else{
39592:     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39593:                       numBytesHigh);
39594:   }
39595: #endif
39596: }
39597: 
39598: /*
39599: ** Unlock a file region.
39600:  */
39601: static BOOL winUnlockFile(
39602:   LPHANDLE phFile,
39603:   DWORD offsetLow,
39604:   DWORD offsetHigh,
39605:   DWORD numBytesLow,
39606:   DWORD numBytesHigh
39607: ){
39608: #if SQLITE_OS_WINCE
39609:   /*
39610:   ** NOTE: Windows CE is handled differently here due its lack of the Win32
39611:   **       API UnlockFile.
39612:   */
39613:   return winceUnlockFile(phFile, offsetLow, offsetHigh,
39614:                          numBytesLow, numBytesHigh);
39615: #else
39616:   if( osIsNT() ){
39617:     OVERLAPPED ovlp;
39618:     memset(&ovlp, 0, sizeof(OVERLAPPED));
39619:     ovlp.Offset = offsetLow;
39620:     ovlp.OffsetHigh = offsetHigh;
39621:     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
39622:   }else{
39623:     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39624:                         numBytesHigh);
39625:   }
39626: #endif
39627: }
39628: 
39629: /*****************************************************************************
39630: ** The next group of routines implement the I/O methods specified
39631: ** by the sqlite3_io_methods object.
39632: ******************************************************************************/
39633: 
39634: /*
39635: ** Some Microsoft compilers lack this definition.
39636: */
39637: #ifndef INVALID_SET_FILE_POINTER
39638: # define INVALID_SET_FILE_POINTER ((DWORD)-1)
39639: #endif
39640: 
39641: /*
39642: ** Move the current position of the file handle passed as the first
39643: ** argument to offset iOffset within the file. If successful, return 0.
39644: ** Otherwise, set pFile->lastErrno and return non-zero.
39645: */
39646: static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
39647: #if !SQLITE_OS_WINRT
39648:   LONG upperBits;                 /* Most sig. 32 bits of new offset */
39649:   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
39650:   DWORD dwRet;                    /* Value returned by SetFilePointer() */
39651:   DWORD lastErrno;                /* Value returned by GetLastError() */
39652: 
39653:   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
39654: 
39655:   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
39656:   lowerBits = (LONG)(iOffset & 0xffffffff);
39657: 
39658:   /* API oddity: If successful, SetFilePointer() returns a dword
39659:   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
39660:   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
39661:   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
39662:   ** whether an error has actually occurred, it is also necessary to call
39663:   ** GetLastError().
39664:   */
39665:   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
39666: 
39667:   if( (dwRet==INVALID_SET_FILE_POINTER
39668:       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
39669:     pFile->lastErrno = lastErrno;
39670:     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39671:                 "winSeekFile", pFile->zPath);
39672:     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39673:     return 1;
39674:   }
39675: 
39676:   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39677:   return 0;
39678: #else
39679:   /*
39680:   ** Same as above, except that this implementation works for WinRT.
39681:   */
39682: 
39683:   LARGE_INTEGER x;                /* The new offset */
39684:   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
39685: 
39686:   x.QuadPart = iOffset;
39687:   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
39688: 
39689:   if(!bRet){
39690:     pFile->lastErrno = osGetLastError();
39691:     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39692:                 "winSeekFile", pFile->zPath);
39693:     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39694:     return 1;
39695:   }
39696: 
39697:   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39698:   return 0;
39699: #endif
39700: }
39701: 
39702: #if SQLITE_MAX_MMAP_SIZE>0
39703: /* Forward references to VFS helper methods used for memory mapped files */
39704: static int winMapfile(winFile*, sqlite3_int64);
39705: static int winUnmapfile(winFile*);
39706: #endif
39707: 
39708: /*
39709: ** Close a file.
39710: **
39711: ** It is reported that an attempt to close a handle might sometimes
39712: ** fail.  This is a very unreasonable result, but Windows is notorious
39713: ** for being unreasonable so I do not doubt that it might happen.  If
39714: ** the close fails, we pause for 100 milliseconds and try again.  As
39715: ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
39716: ** giving up and returning an error.
39717: */
39718: #define MX_CLOSE_ATTEMPT 3
39719: static int winClose(sqlite3_file *id){
39720:   int rc, cnt = 0;
39721:   winFile *pFile = (winFile*)id;
39722: 
39723:   assert( id!=0 );
39724: #ifndef SQLITE_OMIT_WAL
39725:   assert( pFile->pShm==0 );
39726: #endif
39727:   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
39728:   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
39729:            osGetCurrentProcessId(), pFile, pFile->h));
39730: 
39731: #if SQLITE_MAX_MMAP_SIZE>0
39732:   winUnmapfile(pFile);
39733: #endif
39734: 
39735:   do{
39736:     rc = osCloseHandle(pFile->h);
39737:     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
39738:   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
39739: #if SQLITE_OS_WINCE
39740: #define WINCE_DELETION_ATTEMPTS 3
39741:   {
39742:     winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
39743:     if( pAppData==NULL || !pAppData->bNoLock ){
39744:       winceDestroyLock(pFile);
39745:     }
39746:   }
39747:   if( pFile->zDeleteOnClose ){
39748:     int cnt = 0;
39749:     while(
39750:            osDeleteFileW(pFile->zDeleteOnClose)==0
39751:         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
39752:         && cnt++ < WINCE_DELETION_ATTEMPTS
39753:     ){
39754:        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
39755:     }
39756:     sqlite3_free(pFile->zDeleteOnClose);
39757:   }
39758: #endif
39759:   if( rc ){
39760:     pFile->h = NULL;
39761:   }
39762:   OpenCounter(-1);
39763:   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
39764:            osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
39765:   return rc ? SQLITE_OK
39766:             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
39767:                           "winClose", pFile->zPath);
39768: }
39769: 
39770: /*
39771: ** Read data from a file into a buffer.  Return SQLITE_OK if all
39772: ** bytes were read successfully and SQLITE_IOERR if anything goes
39773: ** wrong.
39774: */
39775: static int winRead(
39776:   sqlite3_file *id,          /* File to read from */
39777:   void *pBuf,                /* Write content into this buffer */
39778:   int amt,                   /* Number of bytes to read */
39779:   sqlite3_int64 offset       /* Begin reading at this offset */
39780: ){
39781: #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39782:   OVERLAPPED overlapped;          /* The offset for ReadFile. */
39783: #endif
39784:   winFile *pFile = (winFile*)id;  /* file handle */
39785:   DWORD nRead;                    /* Number of bytes actually read from file */
39786:   int nRetry = 0;                 /* Number of retrys */
39787: 
39788:   assert( id!=0 );
39789:   assert( amt>0 );
39790:   assert( offset>=0 );
39791:   SimulateIOError(return SQLITE_IOERR_READ);
39792:   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39793:            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39794:            pFile->h, pBuf, amt, offset, pFile->locktype));
39795: 
39796: #if SQLITE_MAX_MMAP_SIZE>0
39797:   /* Deal with as much of this read request as possible by transfering
39798:   ** data from the memory mapping using memcpy().  */
39799:   if( offset<pFile->mmapSize ){
39800:     if( offset+amt <= pFile->mmapSize ){
39801:       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
39802:       OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39803:                osGetCurrentProcessId(), pFile, pFile->h));
39804:       return SQLITE_OK;
39805:     }else{
39806:       int nCopy = (int)(pFile->mmapSize - offset);
39807:       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
39808:       pBuf = &((u8 *)pBuf)[nCopy];
39809:       amt -= nCopy;
39810:       offset += nCopy;
39811:     }
39812:   }
39813: #endif
39814: 
39815: #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39816:   if( winSeekFile(pFile, offset) ){
39817:     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39818:              osGetCurrentProcessId(), pFile, pFile->h));
39819:     return SQLITE_FULL;
39820:   }
39821:   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
39822: #else
39823:   memset(&overlapped, 0, sizeof(OVERLAPPED));
39824:   overlapped.Offset = (LONG)(offset & 0xffffffff);
39825:   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39826:   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
39827:          osGetLastError()!=ERROR_HANDLE_EOF ){
39828: #endif
39829:     DWORD lastErrno;
39830:     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39831:     pFile->lastErrno = lastErrno;
39832:     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
39833:              osGetCurrentProcessId(), pFile, pFile->h));
39834:     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
39835:                        "winRead", pFile->zPath);
39836:   }
39837:   winLogIoerr(nRetry, __LINE__);
39838:   if( nRead<(DWORD)amt ){
39839:     /* Unread parts of the buffer must be zero-filled */
39840:     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
39841:     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
39842:              osGetCurrentProcessId(), pFile, pFile->h));
39843:     return SQLITE_IOERR_SHORT_READ;
39844:   }
39845: 
39846:   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39847:            osGetCurrentProcessId(), pFile, pFile->h));
39848:   return SQLITE_OK;
39849: }
39850: 
39851: /*
39852: ** Write data from a buffer into a file.  Return SQLITE_OK on success
39853: ** or some other error code on failure.
39854: */
39855: static int winWrite(
39856:   sqlite3_file *id,               /* File to write into */
39857:   const void *pBuf,               /* The bytes to be written */
39858:   int amt,                        /* Number of bytes to write */
39859:   sqlite3_int64 offset            /* Offset into the file to begin writing at */
39860: ){
39861:   int rc = 0;                     /* True if error has occurred, else false */
39862:   winFile *pFile = (winFile*)id;  /* File handle */
39863:   int nRetry = 0;                 /* Number of retries */
39864: 
39865:   assert( amt>0 );
39866:   assert( pFile );
39867:   SimulateIOError(return SQLITE_IOERR_WRITE);
39868:   SimulateDiskfullError(return SQLITE_FULL);
39869: 
39870:   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39871:            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39872:            pFile->h, pBuf, amt, offset, pFile->locktype));
39873: 
39874: #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
39875:   /* Deal with as much of this write request as possible by transfering
39876:   ** data from the memory mapping using memcpy().  */
39877:   if( offset<pFile->mmapSize ){
39878:     if( offset+amt <= pFile->mmapSize ){
39879:       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
39880:       OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39881:                osGetCurrentProcessId(), pFile, pFile->h));
39882:       return SQLITE_OK;
39883:     }else{
39884:       int nCopy = (int)(pFile->mmapSize - offset);
39885:       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
39886:       pBuf = &((u8 *)pBuf)[nCopy];
39887:       amt -= nCopy;
39888:       offset += nCopy;
39889:     }
39890:   }
39891: #endif
39892: 
39893: #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39894:   rc = winSeekFile(pFile, offset);
39895:   if( rc==0 ){
39896: #else
39897:   {
39898: #endif
39899: #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39900:     OVERLAPPED overlapped;        /* The offset for WriteFile. */
39901: #endif
39902:     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
39903:     int nRem = amt;               /* Number of bytes yet to be written */
39904:     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
39905:     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
39906: 
39907: #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39908:     memset(&overlapped, 0, sizeof(OVERLAPPED));
39909:     overlapped.Offset = (LONG)(offset & 0xffffffff);
39910:     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39911: #endif
39912: 
39913:     while( nRem>0 ){
39914: #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39915:       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
39916: #else
39917:       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
39918: #endif
39919:         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39920:         break;
39921:       }
39922:       assert( nWrite==0 || nWrite<=(DWORD)nRem );
39923:       if( nWrite==0 || nWrite>(DWORD)nRem ){
39924:         lastErrno = osGetLastError();
39925:         break;
39926:       }
39927: #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39928:       offset += nWrite;
39929:       overlapped.Offset = (LONG)(offset & 0xffffffff);
39930:       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39931: #endif
39932:       aRem += nWrite;
39933:       nRem -= nWrite;
39934:     }
39935:     if( nRem>0 ){
39936:       pFile->lastErrno = lastErrno;
39937:       rc = 1;
39938:     }
39939:   }
39940: 
39941:   if( rc ){
39942:     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
39943:        || ( pFile->lastErrno==ERROR_DISK_FULL )){
39944:       OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39945:                osGetCurrentProcessId(), pFile, pFile->h));
39946:       return winLogError(SQLITE_FULL, pFile->lastErrno,
39947:                          "winWrite1", pFile->zPath);
39948:     }
39949:     OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
39950:              osGetCurrentProcessId(), pFile, pFile->h));
39951:     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
39952:                        "winWrite2", pFile->zPath);
39953:   }else{
39954:     winLogIoerr(nRetry, __LINE__);
39955:   }
39956:   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39957:            osGetCurrentProcessId(), pFile, pFile->h));
39958:   return SQLITE_OK;
39959: }
39960: 
39961: /*
39962: ** Truncate an open file to a specified size
39963: */
39964: static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
39965:   winFile *pFile = (winFile*)id;  /* File handle object */
39966:   int rc = SQLITE_OK;             /* Return code for this function */
39967:   DWORD lastErrno;
39968: 
39969:   assert( pFile );
39970:   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
39971:   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
39972:            osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
39973: 
39974:   /* If the user has configured a chunk-size for this file, truncate the
39975:   ** file so that it consists of an integer number of chunks (i.e. the
39976:   ** actual file size after the operation may be larger than the requested
39977:   ** size).
39978:   */
39979:   if( pFile->szChunk>0 ){
39980:     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
39981:   }
39982: 
39983:   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
39984:   if( winSeekFile(pFile, nByte) ){
39985:     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
39986:                      "winTruncate1", pFile->zPath);
39987:   }else if( 0==osSetEndOfFile(pFile->h) &&
39988:             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
39989:     pFile->lastErrno = lastErrno;
39990:     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
39991:                      "winTruncate2", pFile->zPath);
39992:   }
39993: 
39994: #if SQLITE_MAX_MMAP_SIZE>0
39995:   /* If the file was truncated to a size smaller than the currently
39996:   ** mapped region, reduce the effective mapping size as well. SQLite will
39997:   ** use read() and write() to access data beyond this point from now on.
39998:   */
39999:   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
40000:     pFile->mmapSize = nByte;
40001:   }
40002: #endif
40003: 
40004:   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
40005:            osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
40006:   return rc;
40007: }
40008: 
40009: #ifdef SQLITE_TEST
40010: /*
40011: ** Count the number of fullsyncs and normal syncs.  This is used to test
40012: ** that syncs and fullsyncs are occuring at the right times.
40013: */
40014: SQLITE_API int sqlite3_sync_count = 0;
40015: SQLITE_API int sqlite3_fullsync_count = 0;
40016: #endif
40017: 
40018: /*
40019: ** Make sure all writes to a particular file are committed to disk.
40020: */
40021: static int winSync(sqlite3_file *id, int flags){
40022: #ifndef SQLITE_NO_SYNC
40023:   /*
40024:   ** Used only when SQLITE_NO_SYNC is not defined.
40025:    */
40026:   BOOL rc;
40027: #endif
40028: #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
40029:     defined(SQLITE_HAVE_OS_TRACE)
40030:   /*
40031:   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
40032:   ** OSTRACE() macros.
40033:    */
40034:   winFile *pFile = (winFile*)id;
40035: #else
40036:   UNUSED_PARAMETER(id);
40037: #endif
40038: 
40039:   assert( pFile );
40040:   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
40041:   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
40042:       || (flags&0x0F)==SQLITE_SYNC_FULL
40043:   );
40044: 
40045:   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
40046:   ** line is to test that doing so does not cause any problems.
40047:   */
40048:   SimulateDiskfullError( return SQLITE_FULL );
40049: 
40050:   OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
40051:            osGetCurrentProcessId(), pFile, pFile->h, flags,
40052:            pFile->locktype));
40053: 
40054: #ifndef SQLITE_TEST
40055:   UNUSED_PARAMETER(flags);
40056: #else
40057:   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
40058:     sqlite3_fullsync_count++;
40059:   }
40060:   sqlite3_sync_count++;
40061: #endif
40062: 
40063:   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
40064:   ** no-op
40065:   */
40066: #ifdef SQLITE_NO_SYNC
40067:   OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40068:            osGetCurrentProcessId(), pFile, pFile->h));
40069:   return SQLITE_OK;
40070: #else
40071: #if SQLITE_MAX_MMAP_SIZE>0
40072:   if( pFile->pMapRegion ){
40073:     if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
40074:       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40075:                "rc=SQLITE_OK\n", osGetCurrentProcessId(),
40076:                pFile, pFile->pMapRegion));
40077:     }else{
40078:       pFile->lastErrno = osGetLastError();
40079:       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
40080:                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
40081:                pFile, pFile->pMapRegion));
40082:       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
40083:                          "winSync1", pFile->zPath);
40084:     }
40085:   }
40086: #endif
40087:   rc = osFlushFileBuffers(pFile->h);
40088:   SimulateIOError( rc=FALSE );
40089:   if( rc ){
40090:     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
40091:              osGetCurrentProcessId(), pFile, pFile->h));
40092:     return SQLITE_OK;
40093:   }else{
40094:     pFile->lastErrno = osGetLastError();
40095:     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
40096:              osGetCurrentProcessId(), pFile, pFile->h));
40097:     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
40098:                        "winSync2", pFile->zPath);
40099:   }
40100: #endif
40101: }
40102: 
40103: /*
40104: ** Determine the current size of a file in bytes
40105: */
40106: static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
40107:   winFile *pFile = (winFile*)id;
40108:   int rc = SQLITE_OK;
40109: 
40110:   assert( id!=0 );
40111:   assert( pSize!=0 );
40112:   SimulateIOError(return SQLITE_IOERR_FSTAT);
40113:   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
40114: 
40115: #if SQLITE_OS_WINRT
40116:   {
40117:     FILE_STANDARD_INFO info;
40118:     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
40119:                                      &info, sizeof(info)) ){
40120:       *pSize = info.EndOfFile.QuadPart;
40121:     }else{
40122:       pFile->lastErrno = osGetLastError();
40123:       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40124:                        "winFileSize", pFile->zPath);
40125:     }
40126:   }
40127: #else
40128:   {
40129:     DWORD upperBits;
40130:     DWORD lowerBits;
40131:     DWORD lastErrno;
40132: 
40133:     lowerBits = osGetFileSize(pFile->h, &upperBits);
40134:     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
40135:     if(   (lowerBits == INVALID_FILE_SIZE)
40136:        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
40137:       pFile->lastErrno = lastErrno;
40138:       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
40139:                        "winFileSize", pFile->zPath);
40140:     }
40141:   }
40142: #endif
40143:   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
40144:            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
40145:   return rc;
40146: }
40147: 
40148: /*
40149: ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
40150: */
40151: #ifndef LOCKFILE_FAIL_IMMEDIATELY
40152: # define LOCKFILE_FAIL_IMMEDIATELY 1
40153: #endif
40154: 
40155: #ifndef LOCKFILE_EXCLUSIVE_LOCK
40156: # define LOCKFILE_EXCLUSIVE_LOCK 2
40157: #endif
40158: 
40159: /*
40160: ** Historically, SQLite has used both the LockFile and LockFileEx functions.
40161: ** When the LockFile function was used, it was always expected to fail
40162: ** immediately if the lock could not be obtained.  Also, it always expected to
40163: ** obtain an exclusive lock.  These flags are used with the LockFileEx function
40164: ** and reflect those expectations; therefore, they should not be changed.
40165: */
40166: #ifndef SQLITE_LOCKFILE_FLAGS
40167: # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
40168:                                   LOCKFILE_EXCLUSIVE_LOCK)
40169: #endif
40170: 
40171: /*
40172: ** Currently, SQLite never calls the LockFileEx function without wanting the
40173: ** call to fail immediately if the lock cannot be obtained.
40174: */
40175: #ifndef SQLITE_LOCKFILEEX_FLAGS
40176: # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
40177: #endif
40178: 
40179: /*
40180: ** Acquire a reader lock.
40181: ** Different API routines are called depending on whether or not this
40182: ** is Win9x or WinNT.
40183: */
40184: static int winGetReadLock(winFile *pFile){
40185:   int res;
40186:   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40187:   if( osIsNT() ){
40188: #if SQLITE_OS_WINCE
40189:     /*
40190:     ** NOTE: Windows CE is handled differently here due its lack of the Win32
40191:     **       API LockFileEx.
40192:     */
40193:     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
40194: #else
40195:     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
40196:                       SHARED_SIZE, 0);
40197: #endif
40198:   }
40199: #ifdef SQLITE_WIN32_HAS_ANSI
40200:   else{
40201:     int lk;
40202:     sqlite3_randomness(sizeof(lk), &lk);
40203:     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
40204:     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40205:                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40206:   }
40207: #endif
40208:   if( res == 0 ){
40209:     pFile->lastErrno = osGetLastError();
40210:     /* No need to log a failure to lock */
40211:   }
40212:   OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
40213:   return res;
40214: }
40215: 
40216: /*
40217: ** Undo a readlock
40218: */
40219: static int winUnlockReadLock(winFile *pFile){
40220:   int res;
40221:   DWORD lastErrno;
40222:   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
40223:   if( osIsNT() ){
40224:     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40225:   }
40226: #ifdef SQLITE_WIN32_HAS_ANSI
40227:   else{
40228:     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
40229:   }
40230: #endif
40231:   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
40232:     pFile->lastErrno = lastErrno;
40233:     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
40234:                 "winUnlockReadLock", pFile->zPath);
40235:   }
40236:   OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
40237:   return res;
40238: }
40239: 
40240: /*
40241: ** Lock the file with the lock specified by parameter locktype - one
40242: ** of the following:
40243: **
40244: **     (1) SHARED_LOCK
40245: **     (2) RESERVED_LOCK
40246: **     (3) PENDING_LOCK
40247: **     (4) EXCLUSIVE_LOCK
40248: **
40249: ** Sometimes when requesting one lock state, additional lock states
40250: ** are inserted in between.  The locking might fail on one of the later
40251: ** transitions leaving the lock state different from what it started but
40252: ** still short of its goal.  The following chart shows the allowed
40253: ** transitions and the inserted intermediate states:
40254: **
40255: **    UNLOCKED -> SHARED
40256: **    SHARED -> RESERVED
40257: **    SHARED -> (PENDING) -> EXCLUSIVE
40258: **    RESERVED -> (PENDING) -> EXCLUSIVE
40259: **    PENDING -> EXCLUSIVE
40260: **
40261: ** This routine will only increase a lock.  The winUnlock() routine
40262: ** erases all locks at once and returns us immediately to locking level 0.
40263: ** It is not possible to lower the locking level one step at a time.  You
40264: ** must go straight to locking level 0.
40265: */
40266: static int winLock(sqlite3_file *id, int locktype){
40267:   int rc = SQLITE_OK;    /* Return code from subroutines */
40268:   int res = 1;           /* Result of a Windows lock call */
40269:   int newLocktype;       /* Set pFile->locktype to this value before exiting */
40270:   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
40271:   winFile *pFile = (winFile*)id;
40272:   DWORD lastErrno = NO_ERROR;
40273: 
40274:   assert( id!=0 );
40275:   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40276:            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40277: 
40278:   /* If there is already a lock of this type or more restrictive on the
40279:   ** OsFile, do nothing. Don't use the end_lock: exit path, as
40280:   ** sqlite3OsEnterMutex() hasn't been called yet.
40281:   */
40282:   if( pFile->locktype>=locktype ){
40283:     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
40284:     return SQLITE_OK;
40285:   }
40286: 
40287:   /* Do not allow any kind of write-lock on a read-only database
40288:   */
40289:   if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
40290:     return SQLITE_IOERR_LOCK;
40291:   }
40292: 
40293:   /* Make sure the locking sequence is correct
40294:   */
40295:   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
40296:   assert( locktype!=PENDING_LOCK );
40297:   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
40298: 
40299:   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
40300:   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
40301:   ** the PENDING_LOCK byte is temporary.
40302:   */
40303:   newLocktype = pFile->locktype;
40304:   if( pFile->locktype==NO_LOCK
40305:    || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
40306:   ){
40307:     int cnt = 3;
40308:     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40309:                                          PENDING_BYTE, 0, 1, 0))==0 ){
40310:       /* Try 3 times to get the pending lock.  This is needed to work
40311:       ** around problems caused by indexing and/or anti-virus software on
40312:       ** Windows systems.
40313:       ** If you are using this code as a model for alternative VFSes, do not
40314:       ** copy this retry logic.  It is a hack intended for Windows only.
40315:       */
40316:       lastErrno = osGetLastError();
40317:       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
40318:                pFile->h, cnt, res));
40319:       if( lastErrno==ERROR_INVALID_HANDLE ){
40320:         pFile->lastErrno = lastErrno;
40321:         rc = SQLITE_IOERR_LOCK;
40322:         OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
40323:                  pFile->h, cnt, sqlite3ErrName(rc)));
40324:         return rc;
40325:       }
40326:       if( cnt ) sqlite3_win32_sleep(1);
40327:     }
40328:     gotPendingLock = res;
40329:     if( !res ){
40330:       lastErrno = osGetLastError();
40331:     }
40332:   }
40333: 
40334:   /* Acquire a shared lock
40335:   */
40336:   if( locktype==SHARED_LOCK && res ){
40337:     assert( pFile->locktype==NO_LOCK );
40338:     res = winGetReadLock(pFile);
40339:     if( res ){
40340:       newLocktype = SHARED_LOCK;
40341:     }else{
40342:       lastErrno = osGetLastError();
40343:     }
40344:   }
40345: 
40346:   /* Acquire a RESERVED lock
40347:   */
40348:   if( locktype==RESERVED_LOCK && res ){
40349:     assert( pFile->locktype==SHARED_LOCK );
40350:     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
40351:     if( res ){
40352:       newLocktype = RESERVED_LOCK;
40353:     }else{
40354:       lastErrno = osGetLastError();
40355:     }
40356:   }
40357: 
40358:   /* Acquire a PENDING lock
40359:   */
40360:   if( locktype==EXCLUSIVE_LOCK && res ){
40361:     newLocktype = PENDING_LOCK;
40362:     gotPendingLock = 0;
40363:   }
40364: 
40365:   /* Acquire an EXCLUSIVE lock
40366:   */
40367:   if( locktype==EXCLUSIVE_LOCK && res ){
40368:     assert( pFile->locktype>=SHARED_LOCK );
40369:     res = winUnlockReadLock(pFile);
40370:     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
40371:                       SHARED_SIZE, 0);
40372:     if( res ){
40373:       newLocktype = EXCLUSIVE_LOCK;
40374:     }else{
40375:       lastErrno = osGetLastError();
40376:       winGetReadLock(pFile);
40377:     }
40378:   }
40379: 
40380:   /* If we are holding a PENDING lock that ought to be released, then
40381:   ** release it now.
40382:   */
40383:   if( gotPendingLock && locktype==SHARED_LOCK ){
40384:     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40385:   }
40386: 
40387:   /* Update the state of the lock has held in the file descriptor then
40388:   ** return the appropriate result code.
40389:   */
40390:   if( res ){
40391:     rc = SQLITE_OK;
40392:   }else{
40393:     pFile->lastErrno = lastErrno;
40394:     rc = SQLITE_BUSY;
40395:     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
40396:              pFile->h, locktype, newLocktype));
40397:   }
40398:   pFile->locktype = (u8)newLocktype;
40399:   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
40400:            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40401:   return rc;
40402: }
40403: 
40404: /*
40405: ** This routine checks if there is a RESERVED lock held on the specified
40406: ** file by this or any other process. If such a lock is held, return
40407: ** non-zero, otherwise zero.
40408: */
40409: static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
40410:   int res;
40411:   winFile *pFile = (winFile*)id;
40412: 
40413:   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
40414:   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
40415: 
40416:   assert( id!=0 );
40417:   if( pFile->locktype>=RESERVED_LOCK ){
40418:     res = 1;
40419:     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
40420:   }else{
40421:     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
40422:     if( res ){
40423:       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40424:     }
40425:     res = !res;
40426:     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
40427:   }
40428:   *pResOut = res;
40429:   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
40430:            pFile->h, pResOut, *pResOut));
40431:   return SQLITE_OK;
40432: }
40433: 
40434: /*
40435: ** Lower the locking level on file descriptor id to locktype.  locktype
40436: ** must be either NO_LOCK or SHARED_LOCK.
40437: **
40438: ** If the locking level of the file descriptor is already at or below
40439: ** the requested locking level, this routine is a no-op.
40440: **
40441: ** It is not possible for this routine to fail if the second argument
40442: ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
40443: ** might return SQLITE_IOERR;
40444: */
40445: static int winUnlock(sqlite3_file *id, int locktype){
40446:   int type;
40447:   winFile *pFile = (winFile*)id;
40448:   int rc = SQLITE_OK;
40449:   assert( pFile!=0 );
40450:   assert( locktype<=SHARED_LOCK );
40451:   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40452:            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40453:   type = pFile->locktype;
40454:   if( type>=EXCLUSIVE_LOCK ){
40455:     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40456:     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
40457:       /* This should never happen.  We should always be able to
40458:       ** reacquire the read lock */
40459:       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
40460:                        "winUnlock", pFile->zPath);
40461:     }
40462:   }
40463:   if( type>=RESERVED_LOCK ){
40464:     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40465:   }
40466:   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
40467:     winUnlockReadLock(pFile);
40468:   }
40469:   if( type>=PENDING_LOCK ){
40470:     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40471:   }
40472:   pFile->locktype = (u8)locktype;
40473:   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
40474:            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40475:   return rc;
40476: }
40477: 
40478: /******************************************************************************
40479: ****************************** No-op Locking **********************************
40480: **
40481: ** Of the various locking implementations available, this is by far the
40482: ** simplest:  locking is ignored.  No attempt is made to lock the database
40483: ** file for reading or writing.
40484: **
40485: ** This locking mode is appropriate for use on read-only databases
40486: ** (ex: databases that are burned into CD-ROM, for example.)  It can
40487: ** also be used if the application employs some external mechanism to
40488: ** prevent simultaneous access of the same database by two or more
40489: ** database connections.  But there is a serious risk of database
40490: ** corruption if this locking mode is used in situations where multiple
40491: ** database connections are accessing the same database file at the same
40492: ** time and one or more of those connections are writing.
40493: */
40494: 
40495: static int winNolockLock(sqlite3_file *id, int locktype){
40496:   UNUSED_PARAMETER(id);
40497:   UNUSED_PARAMETER(locktype);
40498:   return SQLITE_OK;
40499: }
40500: 
40501: static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
40502:   UNUSED_PARAMETER(id);
40503:   UNUSED_PARAMETER(pResOut);
40504:   return SQLITE_OK;
40505: }
40506: 
40507: static int winNolockUnlock(sqlite3_file *id, int locktype){
40508:   UNUSED_PARAMETER(id);
40509:   UNUSED_PARAMETER(locktype);
40510:   return SQLITE_OK;
40511: }
40512: 
40513: /******************* End of the no-op lock implementation *********************
40514: ******************************************************************************/
40515: 
40516: /*
40517: ** If *pArg is initially negative then this is a query.  Set *pArg to
40518: ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
40519: **
40520: ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
40521: */
40522: static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
40523:   if( *pArg<0 ){
40524:     *pArg = (pFile->ctrlFlags & mask)!=0;
40525:   }else if( (*pArg)==0 ){
40526:     pFile->ctrlFlags &= ~mask;
40527:   }else{
40528:     pFile->ctrlFlags |= mask;
40529:   }
40530: }
40531: 
40532: /* Forward references to VFS helper methods used for temporary files */
40533: static int winGetTempname(sqlite3_vfs *, char **);
40534: static int winIsDir(const void *);
40535: static BOOL winIsDriveLetterAndColon(const char *);
40536: 
40537: /*
40538: ** Control and query of the open file handle.
40539: */
40540: static int winFileControl(sqlite3_file *id, int op, void *pArg){
40541:   winFile *pFile = (winFile*)id;
40542:   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
40543:   switch( op ){
40544:     case SQLITE_FCNTL_LOCKSTATE: {
40545:       *(int*)pArg = pFile->locktype;
40546:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40547:       return SQLITE_OK;
40548:     }
40549:     case SQLITE_FCNTL_LAST_ERRNO: {
40550:       *(int*)pArg = (int)pFile->lastErrno;
40551:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40552:       return SQLITE_OK;
40553:     }
40554:     case SQLITE_FCNTL_CHUNK_SIZE: {
40555:       pFile->szChunk = *(int *)pArg;
40556:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40557:       return SQLITE_OK;
40558:     }
40559:     case SQLITE_FCNTL_SIZE_HINT: {
40560:       if( pFile->szChunk>0 ){
40561:         sqlite3_int64 oldSz;
40562:         int rc = winFileSize(id, &oldSz);
40563:         if( rc==SQLITE_OK ){
40564:           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
40565:           if( newSz>oldSz ){
40566:             SimulateIOErrorBenign(1);
40567:             rc = winTruncate(id, newSz);
40568:             SimulateIOErrorBenign(0);
40569:           }
40570:         }
40571:         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40572:         return rc;
40573:       }
40574:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40575:       return SQLITE_OK;
40576:     }
40577:     case SQLITE_FCNTL_PERSIST_WAL: {
40578:       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
40579:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40580:       return SQLITE_OK;
40581:     }
40582:     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
40583:       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
40584:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40585:       return SQLITE_OK;
40586:     }
40587:     case SQLITE_FCNTL_VFSNAME: {
40588:       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
40589:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40590:       return SQLITE_OK;
40591:     }
40592:     case SQLITE_FCNTL_WIN32_AV_RETRY: {
40593:       int *a = (int*)pArg;
40594:       if( a[0]>0 ){
40595:         winIoerrRetry = a[0];
40596:       }else{
40597:         a[0] = winIoerrRetry;
40598:       }
40599:       if( a[1]>0 ){
40600:         winIoerrRetryDelay = a[1];
40601:       }else{
40602:         a[1] = winIoerrRetryDelay;
40603:       }
40604:       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40605:       return SQLITE_OK;
40606:     }
40607: #ifdef SQLITE_TEST
40608:     case SQLITE_FCNTL_WIN32_SET_HANDLE: {
40609:       LPHANDLE phFile = (LPHANDLE)pArg;
40610:       HANDLE hOldFile = pFile->h;
40611:       pFile->h = *phFile;
40612:       *phFile = hOldFile;
40613:       OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
40614:                hOldFile, pFile->h));
40615:       return SQLITE_OK;
40616:     }
40617: #endif
40618:     case SQLITE_FCNTL_TEMPFILENAME: {
40619:       char *zTFile = 0;
40620:       int rc = winGetTempname(pFile->pVfs, &zTFile);
40621:       if( rc==SQLITE_OK ){
40622:         *(char**)pArg = zTFile;
40623:       }
40624:       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40625:       return rc;
40626:     }
40627: #if SQLITE_MAX_MMAP_SIZE>0
40628:     case SQLITE_FCNTL_MMAP_SIZE: {
40629:       i64 newLimit = *(i64*)pArg;
40630:       int rc = SQLITE_OK;
40631:       if( newLimit>sqlite3GlobalConfig.mxMmap ){
40632:         newLimit = sqlite3GlobalConfig.mxMmap;
40633:       }
40634:       *(i64*)pArg = pFile->mmapSizeMax;
40635:       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
40636:         pFile->mmapSizeMax = newLimit;
40637:         if( pFile->mmapSize>0 ){
40638:           winUnmapfile(pFile);
40639:           rc = winMapfile(pFile, -1);
40640:         }
40641:       }
40642:       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40643:       return rc;
40644:     }
40645: #endif
40646:   }
40647:   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
40648:   return SQLITE_NOTFOUND;
40649: }
40650: 
40651: /*
40652: ** Return the sector size in bytes of the underlying block device for
40653: ** the specified file. This is almost always 512 bytes, but may be
40654: ** larger for some devices.
40655: **
40656: ** SQLite code assumes this function cannot fail. It also assumes that
40657: ** if two files are created in the same file-system directory (i.e.
40658: ** a database and its journal file) that the sector size will be the
40659: ** same for both.
40660: */
40661: static int winSectorSize(sqlite3_file *id){
40662:   (void)id;
40663:   return SQLITE_DEFAULT_SECTOR_SIZE;
40664: }
40665: 
40666: /*
40667: ** Return a vector of device characteristics.
40668: */
40669: static int winDeviceCharacteristics(sqlite3_file *id){
40670:   winFile *p = (winFile*)id;
40671:   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
40672:          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
40673: }
40674: 
40675: /*
40676: ** Windows will only let you create file view mappings
40677: ** on allocation size granularity boundaries.
40678: ** During sqlite3_os_init() we do a GetSystemInfo()
40679: ** to get the granularity size.
40680: */
40681: static SYSTEM_INFO winSysInfo;
40682: 
40683: #ifndef SQLITE_OMIT_WAL
40684: 
40685: /*
40686: ** Helper functions to obtain and relinquish the global mutex. The
40687: ** global mutex is used to protect the winLockInfo objects used by
40688: ** this file, all of which may be shared by multiple threads.
40689: **
40690: ** Function winShmMutexHeld() is used to assert() that the global mutex
40691: ** is held when required. This function is only used as part of assert()
40692: ** statements. e.g.
40693: **
40694: **   winShmEnterMutex()
40695: **     assert( winShmMutexHeld() );
40696: **   winShmLeaveMutex()
40697: */
40698: static void winShmEnterMutex(void){
40699:   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40700: }
40701: static void winShmLeaveMutex(void){
40702:   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40703: }
40704: #ifndef NDEBUG
40705: static int winShmMutexHeld(void) {
40706:   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
40707: }
40708: #endif
40709: 
40710: /*
40711: ** Object used to represent a single file opened and mmapped to provide
40712: ** shared memory.  When multiple threads all reference the same
40713: ** log-summary, each thread has its own winFile object, but they all
40714: ** point to a single instance of this object.  In other words, each
40715: ** log-summary is opened only once per process.
40716: **
40717: ** winShmMutexHeld() must be true when creating or destroying
40718: ** this object or while reading or writing the following fields:
40719: **
40720: **      nRef
40721: **      pNext
40722: **
40723: ** The following fields are read-only after the object is created:
40724: **
40725: **      fid
40726: **      zFilename
40727: **
40728: ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
40729: ** winShmMutexHeld() is true when reading or writing any other field
40730: ** in this structure.
40731: **
40732: */
40733: struct winShmNode {
40734:   sqlite3_mutex *mutex;      /* Mutex to access this object */
40735:   char *zFilename;           /* Name of the file */
40736:   winFile hFile;             /* File handle from winOpen */
40737: 
40738:   int szRegion;              /* Size of shared-memory regions */
40739:   int nRegion;               /* Size of array apRegion */
40740:   struct ShmRegion {
40741:     HANDLE hMap;             /* File handle from CreateFileMapping */
40742:     void *pMap;
40743:   } *aRegion;
40744:   DWORD lastErrno;           /* The Windows errno from the last I/O error */
40745: 
40746:   int nRef;                  /* Number of winShm objects pointing to this */
40747:   winShm *pFirst;            /* All winShm objects pointing to this */
40748:   winShmNode *pNext;         /* Next in list of all winShmNode objects */
40749: #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40750:   u8 nextShmId;              /* Next available winShm.id value */
40751: #endif
40752: };
40753: 
40754: /*
40755: ** A global array of all winShmNode objects.
40756: **
40757: ** The winShmMutexHeld() must be true while reading or writing this list.
40758: */
40759: static winShmNode *winShmNodeList = 0;
40760: 
40761: /*
40762: ** Structure used internally by this VFS to record the state of an
40763: ** open shared memory connection.
40764: **
40765: ** The following fields are initialized when this object is created and
40766: ** are read-only thereafter:
40767: **
40768: **    winShm.pShmNode
40769: **    winShm.id
40770: **
40771: ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
40772: ** while accessing any read/write fields.
40773: */
40774: struct winShm {
40775:   winShmNode *pShmNode;      /* The underlying winShmNode object */
40776:   winShm *pNext;             /* Next winShm with the same winShmNode */
40777:   u8 hasMutex;               /* True if holding the winShmNode mutex */
40778:   u16 sharedMask;            /* Mask of shared locks held */
40779:   u16 exclMask;              /* Mask of exclusive locks held */
40780: #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40781:   u8 id;                     /* Id of this connection with its winShmNode */
40782: #endif
40783: };
40784: 
40785: /*
40786: ** Constants used for locking
40787: */
40788: #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
40789: #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
40790: 
40791: /*
40792: ** Apply advisory locks for all n bytes beginning at ofst.
40793: */
40794: #define WINSHM_UNLCK  1
40795: #define WINSHM_RDLCK  2
40796: #define WINSHM_WRLCK  3
40797: static int winShmSystemLock(
40798:   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
40799:   int lockType,         /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
40800:   int ofst,             /* Offset to first byte to be locked/unlocked */
40801:   int nByte             /* Number of bytes to lock or unlock */
40802: ){
40803:   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
40804: 
40805:   /* Access to the winShmNode object is serialized by the caller */
40806:   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
40807: 
40808:   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
40809:            pFile->hFile.h, lockType, ofst, nByte));
40810: 
40811:   /* Release/Acquire the system-level lock */
40812:   if( lockType==WINSHM_UNLCK ){
40813:     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
40814:   }else{
40815:     /* Initialize the locking parameters */
40816:     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
40817:     if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
40818:     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
40819:   }
40820: 
40821:   if( rc!= 0 ){
40822:     rc = SQLITE_OK;
40823:   }else{
40824:     pFile->lastErrno =  osGetLastError();
40825:     rc = SQLITE_BUSY;
40826:   }
40827: 
40828:   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
40829:            pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
40830:            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
40831: 
40832:   return rc;
40833: }
40834: 
40835: /* Forward references to VFS methods */
40836: static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
40837: static int winDelete(sqlite3_vfs *,const char*,int);
40838: 
40839: /*
40840: ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
40841: **
40842: ** This is not a VFS shared-memory method; it is a utility function called
40843: ** by VFS shared-memory methods.
40844: */
40845: static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
40846:   winShmNode **pp;
40847:   winShmNode *p;
40848:   assert( winShmMutexHeld() );
40849:   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
40850:            osGetCurrentProcessId(), deleteFlag));
40851:   pp = &winShmNodeList;
40852:   while( (p = *pp)!=0 ){
40853:     if( p->nRef==0 ){
40854:       int i;
40855:       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
40856:       for(i=0; i<p->nRegion; i++){
40857:         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
40858:         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
40859:                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40860:         UNUSED_VARIABLE_VALUE(bRc);
40861:         bRc = osCloseHandle(p->aRegion[i].hMap);
40862:         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
40863:                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40864:         UNUSED_VARIABLE_VALUE(bRc);
40865:       }
40866:       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
40867:         SimulateIOErrorBenign(1);
40868:         winClose((sqlite3_file *)&p->hFile);
40869:         SimulateIOErrorBenign(0);
40870:       }
40871:       if( deleteFlag ){
40872:         SimulateIOErrorBenign(1);
40873:         sqlite3BeginBenignMalloc();
40874:         winDelete(pVfs, p->zFilename, 0);
40875:         sqlite3EndBenignMalloc();
40876:         SimulateIOErrorBenign(0);
40877:       }
40878:       *pp = p->pNext;
40879:       sqlite3_free(p->aRegion);
40880:       sqlite3_free(p);
40881:     }else{
40882:       pp = &p->pNext;
40883:     }
40884:   }
40885: }
40886: 
40887: /*
40888: ** Open the shared-memory area associated with database file pDbFd.
40889: **
40890: ** When opening a new shared-memory file, if no other instances of that
40891: ** file are currently open, in this process or in other processes, then
40892: ** the file must be truncated to zero length or have its header cleared.
40893: */
40894: static int winOpenSharedMemory(winFile *pDbFd){
40895:   struct winShm *p;                  /* The connection to be opened */
40896:   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
40897:   int rc;                            /* Result code */
40898:   struct winShmNode *pNew;           /* Newly allocated winShmNode */
40899:   int nName;                         /* Size of zName in bytes */
40900: 
40901:   assert( pDbFd->pShm==0 );    /* Not previously opened */
40902: 
40903:   /* Allocate space for the new sqlite3_shm object.  Also speculatively
40904:   ** allocate space for a new winShmNode and filename.
40905:   */
40906:   p = sqlite3MallocZero( sizeof(*p) );
40907:   if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
40908:   nName = sqlite3Strlen30(pDbFd->zPath);
40909:   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
40910:   if( pNew==0 ){
40911:     sqlite3_free(p);
40912:     return SQLITE_IOERR_NOMEM_BKPT;
40913:   }
40914:   pNew->zFilename = (char*)&pNew[1];
40915:   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
40916:   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
40917: 
40918:   /* Look to see if there is an existing winShmNode that can be used.
40919:   ** If no matching winShmNode currently exists, create a new one.
40920:   */
40921:   winShmEnterMutex();
40922:   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
40923:     /* TBD need to come up with better match here.  Perhaps
40924:     ** use FILE_ID_BOTH_DIR_INFO Structure.
40925:     */
40926:     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
40927:   }
40928:   if( pShmNode ){
40929:     sqlite3_free(pNew);
40930:   }else{
40931:     pShmNode = pNew;
40932:     pNew = 0;
40933:     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
40934:     pShmNode->pNext = winShmNodeList;
40935:     winShmNodeList = pShmNode;
40936: 
40937:     if( sqlite3GlobalConfig.bCoreMutex ){
40938:       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
40939:       if( pShmNode->mutex==0 ){
40940:         rc = SQLITE_IOERR_NOMEM_BKPT;
40941:         goto shm_open_err;
40942:       }
40943:     }
40944: 
40945:     rc = winOpen(pDbFd->pVfs,
40946:                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
40947:                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
40948:                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
40949:                  0);
40950:     if( SQLITE_OK!=rc ){
40951:       goto shm_open_err;
40952:     }
40953: 
40954:     /* Check to see if another process is holding the dead-man switch.
40955:     ** If not, truncate the file to zero length.
40956:     */
40957:     if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
40958:       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
40959:       if( rc!=SQLITE_OK ){
40960:         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
40961:                          "winOpenShm", pDbFd->zPath);
40962:       }
40963:     }
40964:     if( rc==SQLITE_OK ){
40965:       winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
40966:       rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
40967:     }
40968:     if( rc ) goto shm_open_err;
40969:   }
40970: 
40971:   /* Make the new connection a child of the winShmNode */
40972:   p->pShmNode = pShmNode;
40973: #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40974:   p->id = pShmNode->nextShmId++;
40975: #endif
40976:   pShmNode->nRef++;
40977:   pDbFd->pShm = p;
40978:   winShmLeaveMutex();
40979: 
40980:   /* The reference count on pShmNode has already been incremented under
40981:   ** the cover of the winShmEnterMutex() mutex and the pointer from the
40982:   ** new (struct winShm) object to the pShmNode has been set. All that is
40983:   ** left to do is to link the new object into the linked list starting
40984:   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
40985:   ** mutex.
40986:   */
40987:   sqlite3_mutex_enter(pShmNode->mutex);
40988:   p->pNext = pShmNode->pFirst;
40989:   pShmNode->pFirst = p;
40990:   sqlite3_mutex_leave(pShmNode->mutex);
40991:   return SQLITE_OK;
40992: 
40993:   /* Jump here on any error */
40994: shm_open_err:
40995:   winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
40996:   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
40997:   sqlite3_free(p);
40998:   sqlite3_free(pNew);
40999:   winShmLeaveMutex();
41000:   return rc;
41001: }
41002: 
41003: /*
41004: ** Close a connection to shared-memory.  Delete the underlying
41005: ** storage if deleteFlag is true.
41006: */
41007: static int winShmUnmap(
41008:   sqlite3_file *fd,          /* Database holding shared memory */
41009:   int deleteFlag             /* Delete after closing if true */
41010: ){
41011:   winFile *pDbFd;       /* Database holding shared-memory */
41012:   winShm *p;            /* The connection to be closed */
41013:   winShmNode *pShmNode; /* The underlying shared-memory file */
41014:   winShm **pp;          /* For looping over sibling connections */
41015: 
41016:   pDbFd = (winFile*)fd;
41017:   p = pDbFd->pShm;
41018:   if( p==0 ) return SQLITE_OK;
41019:   pShmNode = p->pShmNode;
41020: 
41021:   /* Remove connection p from the set of connections associated
41022:   ** with pShmNode */
41023:   sqlite3_mutex_enter(pShmNode->mutex);
41024:   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
41025:   *pp = p->pNext;
41026: 
41027:   /* Free the connection p */
41028:   sqlite3_free(p);
41029:   pDbFd->pShm = 0;
41030:   sqlite3_mutex_leave(pShmNode->mutex);
41031: 
41032:   /* If pShmNode->nRef has reached 0, then close the underlying
41033:   ** shared-memory file, too */
41034:   winShmEnterMutex();
41035:   assert( pShmNode->nRef>0 );
41036:   pShmNode->nRef--;
41037:   if( pShmNode->nRef==0 ){
41038:     winShmPurge(pDbFd->pVfs, deleteFlag);
41039:   }
41040:   winShmLeaveMutex();
41041: 
41042:   return SQLITE_OK;
41043: }
41044: 
41045: /*
41046: ** Change the lock state for a shared-memory segment.
41047: */
41048: static int winShmLock(
41049:   sqlite3_file *fd,          /* Database file holding the shared memory */
41050:   int ofst,                  /* First lock to acquire or release */
41051:   int n,                     /* Number of locks to acquire or release */
41052:   int flags                  /* What to do with the lock */
41053: ){
41054:   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
41055:   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
41056:   winShm *pX;                           /* For looping over all siblings */
41057:   winShmNode *pShmNode = p->pShmNode;
41058:   int rc = SQLITE_OK;                   /* Result code */
41059:   u16 mask;                             /* Mask of locks to take or release */
41060: 
41061:   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
41062:   assert( n>=1 );
41063:   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
41064:        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
41065:        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
41066:        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
41067:   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
41068: 
41069:   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
41070:   assert( n>1 || mask==(1<<ofst) );
41071:   sqlite3_mutex_enter(pShmNode->mutex);
41072:   if( flags & SQLITE_SHM_UNLOCK ){
41073:     u16 allMask = 0; /* Mask of locks held by siblings */
41074: 
41075:     /* See if any siblings hold this same lock */
41076:     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41077:       if( pX==p ) continue;
41078:       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
41079:       allMask |= pX->sharedMask;
41080:     }
41081: 
41082:     /* Unlock the system-level locks */
41083:     if( (mask & allMask)==0 ){
41084:       rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
41085:     }else{
41086:       rc = SQLITE_OK;
41087:     }
41088: 
41089:     /* Undo the local locks */
41090:     if( rc==SQLITE_OK ){
41091:       p->exclMask &= ~mask;
41092:       p->sharedMask &= ~mask;
41093:     }
41094:   }else if( flags & SQLITE_SHM_SHARED ){
41095:     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
41096: 
41097:     /* Find out which shared locks are already held by sibling connections.
41098:     ** If any sibling already holds an exclusive lock, go ahead and return
41099:     ** SQLITE_BUSY.
41100:     */
41101:     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41102:       if( (pX->exclMask & mask)!=0 ){
41103:         rc = SQLITE_BUSY;
41104:         break;
41105:       }
41106:       allShared |= pX->sharedMask;
41107:     }
41108: 
41109:     /* Get shared locks at the system level, if necessary */
41110:     if( rc==SQLITE_OK ){
41111:       if( (allShared & mask)==0 ){
41112:         rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
41113:       }else{
41114:         rc = SQLITE_OK;
41115:       }
41116:     }
41117: 
41118:     /* Get the local shared locks */
41119:     if( rc==SQLITE_OK ){
41120:       p->sharedMask |= mask;
41121:     }
41122:   }else{
41123:     /* Make sure no sibling connections hold locks that will block this
41124:     ** lock.  If any do, return SQLITE_BUSY right away.
41125:     */
41126:     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41127:       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
41128:         rc = SQLITE_BUSY;
41129:         break;
41130:       }
41131:     }
41132: 
41133:     /* Get the exclusive locks at the system level.  Then if successful
41134:     ** also mark the local connection as being locked.
41135:     */
41136:     if( rc==SQLITE_OK ){
41137:       rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
41138:       if( rc==SQLITE_OK ){
41139:         assert( (p->sharedMask & mask)==0 );
41140:         p->exclMask |= mask;
41141:       }
41142:     }
41143:   }
41144:   sqlite3_mutex_leave(pShmNode->mutex);
41145:   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
41146:            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
41147:            sqlite3ErrName(rc)));
41148:   return rc;
41149: }
41150: 
41151: /*
41152: ** Implement a memory barrier or memory fence on shared memory.
41153: **
41154: ** All loads and stores begun before the barrier must complete before
41155: ** any load or store begun after the barrier.
41156: */
41157: static void winShmBarrier(
41158:   sqlite3_file *fd          /* Database holding the shared memory */
41159: ){
41160:   UNUSED_PARAMETER(fd);
41161:   sqlite3MemoryBarrier();   /* compiler-defined memory barrier */
41162:   winShmEnterMutex();       /* Also mutex, for redundancy */
41163:   winShmLeaveMutex();
41164: }
41165: 
41166: /*
41167: ** This function is called to obtain a pointer to region iRegion of the
41168: ** shared-memory associated with the database file fd. Shared-memory regions
41169: ** are numbered starting from zero. Each shared-memory region is szRegion
41170: ** bytes in size.
41171: **
41172: ** If an error occurs, an error code is returned and *pp is set to NULL.
41173: **
41174: ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
41175: ** region has not been allocated (by any client, including one running in a
41176: ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
41177: ** isWrite is non-zero and the requested shared-memory region has not yet
41178: ** been allocated, it is allocated by this function.
41179: **
41180: ** If the shared-memory region has already been allocated or is allocated by
41181: ** this call as described above, then it is mapped into this processes
41182: ** address space (if it is not already), *pp is set to point to the mapped
41183: ** memory and SQLITE_OK returned.
41184: */
41185: static int winShmMap(
41186:   sqlite3_file *fd,               /* Handle open on database file */
41187:   int iRegion,                    /* Region to retrieve */
41188:   int szRegion,                   /* Size of regions */
41189:   int isWrite,                    /* True to extend file if necessary */
41190:   void volatile **pp              /* OUT: Mapped memory */
41191: ){
41192:   winFile *pDbFd = (winFile*)fd;
41193:   winShm *pShm = pDbFd->pShm;
41194:   winShmNode *pShmNode;
41195:   int rc = SQLITE_OK;
41196: 
41197:   if( !pShm ){
41198:     rc = winOpenSharedMemory(pDbFd);
41199:     if( rc!=SQLITE_OK ) return rc;
41200:     pShm = pDbFd->pShm;
41201:   }
41202:   pShmNode = pShm->pShmNode;
41203: 
41204:   sqlite3_mutex_enter(pShmNode->mutex);
41205:   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
41206: 
41207:   if( pShmNode->nRegion<=iRegion ){
41208:     struct ShmRegion *apNew;           /* New aRegion[] array */
41209:     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
41210:     sqlite3_int64 sz;                  /* Current size of wal-index file */
41211: 
41212:     pShmNode->szRegion = szRegion;
41213: 
41214:     /* The requested region is not mapped into this processes address space.
41215:     ** Check to see if it has been allocated (i.e. if the wal-index file is
41216:     ** large enough to contain the requested region).
41217:     */
41218:     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
41219:     if( rc!=SQLITE_OK ){
41220:       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41221:                        "winShmMap1", pDbFd->zPath);
41222:       goto shmpage_out;
41223:     }
41224: 
41225:     if( sz<nByte ){
41226:       /* The requested memory region does not exist. If isWrite is set to
41227:       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
41228:       **
41229:       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
41230:       ** the requested memory region.
41231:       */
41232:       if( !isWrite ) goto shmpage_out;
41233:       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
41234:       if( rc!=SQLITE_OK ){
41235:         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
41236:                          "winShmMap2", pDbFd->zPath);
41237:         goto shmpage_out;
41238:       }
41239:     }
41240: 
41241:     /* Map the requested memory region into this processes address space. */
41242:     apNew = (struct ShmRegion *)sqlite3_realloc64(
41243:         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
41244:     );
41245:     if( !apNew ){
41246:       rc = SQLITE_IOERR_NOMEM_BKPT;
41247:       goto shmpage_out;
41248:     }
41249:     pShmNode->aRegion = apNew;
41250: 
41251:     while( pShmNode->nRegion<=iRegion ){
41252:       HANDLE hMap = NULL;         /* file-mapping handle */
41253:       void *pMap = 0;             /* Mapped memory region */
41254: 
41255: #if SQLITE_OS_WINRT
41256:       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
41257:           NULL, PAGE_READWRITE, nByte, NULL
41258:       );
41259: #elif defined(SQLITE_WIN32_HAS_WIDE)
41260:       hMap = osCreateFileMappingW(pShmNode->hFile.h,
41261:           NULL, PAGE_READWRITE, 0, nByte, NULL
41262:       );
41263: #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41264:       hMap = osCreateFileMappingA(pShmNode->hFile.h,
41265:           NULL, PAGE_READWRITE, 0, nByte, NULL
41266:       );
41267: #endif
41268:       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
41269:                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
41270:                hMap ? "ok" : "failed"));
41271:       if( hMap ){
41272:         int iOffset = pShmNode->nRegion*szRegion;
41273:         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41274: #if SQLITE_OS_WINRT
41275:         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41276:             iOffset - iOffsetShift, szRegion + iOffsetShift
41277:         );
41278: #else
41279:         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
41280:             0, iOffset - iOffsetShift, szRegion + iOffsetShift
41281:         );
41282: #endif
41283:         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
41284:                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
41285:                  szRegion, pMap ? "ok" : "failed"));
41286:       }
41287:       if( !pMap ){
41288:         pShmNode->lastErrno = osGetLastError();
41289:         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
41290:                          "winShmMap3", pDbFd->zPath);
41291:         if( hMap ) osCloseHandle(hMap);
41292:         goto shmpage_out;
41293:       }
41294: 
41295:       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
41296:       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
41297:       pShmNode->nRegion++;
41298:     }
41299:   }
41300: 
41301: shmpage_out:
41302:   if( pShmNode->nRegion>iRegion ){
41303:     int iOffset = iRegion*szRegion;
41304:     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
41305:     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
41306:     *pp = (void *)&p[iOffsetShift];
41307:   }else{
41308:     *pp = 0;
41309:   }
41310:   sqlite3_mutex_leave(pShmNode->mutex);
41311:   return rc;
41312: }
41313: 
41314: #else
41315: # define winShmMap     0
41316: # define winShmLock    0
41317: # define winShmBarrier 0
41318: # define winShmUnmap   0
41319: #endif /* #ifndef SQLITE_OMIT_WAL */
41320: 
41321: /*
41322: ** Cleans up the mapped region of the specified file, if any.
41323: */
41324: #if SQLITE_MAX_MMAP_SIZE>0
41325: static int winUnmapfile(winFile *pFile){
41326:   assert( pFile!=0 );
41327:   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
41328:            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
41329:            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
41330:            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
41331:   if( pFile->pMapRegion ){
41332:     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
41333:       pFile->lastErrno = osGetLastError();
41334:       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
41335:                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
41336:                pFile->pMapRegion));
41337:       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41338:                          "winUnmapfile1", pFile->zPath);
41339:     }
41340:     pFile->pMapRegion = 0;
41341:     pFile->mmapSize = 0;
41342:     pFile->mmapSizeActual = 0;
41343:   }
41344:   if( pFile->hMap!=NULL ){
41345:     if( !osCloseHandle(pFile->hMap) ){
41346:       pFile->lastErrno = osGetLastError();
41347:       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
41348:                osGetCurrentProcessId(), pFile, pFile->hMap));
41349:       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41350:                          "winUnmapfile2", pFile->zPath);
41351:     }
41352:     pFile->hMap = NULL;
41353:   }
41354:   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41355:            osGetCurrentProcessId(), pFile));
41356:   return SQLITE_OK;
41357: }
41358: 
41359: /*
41360: ** Memory map or remap the file opened by file-descriptor pFd (if the file
41361: ** is already mapped, the existing mapping is replaced by the new). Or, if
41362: ** there already exists a mapping for this file, and there are still
41363: ** outstanding xFetch() references to it, this function is a no-op.
41364: **
41365: ** If parameter nByte is non-negative, then it is the requested size of
41366: ** the mapping to create. Otherwise, if nByte is less than zero, then the
41367: ** requested size is the size of the file on disk. The actual size of the
41368: ** created mapping is either the requested size or the value configured
41369: ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
41370: **
41371: ** SQLITE_OK is returned if no error occurs (even if the mapping is not
41372: ** recreated as a result of outstanding references) or an SQLite error
41373: ** code otherwise.
41374: */
41375: static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
41376:   sqlite3_int64 nMap = nByte;
41377:   int rc;
41378: 
41379:   assert( nMap>=0 || pFd->nFetchOut==0 );
41380:   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
41381:            osGetCurrentProcessId(), pFd, nByte));
41382: 
41383:   if( pFd->nFetchOut>0 ) return SQLITE_OK;
41384: 
41385:   if( nMap<0 ){
41386:     rc = winFileSize((sqlite3_file*)pFd, &nMap);
41387:     if( rc ){
41388:       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
41389:                osGetCurrentProcessId(), pFd));
41390:       return SQLITE_IOERR_FSTAT;
41391:     }
41392:   }
41393:   if( nMap>pFd->mmapSizeMax ){
41394:     nMap = pFd->mmapSizeMax;
41395:   }
41396:   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
41397: 
41398:   if( nMap==0 && pFd->mmapSize>0 ){
41399:     winUnmapfile(pFd);
41400:   }
41401:   if( nMap!=pFd->mmapSize ){
41402:     void *pNew = 0;
41403:     DWORD protect = PAGE_READONLY;
41404:     DWORD flags = FILE_MAP_READ;
41405: 
41406:     winUnmapfile(pFd);
41407: #ifdef SQLITE_MMAP_READWRITE
41408:     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
41409:       protect = PAGE_READWRITE;
41410:       flags |= FILE_MAP_WRITE;
41411:     }
41412: #endif
41413: #if SQLITE_OS_WINRT
41414:     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
41415: #elif defined(SQLITE_WIN32_HAS_WIDE)
41416:     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
41417:                                 (DWORD)((nMap>>32) & 0xffffffff),
41418:                                 (DWORD)(nMap & 0xffffffff), NULL);
41419: #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41420:     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
41421:                                 (DWORD)((nMap>>32) & 0xffffffff),
41422:                                 (DWORD)(nMap & 0xffffffff), NULL);
41423: #endif
41424:     if( pFd->hMap==NULL ){
41425:       pFd->lastErrno = osGetLastError();
41426:       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41427:                        "winMapfile1", pFd->zPath);
41428:       /* Log the error, but continue normal operation using xRead/xWrite */
41429:       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
41430:                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41431:       return SQLITE_OK;
41432:     }
41433:     assert( (nMap % winSysInfo.dwPageSize)==0 );
41434:     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
41435: #if SQLITE_OS_WINRT
41436:     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
41437: #else
41438:     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
41439: #endif
41440:     if( pNew==NULL ){
41441:       osCloseHandle(pFd->hMap);
41442:       pFd->hMap = NULL;
41443:       pFd->lastErrno = osGetLastError();
41444:       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41445:                        "winMapfile2", pFd->zPath);
41446:       /* Log the error, but continue normal operation using xRead/xWrite */
41447:       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
41448:                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41449:       return SQLITE_OK;
41450:     }
41451:     pFd->pMapRegion = pNew;
41452:     pFd->mmapSize = nMap;
41453:     pFd->mmapSizeActual = nMap;
41454:   }
41455: 
41456:   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41457:            osGetCurrentProcessId(), pFd));
41458:   return SQLITE_OK;
41459: }
41460: #endif /* SQLITE_MAX_MMAP_SIZE>0 */
41461: 
41462: /*
41463: ** If possible, return a pointer to a mapping of file fd starting at offset
41464: ** iOff. The mapping must be valid for at least nAmt bytes.
41465: **
41466: ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
41467: ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
41468: ** Finally, if an error does occur, return an SQLite error code. The final
41469: ** value of *pp is undefined in this case.
41470: **
41471: ** If this function does return a pointer, the caller must eventually
41472: ** release the reference by calling winUnfetch().
41473: */
41474: static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
41475: #if SQLITE_MAX_MMAP_SIZE>0
41476:   winFile *pFd = (winFile*)fd;   /* The underlying database file */
41477: #endif
41478:   *pp = 0;
41479: 
41480:   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
41481:            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
41482: 
41483: #if SQLITE_MAX_MMAP_SIZE>0
41484:   if( pFd->mmapSizeMax>0 ){
41485:     if( pFd->pMapRegion==0 ){
41486:       int rc = winMapfile(pFd, -1);
41487:       if( rc!=SQLITE_OK ){
41488:         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
41489:                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41490:         return rc;
41491:       }
41492:     }
41493:     if( pFd->mmapSize >= iOff+nAmt ){
41494:       *pp = &((u8 *)pFd->pMapRegion)[iOff];
41495:       pFd->nFetchOut++;
41496:     }
41497:   }
41498: #endif
41499: 
41500:   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
41501:            osGetCurrentProcessId(), fd, pp, *pp));
41502:   return SQLITE_OK;
41503: }
41504: 
41505: /*
41506: ** If the third argument is non-NULL, then this function releases a
41507: ** reference obtained by an earlier call to winFetch(). The second
41508: ** argument passed to this function must be the same as the corresponding
41509: ** argument that was passed to the winFetch() invocation.
41510: **
41511: ** Or, if the third argument is NULL, then this function is being called
41512: ** to inform the VFS layer that, according to POSIX, any existing mapping
41513: ** may now be invalid and should be unmapped.
41514: */
41515: static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
41516: #if SQLITE_MAX_MMAP_SIZE>0
41517:   winFile *pFd = (winFile*)fd;   /* The underlying database file */
41518: 
41519:   /* If p==0 (unmap the entire file) then there must be no outstanding
41520:   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
41521:   ** then there must be at least one outstanding.  */
41522:   assert( (p==0)==(pFd->nFetchOut==0) );
41523: 
41524:   /* If p!=0, it must match the iOff value. */
41525:   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
41526: 
41527:   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
41528:            osGetCurrentProcessId(), pFd, iOff, p));
41529: 
41530:   if( p ){
41531:     pFd->nFetchOut--;
41532:   }else{
41533:     /* FIXME:  If Windows truly always prevents truncating or deleting a
41534:     ** file while a mapping is held, then the following winUnmapfile() call
41535:     ** is unnecessary can be omitted - potentially improving
41536:     ** performance.  */
41537:     winUnmapfile(pFd);
41538:   }
41539: 
41540:   assert( pFd->nFetchOut>=0 );
41541: #endif
41542: 
41543:   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41544:            osGetCurrentProcessId(), fd));
41545:   return SQLITE_OK;
41546: }
41547: 
41548: /*
41549: ** Here ends the implementation of all sqlite3_file methods.
41550: **
41551: ********************** End sqlite3_file Methods *******************************
41552: ******************************************************************************/
41553: 
41554: /*
41555: ** This vector defines all the methods that can operate on an
41556: ** sqlite3_file for win32.
41557: */
41558: static const sqlite3_io_methods winIoMethod = {
41559:   3,                              /* iVersion */
41560:   winClose,                       /* xClose */
41561:   winRead,                        /* xRead */
41562:   winWrite,                       /* xWrite */
41563:   winTruncate,                    /* xTruncate */
41564:   winSync,                        /* xSync */
41565:   winFileSize,                    /* xFileSize */
41566:   winLock,                        /* xLock */
41567:   winUnlock,                      /* xUnlock */
41568:   winCheckReservedLock,           /* xCheckReservedLock */
41569:   winFileControl,                 /* xFileControl */
41570:   winSectorSize,                  /* xSectorSize */
41571:   winDeviceCharacteristics,       /* xDeviceCharacteristics */
41572:   winShmMap,                      /* xShmMap */
41573:   winShmLock,                     /* xShmLock */
41574:   winShmBarrier,                  /* xShmBarrier */
41575:   winShmUnmap,                    /* xShmUnmap */
41576:   winFetch,                       /* xFetch */
41577:   winUnfetch                      /* xUnfetch */
41578: };
41579: 
41580: /*
41581: ** This vector defines all the methods that can operate on an
41582: ** sqlite3_file for win32 without performing any locking.
41583: */
41584: static const sqlite3_io_methods winIoNolockMethod = {
41585:   3,                              /* iVersion */
41586:   winClose,                       /* xClose */
41587:   winRead,                        /* xRead */
41588:   winWrite,                       /* xWrite */
41589:   winTruncate,                    /* xTruncate */
41590:   winSync,                        /* xSync */
41591:   winFileSize,                    /* xFileSize */
41592:   winNolockLock,                  /* xLock */
41593:   winNolockUnlock,                /* xUnlock */
41594:   winNolockCheckReservedLock,     /* xCheckReservedLock */
41595:   winFileControl,                 /* xFileControl */
41596:   winSectorSize,                  /* xSectorSize */
41597:   winDeviceCharacteristics,       /* xDeviceCharacteristics */
41598:   winShmMap,                      /* xShmMap */
41599:   winShmLock,                     /* xShmLock */
41600:   winShmBarrier,                  /* xShmBarrier */
41601:   winShmUnmap,                    /* xShmUnmap */
41602:   winFetch,                       /* xFetch */
41603:   winUnfetch                      /* xUnfetch */
41604: };
41605: 
41606: static winVfsAppData winAppData = {
41607:   &winIoMethod,       /* pMethod */
41608:   0,                  /* pAppData */
41609:   0                   /* bNoLock */
41610: };
41611: 
41612: static winVfsAppData winNolockAppData = {
41613:   &winIoNolockMethod, /* pMethod */
41614:   0,                  /* pAppData */
41615:   1                   /* bNoLock */
41616: };
41617: 
41618: /****************************************************************************
41619: **************************** sqlite3_vfs methods ****************************
41620: **
41621: ** This division contains the implementation of methods on the
41622: ** sqlite3_vfs object.
41623: */
41624: 
41625: #if defined(__CYGWIN__)
41626: /*
41627: ** Convert a filename from whatever the underlying operating system
41628: ** supports for filenames into UTF-8.  Space to hold the result is
41629: ** obtained from malloc and must be freed by the calling function.
41630: */
41631: static char *winConvertToUtf8Filename(const void *zFilename){
41632:   char *zConverted = 0;
41633:   if( osIsNT() ){
41634:     zConverted = winUnicodeToUtf8(zFilename);
41635:   }
41636: #ifdef SQLITE_WIN32_HAS_ANSI
41637:   else{
41638:     zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
41639:   }
41640: #endif
41641:   /* caller will handle out of memory */
41642:   return zConverted;
41643: }
41644: #endif
41645: 
41646: /*
41647: ** Convert a UTF-8 filename into whatever form the underlying
41648: ** operating system wants filenames in.  Space to hold the result
41649: ** is obtained from malloc and must be freed by the calling
41650: ** function.
41651: */
41652: static void *winConvertFromUtf8Filename(const char *zFilename){
41653:   void *zConverted = 0;
41654:   if( osIsNT() ){
41655:     zConverted = winUtf8ToUnicode(zFilename);
41656:   }
41657: #ifdef SQLITE_WIN32_HAS_ANSI
41658:   else{
41659:     zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
41660:   }
41661: #endif
41662:   /* caller will handle out of memory */
41663:   return zConverted;
41664: }
41665: 
41666: /*
41667: ** This function returns non-zero if the specified UTF-8 string buffer
41668: ** ends with a directory separator character or one was successfully
41669: ** added to it.
41670: */
41671: static int winMakeEndInDirSep(int nBuf, char *zBuf){
41672:   if( zBuf ){
41673:     int nLen = sqlite3Strlen30(zBuf);
41674:     if( nLen>0 ){
41675:       if( winIsDirSep(zBuf[nLen-1]) ){
41676:         return 1;
41677:       }else if( nLen+1<nBuf ){
41678:         zBuf[nLen] = winGetDirSep();
41679:         zBuf[nLen+1] = '\0';
41680:         return 1;
41681:       }
41682:     }
41683:   }
41684:   return 0;
41685: }
41686: 
41687: /*
41688: ** Create a temporary file name and store the resulting pointer into pzBuf.
41689: ** The pointer returned in pzBuf must be freed via sqlite3_free().
41690: */
41691: static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
41692:   static char zChars[] =
41693:     "abcdefghijklmnopqrstuvwxyz"
41694:     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
41695:     "0123456789";
41696:   size_t i, j;
41697:   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
41698:   int nMax, nBuf, nDir, nLen;
41699:   char *zBuf;
41700: 
41701:   /* It's odd to simulate an io-error here, but really this is just
41702:   ** using the io-error infrastructure to test that SQLite handles this
41703:   ** function failing.
41704:   */
41705:   SimulateIOError( return SQLITE_IOERR );
41706: 
41707:   /* Allocate a temporary buffer to store the fully qualified file
41708:   ** name for the temporary file.  If this fails, we cannot continue.
41709:   */
41710:   nMax = pVfs->mxPathname; nBuf = nMax + 2;
41711:   zBuf = sqlite3MallocZero( nBuf );
41712:   if( !zBuf ){
41713:     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41714:     return SQLITE_IOERR_NOMEM_BKPT;
41715:   }
41716: 
41717:   /* Figure out the effective temporary directory.  First, check if one
41718:   ** has been explicitly set by the application; otherwise, use the one
41719:   ** configured by the operating system.
41720:   */
41721:   nDir = nMax - (nPre + 15);
41722:   assert( nDir>0 );
41723:   if( sqlite3_temp_directory ){
41724:     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
41725:     if( nDirLen>0 ){
41726:       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
41727:         nDirLen++;
41728:       }
41729:       if( nDirLen>nDir ){
41730:         sqlite3_free(zBuf);
41731:         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41732:         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
41733:       }
41734:       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
41735:     }
41736:   }
41737: #if defined(__CYGWIN__)
41738:   else{
41739:     static const char *azDirs[] = {
41740:        0, /* getenv("SQLITE_TMPDIR") */
41741:        0, /* getenv("TMPDIR") */
41742:        0, /* getenv("TMP") */
41743:        0, /* getenv("TEMP") */
41744:        0, /* getenv("USERPROFILE") */
41745:        "/var/tmp",
41746:        "/usr/tmp",
41747:        "/tmp",
41748:        ".",
41749:        0        /* List terminator */
41750:     };
41751:     unsigned int i;
41752:     const char *zDir = 0;
41753: 
41754:     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
41755:     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
41756:     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
41757:     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
41758:     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
41759:     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
41760:       void *zConverted;
41761:       if( zDir==0 ) continue;
41762:       /* If the path starts with a drive letter followed by the colon
41763:       ** character, assume it is already a native Win32 path; otherwise,
41764:       ** it must be converted to a native Win32 path via the Cygwin API
41765:       ** prior to using it.
41766:       */
41767:       if( winIsDriveLetterAndColon(zDir) ){
41768:         zConverted = winConvertFromUtf8Filename(zDir);
41769:         if( !zConverted ){
41770:           sqlite3_free(zBuf);
41771:           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41772:           return SQLITE_IOERR_NOMEM_BKPT;
41773:         }
41774:         if( winIsDir(zConverted) ){
41775:           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
41776:           sqlite3_free(zConverted);
41777:           break;
41778:         }
41779:         sqlite3_free(zConverted);
41780:       }else{
41781:         zConverted = sqlite3MallocZero( nMax+1 );
41782:         if( !zConverted ){
41783:           sqlite3_free(zBuf);
41784:           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41785:           return SQLITE_IOERR_NOMEM_BKPT;
41786:         }
41787:         if( cygwin_conv_path(
41788:                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
41789:                 zConverted, nMax+1)<0 ){
41790:           sqlite3_free(zConverted);
41791:           sqlite3_free(zBuf);
41792:           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
41793:           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
41794:                              "winGetTempname2", zDir);
41795:         }
41796:         if( winIsDir(zConverted) ){
41797:           /* At this point, we know the candidate directory exists and should
41798:           ** be used.  However, we may need to convert the string containing
41799:           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
41800:           */
41801:           char *zUtf8 = winConvertToUtf8Filename(zConverted);
41802:           if( !zUtf8 ){
41803:             sqlite3_free(zConverted);
41804:             sqlite3_free(zBuf);
41805:             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41806:             return SQLITE_IOERR_NOMEM_BKPT;
41807:           }
41808:           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41809:           sqlite3_free(zUtf8);
41810:           sqlite3_free(zConverted);
41811:           break;
41812:         }
41813:         sqlite3_free(zConverted);
41814:       }
41815:     }
41816:   }
41817: #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
41818:   else if( osIsNT() ){
41819:     char *zMulti;
41820:     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
41821:     if( !zWidePath ){
41822:       sqlite3_free(zBuf);
41823:       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41824:       return SQLITE_IOERR_NOMEM_BKPT;
41825:     }
41826:     if( osGetTempPathW(nMax, zWidePath)==0 ){
41827:       sqlite3_free(zWidePath);
41828:       sqlite3_free(zBuf);
41829:       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41830:       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41831:                          "winGetTempname2", 0);
41832:     }
41833:     zMulti = winUnicodeToUtf8(zWidePath);
41834:     if( zMulti ){
41835:       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
41836:       sqlite3_free(zMulti);
41837:       sqlite3_free(zWidePath);
41838:     }else{
41839:       sqlite3_free(zWidePath);
41840:       sqlite3_free(zBuf);
41841:       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41842:       return SQLITE_IOERR_NOMEM_BKPT;
41843:     }
41844:   }
41845: #ifdef SQLITE_WIN32_HAS_ANSI
41846:   else{
41847:     char *zUtf8;
41848:     char *zMbcsPath = sqlite3MallocZero( nMax );
41849:     if( !zMbcsPath ){
41850:       sqlite3_free(zBuf);
41851:       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41852:       return SQLITE_IOERR_NOMEM_BKPT;
41853:     }
41854:     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
41855:       sqlite3_free(zBuf);
41856:       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41857:       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41858:                          "winGetTempname3", 0);
41859:     }
41860:     zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
41861:     if( zUtf8 ){
41862:       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41863:       sqlite3_free(zUtf8);
41864:     }else{
41865:       sqlite3_free(zBuf);
41866:       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41867:       return SQLITE_IOERR_NOMEM_BKPT;
41868:     }
41869:   }
41870: #endif /* SQLITE_WIN32_HAS_ANSI */
41871: #endif /* !SQLITE_OS_WINRT */
41872: 
41873:   /*
41874:   ** Check to make sure the temporary directory ends with an appropriate
41875:   ** separator.  If it does not and there is not enough space left to add
41876:   ** one, fail.
41877:   */
41878:   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
41879:     sqlite3_free(zBuf);
41880:     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41881:     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
41882:   }
41883: 
41884:   /*
41885:   ** Check that the output buffer is large enough for the temporary file
41886:   ** name in the following format:
41887:   **
41888:   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
41889:   **
41890:   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
41891:   ** account for the space used by the 15 character random suffix and the
41892:   ** two trailing NUL characters.  The final directory separator character
41893:   ** has already added if it was not already present.
41894:   */
41895:   nLen = sqlite3Strlen30(zBuf);
41896:   if( (nLen + nPre + 17) > nBuf ){
41897:     sqlite3_free(zBuf);
41898:     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41899:     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
41900:   }
41901: 
41902:   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
41903: 
41904:   j = sqlite3Strlen30(zBuf);
41905:   sqlite3_randomness(15, &zBuf[j]);
41906:   for(i=0; i<15; i++, j++){
41907:     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
41908:   }
41909:   zBuf[j] = 0;
41910:   zBuf[j+1] = 0;
41911:   *pzBuf = zBuf;
41912: 
41913:   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
41914:   return SQLITE_OK;
41915: }
41916: 
41917: /*
41918: ** Return TRUE if the named file is really a directory.  Return false if
41919: ** it is something other than a directory, or if there is any kind of memory
41920: ** allocation failure.
41921: */
41922: static int winIsDir(const void *zConverted){
41923:   DWORD attr;
41924:   int rc = 0;
41925:   DWORD lastErrno;
41926: 
41927:   if( osIsNT() ){
41928:     int cnt = 0;
41929:     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
41930:     memset(&sAttrData, 0, sizeof(sAttrData));
41931:     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
41932:                              GetFileExInfoStandard,
41933:                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
41934:     if( !rc ){
41935:       return 0; /* Invalid name? */
41936:     }
41937:     attr = sAttrData.dwFileAttributes;
41938: #if SQLITE_OS_WINCE==0
41939:   }else{
41940:     attr = osGetFileAttributesA((char*)zConverted);
41941: #endif
41942:   }
41943:   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
41944: }
41945: 
41946: /*
41947: ** Open a file.
41948: */
41949: static int winOpen(
41950:   sqlite3_vfs *pVfs,        /* Used to get maximum path length and AppData */
41951:   const char *zName,        /* Name of the file (UTF-8) */
41952:   sqlite3_file *id,         /* Write the SQLite file handle here */
41953:   int flags,                /* Open mode flags */
41954:   int *pOutFlags            /* Status return flags */
41955: ){
41956:   HANDLE h;
41957:   DWORD lastErrno = 0;
41958:   DWORD dwDesiredAccess;
41959:   DWORD dwShareMode;
41960:   DWORD dwCreationDisposition;
41961:   DWORD dwFlagsAndAttributes = 0;
41962: #if SQLITE_OS_WINCE
41963:   int isTemp = 0;
41964: #endif
41965:   winVfsAppData *pAppData;
41966:   winFile *pFile = (winFile*)id;
41967:   void *zConverted;              /* Filename in OS encoding */
41968:   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
41969:   int cnt = 0;
41970: 
41971:   /* If argument zPath is a NULL pointer, this function is required to open
41972:   ** a temporary file. Use this buffer to store the file name in.
41973:   */
41974:   char *zTmpname = 0; /* For temporary filename, if necessary. */
41975: 
41976:   int rc = SQLITE_OK;            /* Function Return Code */
41977: #if !defined(NDEBUG) || SQLITE_OS_WINCE
41978:   int eType = flags&0xFFFFFF00;  /* Type of file to open */
41979: #endif
41980: 
41981:   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
41982:   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
41983:   int isCreate     = (flags & SQLITE_OPEN_CREATE);
41984:   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
41985:   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
41986: 
41987: #ifndef NDEBUG
41988:   int isOpenJournal = (isCreate && (
41989:         eType==SQLITE_OPEN_MASTER_JOURNAL
41990:      || eType==SQLITE_OPEN_MAIN_JOURNAL
41991:      || eType==SQLITE_OPEN_WAL
41992:   ));
41993: #endif
41994: 
41995:   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
41996:            zUtf8Name, id, flags, pOutFlags));
41997: 
41998:   /* Check the following statements are true:
41999:   **
42000:   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
42001:   **   (b) if CREATE is set, then READWRITE must also be set, and
42002:   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
42003:   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
42004:   */
42005:   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
42006:   assert(isCreate==0 || isReadWrite);
42007:   assert(isExclusive==0 || isCreate);
42008:   assert(isDelete==0 || isCreate);
42009: 
42010:   /* The main DB, main journal, WAL file and master journal are never
42011:   ** automatically deleted. Nor are they ever temporary files.  */
42012:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
42013:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
42014:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
42015:   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
42016: 
42017:   /* Assert that the upper layer has set one of the "file-type" flags. */
42018:   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
42019:        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
42020:        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
42021:        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
42022:   );
42023: 
42024:   assert( pFile!=0 );
42025:   memset(pFile, 0, sizeof(winFile));
42026:   pFile->h = INVALID_HANDLE_VALUE;
42027: 
42028: #if SQLITE_OS_WINRT
42029:   if( !zUtf8Name && !sqlite3_temp_directory ){
42030:     sqlite3_log(SQLITE_ERROR,
42031:         "sqlite3_temp_directory variable should be set for WinRT");
42032:   }
42033: #endif
42034: 
42035:   /* If the second argument to this function is NULL, generate a
42036:   ** temporary file name to use
42037:   */
42038:   if( !zUtf8Name ){
42039:     assert( isDelete && !isOpenJournal );
42040:     rc = winGetTempname(pVfs, &zTmpname);
42041:     if( rc!=SQLITE_OK ){
42042:       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
42043:       return rc;
42044:     }
42045:     zUtf8Name = zTmpname;
42046:   }
42047: 
42048:   /* Database filenames are double-zero terminated if they are not
42049:   ** URIs with parameters.  Hence, they can always be passed into
42050:   ** sqlite3_uri_parameter().
42051:   */
42052:   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
42053:        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
42054: 
42055:   /* Convert the filename to the system encoding. */
42056:   zConverted = winConvertFromUtf8Filename(zUtf8Name);
42057:   if( zConverted==0 ){
42058:     sqlite3_free(zTmpname);
42059:     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
42060:     return SQLITE_IOERR_NOMEM_BKPT;
42061:   }
42062: 
42063:   if( winIsDir(zConverted) ){
42064:     sqlite3_free(zConverted);
42065:     sqlite3_free(zTmpname);
42066:     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
42067:     return SQLITE_CANTOPEN_ISDIR;
42068:   }
42069: 
42070:   if( isReadWrite ){
42071:     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
42072:   }else{
42073:     dwDesiredAccess = GENERIC_READ;
42074:   }
42075: 
42076:   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
42077:   ** created. SQLite doesn't use it to indicate "exclusive access"
42078:   ** as it is usually understood.
42079:   */
42080:   if( isExclusive ){
42081:     /* Creates a new file, only if it does not already exist. */
42082:     /* If the file exists, it fails. */
42083:     dwCreationDisposition = CREATE_NEW;
42084:   }else if( isCreate ){
42085:     /* Open existing file, or create if it doesn't exist */
42086:     dwCreationDisposition = OPEN_ALWAYS;
42087:   }else{
42088:     /* Opens a file, only if it exists. */
42089:     dwCreationDisposition = OPEN_EXISTING;
42090:   }
42091: 
42092:   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
42093: 
42094:   if( isDelete ){
42095: #if SQLITE_OS_WINCE
42096:     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
42097:     isTemp = 1;
42098: #else
42099:     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
42100:                                | FILE_ATTRIBUTE_HIDDEN
42101:                                | FILE_FLAG_DELETE_ON_CLOSE;
42102: #endif
42103:   }else{
42104:     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
42105:   }
42106:   /* Reports from the internet are that performance is always
42107:   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
42108: #if SQLITE_OS_WINCE
42109:   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
42110: #endif
42111: 
42112:   if( osIsNT() ){
42113: #if SQLITE_OS_WINRT
42114:     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
42115:     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
42116:     extendedParameters.dwFileAttributes =
42117:             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
42118:     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
42119:     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
42120:     extendedParameters.lpSecurityAttributes = NULL;
42121:     extendedParameters.hTemplateFile = NULL;
42122:     while( (h = osCreateFile2((LPCWSTR)zConverted,
42123:                               dwDesiredAccess,
42124:                               dwShareMode,
42125:                               dwCreationDisposition,
42126:                               &extendedParameters))==INVALID_HANDLE_VALUE &&
42127:                               winRetryIoerr(&cnt, &lastErrno) ){
42128:                /* Noop */
42129:     }
42130: #else
42131:     while( (h = osCreateFileW((LPCWSTR)zConverted,
42132:                               dwDesiredAccess,
42133:                               dwShareMode, NULL,
42134:                               dwCreationDisposition,
42135:                               dwFlagsAndAttributes,
42136:                               NULL))==INVALID_HANDLE_VALUE &&
42137:                               winRetryIoerr(&cnt, &lastErrno) ){
42138:                /* Noop */
42139:     }
42140: #endif
42141:   }
42142: #ifdef SQLITE_WIN32_HAS_ANSI
42143:   else{
42144:     while( (h = osCreateFileA((LPCSTR)zConverted,
42145:                               dwDesiredAccess,
42146:                               dwShareMode, NULL,
42147:                               dwCreationDisposition,
42148:                               dwFlagsAndAttributes,
42149:                               NULL))==INVALID_HANDLE_VALUE &&
42150:                               winRetryIoerr(&cnt, &lastErrno) ){
42151:                /* Noop */
42152:     }
42153:   }
42154: #endif
42155:   winLogIoerr(cnt, __LINE__);
42156: 
42157:   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
42158:            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42159: 
42160:   if( h==INVALID_HANDLE_VALUE ){
42161:     pFile->lastErrno = lastErrno;
42162:     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
42163:     sqlite3_free(zConverted);
42164:     sqlite3_free(zTmpname);
42165:     if( isReadWrite && !isExclusive ){
42166:       return winOpen(pVfs, zName, id,
42167:          ((flags|SQLITE_OPEN_READONLY) &
42168:                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
42169:          pOutFlags);
42170:     }else{
42171:       return SQLITE_CANTOPEN_BKPT;
42172:     }
42173:   }
42174: 
42175:   if( pOutFlags ){
42176:     if( isReadWrite ){
42177:       *pOutFlags = SQLITE_OPEN_READWRITE;
42178:     }else{
42179:       *pOutFlags = SQLITE_OPEN_READONLY;
42180:     }
42181:   }
42182: 
42183:   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
42184:            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
42185:            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
42186: 
42187:   pAppData = (winVfsAppData*)pVfs->pAppData;
42188: 
42189: #if SQLITE_OS_WINCE
42190:   {
42191:     if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
42192:          && ((pAppData==NULL) || !pAppData->bNoLock)
42193:          && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
42194:     ){
42195:       osCloseHandle(h);
42196:       sqlite3_free(zConverted);
42197:       sqlite3_free(zTmpname);
42198:       OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
42199:       return rc;
42200:     }
42201:   }
42202:   if( isTemp ){
42203:     pFile->zDeleteOnClose = zConverted;
42204:   }else
42205: #endif
42206:   {
42207:     sqlite3_free(zConverted);
42208:   }
42209: 
42210:   sqlite3_free(zTmpname);
42211:   pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
42212:   pFile->pVfs = pVfs;
42213:   pFile->h = h;
42214:   if( isReadonly ){
42215:     pFile->ctrlFlags |= WINFILE_RDONLY;
42216:   }
42217:   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
42218:     pFile->ctrlFlags |= WINFILE_PSOW;
42219:   }
42220:   pFile->lastErrno = NO_ERROR;
42221:   pFile->zPath = zName;
42222: #if SQLITE_MAX_MMAP_SIZE>0
42223:   pFile->hMap = NULL;
42224:   pFile->pMapRegion = 0;
42225:   pFile->mmapSize = 0;
42226:   pFile->mmapSizeActual = 0;
42227:   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
42228: #endif
42229: 
42230:   OpenCounter(+1);
42231:   return rc;
42232: }
42233: 
42234: /*
42235: ** Delete the named file.
42236: **
42237: ** Note that Windows does not allow a file to be deleted if some other
42238: ** process has it open.  Sometimes a virus scanner or indexing program
42239: ** will open a journal file shortly after it is created in order to do
42240: ** whatever it does.  While this other process is holding the
42241: ** file open, we will be unable to delete it.  To work around this
42242: ** problem, we delay 100 milliseconds and try to delete again.  Up
42243: ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
42244: ** up and returning an error.
42245: */
42246: static int winDelete(
42247:   sqlite3_vfs *pVfs,          /* Not used on win32 */
42248:   const char *zFilename,      /* Name of file to delete */
42249:   int syncDir                 /* Not used on win32 */
42250: ){
42251:   int cnt = 0;
42252:   int rc;
42253:   DWORD attr;
42254:   DWORD lastErrno = 0;
42255:   void *zConverted;
42256:   UNUSED_PARAMETER(pVfs);
42257:   UNUSED_PARAMETER(syncDir);
42258: 
42259:   SimulateIOError(return SQLITE_IOERR_DELETE);
42260:   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
42261: 
42262:   zConverted = winConvertFromUtf8Filename(zFilename);
42263:   if( zConverted==0 ){
42264:     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42265:     return SQLITE_IOERR_NOMEM_BKPT;
42266:   }
42267:   if( osIsNT() ){
42268:     do {
42269: #if SQLITE_OS_WINRT
42270:       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42271:       memset(&sAttrData, 0, sizeof(sAttrData));
42272:       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
42273:                                   &sAttrData) ){
42274:         attr = sAttrData.dwFileAttributes;
42275:       }else{
42276:         lastErrno = osGetLastError();
42277:         if( lastErrno==ERROR_FILE_NOT_FOUND
42278:          || lastErrno==ERROR_PATH_NOT_FOUND ){
42279:           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42280:         }else{
42281:           rc = SQLITE_ERROR;
42282:         }
42283:         break;
42284:       }
42285: #else
42286:       attr = osGetFileAttributesW(zConverted);
42287: #endif
42288:       if ( attr==INVALID_FILE_ATTRIBUTES ){
42289:         lastErrno = osGetLastError();
42290:         if( lastErrno==ERROR_FILE_NOT_FOUND
42291:          || lastErrno==ERROR_PATH_NOT_FOUND ){
42292:           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42293:         }else{
42294:           rc = SQLITE_ERROR;
42295:         }
42296:         break;
42297:       }
42298:       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42299:         rc = SQLITE_ERROR; /* Files only. */
42300:         break;
42301:       }
42302:       if ( osDeleteFileW(zConverted) ){
42303:         rc = SQLITE_OK; /* Deleted OK. */
42304:         break;
42305:       }
42306:       if ( !winRetryIoerr(&cnt, &lastErrno) ){
42307:         rc = SQLITE_ERROR; /* No more retries. */
42308:         break;
42309:       }
42310:     } while(1);
42311:   }
42312: #ifdef SQLITE_WIN32_HAS_ANSI
42313:   else{
42314:     do {
42315:       attr = osGetFileAttributesA(zConverted);
42316:       if ( attr==INVALID_FILE_ATTRIBUTES ){
42317:         lastErrno = osGetLastError();
42318:         if( lastErrno==ERROR_FILE_NOT_FOUND
42319:          || lastErrno==ERROR_PATH_NOT_FOUND ){
42320:           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
42321:         }else{
42322:           rc = SQLITE_ERROR;
42323:         }
42324:         break;
42325:       }
42326:       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
42327:         rc = SQLITE_ERROR; /* Files only. */
42328:         break;
42329:       }
42330:       if ( osDeleteFileA(zConverted) ){
42331:         rc = SQLITE_OK; /* Deleted OK. */
42332:         break;
42333:       }
42334:       if ( !winRetryIoerr(&cnt, &lastErrno) ){
42335:         rc = SQLITE_ERROR; /* No more retries. */
42336:         break;
42337:       }
42338:     } while(1);
42339:   }
42340: #endif
42341:   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
42342:     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
42343:   }else{
42344:     winLogIoerr(cnt, __LINE__);
42345:   }
42346:   sqlite3_free(zConverted);
42347:   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
42348:   return rc;
42349: }
42350: 
42351: /*
42352: ** Check the existence and status of a file.
42353: */
42354: static int winAccess(
42355:   sqlite3_vfs *pVfs,         /* Not used on win32 */
42356:   const char *zFilename,     /* Name of file to check */
42357:   int flags,                 /* Type of test to make on this file */
42358:   int *pResOut               /* OUT: Result */
42359: ){
42360:   DWORD attr;
42361:   int rc = 0;
42362:   DWORD lastErrno = 0;
42363:   void *zConverted;
42364:   UNUSED_PARAMETER(pVfs);
42365: 
42366:   SimulateIOError( return SQLITE_IOERR_ACCESS; );
42367:   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
42368:            zFilename, flags, pResOut));
42369: 
42370:   zConverted = winConvertFromUtf8Filename(zFilename);
42371:   if( zConverted==0 ){
42372:     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
42373:     return SQLITE_IOERR_NOMEM_BKPT;
42374:   }
42375:   if( osIsNT() ){
42376:     int cnt = 0;
42377:     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
42378:     memset(&sAttrData, 0, sizeof(sAttrData));
42379:     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
42380:                              GetFileExInfoStandard,
42381:                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42382:     if( rc ){
42383:       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
42384:       ** as if it does not exist.
42385:       */
42386:       if(    flags==SQLITE_ACCESS_EXISTS
42387:           && sAttrData.nFileSizeHigh==0
42388:           && sAttrData.nFileSizeLow==0 ){
42389:         attr = INVALID_FILE_ATTRIBUTES;
42390:       }else{
42391:         attr = sAttrData.dwFileAttributes;
42392:       }
42393:     }else{
42394:       winLogIoerr(cnt, __LINE__);
42395:       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
42396:         sqlite3_free(zConverted);
42397:         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
42398:                            zFilename);
42399:       }else{
42400:         attr = INVALID_FILE_ATTRIBUTES;
42401:       }
42402:     }
42403:   }
42404: #ifdef SQLITE_WIN32_HAS_ANSI
42405:   else{
42406:     attr = osGetFileAttributesA((char*)zConverted);
42407:   }
42408: #endif
42409:   sqlite3_free(zConverted);
42410:   switch( flags ){
42411:     case SQLITE_ACCESS_READ:
42412:     case SQLITE_ACCESS_EXISTS:
42413:       rc = attr!=INVALID_FILE_ATTRIBUTES;
42414:       break;
42415:     case SQLITE_ACCESS_READWRITE:
42416:       rc = attr!=INVALID_FILE_ATTRIBUTES &&
42417:              (attr & FILE_ATTRIBUTE_READONLY)==0;
42418:       break;
42419:     default:
42420:       assert(!"Invalid flags argument");
42421:   }
42422:   *pResOut = rc;
42423:   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
42424:            zFilename, pResOut, *pResOut));
42425:   return SQLITE_OK;
42426: }
42427: 
42428: /*
42429: ** Returns non-zero if the specified path name starts with a drive letter
42430: ** followed by a colon character.
42431: */
42432: static BOOL winIsDriveLetterAndColon(
42433:   const char *zPathname
42434: ){
42435:   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
42436: }
42437: 
42438: /*
42439: ** Returns non-zero if the specified path name should be used verbatim.  If
42440: ** non-zero is returned from this function, the calling function must simply
42441: ** use the provided path name verbatim -OR- resolve it into a full path name
42442: ** using the GetFullPathName Win32 API function (if available).
42443: */
42444: static BOOL winIsVerbatimPathname(
42445:   const char *zPathname
42446: ){
42447:   /*
42448:   ** If the path name starts with a forward slash or a backslash, it is either
42449:   ** a legal UNC name, a volume relative path, or an absolute path name in the
42450:   ** "Unix" format on Windows.  There is no easy way to differentiate between
42451:   ** the final two cases; therefore, we return the safer return value of TRUE
42452:   ** so that callers of this function will simply use it verbatim.
42453:   */
42454:   if ( winIsDirSep(zPathname[0]) ){
42455:     return TRUE;
42456:   }
42457: 
42458:   /*
42459:   ** If the path name starts with a letter and a colon it is either a volume
42460:   ** relative path or an absolute path.  Callers of this function must not
42461:   ** attempt to treat it as a relative path name (i.e. they should simply use
42462:   ** it verbatim).
42463:   */
42464:   if ( winIsDriveLetterAndColon(zPathname) ){
42465:     return TRUE;
42466:   }
42467: 
42468:   /*
42469:   ** If we get to this point, the path name should almost certainly be a purely
42470:   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
42471:   */
42472:   return FALSE;
42473: }
42474: 
42475: /*
42476: ** Turn a relative pathname into a full pathname.  Write the full
42477: ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
42478: ** bytes in size.
42479: */
42480: static int winFullPathname(
42481:   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
42482:   const char *zRelative,        /* Possibly relative input path */
42483:   int nFull,                    /* Size of output buffer in bytes */
42484:   char *zFull                   /* Output buffer */
42485: ){
42486: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42487:   DWORD nByte;
42488:   void *zConverted;
42489:   char *zOut;
42490: #endif
42491: 
42492:   /* If this path name begins with "/X:", where "X" is any alphabetic
42493:   ** character, discard the initial "/" from the pathname.
42494:   */
42495:   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
42496:     zRelative++;
42497:   }
42498: 
42499: #if defined(__CYGWIN__)
42500:   SimulateIOError( return SQLITE_ERROR );
42501:   UNUSED_PARAMETER(nFull);
42502:   assert( nFull>=pVfs->mxPathname );
42503:   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42504:     /*
42505:     ** NOTE: We are dealing with a relative path name and the data
42506:     **       directory has been set.  Therefore, use it as the basis
42507:     **       for converting the relative path name to an absolute
42508:     **       one by prepending the data directory and a slash.
42509:     */
42510:     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42511:     if( !zOut ){
42512:       return SQLITE_IOERR_NOMEM_BKPT;
42513:     }
42514:     if( cygwin_conv_path(
42515:             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
42516:             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
42517:       sqlite3_free(zOut);
42518:       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42519:                          "winFullPathname1", zRelative);
42520:     }else{
42521:       char *zUtf8 = winConvertToUtf8Filename(zOut);
42522:       if( !zUtf8 ){
42523:         sqlite3_free(zOut);
42524:         return SQLITE_IOERR_NOMEM_BKPT;
42525:       }
42526:       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42527:                        sqlite3_data_directory, winGetDirSep(), zUtf8);
42528:       sqlite3_free(zUtf8);
42529:       sqlite3_free(zOut);
42530:     }
42531:   }else{
42532:     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42533:     if( !zOut ){
42534:       return SQLITE_IOERR_NOMEM_BKPT;
42535:     }
42536:     if( cygwin_conv_path(
42537:             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
42538:             zRelative, zOut, pVfs->mxPathname+1)<0 ){
42539:       sqlite3_free(zOut);
42540:       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42541:                          "winFullPathname2", zRelative);
42542:     }else{
42543:       char *zUtf8 = winConvertToUtf8Filename(zOut);
42544:       if( !zUtf8 ){
42545:         sqlite3_free(zOut);
42546:         return SQLITE_IOERR_NOMEM_BKPT;
42547:       }
42548:       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
42549:       sqlite3_free(zUtf8);
42550:       sqlite3_free(zOut);
42551:     }
42552:   }
42553:   return SQLITE_OK;
42554: #endif
42555: 
42556: #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
42557:   SimulateIOError( return SQLITE_ERROR );
42558:   /* WinCE has no concept of a relative pathname, or so I am told. */
42559:   /* WinRT has no way to convert a relative path to an absolute one. */
42560:   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42561:     /*
42562:     ** NOTE: We are dealing with a relative path name and the data
42563:     **       directory has been set.  Therefore, use it as the basis
42564:     **       for converting the relative path name to an absolute
42565:     **       one by prepending the data directory and a backslash.
42566:     */
42567:     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42568:                      sqlite3_data_directory, winGetDirSep(), zRelative);
42569:   }else{
42570:     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
42571:   }
42572:   return SQLITE_OK;
42573: #endif
42574: 
42575: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42576:   /* It's odd to simulate an io-error here, but really this is just
42577:   ** using the io-error infrastructure to test that SQLite handles this
42578:   ** function failing. This function could fail if, for example, the
42579:   ** current working directory has been unlinked.
42580:   */
42581:   SimulateIOError( return SQLITE_ERROR );
42582:   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42583:     /*
42584:     ** NOTE: We are dealing with a relative path name and the data
42585:     **       directory has been set.  Therefore, use it as the basis
42586:     **       for converting the relative path name to an absolute
42587:     **       one by prepending the data directory and a backslash.
42588:     */
42589:     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42590:                      sqlite3_data_directory, winGetDirSep(), zRelative);
42591:     return SQLITE_OK;
42592:   }
42593:   zConverted = winConvertFromUtf8Filename(zRelative);
42594:   if( zConverted==0 ){
42595:     return SQLITE_IOERR_NOMEM_BKPT;
42596:   }
42597:   if( osIsNT() ){
42598:     LPWSTR zTemp;
42599:     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
42600:     if( nByte==0 ){
42601:       sqlite3_free(zConverted);
42602:       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42603:                          "winFullPathname1", zRelative);
42604:     }
42605:     nByte += 3;
42606:     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42607:     if( zTemp==0 ){
42608:       sqlite3_free(zConverted);
42609:       return SQLITE_IOERR_NOMEM_BKPT;
42610:     }
42611:     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
42612:     if( nByte==0 ){
42613:       sqlite3_free(zConverted);
42614:       sqlite3_free(zTemp);
42615:       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42616:                          "winFullPathname2", zRelative);
42617:     }
42618:     sqlite3_free(zConverted);
42619:     zOut = winUnicodeToUtf8(zTemp);
42620:     sqlite3_free(zTemp);
42621:   }
42622: #ifdef SQLITE_WIN32_HAS_ANSI
42623:   else{
42624:     char *zTemp;
42625:     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
42626:     if( nByte==0 ){
42627:       sqlite3_free(zConverted);
42628:       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42629:                          "winFullPathname3", zRelative);
42630:     }
42631:     nByte += 3;
42632:     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42633:     if( zTemp==0 ){
42634:       sqlite3_free(zConverted);
42635:       return SQLITE_IOERR_NOMEM_BKPT;
42636:     }
42637:     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
42638:     if( nByte==0 ){
42639:       sqlite3_free(zConverted);
42640:       sqlite3_free(zTemp);
42641:       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42642:                          "winFullPathname4", zRelative);
42643:     }
42644:     sqlite3_free(zConverted);
42645:     zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
42646:     sqlite3_free(zTemp);
42647:   }
42648: #endif
42649:   if( zOut ){
42650:     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
42651:     sqlite3_free(zOut);
42652:     return SQLITE_OK;
42653:   }else{
42654:     return SQLITE_IOERR_NOMEM_BKPT;
42655:   }
42656: #endif
42657: }
42658: 
42659: #ifndef SQLITE_OMIT_LOAD_EXTENSION
42660: /*
42661: ** Interfaces for opening a shared library, finding entry points
42662: ** within the shared library, and closing the shared library.
42663: */
42664: static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
42665:   HANDLE h;
42666: #if defined(__CYGWIN__)
42667:   int nFull = pVfs->mxPathname+1;
42668:   char *zFull = sqlite3MallocZero( nFull );
42669:   void *zConverted = 0;
42670:   if( zFull==0 ){
42671:     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42672:     return 0;
42673:   }
42674:   if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
42675:     sqlite3_free(zFull);
42676:     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42677:     return 0;
42678:   }
42679:   zConverted = winConvertFromUtf8Filename(zFull);
42680:   sqlite3_free(zFull);
42681: #else
42682:   void *zConverted = winConvertFromUtf8Filename(zFilename);
42683:   UNUSED_PARAMETER(pVfs);
42684: #endif
42685:   if( zConverted==0 ){
42686:     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42687:     return 0;
42688:   }
42689:   if( osIsNT() ){
42690: #if SQLITE_OS_WINRT
42691:     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
42692: #else
42693:     h = osLoadLibraryW((LPCWSTR)zConverted);
42694: #endif
42695:   }
42696: #ifdef SQLITE_WIN32_HAS_ANSI
42697:   else{
42698:     h = osLoadLibraryA((char*)zConverted);
42699:   }
42700: #endif
42701:   OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
42702:   sqlite3_free(zConverted);
42703:   return (void*)h;
42704: }
42705: static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
42706:   UNUSED_PARAMETER(pVfs);
42707:   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
42708: }
42709: static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
42710:   FARPROC proc;
42711:   UNUSED_PARAMETER(pVfs);
42712:   proc = osGetProcAddressA((HANDLE)pH, zSym);
42713:   OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
42714:            (void*)pH, zSym, (void*)proc));
42715:   return (void(*)(void))proc;
42716: }
42717: static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
42718:   UNUSED_PARAMETER(pVfs);
42719:   osFreeLibrary((HANDLE)pHandle);
42720:   OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
42721: }
42722: #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
42723:   #define winDlOpen  0
42724:   #define winDlError 0
42725:   #define winDlSym   0
42726:   #define winDlClose 0
42727: #endif
42728: 
42729: /* State information for the randomness gatherer. */
42730: typedef struct EntropyGatherer EntropyGatherer;
42731: struct EntropyGatherer {
42732:   unsigned char *a;   /* Gather entropy into this buffer */
42733:   int na;             /* Size of a[] in bytes */
42734:   int i;              /* XOR next input into a[i] */
42735:   int nXor;           /* Number of XOR operations done */
42736: };
42737: 
42738: #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
42739: /* Mix sz bytes of entropy into p. */
42740: static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
42741:   int j, k;
42742:   for(j=0, k=p->i; j<sz; j++){
42743:     p->a[k++] ^= x[j];
42744:     if( k>=p->na ) k = 0;
42745:   }
42746:   p->i = k;
42747:   p->nXor += sz;
42748: }
42749: #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
42750: 
42751: /*
42752: ** Write up to nBuf bytes of randomness into zBuf.
42753: */
42754: static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42755: #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
42756:   UNUSED_PARAMETER(pVfs);
42757:   memset(zBuf, 0, nBuf);
42758:   return nBuf;
42759: #else
42760:   EntropyGatherer e;
42761:   UNUSED_PARAMETER(pVfs);
42762:   memset(zBuf, 0, nBuf);
42763: #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
42764:   rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
42765: #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
42766:   e.a = (unsigned char*)zBuf;
42767:   e.na = nBuf;
42768:   e.nXor = 0;
42769:   e.i = 0;
42770:   {
42771:     SYSTEMTIME x;
42772:     osGetSystemTime(&x);
42773:     xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
42774:   }
42775:   {
42776:     DWORD pid = osGetCurrentProcessId();
42777:     xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
42778:   }
42779: #if SQLITE_OS_WINRT
42780:   {
42781:     ULONGLONG cnt = osGetTickCount64();
42782:     xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
42783:   }
42784: #else
42785:   {
42786:     DWORD cnt = osGetTickCount();
42787:     xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
42788:   }
42789: #endif /* SQLITE_OS_WINRT */
42790:   {
42791:     LARGE_INTEGER i;
42792:     osQueryPerformanceCounter(&i);
42793:     xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
42794:   }
42795: #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
42796:   {
42797:     UUID id;
42798:     memset(&id, 0, sizeof(UUID));
42799:     osUuidCreate(&id);
42800:     xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42801:     memset(&id, 0, sizeof(UUID));
42802:     osUuidCreateSequential(&id);
42803:     xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42804:   }
42805: #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
42806:   return e.nXor>nBuf ? nBuf : e.nXor;
42807: #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
42808: }
42809: 
42810: 
42811: /*
42812: ** Sleep for a little while.  Return the amount of time slept.
42813: */
42814: static int winSleep(sqlite3_vfs *pVfs, int microsec){
42815:   sqlite3_win32_sleep((microsec+999)/1000);
42816:   UNUSED_PARAMETER(pVfs);
42817:   return ((microsec+999)/1000)*1000;
42818: }
42819: 
42820: /*
42821: ** The following variable, if set to a non-zero value, is interpreted as
42822: ** the number of seconds since 1970 and is used to set the result of
42823: ** sqlite3OsCurrentTime() during testing.
42824: */
42825: #ifdef SQLITE_TEST
42826: SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
42827: #endif
42828: 
42829: /*
42830: ** Find the current time (in Universal Coordinated Time).  Write into *piNow
42831: ** the current time and date as a Julian Day number times 86_400_000.  In
42832: ** other words, write into *piNow the number of milliseconds since the Julian
42833: ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
42834: ** proleptic Gregorian calendar.
42835: **
42836: ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
42837: ** cannot be found.
42838: */
42839: static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
42840:   /* FILETIME structure is a 64-bit value representing the number of
42841:      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
42842:   */
42843:   FILETIME ft;
42844:   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
42845: #ifdef SQLITE_TEST
42846:   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
42847: #endif
42848:   /* 2^32 - to avoid use of LL and warnings in gcc */
42849:   static const sqlite3_int64 max32BitValue =
42850:       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
42851:       (sqlite3_int64)294967296;
42852: 
42853: #if SQLITE_OS_WINCE
42854:   SYSTEMTIME time;
42855:   osGetSystemTime(&time);
42856:   /* if SystemTimeToFileTime() fails, it returns zero. */
42857:   if (!osSystemTimeToFileTime(&time,&ft)){
42858:     return SQLITE_ERROR;
42859:   }
42860: #else
42861:   osGetSystemTimeAsFileTime( &ft );
42862: #endif
42863: 
42864:   *piNow = winFiletimeEpoch +
42865:             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
42866:                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
42867: 
42868: #ifdef SQLITE_TEST
42869:   if( sqlite3_current_time ){
42870:     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
42871:   }
42872: #endif
42873:   UNUSED_PARAMETER(pVfs);
42874:   return SQLITE_OK;
42875: }
42876: 
42877: /*
42878: ** Find the current time (in Universal Coordinated Time).  Write the
42879: ** current time and date as a Julian Day number into *prNow and
42880: ** return 0.  Return 1 if the time and date cannot be found.
42881: */
42882: static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
42883:   int rc;
42884:   sqlite3_int64 i;
42885:   rc = winCurrentTimeInt64(pVfs, &i);
42886:   if( !rc ){
42887:     *prNow = i/86400000.0;
42888:   }
42889:   return rc;
42890: }
42891: 
42892: /*
42893: ** The idea is that this function works like a combination of
42894: ** GetLastError() and FormatMessage() on Windows (or errno and
42895: ** strerror_r() on Unix). After an error is returned by an OS
42896: ** function, SQLite calls this function with zBuf pointing to
42897: ** a buffer of nBuf bytes. The OS layer should populate the
42898: ** buffer with a nul-terminated UTF-8 encoded error message
42899: ** describing the last IO error to have occurred within the calling
42900: ** thread.
42901: **
42902: ** If the error message is too large for the supplied buffer,
42903: ** it should be truncated. The return value of xGetLastError
42904: ** is zero if the error message fits in the buffer, or non-zero
42905: ** otherwise (if the message was truncated). If non-zero is returned,
42906: ** then it is not necessary to include the nul-terminator character
42907: ** in the output buffer.
42908: **
42909: ** Not supplying an error message will have no adverse effect
42910: ** on SQLite. It is fine to have an implementation that never
42911: ** returns an error message:
42912: **
42913: **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42914: **     assert(zBuf[0]=='\0');
42915: **     return 0;
42916: **   }
42917: **
42918: ** However if an error message is supplied, it will be incorporated
42919: ** by sqlite into the error message available to the user using
42920: ** sqlite3_errmsg(), possibly making IO errors easier to debug.
42921: */
42922: static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42923:   DWORD e = osGetLastError();
42924:   UNUSED_PARAMETER(pVfs);
42925:   if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
42926:   return e;
42927: }
42928: 
42929: /*
42930: ** Initialize and deinitialize the operating system interface.
42931: */
42932: SQLITE_API int sqlite3_os_init(void){
42933:   static sqlite3_vfs winVfs = {
42934:     3,                     /* iVersion */
42935:     sizeof(winFile),       /* szOsFile */
42936:     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
42937:     0,                     /* pNext */
42938:     "win32",               /* zName */
42939:     &winAppData,           /* pAppData */
42940:     winOpen,               /* xOpen */
42941:     winDelete,             /* xDelete */
42942:     winAccess,             /* xAccess */
42943:     winFullPathname,       /* xFullPathname */
42944:     winDlOpen,             /* xDlOpen */
42945:     winDlError,            /* xDlError */
42946:     winDlSym,              /* xDlSym */
42947:     winDlClose,            /* xDlClose */
42948:     winRandomness,         /* xRandomness */
42949:     winSleep,              /* xSleep */
42950:     winCurrentTime,        /* xCurrentTime */
42951:     winGetLastError,       /* xGetLastError */
42952:     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
42953:     winSetSystemCall,      /* xSetSystemCall */
42954:     winGetSystemCall,      /* xGetSystemCall */
42955:     winNextSystemCall,     /* xNextSystemCall */
42956:   };
42957: #if defined(SQLITE_WIN32_HAS_WIDE)
42958:   static sqlite3_vfs winLongPathVfs = {
42959:     3,                     /* iVersion */
42960:     sizeof(winFile),       /* szOsFile */
42961:     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
42962:     0,                     /* pNext */
42963:     "win32-longpath",      /* zName */
42964:     &winAppData,           /* pAppData */
42965:     winOpen,               /* xOpen */
42966:     winDelete,             /* xDelete */
42967:     winAccess,             /* xAccess */
42968:     winFullPathname,       /* xFullPathname */
42969:     winDlOpen,             /* xDlOpen */
42970:     winDlError,            /* xDlError */
42971:     winDlSym,              /* xDlSym */
42972:     winDlClose,            /* xDlClose */
42973:     winRandomness,         /* xRandomness */
42974:     winSleep,              /* xSleep */
42975:     winCurrentTime,        /* xCurrentTime */
42976:     winGetLastError,       /* xGetLastError */
42977:     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
42978:     winSetSystemCall,      /* xSetSystemCall */
42979:     winGetSystemCall,      /* xGetSystemCall */
42980:     winNextSystemCall,     /* xNextSystemCall */
42981:   };
42982: #endif
42983:   static sqlite3_vfs winNolockVfs = {
42984:     3,                     /* iVersion */
42985:     sizeof(winFile),       /* szOsFile */
42986:     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
42987:     0,                     /* pNext */
42988:     "win32-none",          /* zName */
42989:     &winNolockAppData,     /* pAppData */
42990:     winOpen,               /* xOpen */
42991:     winDelete,             /* xDelete */
42992:     winAccess,             /* xAccess */
42993:     winFullPathname,       /* xFullPathname */
42994:     winDlOpen,             /* xDlOpen */
42995:     winDlError,            /* xDlError */
42996:     winDlSym,              /* xDlSym */
42997:     winDlClose,            /* xDlClose */
42998:     winRandomness,         /* xRandomness */
42999:     winSleep,              /* xSleep */
43000:     winCurrentTime,        /* xCurrentTime */
43001:     winGetLastError,       /* xGetLastError */
43002:     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43003:     winSetSystemCall,      /* xSetSystemCall */
43004:     winGetSystemCall,      /* xGetSystemCall */
43005:     winNextSystemCall,     /* xNextSystemCall */
43006:   };
43007: #if defined(SQLITE_WIN32_HAS_WIDE)
43008:   static sqlite3_vfs winLongPathNolockVfs = {
43009:     3,                     /* iVersion */
43010:     sizeof(winFile),       /* szOsFile */
43011:     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
43012:     0,                     /* pNext */
43013:     "win32-longpath-none", /* zName */
43014:     &winNolockAppData,     /* pAppData */
43015:     winOpen,               /* xOpen */
43016:     winDelete,             /* xDelete */
43017:     winAccess,             /* xAccess */
43018:     winFullPathname,       /* xFullPathname */
43019:     winDlOpen,             /* xDlOpen */
43020:     winDlError,            /* xDlError */
43021:     winDlSym,              /* xDlSym */
43022:     winDlClose,            /* xDlClose */
43023:     winRandomness,         /* xRandomness */
43024:     winSleep,              /* xSleep */
43025:     winCurrentTime,        /* xCurrentTime */
43026:     winGetLastError,       /* xGetLastError */
43027:     winCurrentTimeInt64,   /* xCurrentTimeInt64 */
43028:     winSetSystemCall,      /* xSetSystemCall */
43029:     winGetSystemCall,      /* xGetSystemCall */
43030:     winNextSystemCall,     /* xNextSystemCall */
43031:   };
43032: #endif
43033: 
43034:   /* Double-check that the aSyscall[] array has been constructed
43035:   ** correctly.  See ticket [bb3a86e890c8e96ab] */
43036:   assert( ArraySize(aSyscall)==80 );
43037: 
43038:   /* get memory map allocation granularity */
43039:   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
43040: #if SQLITE_OS_WINRT
43041:   osGetNativeSystemInfo(&winSysInfo);
43042: #else
43043:   osGetSystemInfo(&winSysInfo);
43044: #endif
43045:   assert( winSysInfo.dwAllocationGranularity>0 );
43046:   assert( winSysInfo.dwPageSize>0 );
43047: 
43048:   sqlite3_vfs_register(&winVfs, 1);
43049: 
43050: #if defined(SQLITE_WIN32_HAS_WIDE)
43051:   sqlite3_vfs_register(&winLongPathVfs, 0);
43052: #endif
43053: 
43054:   sqlite3_vfs_register(&winNolockVfs, 0);
43055: 
43056: #if defined(SQLITE_WIN32_HAS_WIDE)
43057:   sqlite3_vfs_register(&winLongPathNolockVfs, 0);
43058: #endif
43059: 
43060:   return SQLITE_OK;
43061: }
43062: 
43063: SQLITE_API int sqlite3_os_end(void){
43064: #if SQLITE_OS_WINRT
43065:   if( sleepObj!=NULL ){
43066:     osCloseHandle(sleepObj);
43067:     sleepObj = NULL;
43068:   }
43069: #endif
43070:   return SQLITE_OK;
43071: }
43072: 
43073: #endif /* SQLITE_OS_WIN */
43074: 
43075: /************** End of os_win.c **********************************************/
43076: /************** Begin file bitvec.c ******************************************/
43077: /*
43078: ** 2008 February 16
43079: **
43080: ** The author disclaims copyright to this source code.  In place of
43081: ** a legal notice, here is a blessing:
43082: **
43083: **    May you do good and not evil.
43084: **    May you find forgiveness for yourself and forgive others.
43085: **    May you share freely, never taking more than you give.
43086: **
43087: *************************************************************************
43088: ** This file implements an object that represents a fixed-length
43089: ** bitmap.  Bits are numbered starting with 1.
43090: **
43091: ** A bitmap is used to record which pages of a database file have been
43092: ** journalled during a transaction, or which pages have the "dont-write"
43093: ** property.  Usually only a few pages are meet either condition.
43094: ** So the bitmap is usually sparse and has low cardinality.
43095: ** But sometimes (for example when during a DROP of a large table) most
43096: ** or all of the pages in a database can get journalled.  In those cases, 
43097: ** the bitmap becomes dense with high cardinality.  The algorithm needs 
43098: ** to handle both cases well.
43099: **
43100: ** The size of the bitmap is fixed when the object is created.
43101: **
43102: ** All bits are clear when the bitmap is created.  Individual bits
43103: ** may be set or cleared one at a time.
43104: **
43105: ** Test operations are about 100 times more common that set operations.
43106: ** Clear operations are exceedingly rare.  There are usually between
43107: ** 5 and 500 set operations per Bitvec object, though the number of sets can
43108: ** sometimes grow into tens of thousands or larger.  The size of the
43109: ** Bitvec object is the number of pages in the database file at the
43110: ** start of a transaction, and is thus usually less than a few thousand,
43111: ** but can be as large as 2 billion for a really big database.
43112: */
43113: /* #include "sqliteInt.h" */
43114: 
43115: /* Size of the Bitvec structure in bytes. */
43116: #define BITVEC_SZ        512
43117: 
43118: /* Round the union size down to the nearest pointer boundary, since that's how 
43119: ** it will be aligned within the Bitvec struct. */
43120: #define BITVEC_USIZE \
43121:     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
43122: 
43123: /* Type of the array "element" for the bitmap representation. 
43124: ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
43125: ** Setting this to the "natural word" size of your CPU may improve
43126: ** performance. */
43127: #define BITVEC_TELEM     u8
43128: /* Size, in bits, of the bitmap element. */
43129: #define BITVEC_SZELEM    8
43130: /* Number of elements in a bitmap array. */
43131: #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
43132: /* Number of bits in the bitmap array. */
43133: #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
43134: 
43135: /* Number of u32 values in hash table. */
43136: #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
43137: /* Maximum number of entries in hash table before 
43138: ** sub-dividing and re-hashing. */
43139: #define BITVEC_MXHASH    (BITVEC_NINT/2)
43140: /* Hashing function for the aHash representation.
43141: ** Empirical testing showed that the *37 multiplier 
43142: ** (an arbitrary prime)in the hash function provided 
43143: ** no fewer collisions than the no-op *1. */
43144: #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
43145: 
43146: #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
43147: 
43148: 
43149: /*
43150: ** A bitmap is an instance of the following structure.
43151: **
43152: ** This bitmap records the existence of zero or more bits
43153: ** with values between 1 and iSize, inclusive.
43154: **
43155: ** There are three possible representations of the bitmap.
43156: ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
43157: ** bitmap.  The least significant bit is bit 1.
43158: **
43159: ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
43160: ** a hash table that will hold up to BITVEC_MXHASH distinct values.
43161: **
43162: ** Otherwise, the value i is redirected into one of BITVEC_NPTR
43163: ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
43164: ** handles up to iDivisor separate values of i.  apSub[0] holds
43165: ** values between 1 and iDivisor.  apSub[1] holds values between
43166: ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
43167: ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
43168: ** to hold deal with values between 1 and iDivisor.
43169: */
43170: struct Bitvec {
43171:   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
43172:   u32 nSet;       /* Number of bits that are set - only valid for aHash
43173:                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
43174:                   ** this would be 125. */
43175:   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
43176:                   /* Should >=0 for apSub element. */
43177:                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
43178:                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
43179:   union {
43180:     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
43181:     u32 aHash[BITVEC_NINT];      /* Hash table representation */
43182:     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
43183:   } u;
43184: };
43185: 
43186: /*
43187: ** Create a new bitmap object able to handle bits between 0 and iSize,
43188: ** inclusive.  Return a pointer to the new object.  Return NULL if 
43189: ** malloc fails.
43190: */
43191: SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
43192:   Bitvec *p;
43193:   assert( sizeof(*p)==BITVEC_SZ );
43194:   p = sqlite3MallocZero( sizeof(*p) );
43195:   if( p ){
43196:     p->iSize = iSize;
43197:   }
43198:   return p;
43199: }
43200: 
43201: /*
43202: ** Check to see if the i-th bit is set.  Return true or false.
43203: ** If p is NULL (if the bitmap has not been created) or if
43204: ** i is out of range, then return false.
43205: */
43206: SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
43207:   assert( p!=0 );
43208:   i--;
43209:   if( i>=p->iSize ) return 0;
43210:   while( p->iDivisor ){
43211:     u32 bin = i/p->iDivisor;
43212:     i = i%p->iDivisor;
43213:     p = p->u.apSub[bin];
43214:     if (!p) {
43215:       return 0;
43216:     }
43217:   }
43218:   if( p->iSize<=BITVEC_NBIT ){
43219:     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
43220:   } else{
43221:     u32 h = BITVEC_HASH(i++);
43222:     while( p->u.aHash[h] ){
43223:       if( p->u.aHash[h]==i ) return 1;
43224:       h = (h+1) % BITVEC_NINT;
43225:     }
43226:     return 0;
43227:   }
43228: }
43229: SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
43230:   return p!=0 && sqlite3BitvecTestNotNull(p,i);
43231: }
43232: 
43233: /*
43234: ** Set the i-th bit.  Return 0 on success and an error code if
43235: ** anything goes wrong.
43236: **
43237: ** This routine might cause sub-bitmaps to be allocated.  Failing
43238: ** to get the memory needed to hold the sub-bitmap is the only
43239: ** that can go wrong with an insert, assuming p and i are valid.
43240: **
43241: ** The calling function must ensure that p is a valid Bitvec object
43242: ** and that the value for "i" is within range of the Bitvec object.
43243: ** Otherwise the behavior is undefined.
43244: */
43245: SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
43246:   u32 h;
43247:   if( p==0 ) return SQLITE_OK;
43248:   assert( i>0 );
43249:   assert( i<=p->iSize );
43250:   i--;
43251:   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
43252:     u32 bin = i/p->iDivisor;
43253:     i = i%p->iDivisor;
43254:     if( p->u.apSub[bin]==0 ){
43255:       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
43256:       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
43257:     }
43258:     p = p->u.apSub[bin];
43259:   }
43260:   if( p->iSize<=BITVEC_NBIT ){
43261:     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
43262:     return SQLITE_OK;
43263:   }
43264:   h = BITVEC_HASH(i++);
43265:   /* if there wasn't a hash collision, and this doesn't */
43266:   /* completely fill the hash, then just add it without */
43267:   /* worring about sub-dividing and re-hashing. */
43268:   if( !p->u.aHash[h] ){
43269:     if (p->nSet<(BITVEC_NINT-1)) {
43270:       goto bitvec_set_end;
43271:     } else {
43272:       goto bitvec_set_rehash;
43273:     }
43274:   }
43275:   /* there was a collision, check to see if it's already */
43276:   /* in hash, if not, try to find a spot for it */
43277:   do {
43278:     if( p->u.aHash[h]==i ) return SQLITE_OK;
43279:     h++;
43280:     if( h>=BITVEC_NINT ) h = 0;
43281:   } while( p->u.aHash[h] );
43282:   /* we didn't find it in the hash.  h points to the first */
43283:   /* available free spot. check to see if this is going to */
43284:   /* make our hash too "full".  */
43285: bitvec_set_rehash:
43286:   if( p->nSet>=BITVEC_MXHASH ){
43287:     unsigned int j;
43288:     int rc;
43289:     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
43290:     if( aiValues==0 ){
43291:       return SQLITE_NOMEM_BKPT;
43292:     }else{
43293:       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43294:       memset(p->u.apSub, 0, sizeof(p->u.apSub));
43295:       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
43296:       rc = sqlite3BitvecSet(p, i);
43297:       for(j=0; j<BITVEC_NINT; j++){
43298:         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
43299:       }
43300:       sqlite3StackFree(0, aiValues);
43301:       return rc;
43302:     }
43303:   }
43304: bitvec_set_end:
43305:   p->nSet++;
43306:   p->u.aHash[h] = i;
43307:   return SQLITE_OK;
43308: }
43309: 
43310: /*
43311: ** Clear the i-th bit.
43312: **
43313: ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
43314: ** that BitvecClear can use to rebuilt its hash table.
43315: */
43316: SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
43317:   if( p==0 ) return;
43318:   assert( i>0 );
43319:   i--;
43320:   while( p->iDivisor ){
43321:     u32 bin = i/p->iDivisor;
43322:     i = i%p->iDivisor;
43323:     p = p->u.apSub[bin];
43324:     if (!p) {
43325:       return;
43326:     }
43327:   }
43328:   if( p->iSize<=BITVEC_NBIT ){
43329:     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
43330:   }else{
43331:     unsigned int j;
43332:     u32 *aiValues = pBuf;
43333:     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
43334:     memset(p->u.aHash, 0, sizeof(p->u.aHash));
43335:     p->nSet = 0;
43336:     for(j=0; j<BITVEC_NINT; j++){
43337:       if( aiValues[j] && aiValues[j]!=(i+1) ){
43338:         u32 h = BITVEC_HASH(aiValues[j]-1);
43339:         p->nSet++;
43340:         while( p->u.aHash[h] ){
43341:           h++;
43342:           if( h>=BITVEC_NINT ) h = 0;
43343:         }
43344:         p->u.aHash[h] = aiValues[j];
43345:       }
43346:     }
43347:   }
43348: }
43349: 
43350: /*
43351: ** Destroy a bitmap object.  Reclaim all memory used.
43352: */
43353: SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
43354:   if( p==0 ) return;
43355:   if( p->iDivisor ){
43356:     unsigned int i;
43357:     for(i=0; i<BITVEC_NPTR; i++){
43358:       sqlite3BitvecDestroy(p->u.apSub[i]);
43359:     }
43360:   }
43361:   sqlite3_free(p);
43362: }
43363: 
43364: /*
43365: ** Return the value of the iSize parameter specified when Bitvec *p
43366: ** was created.
43367: */
43368: SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
43369:   return p->iSize;
43370: }
43371: 
43372: #ifndef SQLITE_OMIT_BUILTIN_TEST
43373: /*
43374: ** Let V[] be an array of unsigned characters sufficient to hold
43375: ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
43376: ** Then the following macros can be used to set, clear, or test
43377: ** individual bits within V.
43378: */
43379: #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
43380: #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
43381: #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
43382: 
43383: /*
43384: ** This routine runs an extensive test of the Bitvec code.
43385: **
43386: ** The input is an array of integers that acts as a program
43387: ** to test the Bitvec.  The integers are opcodes followed
43388: ** by 0, 1, or 3 operands, depending on the opcode.  Another
43389: ** opcode follows immediately after the last operand.
43390: **
43391: ** There are 6 opcodes numbered from 0 through 5.  0 is the
43392: ** "halt" opcode and causes the test to end.
43393: **
43394: **    0          Halt and return the number of errors
43395: **    1 N S X    Set N bits beginning with S and incrementing by X
43396: **    2 N S X    Clear N bits beginning with S and incrementing by X
43397: **    3 N        Set N randomly chosen bits
43398: **    4 N        Clear N randomly chosen bits
43399: **    5 N S X    Set N bits from S increment X in array only, not in bitvec
43400: **
43401: ** The opcodes 1 through 4 perform set and clear operations are performed
43402: ** on both a Bitvec object and on a linear array of bits obtained from malloc.
43403: ** Opcode 5 works on the linear array only, not on the Bitvec.
43404: ** Opcode 5 is used to deliberately induce a fault in order to
43405: ** confirm that error detection works.
43406: **
43407: ** At the conclusion of the test the linear array is compared
43408: ** against the Bitvec object.  If there are any differences,
43409: ** an error is returned.  If they are the same, zero is returned.
43410: **
43411: ** If a memory allocation error occurs, return -1.
43412: */
43413: SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
43414:   Bitvec *pBitvec = 0;
43415:   unsigned char *pV = 0;
43416:   int rc = -1;
43417:   int i, nx, pc, op;
43418:   void *pTmpSpace;
43419: 
43420:   /* Allocate the Bitvec to be tested and a linear array of
43421:   ** bits to act as the reference */
43422:   pBitvec = sqlite3BitvecCreate( sz );
43423:   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
43424:   pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
43425:   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
43426: 
43427:   /* NULL pBitvec tests */
43428:   sqlite3BitvecSet(0, 1);
43429:   sqlite3BitvecClear(0, 1, pTmpSpace);
43430: 
43431:   /* Run the program */
43432:   pc = 0;
43433:   while( (op = aOp[pc])!=0 ){
43434:     switch( op ){
43435:       case 1:
43436:       case 2:
43437:       case 5: {
43438:         nx = 4;
43439:         i = aOp[pc+2] - 1;
43440:         aOp[pc+2] += aOp[pc+3];
43441:         break;
43442:       }
43443:       case 3:
43444:       case 4: 
43445:       default: {
43446:         nx = 2;
43447:         sqlite3_randomness(sizeof(i), &i);
43448:         break;
43449:       }
43450:     }
43451:     if( (--aOp[pc+1]) > 0 ) nx = 0;
43452:     pc += nx;
43453:     i = (i & 0x7fffffff)%sz;
43454:     if( (op & 1)!=0 ){
43455:       SETBIT(pV, (i+1));
43456:       if( op!=5 ){
43457:         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
43458:       }
43459:     }else{
43460:       CLEARBIT(pV, (i+1));
43461:       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
43462:     }
43463:   }
43464: 
43465:   /* Test to make sure the linear array exactly matches the
43466:   ** Bitvec object.  Start with the assumption that they do
43467:   ** match (rc==0).  Change rc to non-zero if a discrepancy
43468:   ** is found.
43469:   */
43470:   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
43471:           + sqlite3BitvecTest(pBitvec, 0)
43472:           + (sqlite3BitvecSize(pBitvec) - sz);
43473:   for(i=1; i<=sz; i++){
43474:     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
43475:       rc = i;
43476:       break;
43477:     }
43478:   }
43479: 
43480:   /* Free allocated structure */
43481: bitvec_end:
43482:   sqlite3_free(pTmpSpace);
43483:   sqlite3_free(pV);
43484:   sqlite3BitvecDestroy(pBitvec);
43485:   return rc;
43486: }
43487: #endif /* SQLITE_OMIT_BUILTIN_TEST */
43488: 
43489: /************** End of bitvec.c **********************************************/
43490: /************** Begin file pcache.c ******************************************/
43491: /*
43492: ** 2008 August 05
43493: **
43494: ** The author disclaims copyright to this source code.  In place of
43495: ** a legal notice, here is a blessing:
43496: **
43497: **    May you do good and not evil.
43498: **    May you find forgiveness for yourself and forgive others.
43499: **    May you share freely, never taking more than you give.
43500: **
43501: *************************************************************************
43502: ** This file implements that page cache.
43503: */
43504: /* #include "sqliteInt.h" */
43505: 
43506: /*
43507: ** A complete page cache is an instance of this structure.  Every
43508: ** entry in the cache holds a single page of the database file.  The
43509: ** btree layer only operates on the cached copy of the database pages.
43510: **
43511: ** A page cache entry is "clean" if it exactly matches what is currently
43512: ** on disk.  A page is "dirty" if it has been modified and needs to be
43513: ** persisted to disk.
43514: **
43515: ** pDirty, pDirtyTail, pSynced:
43516: **   All dirty pages are linked into the doubly linked list using
43517: **   PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
43518: **   such that p was added to the list more recently than p->pDirtyNext.
43519: **   PCache.pDirty points to the first (newest) element in the list and
43520: **   pDirtyTail to the last (oldest).
43521: **
43522: **   The PCache.pSynced variable is used to optimize searching for a dirty
43523: **   page to eject from the cache mid-transaction. It is better to eject
43524: **   a page that does not require a journal sync than one that does. 
43525: **   Therefore, pSynced is maintained to that it *almost* always points
43526: **   to either the oldest page in the pDirty/pDirtyTail list that has a
43527: **   clear PGHDR_NEED_SYNC flag or to a page that is older than this one
43528: **   (so that the right page to eject can be found by following pDirtyPrev
43529: **   pointers).
43530: */
43531: struct PCache {
43532:   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
43533:   PgHdr *pSynced;                     /* Last synced page in dirty page list */
43534:   int nRefSum;                        /* Sum of ref counts over all pages */
43535:   int szCache;                        /* Configured cache size */
43536:   int szSpill;                        /* Size before spilling occurs */
43537:   int szPage;                         /* Size of every page in this cache */
43538:   int szExtra;                        /* Size of extra space for each page */
43539:   u8 bPurgeable;                      /* True if pages are on backing store */
43540:   u8 eCreate;                         /* eCreate value for for xFetch() */
43541:   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
43542:   void *pStress;                      /* Argument to xStress */
43543:   sqlite3_pcache *pCache;             /* Pluggable cache module */
43544: };
43545: 
43546: /********************************** Test and Debug Logic **********************/
43547: /*
43548: ** Debug tracing macros.  Enable by by changing the "0" to "1" and
43549: ** recompiling.
43550: **
43551: ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
43552: ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
43553: ** is displayed for many operations, resulting in a lot of output.
43554: */
43555: #if defined(SQLITE_DEBUG) && 0
43556:   int sqlite3PcacheTrace = 2;       /* 0: off  1: simple  2: cache dumps */
43557:   int sqlite3PcacheMxDump = 9999;   /* Max cache entries for pcacheDump() */
43558: # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
43559:   void pcacheDump(PCache *pCache){
43560:     int N;
43561:     int i, j;
43562:     sqlite3_pcache_page *pLower;
43563:     PgHdr *pPg;
43564:     unsigned char *a;
43565:   
43566:     if( sqlite3PcacheTrace<2 ) return;
43567:     if( pCache->pCache==0 ) return;
43568:     N = sqlite3PcachePagecount(pCache);
43569:     if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
43570:     for(i=1; i<=N; i++){
43571:        pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
43572:        if( pLower==0 ) continue;
43573:        pPg = (PgHdr*)pLower->pExtra;
43574:        printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
43575:        a = (unsigned char *)pLower->pBuf;
43576:        for(j=0; j<12; j++) printf("%02x", a[j]);
43577:        printf("\n");
43578:        if( pPg->pPage==0 ){
43579:          sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
43580:        }
43581:     }
43582:   }
43583:   #else
43584: # define pcacheTrace(X)
43585: # define pcacheDump(X)
43586: #endif
43587: 
43588: /*
43589: ** Check invariants on a PgHdr entry.  Return true if everything is OK.
43590: ** Return false if any invariant is violated.
43591: **
43592: ** This routine is for use inside of assert() statements only.  For
43593: ** example:
43594: **
43595: **          assert( sqlite3PcachePageSanity(pPg) );
43596: */
43597: #if SQLITE_DEBUG
43598: SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
43599:   PCache *pCache;
43600:   assert( pPg!=0 );
43601:   assert( pPg->pgno>0 );    /* Page number is 1 or more */
43602:   pCache = pPg->pCache;
43603:   assert( pCache!=0 );      /* Every page has an associated PCache */
43604:   if( pPg->flags & PGHDR_CLEAN ){
43605:     assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
43606:     assert( pCache->pDirty!=pPg );          /* CLEAN pages not on dirty list */
43607:     assert( pCache->pDirtyTail!=pPg );
43608:   }
43609:   /* WRITEABLE pages must also be DIRTY */
43610:   if( pPg->flags & PGHDR_WRITEABLE ){
43611:     assert( pPg->flags & PGHDR_DIRTY );     /* WRITEABLE implies DIRTY */
43612:   }
43613:   /* NEED_SYNC can be set independently of WRITEABLE.  This can happen,
43614:   ** for example, when using the sqlite3PagerDontWrite() optimization:
43615:   **    (1)  Page X is journalled, and gets WRITEABLE and NEED_SEEK.
43616:   **    (2)  Page X moved to freelist, WRITEABLE is cleared
43617:   **    (3)  Page X reused, WRITEABLE is set again
43618:   ** If NEED_SYNC had been cleared in step 2, then it would not be reset
43619:   ** in step 3, and page might be written into the database without first
43620:   ** syncing the rollback journal, which might cause corruption on a power
43621:   ** loss.
43622:   **
43623:   ** Another example is when the database page size is smaller than the
43624:   ** disk sector size.  When any page of a sector is journalled, all pages
43625:   ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
43626:   ** in case they are later modified, since all pages in the same sector
43627:   ** must be journalled and synced before any of those pages can be safely
43628:   ** written.
43629:   */
43630:   return 1;
43631: }
43632: #endif /* SQLITE_DEBUG */
43633: 
43634: 
43635: /********************************** Linked List Management ********************/
43636: 
43637: /* Allowed values for second argument to pcacheManageDirtyList() */
43638: #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
43639: #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
43640: #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
43641: 
43642: /*
43643: ** Manage pPage's participation on the dirty list.  Bits of the addRemove
43644: ** argument determines what operation to do.  The 0x01 bit means first
43645: ** remove pPage from the dirty list.  The 0x02 means add pPage back to
43646: ** the dirty list.  Doing both moves pPage to the front of the dirty list.
43647: */
43648: static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
43649:   PCache *p = pPage->pCache;
43650: 
43651:   pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
43652:                 addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
43653:                 pPage->pgno));
43654:   if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
43655:     assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
43656:     assert( pPage->pDirtyPrev || pPage==p->pDirty );
43657:   
43658:     /* Update the PCache1.pSynced variable if necessary. */
43659:     if( p->pSynced==pPage ){
43660:       p->pSynced = pPage->pDirtyPrev;
43661:     }
43662:   
43663:     if( pPage->pDirtyNext ){
43664:       pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
43665:     }else{
43666:       assert( pPage==p->pDirtyTail );
43667:       p->pDirtyTail = pPage->pDirtyPrev;
43668:     }
43669:     if( pPage->pDirtyPrev ){
43670:       pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
43671:     }else{
43672:       /* If there are now no dirty pages in the cache, set eCreate to 2. 
43673:       ** This is an optimization that allows sqlite3PcacheFetch() to skip
43674:       ** searching for a dirty page to eject from the cache when it might
43675:       ** otherwise have to.  */
43676:       assert( pPage==p->pDirty );
43677:       p->pDirty = pPage->pDirtyNext;
43678:       assert( p->bPurgeable || p->eCreate==2 );
43679:       if( p->pDirty==0 ){         /*OPTIMIZATION-IF-TRUE*/
43680:         assert( p->bPurgeable==0 || p->eCreate==1 );
43681:         p->eCreate = 2;
43682:       }
43683:     }
43684:     pPage->pDirtyNext = 0;
43685:     pPage->pDirtyPrev = 0;
43686:   }
43687:   if( addRemove & PCACHE_DIRTYLIST_ADD ){
43688:     assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
43689:   
43690:     pPage->pDirtyNext = p->pDirty;
43691:     if( pPage->pDirtyNext ){
43692:       assert( pPage->pDirtyNext->pDirtyPrev==0 );
43693:       pPage->pDirtyNext->pDirtyPrev = pPage;
43694:     }else{
43695:       p->pDirtyTail = pPage;
43696:       if( p->bPurgeable ){
43697:         assert( p->eCreate==2 );
43698:         p->eCreate = 1;
43699:       }
43700:     }
43701:     p->pDirty = pPage;
43702: 
43703:     /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
43704:     ** pSynced to point to it. Checking the NEED_SYNC flag is an 
43705:     ** optimization, as if pSynced points to a page with the NEED_SYNC
43706:     ** flag set sqlite3PcacheFetchStress() searches through all newer 
43707:     ** entries of the dirty-list for a page with NEED_SYNC clear anyway.  */
43708:     if( !p->pSynced 
43709:      && 0==(pPage->flags&PGHDR_NEED_SYNC)   /*OPTIMIZATION-IF-FALSE*/
43710:     ){
43711:       p->pSynced = pPage;
43712:     }
43713:   }
43714:   pcacheDump(p);
43715: }
43716: 
43717: /*
43718: ** Wrapper around the pluggable caches xUnpin method. If the cache is
43719: ** being used for an in-memory database, this function is a no-op.
43720: */
43721: static void pcacheUnpin(PgHdr *p){
43722:   if( p->pCache->bPurgeable ){
43723:     pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
43724:     sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
43725:     pcacheDump(p->pCache);
43726:   }
43727: }
43728: 
43729: /*
43730: ** Compute the number of pages of cache requested.   p->szCache is the
43731: ** cache size requested by the "PRAGMA cache_size" statement.
43732: */
43733: static int numberOfCachePages(PCache *p){
43734:   if( p->szCache>=0 ){
43735:     /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
43736:     ** suggested cache size is set to N. */
43737:     return p->szCache;
43738:   }else{
43739:     /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
43740:     ** the number of cache pages is adjusted to use approximately abs(N*1024)
43741:     ** bytes of memory. */
43742:     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
43743:   }
43744: }
43745: 
43746: /*************************************************** General Interfaces ******
43747: **
43748: ** Initialize and shutdown the page cache subsystem. Neither of these 
43749: ** functions are threadsafe.
43750: */
43751: SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
43752:   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
43753:     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
43754:     ** built-in default page cache is used instead of the application defined
43755:     ** page cache. */
43756:     sqlite3PCacheSetDefault();
43757:   }
43758:   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
43759: }
43760: SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
43761:   if( sqlite3GlobalConfig.pcache2.xShutdown ){
43762:     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
43763:     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
43764:   }
43765: }
43766: 
43767: /*
43768: ** Return the size in bytes of a PCache object.
43769: */
43770: SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
43771: 
43772: /*
43773: ** Create a new PCache object. Storage space to hold the object
43774: ** has already been allocated and is passed in as the p pointer. 
43775: ** The caller discovers how much space needs to be allocated by 
43776: ** calling sqlite3PcacheSize().
43777: */
43778: SQLITE_PRIVATE int sqlite3PcacheOpen(
43779:   int szPage,                  /* Size of every page */
43780:   int szExtra,                 /* Extra space associated with each page */
43781:   int bPurgeable,              /* True if pages are on backing store */
43782:   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
43783:   void *pStress,               /* Argument to xStress */
43784:   PCache *p                    /* Preallocated space for the PCache */
43785: ){
43786:   memset(p, 0, sizeof(PCache));
43787:   p->szPage = 1;
43788:   p->szExtra = szExtra;
43789:   p->bPurgeable = bPurgeable;
43790:   p->eCreate = 2;
43791:   p->xStress = xStress;
43792:   p->pStress = pStress;
43793:   p->szCache = 100;
43794:   p->szSpill = 1;
43795:   pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
43796:   return sqlite3PcacheSetPageSize(p, szPage);
43797: }
43798: 
43799: /*
43800: ** Change the page size for PCache object. The caller must ensure that there
43801: ** are no outstanding page references when this function is called.
43802: */
43803: SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
43804:   assert( pCache->nRefSum==0 && pCache->pDirty==0 );
43805:   if( pCache->szPage ){
43806:     sqlite3_pcache *pNew;
43807:     pNew = sqlite3GlobalConfig.pcache2.xCreate(
43808:                 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
43809:                 pCache->bPurgeable
43810:     );
43811:     if( pNew==0 ) return SQLITE_NOMEM_BKPT;
43812:     sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
43813:     if( pCache->pCache ){
43814:       sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43815:     }
43816:     pCache->pCache = pNew;
43817:     pCache->szPage = szPage;
43818:     pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
43819:   }
43820:   return SQLITE_OK;
43821: }
43822: 
43823: /*
43824: ** Try to obtain a page from the cache.
43825: **
43826: ** This routine returns a pointer to an sqlite3_pcache_page object if
43827: ** such an object is already in cache, or if a new one is created.
43828: ** This routine returns a NULL pointer if the object was not in cache
43829: ** and could not be created.
43830: **
43831: ** The createFlags should be 0 to check for existing pages and should
43832: ** be 3 (not 1, but 3) to try to create a new page.
43833: **
43834: ** If the createFlag is 0, then NULL is always returned if the page
43835: ** is not already in the cache.  If createFlag is 1, then a new page
43836: ** is created only if that can be done without spilling dirty pages
43837: ** and without exceeding the cache size limit.
43838: **
43839: ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
43840: ** initialize the sqlite3_pcache_page object and convert it into a
43841: ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
43842: ** routines are split this way for performance reasons. When separated
43843: ** they can both (usually) operate without having to push values to
43844: ** the stack on entry and pop them back off on exit, which saves a
43845: ** lot of pushing and popping.
43846: */
43847: SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
43848:   PCache *pCache,       /* Obtain the page from this cache */
43849:   Pgno pgno,            /* Page number to obtain */
43850:   int createFlag        /* If true, create page if it does not exist already */
43851: ){
43852:   int eCreate;
43853:   sqlite3_pcache_page *pRes;
43854: 
43855:   assert( pCache!=0 );
43856:   assert( pCache->pCache!=0 );
43857:   assert( createFlag==3 || createFlag==0 );
43858:   assert( pgno>0 );
43859:   assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
43860: 
43861:   /* eCreate defines what to do if the page does not exist.
43862:   **    0     Do not allocate a new page.  (createFlag==0)
43863:   **    1     Allocate a new page if doing so is inexpensive.
43864:   **          (createFlag==1 AND bPurgeable AND pDirty)
43865:   **    2     Allocate a new page even it doing so is difficult.
43866:   **          (createFlag==1 AND !(bPurgeable AND pDirty)
43867:   */
43868:   eCreate = createFlag & pCache->eCreate;
43869:   assert( eCreate==0 || eCreate==1 || eCreate==2 );
43870:   assert( createFlag==0 || pCache->eCreate==eCreate );
43871:   assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
43872:   pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43873:   pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
43874:                createFlag?" create":"",pRes));
43875:   return pRes;
43876: }
43877: 
43878: /*
43879: ** If the sqlite3PcacheFetch() routine is unable to allocate a new
43880: ** page because no clean pages are available for reuse and the cache
43881: ** size limit has been reached, then this routine can be invoked to 
43882: ** try harder to allocate a page.  This routine might invoke the stress
43883: ** callback to spill dirty pages to the journal.  It will then try to
43884: ** allocate the new page and will only fail to allocate a new page on
43885: ** an OOM error.
43886: **
43887: ** This routine should be invoked only after sqlite3PcacheFetch() fails.
43888: */
43889: SQLITE_PRIVATE int sqlite3PcacheFetchStress(
43890:   PCache *pCache,                 /* Obtain the page from this cache */
43891:   Pgno pgno,                      /* Page number to obtain */
43892:   sqlite3_pcache_page **ppPage    /* Write result here */
43893: ){
43894:   PgHdr *pPg;
43895:   if( pCache->eCreate==2 ) return 0;
43896: 
43897:   if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
43898:     /* Find a dirty page to write-out and recycle. First try to find a 
43899:     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
43900:     ** cleared), but if that is not possible settle for any other 
43901:     ** unreferenced dirty page.
43902:     **
43903:     ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
43904:     ** flag is currently referenced, then the following may leave pSynced
43905:     ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
43906:     ** cleared). This is Ok, as pSynced is just an optimization.  */
43907:     for(pPg=pCache->pSynced; 
43908:         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
43909:         pPg=pPg->pDirtyPrev
43910:     );
43911:     pCache->pSynced = pPg;
43912:     if( !pPg ){
43913:       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
43914:     }
43915:     if( pPg ){
43916:       int rc;
43917: #ifdef SQLITE_LOG_CACHE_SPILL
43918:       sqlite3_log(SQLITE_FULL, 
43919:                   "spill page %d making room for %d - cache used: %d/%d",
43920:                   pPg->pgno, pgno,
43921:                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
43922:                 numberOfCachePages(pCache));
43923: #endif
43924:       pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
43925:       rc = pCache->xStress(pCache->pStress, pPg);
43926:       pcacheDump(pCache);
43927:       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
43928:         return rc;
43929:       }
43930:     }
43931:   }
43932:   *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
43933:   return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
43934: }
43935: 
43936: /*
43937: ** This is a helper routine for sqlite3PcacheFetchFinish()
43938: **
43939: ** In the uncommon case where the page being fetched has not been
43940: ** initialized, this routine is invoked to do the initialization.
43941: ** This routine is broken out into a separate function since it
43942: ** requires extra stack manipulation that can be avoided in the common
43943: ** case.
43944: */
43945: static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
43946:   PCache *pCache,             /* Obtain the page from this cache */
43947:   Pgno pgno,                  /* Page number obtained */
43948:   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
43949: ){
43950:   PgHdr *pPgHdr;
43951:   assert( pPage!=0 );
43952:   pPgHdr = (PgHdr*)pPage->pExtra;
43953:   assert( pPgHdr->pPage==0 );
43954:   memset(pPgHdr, 0, sizeof(PgHdr));
43955:   pPgHdr->pPage = pPage;
43956:   pPgHdr->pData = pPage->pBuf;
43957:   pPgHdr->pExtra = (void *)&pPgHdr[1];
43958:   memset(pPgHdr->pExtra, 0, pCache->szExtra);
43959:   pPgHdr->pCache = pCache;
43960:   pPgHdr->pgno = pgno;
43961:   pPgHdr->flags = PGHDR_CLEAN;
43962:   return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
43963: }
43964: 
43965: /*
43966: ** This routine converts the sqlite3_pcache_page object returned by
43967: ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
43968: ** must be called after sqlite3PcacheFetch() in order to get a usable
43969: ** result.
43970: */
43971: SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
43972:   PCache *pCache,             /* Obtain the page from this cache */
43973:   Pgno pgno,                  /* Page number obtained */
43974:   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
43975: ){
43976:   PgHdr *pPgHdr;
43977: 
43978:   assert( pPage!=0 );
43979:   pPgHdr = (PgHdr *)pPage->pExtra;
43980: 
43981:   if( !pPgHdr->pPage ){
43982:     return pcacheFetchFinishWithInit(pCache, pgno, pPage);
43983:   }
43984:   pCache->nRefSum++;
43985:   pPgHdr->nRef++;
43986:   assert( sqlite3PcachePageSanity(pPgHdr) );
43987:   return pPgHdr;
43988: }
43989: 
43990: /*
43991: ** Decrement the reference count on a page. If the page is clean and the
43992: ** reference count drops to 0, then it is made eligible for recycling.
43993: */
43994: SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
43995:   assert( p->nRef>0 );
43996:   p->pCache->nRefSum--;
43997:   if( (--p->nRef)==0 ){
43998:     if( p->flags&PGHDR_CLEAN ){
43999:       pcacheUnpin(p);
44000:     }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
44001:       /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
44002:       ** then page p is already at the head of the dirty list and the
44003:       ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
44004:       ** tag above.  */
44005:       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44006:     }
44007:   }
44008: }
44009: 
44010: /*
44011: ** Increase the reference count of a supplied page by 1.
44012: */
44013: SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
44014:   assert(p->nRef>0);
44015:   assert( sqlite3PcachePageSanity(p) );
44016:   p->nRef++;
44017:   p->pCache->nRefSum++;
44018: }
44019: 
44020: /*
44021: ** Drop a page from the cache. There must be exactly one reference to the
44022: ** page. This function deletes that reference, so after it returns the
44023: ** page pointed to by p is invalid.
44024: */
44025: SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
44026:   assert( p->nRef==1 );
44027:   assert( sqlite3PcachePageSanity(p) );
44028:   if( p->flags&PGHDR_DIRTY ){
44029:     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44030:   }
44031:   p->pCache->nRefSum--;
44032:   sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
44033: }
44034: 
44035: /*
44036: ** Make sure the page is marked as dirty. If it isn't dirty already,
44037: ** make it so.
44038: */
44039: SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
44040:   assert( p->nRef>0 );
44041:   assert( sqlite3PcachePageSanity(p) );
44042:   if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){    /*OPTIMIZATION-IF-FALSE*/
44043:     p->flags &= ~PGHDR_DONT_WRITE;
44044:     if( p->flags & PGHDR_CLEAN ){
44045:       p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
44046:       pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
44047:       assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
44048:       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
44049:     }
44050:     assert( sqlite3PcachePageSanity(p) );
44051:   }
44052: }
44053: 
44054: /*
44055: ** Make sure the page is marked as clean. If it isn't clean already,
44056: ** make it so.
44057: */
44058: SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
44059:   assert( sqlite3PcachePageSanity(p) );
44060:   if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
44061:     assert( (p->flags & PGHDR_CLEAN)==0 );
44062:     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
44063:     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44064:     p->flags |= PGHDR_CLEAN;
44065:     pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
44066:     assert( sqlite3PcachePageSanity(p) );
44067:     if( p->nRef==0 ){
44068:       pcacheUnpin(p);
44069:     }
44070:   }
44071: }
44072: 
44073: /*
44074: ** Make every page in the cache clean.
44075: */
44076: SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
44077:   PgHdr *p;
44078:   pcacheTrace(("%p.CLEAN-ALL\n",pCache));
44079:   while( (p = pCache->pDirty)!=0 ){
44080:     sqlite3PcacheMakeClean(p);
44081:   }
44082: }
44083: 
44084: /*
44085: ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
44086: */
44087: SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
44088:   PgHdr *p;
44089:   pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
44090:   for(p=pCache->pDirty; p; p=p->pDirtyNext){
44091:     p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
44092:   }
44093:   pCache->pSynced = pCache->pDirtyTail;
44094: }
44095: 
44096: /*
44097: ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
44098: */
44099: SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
44100:   PgHdr *p;
44101:   for(p=pCache->pDirty; p; p=p->pDirtyNext){
44102:     p->flags &= ~PGHDR_NEED_SYNC;
44103:   }
44104:   pCache->pSynced = pCache->pDirtyTail;
44105: }
44106: 
44107: /*
44108: ** Change the page number of page p to newPgno. 
44109: */
44110: SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
44111:   PCache *pCache = p->pCache;
44112:   assert( p->nRef>0 );
44113:   assert( newPgno>0 );
44114:   assert( sqlite3PcachePageSanity(p) );
44115:   pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
44116:   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
44117:   p->pgno = newPgno;
44118:   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
44119:     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
44120:   }
44121: }
44122: 
44123: /*
44124: ** Drop every cache entry whose page number is greater than "pgno". The
44125: ** caller must ensure that there are no outstanding references to any pages
44126: ** other than page 1 with a page number greater than pgno.
44127: **
44128: ** If there is a reference to page 1 and the pgno parameter passed to this
44129: ** function is 0, then the data area associated with page 1 is zeroed, but
44130: ** the page object is not dropped.
44131: */
44132: SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
44133:   if( pCache->pCache ){
44134:     PgHdr *p;
44135:     PgHdr *pNext;
44136:     pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
44137:     for(p=pCache->pDirty; p; p=pNext){
44138:       pNext = p->pDirtyNext;
44139:       /* This routine never gets call with a positive pgno except right
44140:       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
44141:       ** it must be that pgno==0.
44142:       */
44143:       assert( p->pgno>0 );
44144:       if( p->pgno>pgno ){
44145:         assert( p->flags&PGHDR_DIRTY );
44146:         sqlite3PcacheMakeClean(p);
44147:       }
44148:     }
44149:     if( pgno==0 && pCache->nRefSum ){
44150:       sqlite3_pcache_page *pPage1;
44151:       pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
44152:       if( ALWAYS(pPage1) ){  /* Page 1 is always available in cache, because
44153:                              ** pCache->nRefSum>0 */
44154:         memset(pPage1->pBuf, 0, pCache->szPage);
44155:         pgno = 1;
44156:       }
44157:     }
44158:     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
44159:   }
44160: }
44161: 
44162: /*
44163: ** Close a cache.
44164: */
44165: SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
44166:   assert( pCache->pCache!=0 );
44167:   pcacheTrace(("%p.CLOSE\n",pCache));
44168:   sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
44169: }
44170: 
44171: /* 
44172: ** Discard the contents of the cache.
44173: */
44174: SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
44175:   sqlite3PcacheTruncate(pCache, 0);
44176: }
44177: 
44178: /*
44179: ** Merge two lists of pages connected by pDirty and in pgno order.
44180: ** Do not bother fixing the pDirtyPrev pointers.
44181: */
44182: static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
44183:   PgHdr result, *pTail;
44184:   pTail = &result;
44185:   assert( pA!=0 && pB!=0 );
44186:   for(;;){
44187:     if( pA->pgno<pB->pgno ){
44188:       pTail->pDirty = pA;
44189:       pTail = pA;
44190:       pA = pA->pDirty;
44191:       if( pA==0 ){
44192:         pTail->pDirty = pB;
44193:         break;
44194:       }
44195:     }else{
44196:       pTail->pDirty = pB;
44197:       pTail = pB;
44198:       pB = pB->pDirty;
44199:       if( pB==0 ){
44200:         pTail->pDirty = pA;
44201:         break;
44202:       }
44203:     }
44204:   }
44205:   return result.pDirty;
44206: }
44207: 
44208: /*
44209: ** Sort the list of pages in accending order by pgno.  Pages are
44210: ** connected by pDirty pointers.  The pDirtyPrev pointers are
44211: ** corrupted by this sort.
44212: **
44213: ** Since there cannot be more than 2^31 distinct pages in a database,
44214: ** there cannot be more than 31 buckets required by the merge sorter.
44215: ** One extra bucket is added to catch overflow in case something
44216: ** ever changes to make the previous sentence incorrect.
44217: */
44218: #define N_SORT_BUCKET  32
44219: static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
44220:   PgHdr *a[N_SORT_BUCKET], *p;
44221:   int i;
44222:   memset(a, 0, sizeof(a));
44223:   while( pIn ){
44224:     p = pIn;
44225:     pIn = p->pDirty;
44226:     p->pDirty = 0;
44227:     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
44228:       if( a[i]==0 ){
44229:         a[i] = p;
44230:         break;
44231:       }else{
44232:         p = pcacheMergeDirtyList(a[i], p);
44233:         a[i] = 0;
44234:       }
44235:     }
44236:     if( NEVER(i==N_SORT_BUCKET-1) ){
44237:       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
44238:       ** the input list.  But that is impossible.
44239:       */
44240:       a[i] = pcacheMergeDirtyList(a[i], p);
44241:     }
44242:   }
44243:   p = a[0];
44244:   for(i=1; i<N_SORT_BUCKET; i++){
44245:     if( a[i]==0 ) continue;
44246:     p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
44247:   }
44248:   return p;
44249: }
44250: 
44251: /*
44252: ** Return a list of all dirty pages in the cache, sorted by page number.
44253: */
44254: SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
44255:   PgHdr *p;
44256:   for(p=pCache->pDirty; p; p=p->pDirtyNext){
44257:     p->pDirty = p->pDirtyNext;
44258:   }
44259:   return pcacheSortDirtyList(pCache->pDirty);
44260: }
44261: 
44262: /* 
44263: ** Return the total number of references to all pages held by the cache.
44264: **
44265: ** This is not the total number of pages referenced, but the sum of the
44266: ** reference count for all pages.
44267: */
44268: SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
44269:   return pCache->nRefSum;
44270: }
44271: 
44272: /*
44273: ** Return the number of references to the page supplied as an argument.
44274: */
44275: SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
44276:   return p->nRef;
44277: }
44278: 
44279: /* 
44280: ** Return the total number of pages in the cache.
44281: */
44282: SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
44283:   assert( pCache->pCache!=0 );
44284:   return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
44285: }
44286: 
44287: #ifdef SQLITE_TEST
44288: /*
44289: ** Get the suggested cache-size value.
44290: */
44291: SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
44292:   return numberOfCachePages(pCache);
44293: }
44294: #endif
44295: 
44296: /*
44297: ** Set the suggested cache-size value.
44298: */
44299: SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
44300:   assert( pCache->pCache!=0 );
44301:   pCache->szCache = mxPage;
44302:   sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
44303:                                          numberOfCachePages(pCache));
44304: }
44305: 
44306: /*
44307: ** Set the suggested cache-spill value.  Make no changes if if the
44308: ** argument is zero.  Return the effective cache-spill size, which will
44309: ** be the larger of the szSpill and szCache.
44310: */
44311: SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
44312:   int res;
44313:   assert( p->pCache!=0 );
44314:   if( mxPage ){
44315:     if( mxPage<0 ){
44316:       mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
44317:     }
44318:     p->szSpill = mxPage;
44319:   }
44320:   res = numberOfCachePages(p);
44321:   if( res<p->szSpill ) res = p->szSpill; 
44322:   return res;
44323: }
44324: 
44325: /*
44326: ** Free up as much memory as possible from the page cache.
44327: */
44328: SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
44329:   assert( pCache->pCache!=0 );
44330:   sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
44331: }
44332: 
44333: /*
44334: ** Return the size of the header added by this middleware layer
44335: ** in the page-cache hierarchy.
44336: */
44337: SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
44338: 
44339: /*
44340: ** Return the number of dirty pages currently in the cache, as a percentage
44341: ** of the configured cache size.
44342: */
44343: SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
44344:   PgHdr *pDirty;
44345:   int nDirty = 0;
44346:   int nCache = numberOfCachePages(pCache);
44347:   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
44348:   return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
44349: }
44350: 
44351: #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
44352: /*
44353: ** For all dirty pages currently in the cache, invoke the specified
44354: ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
44355: ** defined.
44356: */
44357: SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
44358:   PgHdr *pDirty;
44359:   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
44360:     xIter(pDirty);
44361:   }
44362: }
44363: #endif
44364: 
44365: /************** End of pcache.c **********************************************/
44366: /************** Begin file pcache1.c *****************************************/
44367: /*
44368: ** 2008 November 05
44369: **
44370: ** The author disclaims copyright to this source code.  In place of
44371: ** a legal notice, here is a blessing:
44372: **
44373: **    May you do good and not evil.
44374: **    May you find forgiveness for yourself and forgive others.
44375: **    May you share freely, never taking more than you give.
44376: **
44377: *************************************************************************
44378: **
44379: ** This file implements the default page cache implementation (the
44380: ** sqlite3_pcache interface). It also contains part of the implementation
44381: ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
44382: ** If the default page cache implementation is overridden, then neither of
44383: ** these two features are available.
44384: **
44385: ** A Page cache line looks like this:
44386: **
44387: **  -------------------------------------------------------------
44388: **  |  database page content   |  PgHdr1  |  MemPage  |  PgHdr  |
44389: **  -------------------------------------------------------------
44390: **
44391: ** The database page content is up front (so that buffer overreads tend to
44392: ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions).   MemPage
44393: ** is the extension added by the btree.c module containing information such
44394: ** as the database page number and how that database page is used.  PgHdr
44395: ** is added by the pcache.c layer and contains information used to keep track
44396: ** of which pages are "dirty".  PgHdr1 is an extension added by this
44397: ** module (pcache1.c).  The PgHdr1 header is a subclass of sqlite3_pcache_page.
44398: ** PgHdr1 contains information needed to look up a page by its page number.
44399: ** The superclass sqlite3_pcache_page.pBuf points to the start of the
44400: ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
44401: **
44402: ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
44403: ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size).  The
44404: ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
44405: ** size can vary according to architecture, compile-time options, and
44406: ** SQLite library version number.
44407: **
44408: ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
44409: ** using a separate memory allocation from the database page content.  This
44410: ** seeks to overcome the "clownshoe" problem (also called "internal
44411: ** fragmentation" in academic literature) of allocating a few bytes more
44412: ** than a power of two with the memory allocator rounding up to the next
44413: ** power of two, and leaving the rounded-up space unused.
44414: **
44415: ** This module tracks pointers to PgHdr1 objects.  Only pcache.c communicates
44416: ** with this module.  Information is passed back and forth as PgHdr1 pointers.
44417: **
44418: ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
44419: ** The btree.c module deals with pointers to MemPage objects.
44420: **
44421: ** SOURCE OF PAGE CACHE MEMORY:
44422: **
44423: ** Memory for a page might come from any of three sources:
44424: **
44425: **    (1)  The general-purpose memory allocator - sqlite3Malloc()
44426: **    (2)  Global page-cache memory provided using sqlite3_config() with
44427: **         SQLITE_CONFIG_PAGECACHE.
44428: **    (3)  PCache-local bulk allocation.
44429: **
44430: ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
44431: ** that is allocated when the page cache is created.  The size of the local
44432: ** bulk allocation can be adjusted using 
44433: **
44434: **     sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
44435: **
44436: ** If N is positive, then N pages worth of memory are allocated using a single
44437: ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
44438: ** Or if N is negative, then -1024*N bytes of memory are allocated and used
44439: ** for as many pages as can be accomodated.
44440: **
44441: ** Only one of (2) or (3) can be used.  Once the memory available to (2) or
44442: ** (3) is exhausted, subsequent allocations fail over to the general-purpose
44443: ** memory allocator (1).
44444: **
44445: ** Earlier versions of SQLite used only methods (1) and (2).  But experiments
44446: ** show that method (3) with N==100 provides about a 5% performance boost for
44447: ** common workloads.
44448: */
44449: /* #include "sqliteInt.h" */
44450: 
44451: typedef struct PCache1 PCache1;
44452: typedef struct PgHdr1 PgHdr1;
44453: typedef struct PgFreeslot PgFreeslot;
44454: typedef struct PGroup PGroup;
44455: 
44456: /*
44457: ** Each cache entry is represented by an instance of the following 
44458: ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
44459: ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
44460: ** in memory.
44461: */
44462: struct PgHdr1 {
44463:   sqlite3_pcache_page page;      /* Base class. Must be first. pBuf & pExtra */
44464:   unsigned int iKey;             /* Key value (page number) */
44465:   u8 isPinned;                   /* Page in use, not on the LRU list */
44466:   u8 isBulkLocal;                /* This page from bulk local storage */
44467:   u8 isAnchor;                   /* This is the PGroup.lru element */
44468:   PgHdr1 *pNext;                 /* Next in hash table chain */
44469:   PCache1 *pCache;               /* Cache that currently owns this page */
44470:   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
44471:   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
44472: };
44473: 
44474: /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
44475: ** of one or more PCaches that are able to recycle each other's unpinned
44476: ** pages when they are under memory pressure.  A PGroup is an instance of
44477: ** the following object.
44478: **
44479: ** This page cache implementation works in one of two modes:
44480: **
44481: **   (1)  Every PCache is the sole member of its own PGroup.  There is
44482: **        one PGroup per PCache.
44483: **
44484: **   (2)  There is a single global PGroup that all PCaches are a member
44485: **        of.
44486: **
44487: ** Mode 1 uses more memory (since PCache instances are not able to rob
44488: ** unused pages from other PCaches) but it also operates without a mutex,
44489: ** and is therefore often faster.  Mode 2 requires a mutex in order to be
44490: ** threadsafe, but recycles pages more efficiently.
44491: **
44492: ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
44493: ** PGroup which is the pcache1.grp global variable and its mutex is
44494: ** SQLITE_MUTEX_STATIC_LRU.
44495: */
44496: struct PGroup {
44497:   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
44498:   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
44499:   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
44500:   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
44501:   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
44502:   PgHdr1 lru;                    /* The beginning and end of the LRU list */
44503: };
44504: 
44505: /* Each page cache is an instance of the following object.  Every
44506: ** open database file (including each in-memory database and each
44507: ** temporary or transient database) has a single page cache which
44508: ** is an instance of this object.
44509: **
44510: ** Pointers to structures of this type are cast and returned as 
44511: ** opaque sqlite3_pcache* handles.
44512: */
44513: struct PCache1 {
44514:   /* Cache configuration parameters. Page size (szPage) and the purgeable
44515:   ** flag (bPurgeable) are set when the cache is created. nMax may be 
44516:   ** modified at any time by a call to the pcache1Cachesize() method.
44517:   ** The PGroup mutex must be held when accessing nMax.
44518:   */
44519:   PGroup *pGroup;                     /* PGroup this cache belongs to */
44520:   int szPage;                         /* Size of database content section */
44521:   int szExtra;                        /* sizeof(MemPage)+sizeof(PgHdr) */
44522:   int szAlloc;                        /* Total size of one pcache line */
44523:   int bPurgeable;                     /* True if cache is purgeable */
44524:   unsigned int nMin;                  /* Minimum number of pages reserved */
44525:   unsigned int nMax;                  /* Configured "cache_size" value */
44526:   unsigned int n90pct;                /* nMax*9/10 */
44527:   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
44528: 
44529:   /* Hash table of all pages. The following variables may only be accessed
44530:   ** when the accessor is holding the PGroup mutex.
44531:   */
44532:   unsigned int nRecyclable;           /* Number of pages in the LRU list */
44533:   unsigned int nPage;                 /* Total number of pages in apHash */
44534:   unsigned int nHash;                 /* Number of slots in apHash[] */
44535:   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
44536:   PgHdr1 *pFree;                      /* List of unused pcache-local pages */
44537:   void *pBulk;                        /* Bulk memory used by pcache-local */
44538: };
44539: 
44540: /*
44541: ** Free slots in the allocator used to divide up the global page cache
44542: ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
44543: */
44544: struct PgFreeslot {
44545:   PgFreeslot *pNext;  /* Next free slot */
44546: };
44547: 
44548: /*
44549: ** Global data used by this cache.
44550: */
44551: static SQLITE_WSD struct PCacheGlobal {
44552:   PGroup grp;                    /* The global PGroup for mode (2) */
44553: 
44554:   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
44555:   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
44556:   ** fixed at sqlite3_initialize() time and do not require mutex protection.
44557:   ** The nFreeSlot and pFree values do require mutex protection.
44558:   */
44559:   int isInit;                    /* True if initialized */
44560:   int separateCache;             /* Use a new PGroup for each PCache */
44561:   int nInitPage;                 /* Initial bulk allocation size */   
44562:   int szSlot;                    /* Size of each free slot */
44563:   int nSlot;                     /* The number of pcache slots */
44564:   int nReserve;                  /* Try to keep nFreeSlot above this */
44565:   void *pStart, *pEnd;           /* Bounds of global page cache memory */
44566:   /* Above requires no mutex.  Use mutex below for variable that follow. */
44567:   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
44568:   PgFreeslot *pFree;             /* Free page blocks */
44569:   int nFreeSlot;                 /* Number of unused pcache slots */
44570:   /* The following value requires a mutex to change.  We skip the mutex on
44571:   ** reading because (1) most platforms read a 32-bit integer atomically and
44572:   ** (2) even if an incorrect value is read, no great harm is done since this
44573:   ** is really just an optimization. */
44574:   int bUnderPressure;            /* True if low on PAGECACHE memory */
44575: } pcache1_g;
44576: 
44577: /*
44578: ** All code in this file should access the global structure above via the
44579: ** alias "pcache1". This ensures that the WSD emulation is used when
44580: ** compiling for systems that do not support real WSD.
44581: */
44582: #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
44583: 
44584: /*
44585: ** Macros to enter and leave the PCache LRU mutex.
44586: */
44587: #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
44588: # define pcache1EnterMutex(X)  assert((X)->mutex==0)
44589: # define pcache1LeaveMutex(X)  assert((X)->mutex==0)
44590: # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
44591: #else
44592: # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
44593: # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
44594: # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
44595: #endif
44596: 
44597: /******************************************************************************/
44598: /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
44599: 
44600: 
44601: /*
44602: ** This function is called during initialization if a static buffer is 
44603: ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
44604: ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
44605: ** enough to contain 'n' buffers of 'sz' bytes each.
44606: **
44607: ** This routine is called from sqlite3_initialize() and so it is guaranteed
44608: ** to be serialized already.  There is no need for further mutexing.
44609: */
44610: SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
44611:   if( pcache1.isInit ){
44612:     PgFreeslot *p;
44613:     if( pBuf==0 ) sz = n = 0;
44614:     sz = ROUNDDOWN8(sz);
44615:     pcache1.szSlot = sz;
44616:     pcache1.nSlot = pcache1.nFreeSlot = n;
44617:     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
44618:     pcache1.pStart = pBuf;
44619:     pcache1.pFree = 0;
44620:     pcache1.bUnderPressure = 0;
44621:     while( n-- ){
44622:       p = (PgFreeslot*)pBuf;
44623:       p->pNext = pcache1.pFree;
44624:       pcache1.pFree = p;
44625:       pBuf = (void*)&((char*)pBuf)[sz];
44626:     }
44627:     pcache1.pEnd = pBuf;
44628:   }
44629: }
44630: 
44631: /*
44632: ** Try to initialize the pCache->pFree and pCache->pBulk fields.  Return
44633: ** true if pCache->pFree ends up containing one or more free pages.
44634: */
44635: static int pcache1InitBulk(PCache1 *pCache){
44636:   i64 szBulk;
44637:   char *zBulk;
44638:   if( pcache1.nInitPage==0 ) return 0;
44639:   /* Do not bother with a bulk allocation if the cache size very small */
44640:   if( pCache->nMax<3 ) return 0;
44641:   sqlite3BeginBenignMalloc();
44642:   if( pcache1.nInitPage>0 ){
44643:     szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
44644:   }else{
44645:     szBulk = -1024 * (i64)pcache1.nInitPage;
44646:   }
44647:   if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
44648:     szBulk = pCache->szAlloc*pCache->nMax;
44649:   }
44650:   zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
44651:   sqlite3EndBenignMalloc();
44652:   if( zBulk ){
44653:     int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
44654:     int i;
44655:     for(i=0; i<nBulk; i++){
44656:       PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
44657:       pX->page.pBuf = zBulk;
44658:       pX->page.pExtra = &pX[1];
44659:       pX->isBulkLocal = 1;
44660:       pX->isAnchor = 0;
44661:       pX->pNext = pCache->pFree;
44662:       pCache->pFree = pX;
44663:       zBulk += pCache->szAlloc;
44664:     }
44665:   }
44666:   return pCache->pFree!=0;
44667: }
44668: 
44669: /*
44670: ** Malloc function used within this file to allocate space from the buffer
44671: ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
44672: ** such buffer exists or there is no space left in it, this function falls 
44673: ** back to sqlite3Malloc().
44674: **
44675: ** Multiple threads can run this routine at the same time.  Global variables
44676: ** in pcache1 need to be protected via mutex.
44677: */
44678: static void *pcache1Alloc(int nByte){
44679:   void *p = 0;
44680:   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
44681:   if( nByte<=pcache1.szSlot ){
44682:     sqlite3_mutex_enter(pcache1.mutex);
44683:     p = (PgHdr1 *)pcache1.pFree;
44684:     if( p ){
44685:       pcache1.pFree = pcache1.pFree->pNext;
44686:       pcache1.nFreeSlot--;
44687:       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44688:       assert( pcache1.nFreeSlot>=0 );
44689:       sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
44690:       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
44691:     }
44692:     sqlite3_mutex_leave(pcache1.mutex);
44693:   }
44694:   if( p==0 ){
44695:     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
44696:     ** it from sqlite3Malloc instead.
44697:     */
44698:     p = sqlite3Malloc(nByte);
44699: #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44700:     if( p ){
44701:       int sz = sqlite3MallocSize(p);
44702:       sqlite3_mutex_enter(pcache1.mutex);
44703:       sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
44704:       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
44705:       sqlite3_mutex_leave(pcache1.mutex);
44706:     }
44707: #endif
44708:     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
44709:   }
44710:   return p;
44711: }
44712: 
44713: /*
44714: ** Free an allocated buffer obtained from pcache1Alloc().
44715: */
44716: static void pcache1Free(void *p){
44717:   if( p==0 ) return;
44718:   if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
44719:     PgFreeslot *pSlot;
44720:     sqlite3_mutex_enter(pcache1.mutex);
44721:     sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
44722:     pSlot = (PgFreeslot*)p;
44723:     pSlot->pNext = pcache1.pFree;
44724:     pcache1.pFree = pSlot;
44725:     pcache1.nFreeSlot++;
44726:     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44727:     assert( pcache1.nFreeSlot<=pcache1.nSlot );
44728:     sqlite3_mutex_leave(pcache1.mutex);
44729:   }else{
44730:     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44731:     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
44732: #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44733:     {
44734:       int nFreed = 0;
44735:       nFreed = sqlite3MallocSize(p);
44736:       sqlite3_mutex_enter(pcache1.mutex);
44737:       sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
44738:       sqlite3_mutex_leave(pcache1.mutex);
44739:     }
44740: #endif
44741:     sqlite3_free(p);
44742:   }
44743: }
44744: 
44745: #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44746: /*
44747: ** Return the size of a pcache allocation
44748: */
44749: static int pcache1MemSize(void *p){
44750:   if( p>=pcache1.pStart && p<pcache1.pEnd ){
44751:     return pcache1.szSlot;
44752:   }else{
44753:     int iSize;
44754:     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
44755:     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
44756:     iSize = sqlite3MallocSize(p);
44757:     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
44758:     return iSize;
44759:   }
44760: }
44761: #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
44762: 
44763: /*
44764: ** Allocate a new page object initially associated with cache pCache.
44765: */
44766: static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
44767:   PgHdr1 *p = 0;
44768:   void *pPg;
44769: 
44770:   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44771:   if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
44772:     p = pCache->pFree;
44773:     pCache->pFree = p->pNext;
44774:     p->pNext = 0;
44775:   }else{
44776: #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44777:     /* The group mutex must be released before pcache1Alloc() is called. This
44778:     ** is because it might call sqlite3_release_memory(), which assumes that 
44779:     ** this mutex is not held. */
44780:     assert( pcache1.separateCache==0 );
44781:     assert( pCache->pGroup==&pcache1.grp );
44782:     pcache1LeaveMutex(pCache->pGroup);
44783: #endif
44784:     if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
44785: #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44786:     pPg = pcache1Alloc(pCache->szPage);
44787:     p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
44788:     if( !pPg || !p ){
44789:       pcache1Free(pPg);
44790:       sqlite3_free(p);
44791:       pPg = 0;
44792:     }
44793: #else
44794:     pPg = pcache1Alloc(pCache->szAlloc);
44795:     p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
44796: #endif
44797:     if( benignMalloc ){ sqlite3EndBenignMalloc(); }
44798: #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44799:     pcache1EnterMutex(pCache->pGroup);
44800: #endif
44801:     if( pPg==0 ) return 0;
44802:     p->page.pBuf = pPg;
44803:     p->page.pExtra = &p[1];
44804:     p->isBulkLocal = 0;
44805:     p->isAnchor = 0;
44806:   }
44807:   if( pCache->bPurgeable ){
44808:     pCache->pGroup->nCurrentPage++;
44809:   }
44810:   return p;
44811: }
44812: 
44813: /*
44814: ** Free a page object allocated by pcache1AllocPage().
44815: */
44816: static void pcache1FreePage(PgHdr1 *p){
44817:   PCache1 *pCache;
44818:   assert( p!=0 );
44819:   pCache = p->pCache;
44820:   assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
44821:   if( p->isBulkLocal ){
44822:     p->pNext = pCache->pFree;
44823:     pCache->pFree = p;
44824:   }else{
44825:     pcache1Free(p->page.pBuf);
44826: #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44827:     sqlite3_free(p);
44828: #endif
44829:   }
44830:   if( pCache->bPurgeable ){
44831:     pCache->pGroup->nCurrentPage--;
44832:   }
44833: }
44834: 
44835: /*
44836: ** Malloc function used by SQLite to obtain space from the buffer configured
44837: ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
44838: ** exists, this function falls back to sqlite3Malloc().
44839: */
44840: SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
44841:   return pcache1Alloc(sz);
44842: }
44843: 
44844: /*
44845: ** Free an allocated buffer obtained from sqlite3PageMalloc().
44846: */
44847: SQLITE_PRIVATE void sqlite3PageFree(void *p){
44848:   pcache1Free(p);
44849: }
44850: 
44851: 
44852: /*
44853: ** Return true if it desirable to avoid allocating a new page cache
44854: ** entry.
44855: **
44856: ** If memory was allocated specifically to the page cache using
44857: ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
44858: ** it is desirable to avoid allocating a new page cache entry because
44859: ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
44860: ** for all page cache needs and we should not need to spill the
44861: ** allocation onto the heap.
44862: **
44863: ** Or, the heap is used for all page cache memory but the heap is
44864: ** under memory pressure, then again it is desirable to avoid
44865: ** allocating a new page cache entry in order to avoid stressing
44866: ** the heap even further.
44867: */
44868: static int pcache1UnderMemoryPressure(PCache1 *pCache){
44869:   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
44870:     return pcache1.bUnderPressure;
44871:   }else{
44872:     return sqlite3HeapNearlyFull();
44873:   }
44874: }
44875: 
44876: /******************************************************************************/
44877: /******** General Implementation Functions ************************************/
44878: 
44879: /*
44880: ** This function is used to resize the hash table used by the cache passed
44881: ** as the first argument.
44882: **
44883: ** The PCache mutex must be held when this function is called.
44884: */
44885: static void pcache1ResizeHash(PCache1 *p){
44886:   PgHdr1 **apNew;
44887:   unsigned int nNew;
44888:   unsigned int i;
44889: 
44890:   assert( sqlite3_mutex_held(p->pGroup->mutex) );
44891: 
44892:   nNew = p->nHash*2;
44893:   if( nNew<256 ){
44894:     nNew = 256;
44895:   }
44896: 
44897:   pcache1LeaveMutex(p->pGroup);
44898:   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
44899:   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
44900:   if( p->nHash ){ sqlite3EndBenignMalloc(); }
44901:   pcache1EnterMutex(p->pGroup);
44902:   if( apNew ){
44903:     for(i=0; i<p->nHash; i++){
44904:       PgHdr1 *pPage;
44905:       PgHdr1 *pNext = p->apHash[i];
44906:       while( (pPage = pNext)!=0 ){
44907:         unsigned int h = pPage->iKey % nNew;
44908:         pNext = pPage->pNext;
44909:         pPage->pNext = apNew[h];
44910:         apNew[h] = pPage;
44911:       }
44912:     }
44913:     sqlite3_free(p->apHash);
44914:     p->apHash = apNew;
44915:     p->nHash = nNew;
44916:   }
44917: }
44918: 
44919: /*
44920: ** This function is used internally to remove the page pPage from the 
44921: ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
44922: ** LRU list, then this function is a no-op.
44923: **
44924: ** The PGroup mutex must be held when this function is called.
44925: */
44926: static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
44927:   PCache1 *pCache;
44928: 
44929:   assert( pPage!=0 );
44930:   assert( pPage->isPinned==0 );
44931:   pCache = pPage->pCache;
44932:   assert( pPage->pLruNext );
44933:   assert( pPage->pLruPrev );
44934:   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44935:   pPage->pLruPrev->pLruNext = pPage->pLruNext;
44936:   pPage->pLruNext->pLruPrev = pPage->pLruPrev;
44937:   pPage->pLruNext = 0;
44938:   pPage->pLruPrev = 0;
44939:   pPage->isPinned = 1;
44940:   assert( pPage->isAnchor==0 );
44941:   assert( pCache->pGroup->lru.isAnchor==1 );
44942:   pCache->nRecyclable--;
44943:   return pPage;
44944: }
44945: 
44946: 
44947: /*
44948: ** Remove the page supplied as an argument from the hash table 
44949: ** (PCache1.apHash structure) that it is currently stored in.
44950: ** Also free the page if freePage is true.
44951: **
44952: ** The PGroup mutex must be held when this function is called.
44953: */
44954: static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
44955:   unsigned int h;
44956:   PCache1 *pCache = pPage->pCache;
44957:   PgHdr1 **pp;
44958: 
44959:   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44960:   h = pPage->iKey % pCache->nHash;
44961:   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
44962:   *pp = (*pp)->pNext;
44963: 
44964:   pCache->nPage--;
44965:   if( freeFlag ) pcache1FreePage(pPage);
44966: }
44967: 
44968: /*
44969: ** If there are currently more than nMaxPage pages allocated, try
44970: ** to recycle pages to reduce the number allocated to nMaxPage.
44971: */
44972: static void pcache1EnforceMaxPage(PCache1 *pCache){
44973:   PGroup *pGroup = pCache->pGroup;
44974:   PgHdr1 *p;
44975:   assert( sqlite3_mutex_held(pGroup->mutex) );
44976:   while( pGroup->nCurrentPage>pGroup->nMaxPage
44977:       && (p=pGroup->lru.pLruPrev)->isAnchor==0
44978:   ){
44979:     assert( p->pCache->pGroup==pGroup );
44980:     assert( p->isPinned==0 );
44981:     pcache1PinPage(p);
44982:     pcache1RemoveFromHash(p, 1);
44983:   }
44984:   if( pCache->nPage==0 && pCache->pBulk ){
44985:     sqlite3_free(pCache->pBulk);
44986:     pCache->pBulk = pCache->pFree = 0;
44987:   }
44988: }
44989: 
44990: /*
44991: ** Discard all pages from cache pCache with a page number (key value) 
44992: ** greater than or equal to iLimit. Any pinned pages that meet this 
44993: ** criteria are unpinned before they are discarded.
44994: **
44995: ** The PCache mutex must be held when this function is called.
44996: */
44997: static void pcache1TruncateUnsafe(
44998:   PCache1 *pCache,             /* The cache to truncate */
44999:   unsigned int iLimit          /* Drop pages with this pgno or larger */
45000: ){
45001:   TESTONLY( int nPage = 0; )  /* To assert pCache->nPage is correct */
45002:   unsigned int h, iStop;
45003:   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
45004:   assert( pCache->iMaxKey >= iLimit );
45005:   assert( pCache->nHash > 0 );
45006:   if( pCache->iMaxKey - iLimit < pCache->nHash ){
45007:     /* If we are just shaving the last few pages off the end of the
45008:     ** cache, then there is no point in scanning the entire hash table.
45009:     ** Only scan those hash slots that might contain pages that need to
45010:     ** be removed. */
45011:     h = iLimit % pCache->nHash;
45012:     iStop = pCache->iMaxKey % pCache->nHash;
45013:     TESTONLY( nPage = -10; )  /* Disable the pCache->nPage validity check */
45014:   }else{
45015:     /* This is the general case where many pages are being removed.
45016:     ** It is necessary to scan the entire hash table */
45017:     h = pCache->nHash/2;
45018:     iStop = h - 1;
45019:   }
45020:   for(;;){
45021:     PgHdr1 **pp;
45022:     PgHdr1 *pPage;
45023:     assert( h<pCache->nHash );
45024:     pp = &pCache->apHash[h]; 
45025:     while( (pPage = *pp)!=0 ){
45026:       if( pPage->iKey>=iLimit ){
45027:         pCache->nPage--;
45028:         *pp = pPage->pNext;
45029:         if( !pPage->isPinned ) pcache1PinPage(pPage);
45030:         pcache1FreePage(pPage);
45031:       }else{
45032:         pp = &pPage->pNext;
45033:         TESTONLY( if( nPage>=0 ) nPage++; )
45034:       }
45035:     }
45036:     if( h==iStop ) break;
45037:     h = (h+1) % pCache->nHash;
45038:   }
45039:   assert( nPage<0 || pCache->nPage==(unsigned)nPage );
45040: }
45041: 
45042: /******************************************************************************/
45043: /******** sqlite3_pcache Methods **********************************************/
45044: 
45045: /*
45046: ** Implementation of the sqlite3_pcache.xInit method.
45047: */
45048: static int pcache1Init(void *NotUsed){
45049:   UNUSED_PARAMETER(NotUsed);
45050:   assert( pcache1.isInit==0 );
45051:   memset(&pcache1, 0, sizeof(pcache1));
45052: 
45053: 
45054:   /*
45055:   ** The pcache1.separateCache variable is true if each PCache has its own
45056:   ** private PGroup (mode-1).  pcache1.separateCache is false if the single
45057:   ** PGroup in pcache1.grp is used for all page caches (mode-2).
45058:   **
45059:   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
45060:   **
45061:   **   *  Use a unified cache in single-threaded applications that have
45062:   **      configured a start-time buffer for use as page-cache memory using
45063:   **      sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL 
45064:   **      pBuf argument.
45065:   **
45066:   **   *  Otherwise use separate caches (mode-1)
45067:   */
45068: #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
45069:   pcache1.separateCache = 0;
45070: #elif SQLITE_THREADSAFE
45071:   pcache1.separateCache = sqlite3GlobalConfig.pPage==0
45072:                           || sqlite3GlobalConfig.bCoreMutex>0;
45073: #else
45074:   pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
45075: #endif
45076: 
45077: #if SQLITE_THREADSAFE
45078:   if( sqlite3GlobalConfig.bCoreMutex ){
45079:     pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
45080:     pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
45081:   }
45082: #endif
45083:   if( pcache1.separateCache
45084:    && sqlite3GlobalConfig.nPage!=0
45085:    && sqlite3GlobalConfig.pPage==0
45086:   ){
45087:     pcache1.nInitPage = sqlite3GlobalConfig.nPage;
45088:   }else{
45089:     pcache1.nInitPage = 0;
45090:   }
45091:   pcache1.grp.mxPinned = 10;
45092:   pcache1.isInit = 1;
45093:   return SQLITE_OK;
45094: }
45095: 
45096: /*
45097: ** Implementation of the sqlite3_pcache.xShutdown method.
45098: ** Note that the static mutex allocated in xInit does 
45099: ** not need to be freed.
45100: */
45101: static void pcache1Shutdown(void *NotUsed){
45102:   UNUSED_PARAMETER(NotUsed);
45103:   assert( pcache1.isInit!=0 );
45104:   memset(&pcache1, 0, sizeof(pcache1));
45105: }
45106: 
45107: /* forward declaration */
45108: static void pcache1Destroy(sqlite3_pcache *p);
45109: 
45110: /*
45111: ** Implementation of the sqlite3_pcache.xCreate method.
45112: **
45113: ** Allocate a new cache.
45114: */
45115: static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
45116:   PCache1 *pCache;      /* The newly created page cache */
45117:   PGroup *pGroup;       /* The group the new page cache will belong to */
45118:   int sz;               /* Bytes of memory required to allocate the new cache */
45119: 
45120:   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
45121:   assert( szExtra < 300 );
45122: 
45123:   sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
45124:   pCache = (PCache1 *)sqlite3MallocZero(sz);
45125:   if( pCache ){
45126:     if( pcache1.separateCache ){
45127:       pGroup = (PGroup*)&pCache[1];
45128:       pGroup->mxPinned = 10;
45129:     }else{
45130:       pGroup = &pcache1.grp;
45131:     }
45132:     if( pGroup->lru.isAnchor==0 ){
45133:       pGroup->lru.isAnchor = 1;
45134:       pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
45135:     }
45136:     pCache->pGroup = pGroup;
45137:     pCache->szPage = szPage;
45138:     pCache->szExtra = szExtra;
45139:     pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
45140:     pCache->bPurgeable = (bPurgeable ? 1 : 0);
45141:     pcache1EnterMutex(pGroup);
45142:     pcache1ResizeHash(pCache);
45143:     if( bPurgeable ){
45144:       pCache->nMin = 10;
45145:       pGroup->nMinPage += pCache->nMin;
45146:       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45147:     }
45148:     pcache1LeaveMutex(pGroup);
45149:     if( pCache->nHash==0 ){
45150:       pcache1Destroy((sqlite3_pcache*)pCache);
45151:       pCache = 0;
45152:     }
45153:   }
45154:   return (sqlite3_pcache *)pCache;
45155: }
45156: 
45157: /*
45158: ** Implementation of the sqlite3_pcache.xCachesize method. 
45159: **
45160: ** Configure the cache_size limit for a cache.
45161: */
45162: static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
45163:   PCache1 *pCache = (PCache1 *)p;
45164:   if( pCache->bPurgeable ){
45165:     PGroup *pGroup = pCache->pGroup;
45166:     pcache1EnterMutex(pGroup);
45167:     pGroup->nMaxPage += (nMax - pCache->nMax);
45168:     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45169:     pCache->nMax = nMax;
45170:     pCache->n90pct = pCache->nMax*9/10;
45171:     pcache1EnforceMaxPage(pCache);
45172:     pcache1LeaveMutex(pGroup);
45173:   }
45174: }
45175: 
45176: /*
45177: ** Implementation of the sqlite3_pcache.xShrink method. 
45178: **
45179: ** Free up as much memory as possible.
45180: */
45181: static void pcache1Shrink(sqlite3_pcache *p){
45182:   PCache1 *pCache = (PCache1*)p;
45183:   if( pCache->bPurgeable ){
45184:     PGroup *pGroup = pCache->pGroup;
45185:     int savedMaxPage;
45186:     pcache1EnterMutex(pGroup);
45187:     savedMaxPage = pGroup->nMaxPage;
45188:     pGroup->nMaxPage = 0;
45189:     pcache1EnforceMaxPage(pCache);
45190:     pGroup->nMaxPage = savedMaxPage;
45191:     pcache1LeaveMutex(pGroup);
45192:   }
45193: }
45194: 
45195: /*
45196: ** Implementation of the sqlite3_pcache.xPagecount method. 
45197: */
45198: static int pcache1Pagecount(sqlite3_pcache *p){
45199:   int n;
45200:   PCache1 *pCache = (PCache1*)p;
45201:   pcache1EnterMutex(pCache->pGroup);
45202:   n = pCache->nPage;
45203:   pcache1LeaveMutex(pCache->pGroup);
45204:   return n;
45205: }
45206: 
45207: 
45208: /*
45209: ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
45210: ** in the header of the pcache1Fetch() procedure.
45211: **
45212: ** This steps are broken out into a separate procedure because they are
45213: ** usually not needed, and by avoiding the stack initialization required
45214: ** for these steps, the main pcache1Fetch() procedure can run faster.
45215: */
45216: static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
45217:   PCache1 *pCache, 
45218:   unsigned int iKey, 
45219:   int createFlag
45220: ){
45221:   unsigned int nPinned;
45222:   PGroup *pGroup = pCache->pGroup;
45223:   PgHdr1 *pPage = 0;
45224: 
45225:   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
45226:   assert( pCache->nPage >= pCache->nRecyclable );
45227:   nPinned = pCache->nPage - pCache->nRecyclable;
45228:   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
45229:   assert( pCache->n90pct == pCache->nMax*9/10 );
45230:   if( createFlag==1 && (
45231:         nPinned>=pGroup->mxPinned
45232:      || nPinned>=pCache->n90pct
45233:      || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
45234:   )){
45235:     return 0;
45236:   }
45237: 
45238:   if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
45239:   assert( pCache->nHash>0 && pCache->apHash );
45240: 
45241:   /* Step 4. Try to recycle a page. */
45242:   if( pCache->bPurgeable
45243:    && !pGroup->lru.pLruPrev->isAnchor
45244:    && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
45245:   ){
45246:     PCache1 *pOther;
45247:     pPage = pGroup->lru.pLruPrev;
45248:     assert( pPage->isPinned==0 );
45249:     pcache1RemoveFromHash(pPage, 0);
45250:     pcache1PinPage(pPage);
45251:     pOther = pPage->pCache;
45252:     if( pOther->szAlloc != pCache->szAlloc ){
45253:       pcache1FreePage(pPage);
45254:       pPage = 0;
45255:     }else{
45256:       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
45257:     }
45258:   }
45259: 
45260:   /* Step 5. If a usable page buffer has still not been found, 
45261:   ** attempt to allocate a new one. 
45262:   */
45263:   if( !pPage ){
45264:     pPage = pcache1AllocPage(pCache, createFlag==1);
45265:   }
45266: 
45267:   if( pPage ){
45268:     unsigned int h = iKey % pCache->nHash;
45269:     pCache->nPage++;
45270:     pPage->iKey = iKey;
45271:     pPage->pNext = pCache->apHash[h];
45272:     pPage->pCache = pCache;
45273:     pPage->pLruPrev = 0;
45274:     pPage->pLruNext = 0;
45275:     pPage->isPinned = 1;
45276:     *(void **)pPage->page.pExtra = 0;
45277:     pCache->apHash[h] = pPage;
45278:     if( iKey>pCache->iMaxKey ){
45279:       pCache->iMaxKey = iKey;
45280:     }
45281:   }
45282:   return pPage;
45283: }
45284: 
45285: /*
45286: ** Implementation of the sqlite3_pcache.xFetch method. 
45287: **
45288: ** Fetch a page by key value.
45289: **
45290: ** Whether or not a new page may be allocated by this function depends on
45291: ** the value of the createFlag argument.  0 means do not allocate a new
45292: ** page.  1 means allocate a new page if space is easily available.  2 
45293: ** means to try really hard to allocate a new page.
45294: **
45295: ** For a non-purgeable cache (a cache used as the storage for an in-memory
45296: ** database) there is really no difference between createFlag 1 and 2.  So
45297: ** the calling function (pcache.c) will never have a createFlag of 1 on
45298: ** a non-purgeable cache.
45299: **
45300: ** There are three different approaches to obtaining space for a page,
45301: ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
45302: **
45303: **   1. Regardless of the value of createFlag, the cache is searched for a 
45304: **      copy of the requested page. If one is found, it is returned.
45305: **
45306: **   2. If createFlag==0 and the page is not already in the cache, NULL is
45307: **      returned.
45308: **
45309: **   3. If createFlag is 1, and the page is not already in the cache, then
45310: **      return NULL (do not allocate a new page) if any of the following
45311: **      conditions are true:
45312: **
45313: **       (a) the number of pages pinned by the cache is greater than
45314: **           PCache1.nMax, or
45315: **
45316: **       (b) the number of pages pinned by the cache is greater than
45317: **           the sum of nMax for all purgeable caches, less the sum of 
45318: **           nMin for all other purgeable caches, or
45319: **
45320: **   4. If none of the first three conditions apply and the cache is marked
45321: **      as purgeable, and if one of the following is true:
45322: **
45323: **       (a) The number of pages allocated for the cache is already 
45324: **           PCache1.nMax, or
45325: **
45326: **       (b) The number of pages allocated for all purgeable caches is
45327: **           already equal to or greater than the sum of nMax for all
45328: **           purgeable caches,
45329: **
45330: **       (c) The system is under memory pressure and wants to avoid
45331: **           unnecessary pages cache entry allocations
45332: **
45333: **      then attempt to recycle a page from the LRU list. If it is the right
45334: **      size, return the recycled buffer. Otherwise, free the buffer and
45335: **      proceed to step 5. 
45336: **
45337: **   5. Otherwise, allocate and return a new page buffer.
45338: **
45339: ** There are two versions of this routine.  pcache1FetchWithMutex() is
45340: ** the general case.  pcache1FetchNoMutex() is a faster implementation for
45341: ** the common case where pGroup->mutex is NULL.  The pcache1Fetch() wrapper
45342: ** invokes the appropriate routine.
45343: */
45344: static PgHdr1 *pcache1FetchNoMutex(
45345:   sqlite3_pcache *p, 
45346:   unsigned int iKey, 
45347:   int createFlag
45348: ){
45349:   PCache1 *pCache = (PCache1 *)p;
45350:   PgHdr1 *pPage = 0;
45351: 
45352:   /* Step 1: Search the hash table for an existing entry. */
45353:   pPage = pCache->apHash[iKey % pCache->nHash];
45354:   while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
45355: 
45356:   /* Step 2: If the page was found in the hash table, then return it.
45357:   ** If the page was not in the hash table and createFlag is 0, abort.
45358:   ** Otherwise (page not in hash and createFlag!=0) continue with
45359:   ** subsequent steps to try to create the page. */
45360:   if( pPage ){
45361:     if( !pPage->isPinned ){
45362:       return pcache1PinPage(pPage);
45363:     }else{
45364:       return pPage;
45365:     }
45366:   }else if( createFlag ){
45367:     /* Steps 3, 4, and 5 implemented by this subroutine */
45368:     return pcache1FetchStage2(pCache, iKey, createFlag);
45369:   }else{
45370:     return 0;
45371:   }
45372: }
45373: #if PCACHE1_MIGHT_USE_GROUP_MUTEX
45374: static PgHdr1 *pcache1FetchWithMutex(
45375:   sqlite3_pcache *p, 
45376:   unsigned int iKey, 
45377:   int createFlag
45378: ){
45379:   PCache1 *pCache = (PCache1 *)p;
45380:   PgHdr1 *pPage;
45381: 
45382:   pcache1EnterMutex(pCache->pGroup);
45383:   pPage = pcache1FetchNoMutex(p, iKey, createFlag);
45384:   assert( pPage==0 || pCache->iMaxKey>=iKey );
45385:   pcache1LeaveMutex(pCache->pGroup);
45386:   return pPage;
45387: }
45388: #endif
45389: static sqlite3_pcache_page *pcache1Fetch(
45390:   sqlite3_pcache *p, 
45391:   unsigned int iKey, 
45392:   int createFlag
45393: ){
45394: #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
45395:   PCache1 *pCache = (PCache1 *)p;
45396: #endif
45397: 
45398:   assert( offsetof(PgHdr1,page)==0 );
45399:   assert( pCache->bPurgeable || createFlag!=1 );
45400:   assert( pCache->bPurgeable || pCache->nMin==0 );
45401:   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
45402:   assert( pCache->nMin==0 || pCache->bPurgeable );
45403:   assert( pCache->nHash>0 );
45404: #if PCACHE1_MIGHT_USE_GROUP_MUTEX
45405:   if( pCache->pGroup->mutex ){
45406:     return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
45407:   }else
45408: #endif
45409:   {
45410:     return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
45411:   }
45412: }
45413: 
45414: 
45415: /*
45416: ** Implementation of the sqlite3_pcache.xUnpin method.
45417: **
45418: ** Mark a page as unpinned (eligible for asynchronous recycling).
45419: */
45420: static void pcache1Unpin(
45421:   sqlite3_pcache *p, 
45422:   sqlite3_pcache_page *pPg, 
45423:   int reuseUnlikely
45424: ){
45425:   PCache1 *pCache = (PCache1 *)p;
45426:   PgHdr1 *pPage = (PgHdr1 *)pPg;
45427:   PGroup *pGroup = pCache->pGroup;
45428:  
45429:   assert( pPage->pCache==pCache );
45430:   pcache1EnterMutex(pGroup);
45431: 
45432:   /* It is an error to call this function if the page is already 
45433:   ** part of the PGroup LRU list.
45434:   */
45435:   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
45436:   assert( pPage->isPinned==1 );
45437: 
45438:   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
45439:     pcache1RemoveFromHash(pPage, 1);
45440:   }else{
45441:     /* Add the page to the PGroup LRU list. */
45442:     PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
45443:     pPage->pLruPrev = &pGroup->lru;
45444:     (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
45445:     *ppFirst = pPage;
45446:     pCache->nRecyclable++;
45447:     pPage->isPinned = 0;
45448:   }
45449: 
45450:   pcache1LeaveMutex(pCache->pGroup);
45451: }
45452: 
45453: /*
45454: ** Implementation of the sqlite3_pcache.xRekey method. 
45455: */
45456: static void pcache1Rekey(
45457:   sqlite3_pcache *p,
45458:   sqlite3_pcache_page *pPg,
45459:   unsigned int iOld,
45460:   unsigned int iNew
45461: ){
45462:   PCache1 *pCache = (PCache1 *)p;
45463:   PgHdr1 *pPage = (PgHdr1 *)pPg;
45464:   PgHdr1 **pp;
45465:   unsigned int h; 
45466:   assert( pPage->iKey==iOld );
45467:   assert( pPage->pCache==pCache );
45468: 
45469:   pcache1EnterMutex(pCache->pGroup);
45470: 
45471:   h = iOld%pCache->nHash;
45472:   pp = &pCache->apHash[h];
45473:   while( (*pp)!=pPage ){
45474:     pp = &(*pp)->pNext;
45475:   }
45476:   *pp = pPage->pNext;
45477: 
45478:   h = iNew%pCache->nHash;
45479:   pPage->iKey = iNew;
45480:   pPage->pNext = pCache->apHash[h];
45481:   pCache->apHash[h] = pPage;
45482:   if( iNew>pCache->iMaxKey ){
45483:     pCache->iMaxKey = iNew;
45484:   }
45485: 
45486:   pcache1LeaveMutex(pCache->pGroup);
45487: }
45488: 
45489: /*
45490: ** Implementation of the sqlite3_pcache.xTruncate method. 
45491: **
45492: ** Discard all unpinned pages in the cache with a page number equal to
45493: ** or greater than parameter iLimit. Any pinned pages with a page number
45494: ** equal to or greater than iLimit are implicitly unpinned.
45495: */
45496: static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
45497:   PCache1 *pCache = (PCache1 *)p;
45498:   pcache1EnterMutex(pCache->pGroup);
45499:   if( iLimit<=pCache->iMaxKey ){
45500:     pcache1TruncateUnsafe(pCache, iLimit);
45501:     pCache->iMaxKey = iLimit-1;
45502:   }
45503:   pcache1LeaveMutex(pCache->pGroup);
45504: }
45505: 
45506: /*
45507: ** Implementation of the sqlite3_pcache.xDestroy method. 
45508: **
45509: ** Destroy a cache allocated using pcache1Create().
45510: */
45511: static void pcache1Destroy(sqlite3_pcache *p){
45512:   PCache1 *pCache = (PCache1 *)p;
45513:   PGroup *pGroup = pCache->pGroup;
45514:   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
45515:   pcache1EnterMutex(pGroup);
45516:   if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
45517:   assert( pGroup->nMaxPage >= pCache->nMax );
45518:   pGroup->nMaxPage -= pCache->nMax;
45519:   assert( pGroup->nMinPage >= pCache->nMin );
45520:   pGroup->nMinPage -= pCache->nMin;
45521:   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45522:   pcache1EnforceMaxPage(pCache);
45523:   pcache1LeaveMutex(pGroup);
45524:   sqlite3_free(pCache->pBulk);
45525:   sqlite3_free(pCache->apHash);
45526:   sqlite3_free(pCache);
45527: }
45528: 
45529: /*
45530: ** This function is called during initialization (sqlite3_initialize()) to
45531: ** install the default pluggable cache module, assuming the user has not
45532: ** already provided an alternative.
45533: */
45534: SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
45535:   static const sqlite3_pcache_methods2 defaultMethods = {
45536:     1,                       /* iVersion */
45537:     0,                       /* pArg */
45538:     pcache1Init,             /* xInit */
45539:     pcache1Shutdown,         /* xShutdown */
45540:     pcache1Create,           /* xCreate */
45541:     pcache1Cachesize,        /* xCachesize */
45542:     pcache1Pagecount,        /* xPagecount */
45543:     pcache1Fetch,            /* xFetch */
45544:     pcache1Unpin,            /* xUnpin */
45545:     pcache1Rekey,            /* xRekey */
45546:     pcache1Truncate,         /* xTruncate */
45547:     pcache1Destroy,          /* xDestroy */
45548:     pcache1Shrink            /* xShrink */
45549:   };
45550:   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
45551: }
45552: 
45553: /*
45554: ** Return the size of the header on each page of this PCACHE implementation.
45555: */
45556: SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
45557: 
45558: /*
45559: ** Return the global mutex used by this PCACHE implementation.  The
45560: ** sqlite3_status() routine needs access to this mutex.
45561: */
45562: SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
45563:   return pcache1.mutex;
45564: }
45565: 
45566: #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45567: /*
45568: ** This function is called to free superfluous dynamically allocated memory
45569: ** held by the pager system. Memory in use by any SQLite pager allocated
45570: ** by the current thread may be sqlite3_free()ed.
45571: **
45572: ** nReq is the number of bytes of memory required. Once this much has
45573: ** been released, the function returns. The return value is the total number 
45574: ** of bytes of memory released.
45575: */
45576: SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
45577:   int nFree = 0;
45578:   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45579:   assert( sqlite3_mutex_notheld(pcache1.mutex) );
45580:   if( sqlite3GlobalConfig.nPage==0 ){
45581:     PgHdr1 *p;
45582:     pcache1EnterMutex(&pcache1.grp);
45583:     while( (nReq<0 || nFree<nReq)
45584:        &&  (p=pcache1.grp.lru.pLruPrev)!=0
45585:        &&  p->isAnchor==0
45586:     ){
45587:       nFree += pcache1MemSize(p->page.pBuf);
45588: #ifdef SQLITE_PCACHE_SEPARATE_HEADER
45589:       nFree += sqlite3MemSize(p);
45590: #endif
45591:       assert( p->isPinned==0 );
45592:       pcache1PinPage(p);
45593:       pcache1RemoveFromHash(p, 1);
45594:     }
45595:     pcache1LeaveMutex(&pcache1.grp);
45596:   }
45597:   return nFree;
45598: }
45599: #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45600: 
45601: #ifdef SQLITE_TEST
45602: /*
45603: ** This function is used by test procedures to inspect the internal state
45604: ** of the global cache.
45605: */
45606: SQLITE_PRIVATE void sqlite3PcacheStats(
45607:   int *pnCurrent,      /* OUT: Total number of pages cached */
45608:   int *pnMax,          /* OUT: Global maximum cache size */
45609:   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
45610:   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
45611: ){
45612:   PgHdr1 *p;
45613:   int nRecyclable = 0;
45614:   for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
45615:     assert( p->isPinned==0 );
45616:     nRecyclable++;
45617:   }
45618:   *pnCurrent = pcache1.grp.nCurrentPage;
45619:   *pnMax = (int)pcache1.grp.nMaxPage;
45620:   *pnMin = (int)pcache1.grp.nMinPage;
45621:   *pnRecyclable = nRecyclable;
45622: }
45623: #endif
45624: 
45625: /************** End of pcache1.c *********************************************/
45626: /************** Begin file rowset.c ******************************************/
45627: /*
45628: ** 2008 December 3
45629: **
45630: ** The author disclaims copyright to this source code.  In place of
45631: ** a legal notice, here is a blessing:
45632: **
45633: **    May you do good and not evil.
45634: **    May you find forgiveness for yourself and forgive others.
45635: **    May you share freely, never taking more than you give.
45636: **
45637: *************************************************************************
45638: **
45639: ** This module implements an object we call a "RowSet".
45640: **
45641: ** The RowSet object is a collection of rowids.  Rowids
45642: ** are inserted into the RowSet in an arbitrary order.  Inserts
45643: ** can be intermixed with tests to see if a given rowid has been
45644: ** previously inserted into the RowSet.
45645: **
45646: ** After all inserts are finished, it is possible to extract the
45647: ** elements of the RowSet in sorted order.  Once this extraction
45648: ** process has started, no new elements may be inserted.
45649: **
45650: ** Hence, the primitive operations for a RowSet are:
45651: **
45652: **    CREATE
45653: **    INSERT
45654: **    TEST
45655: **    SMALLEST
45656: **    DESTROY
45657: **
45658: ** The CREATE and DESTROY primitives are the constructor and destructor,
45659: ** obviously.  The INSERT primitive adds a new element to the RowSet.
45660: ** TEST checks to see if an element is already in the RowSet.  SMALLEST
45661: ** extracts the least value from the RowSet.
45662: **
45663: ** The INSERT primitive might allocate additional memory.  Memory is
45664: ** allocated in chunks so most INSERTs do no allocation.  There is an 
45665: ** upper bound on the size of allocated memory.  No memory is freed
45666: ** until DESTROY.
45667: **
45668: ** The TEST primitive includes a "batch" number.  The TEST primitive
45669: ** will only see elements that were inserted before the last change
45670: ** in the batch number.  In other words, if an INSERT occurs between
45671: ** two TESTs where the TESTs have the same batch nubmer, then the
45672: ** value added by the INSERT will not be visible to the second TEST.
45673: ** The initial batch number is zero, so if the very first TEST contains
45674: ** a non-zero batch number, it will see all prior INSERTs.
45675: **
45676: ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
45677: ** that is attempted.
45678: **
45679: ** The cost of an INSERT is roughly constant.  (Sometimes new memory
45680: ** has to be allocated on an INSERT.)  The cost of a TEST with a new
45681: ** batch number is O(NlogN) where N is the number of elements in the RowSet.
45682: ** The cost of a TEST using the same batch number is O(logN).  The cost
45683: ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
45684: ** primitives are constant time.  The cost of DESTROY is O(N).
45685: **
45686: ** TEST and SMALLEST may not be used by the same RowSet.  This used to
45687: ** be possible, but the feature was not used, so it was removed in order
45688: ** to simplify the code.
45689: */
45690: /* #include "sqliteInt.h" */
45691: 
45692: 
45693: /*
45694: ** Target size for allocation chunks.
45695: */
45696: #define ROWSET_ALLOCATION_SIZE 1024
45697: 
45698: /*
45699: ** The number of rowset entries per allocation chunk.
45700: */
45701: #define ROWSET_ENTRY_PER_CHUNK  \
45702:                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
45703: 
45704: /*
45705: ** Each entry in a RowSet is an instance of the following object.
45706: **
45707: ** This same object is reused to store a linked list of trees of RowSetEntry
45708: ** objects.  In that alternative use, pRight points to the next entry
45709: ** in the list, pLeft points to the tree, and v is unused.  The
45710: ** RowSet.pForest value points to the head of this forest list.
45711: */
45712: struct RowSetEntry {            
45713:   i64 v;                        /* ROWID value for this entry */
45714:   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
45715:   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
45716: };
45717: 
45718: /*
45719: ** RowSetEntry objects are allocated in large chunks (instances of the
45720: ** following structure) to reduce memory allocation overhead.  The
45721: ** chunks are kept on a linked list so that they can be deallocated
45722: ** when the RowSet is destroyed.
45723: */
45724: struct RowSetChunk {
45725:   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
45726:   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
45727: };
45728: 
45729: /*
45730: ** A RowSet in an instance of the following structure.
45731: **
45732: ** A typedef of this structure if found in sqliteInt.h.
45733: */
45734: struct RowSet {
45735:   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
45736:   sqlite3 *db;                   /* The database connection */
45737:   struct RowSetEntry *pEntry;    /* List of entries using pRight */
45738:   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
45739:   struct RowSetEntry *pFresh;    /* Source of new entry objects */
45740:   struct RowSetEntry *pForest;   /* List of binary trees of entries */
45741:   u16 nFresh;                    /* Number of objects on pFresh */
45742:   u16 rsFlags;                   /* Various flags */
45743:   int iBatch;                    /* Current insert batch */
45744: };
45745: 
45746: /*
45747: ** Allowed values for RowSet.rsFlags
45748: */
45749: #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
45750: #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
45751: 
45752: /*
45753: ** Turn bulk memory into a RowSet object.  N bytes of memory
45754: ** are available at pSpace.  The db pointer is used as a memory context
45755: ** for any subsequent allocations that need to occur.
45756: ** Return a pointer to the new RowSet object.
45757: **
45758: ** It must be the case that N is sufficient to make a Rowset.  If not
45759: ** an assertion fault occurs.
45760: ** 
45761: ** If N is larger than the minimum, use the surplus as an initial
45762: ** allocation of entries available to be filled.
45763: */
45764: SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
45765:   RowSet *p;
45766:   assert( N >= ROUND8(sizeof(*p)) );
45767:   p = pSpace;
45768:   p->pChunk = 0;
45769:   p->db = db;
45770:   p->pEntry = 0;
45771:   p->pLast = 0;
45772:   p->pForest = 0;
45773:   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
45774:   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
45775:   p->rsFlags = ROWSET_SORTED;
45776:   p->iBatch = 0;
45777:   return p;
45778: }
45779: 
45780: /*
45781: ** Deallocate all chunks from a RowSet.  This frees all memory that
45782: ** the RowSet has allocated over its lifetime.  This routine is
45783: ** the destructor for the RowSet.
45784: */
45785: SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
45786:   struct RowSetChunk *pChunk, *pNextChunk;
45787:   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
45788:     pNextChunk = pChunk->pNextChunk;
45789:     sqlite3DbFree(p->db, pChunk);
45790:   }
45791:   p->pChunk = 0;
45792:   p->nFresh = 0;
45793:   p->pEntry = 0;
45794:   p->pLast = 0;
45795:   p->pForest = 0;
45796:   p->rsFlags = ROWSET_SORTED;
45797: }
45798: 
45799: /*
45800: ** Allocate a new RowSetEntry object that is associated with the
45801: ** given RowSet.  Return a pointer to the new and completely uninitialized
45802: ** objected.
45803: **
45804: ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
45805: ** routine returns NULL.
45806: */
45807: static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
45808:   assert( p!=0 );
45809:   if( p->nFresh==0 ){  /*OPTIMIZATION-IF-FALSE*/
45810:     /* We could allocate a fresh RowSetEntry each time one is needed, but it
45811:     ** is more efficient to pull a preallocated entry from the pool */
45812:     struct RowSetChunk *pNew;
45813:     pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
45814:     if( pNew==0 ){
45815:       return 0;
45816:     }
45817:     pNew->pNextChunk = p->pChunk;
45818:     p->pChunk = pNew;
45819:     p->pFresh = pNew->aEntry;
45820:     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
45821:   }
45822:   p->nFresh--;
45823:   return p->pFresh++;
45824: }
45825: 
45826: /*
45827: ** Insert a new value into a RowSet.
45828: **
45829: ** The mallocFailed flag of the database connection is set if a
45830: ** memory allocation fails.
45831: */
45832: SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
45833:   struct RowSetEntry *pEntry;  /* The new entry */
45834:   struct RowSetEntry *pLast;   /* The last prior entry */
45835: 
45836:   /* This routine is never called after sqlite3RowSetNext() */
45837:   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
45838: 
45839:   pEntry = rowSetEntryAlloc(p);
45840:   if( pEntry==0 ) return;
45841:   pEntry->v = rowid;
45842:   pEntry->pRight = 0;
45843:   pLast = p->pLast;
45844:   if( pLast ){
45845:     if( rowid<=pLast->v ){  /*OPTIMIZATION-IF-FALSE*/
45846:       /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45847:       ** where possible */
45848:       p->rsFlags &= ~ROWSET_SORTED;
45849:     }
45850:     pLast->pRight = pEntry;
45851:   }else{
45852:     p->pEntry = pEntry;
45853:   }
45854:   p->pLast = pEntry;
45855: }
45856: 
45857: /*
45858: ** Merge two lists of RowSetEntry objects.  Remove duplicates.
45859: **
45860: ** The input lists are connected via pRight pointers and are 
45861: ** assumed to each already be in sorted order.
45862: */
45863: static struct RowSetEntry *rowSetEntryMerge(
45864:   struct RowSetEntry *pA,    /* First sorted list to be merged */
45865:   struct RowSetEntry *pB     /* Second sorted list to be merged */
45866: ){
45867:   struct RowSetEntry head;
45868:   struct RowSetEntry *pTail;
45869: 
45870:   pTail = &head;
45871:   assert( pA!=0 && pB!=0 );
45872:   for(;;){
45873:     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
45874:     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
45875:     if( pA->v<=pB->v ){
45876:       if( pA->v<pB->v ) pTail = pTail->pRight = pA;
45877:       pA = pA->pRight;
45878:       if( pA==0 ){
45879:         pTail->pRight = pB;
45880:         break;
45881:       }
45882:     }else{
45883:       pTail = pTail->pRight = pB;
45884:       pB = pB->pRight;
45885:       if( pB==0 ){
45886:         pTail->pRight = pA;
45887:         break;
45888:       }
45889:     }
45890:   }
45891:   return head.pRight;
45892: }
45893: 
45894: /*
45895: ** Sort all elements on the list of RowSetEntry objects into order of
45896: ** increasing v.
45897: */ 
45898: static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
45899:   unsigned int i;
45900:   struct RowSetEntry *pNext, *aBucket[40];
45901: 
45902:   memset(aBucket, 0, sizeof(aBucket));
45903:   while( pIn ){
45904:     pNext = pIn->pRight;
45905:     pIn->pRight = 0;
45906:     for(i=0; aBucket[i]; i++){
45907:       pIn = rowSetEntryMerge(aBucket[i], pIn);
45908:       aBucket[i] = 0;
45909:     }
45910:     aBucket[i] = pIn;
45911:     pIn = pNext;
45912:   }
45913:   pIn = aBucket[0];
45914:   for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
45915:     if( aBucket[i]==0 ) continue;
45916:     pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
45917:   }
45918:   return pIn;
45919: }
45920: 
45921: 
45922: /*
45923: ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
45924: ** Convert this tree into a linked list connected by the pRight pointers
45925: ** and return pointers to the first and last elements of the new list.
45926: */
45927: static void rowSetTreeToList(
45928:   struct RowSetEntry *pIn,         /* Root of the input tree */
45929:   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
45930:   struct RowSetEntry **ppLast      /* Write tail of the output list here */
45931: ){
45932:   assert( pIn!=0 );
45933:   if( pIn->pLeft ){
45934:     struct RowSetEntry *p;
45935:     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
45936:     p->pRight = pIn;
45937:   }else{
45938:     *ppFirst = pIn;
45939:   }
45940:   if( pIn->pRight ){
45941:     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
45942:   }else{
45943:     *ppLast = pIn;
45944:   }
45945:   assert( (*ppLast)->pRight==0 );
45946: }
45947: 
45948: 
45949: /*
45950: ** Convert a sorted list of elements (connected by pRight) into a binary
45951: ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
45952: ** node taken from the head of *ppList.  A depth of 2 means a tree with
45953: ** three nodes.  And so forth.
45954: **
45955: ** Use as many entries from the input list as required and update the
45956: ** *ppList to point to the unused elements of the list.  If the input
45957: ** list contains too few elements, then construct an incomplete tree
45958: ** and leave *ppList set to NULL.
45959: **
45960: ** Return a pointer to the root of the constructed binary tree.
45961: */
45962: static struct RowSetEntry *rowSetNDeepTree(
45963:   struct RowSetEntry **ppList,
45964:   int iDepth
45965: ){
45966:   struct RowSetEntry *p;         /* Root of the new tree */
45967:   struct RowSetEntry *pLeft;     /* Left subtree */
45968:   if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
45969:     /* Prevent unnecessary deep recursion when we run out of entries */
45970:     return 0; 
45971:   }
45972:   if( iDepth>1 ){   /*OPTIMIZATION-IF-TRUE*/
45973:     /* This branch causes a *balanced* tree to be generated.  A valid tree
45974:     ** is still generated without this branch, but the tree is wildly
45975:     ** unbalanced and inefficient. */
45976:     pLeft = rowSetNDeepTree(ppList, iDepth-1);
45977:     p = *ppList;
45978:     if( p==0 ){     /*OPTIMIZATION-IF-FALSE*/
45979:       /* It is safe to always return here, but the resulting tree
45980:       ** would be unbalanced */
45981:       return pLeft;
45982:     }
45983:     p->pLeft = pLeft;
45984:     *ppList = p->pRight;
45985:     p->pRight = rowSetNDeepTree(ppList, iDepth-1);
45986:   }else{
45987:     p = *ppList;
45988:     *ppList = p->pRight;
45989:     p->pLeft = p->pRight = 0;
45990:   }
45991:   return p;
45992: }
45993: 
45994: /*
45995: ** Convert a sorted list of elements into a binary tree. Make the tree
45996: ** as deep as it needs to be in order to contain the entire list.
45997: */
45998: static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
45999:   int iDepth;           /* Depth of the tree so far */
46000:   struct RowSetEntry *p;       /* Current tree root */
46001:   struct RowSetEntry *pLeft;   /* Left subtree */
46002: 
46003:   assert( pList!=0 );
46004:   p = pList;
46005:   pList = p->pRight;
46006:   p->pLeft = p->pRight = 0;
46007:   for(iDepth=1; pList; iDepth++){
46008:     pLeft = p;
46009:     p = pList;
46010:     pList = p->pRight;
46011:     p->pLeft = pLeft;
46012:     p->pRight = rowSetNDeepTree(&pList, iDepth);
46013:   }
46014:   return p;
46015: }
46016: 
46017: /*
46018: ** Extract the smallest element from the RowSet.
46019: ** Write the element into *pRowid.  Return 1 on success.  Return
46020: ** 0 if the RowSet is already empty.
46021: **
46022: ** After this routine has been called, the sqlite3RowSetInsert()
46023: ** routine may not be called again.
46024: **
46025: ** This routine may not be called after sqlite3RowSetTest() has
46026: ** been used.  Older versions of RowSet allowed that, but as the
46027: ** capability was not used by the code generator, it was removed
46028: ** for code economy.
46029: */
46030: SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
46031:   assert( p!=0 );
46032:   assert( p->pForest==0 );  /* Cannot be used with sqlite3RowSetText() */
46033: 
46034:   /* Merge the forest into a single sorted list on first call */
46035:   if( (p->rsFlags & ROWSET_NEXT)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46036:     if( (p->rsFlags & ROWSET_SORTED)==0 ){  /*OPTIMIZATION-IF-FALSE*/
46037:       p->pEntry = rowSetEntrySort(p->pEntry);
46038:     }
46039:     p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
46040:   }
46041: 
46042:   /* Return the next entry on the list */
46043:   if( p->pEntry ){
46044:     *pRowid = p->pEntry->v;
46045:     p->pEntry = p->pEntry->pRight;
46046:     if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
46047:       /* Free memory immediately, rather than waiting on sqlite3_finalize() */
46048:       sqlite3RowSetClear(p);
46049:     }
46050:     return 1;
46051:   }else{
46052:     return 0;
46053:   }
46054: }
46055: 
46056: /*
46057: ** Check to see if element iRowid was inserted into the rowset as
46058: ** part of any insert batch prior to iBatch.  Return 1 or 0.
46059: **
46060: ** If this is the first test of a new batch and if there exist entries
46061: ** on pRowSet->pEntry, then sort those entries into the forest at
46062: ** pRowSet->pForest so that they can be tested.
46063: */
46064: SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
46065:   struct RowSetEntry *p, *pTree;
46066: 
46067:   /* This routine is never called after sqlite3RowSetNext() */
46068:   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
46069: 
46070:   /* Sort entries into the forest on the first test of a new batch.
46071:   ** To save unnecessary work, only do this when the batch number changes.
46072:   */
46073:   if( iBatch!=pRowSet->iBatch ){  /*OPTIMIZATION-IF-FALSE*/
46074:     p = pRowSet->pEntry;
46075:     if( p ){
46076:       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
46077:       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
46078:         /* Only sort the current set of entiries if they need it */
46079:         p = rowSetEntrySort(p);
46080:       }
46081:       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46082:         ppPrevTree = &pTree->pRight;
46083:         if( pTree->pLeft==0 ){
46084:           pTree->pLeft = rowSetListToTree(p);
46085:           break;
46086:         }else{
46087:           struct RowSetEntry *pAux, *pTail;
46088:           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
46089:           pTree->pLeft = 0;
46090:           p = rowSetEntryMerge(pAux, p);
46091:         }
46092:       }
46093:       if( pTree==0 ){
46094:         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
46095:         if( pTree ){
46096:           pTree->v = 0;
46097:           pTree->pRight = 0;
46098:           pTree->pLeft = rowSetListToTree(p);
46099:         }
46100:       }
46101:       pRowSet->pEntry = 0;
46102:       pRowSet->pLast = 0;
46103:       pRowSet->rsFlags |= ROWSET_SORTED;
46104:     }
46105:     pRowSet->iBatch = iBatch;
46106:   }
46107: 
46108:   /* Test to see if the iRowid value appears anywhere in the forest.
46109:   ** Return 1 if it does and 0 if not.
46110:   */
46111:   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
46112:     p = pTree->pLeft;
46113:     while( p ){
46114:       if( p->v<iRowid ){
46115:         p = p->pRight;
46116:       }else if( p->v>iRowid ){
46117:         p = p->pLeft;
46118:       }else{
46119:         return 1;
46120:       }
46121:     }
46122:   }
46123:   return 0;
46124: }
46125: 
46126: /************** End of rowset.c **********************************************/
46127: /************** Begin file pager.c *******************************************/
46128: /*
46129: ** 2001 September 15
46130: **
46131: ** The author disclaims copyright to this source code.  In place of
46132: ** a legal notice, here is a blessing:
46133: **
46134: **    May you do good and not evil.
46135: **    May you find forgiveness for yourself and forgive others.
46136: **    May you share freely, never taking more than you give.
46137: **
46138: *************************************************************************
46139: ** This is the implementation of the page cache subsystem or "pager".
46140: ** 
46141: ** The pager is used to access a database disk file.  It implements
46142: ** atomic commit and rollback through the use of a journal file that
46143: ** is separate from the database file.  The pager also implements file
46144: ** locking to prevent two processes from writing the same database
46145: ** file simultaneously, or one process from reading the database while
46146: ** another is writing.
46147: */
46148: #ifndef SQLITE_OMIT_DISKIO
46149: /* #include "sqliteInt.h" */
46150: /************** Include wal.h in the middle of pager.c ***********************/
46151: /************** Begin file wal.h *********************************************/
46152: /*
46153: ** 2010 February 1
46154: **
46155: ** The author disclaims copyright to this source code.  In place of
46156: ** a legal notice, here is a blessing:
46157: **
46158: **    May you do good and not evil.
46159: **    May you find forgiveness for yourself and forgive others.
46160: **    May you share freely, never taking more than you give.
46161: **
46162: *************************************************************************
46163: ** This header file defines the interface to the write-ahead logging 
46164: ** system. Refer to the comments below and the header comment attached to 
46165: ** the implementation of each function in log.c for further details.
46166: */
46167: 
46168: #ifndef SQLITE_WAL_H
46169: #define SQLITE_WAL_H
46170: 
46171: /* #include "sqliteInt.h" */
46172: 
46173: /* Additional values that can be added to the sync_flags argument of
46174: ** sqlite3WalFrames():
46175: */
46176: #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
46177: #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
46178: 
46179: #ifdef SQLITE_OMIT_WAL
46180: # define sqlite3WalOpen(x,y,z)                   0
46181: # define sqlite3WalLimit(x,y)
46182: # define sqlite3WalClose(w,x,y,z)                0
46183: # define sqlite3WalBeginReadTransaction(y,z)     0
46184: # define sqlite3WalEndReadTransaction(z)
46185: # define sqlite3WalDbsize(y)                     0
46186: # define sqlite3WalBeginWriteTransaction(y)      0
46187: # define sqlite3WalEndWriteTransaction(x)        0
46188: # define sqlite3WalUndo(x,y,z)                   0
46189: # define sqlite3WalSavepoint(y,z)
46190: # define sqlite3WalSavepointUndo(y,z)            0
46191: # define sqlite3WalFrames(u,v,w,x,y,z)           0
46192: # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
46193: # define sqlite3WalCallback(z)                   0
46194: # define sqlite3WalExclusiveMode(y,z)            0
46195: # define sqlite3WalHeapMemory(z)                 0
46196: # define sqlite3WalFramesize(z)                  0
46197: # define sqlite3WalFindFrame(x,y,z)              0
46198: # define sqlite3WalFile(x)                       0
46199: #else
46200: 
46201: #define WAL_SAVEPOINT_NDATA 4
46202: 
46203: /* Connection to a write-ahead log (WAL) file. 
46204: ** There is one object of this type for each pager. 
46205: */
46206: typedef struct Wal Wal;
46207: 
46208: /* Open and close a connection to a write-ahead log. */
46209: SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
46210: SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
46211: 
46212: /* Set the limiting size of a WAL file. */
46213: SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
46214: 
46215: /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
46216: ** snapshot is like a read-transaction.  It is the state of the database
46217: ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
46218: ** preserves the current state even if the other threads or processes
46219: ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
46220: ** transaction and releases the lock.
46221: */
46222: SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
46223: SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
46224: 
46225: /* Read a page from the write-ahead log, if it is present. */
46226: SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
46227: SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
46228: 
46229: /* If the WAL is not empty, return the size of the database. */
46230: SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
46231: 
46232: /* Obtain or release the WRITER lock. */
46233: SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
46234: SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
46235: 
46236: /* Undo any frames written (but not committed) to the log */
46237: SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
46238: 
46239: /* Return an integer that records the current (uncommitted) write
46240: ** position in the WAL */
46241: SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
46242: 
46243: /* Move the write position of the WAL back to iFrame.  Called in
46244: ** response to a ROLLBACK TO command. */
46245: SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
46246: 
46247: /* Write a frame or frames to the log. */
46248: SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
46249: 
46250: /* Copy pages from the log to the database file */ 
46251: SQLITE_PRIVATE int sqlite3WalCheckpoint(
46252:   Wal *pWal,                      /* Write-ahead log connection */
46253:   int eMode,                      /* One of PASSIVE, FULL and RESTART */
46254:   int (*xBusy)(void*),            /* Function to call when busy */
46255:   void *pBusyArg,                 /* Context argument for xBusyHandler */
46256:   int sync_flags,                 /* Flags to sync db file with (or 0) */
46257:   int nBuf,                       /* Size of buffer nBuf */
46258:   u8 *zBuf,                       /* Temporary buffer to use */
46259:   int *pnLog,                     /* OUT: Number of frames in WAL */
46260:   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
46261: );
46262: 
46263: /* Return the value to pass to a sqlite3_wal_hook callback, the
46264: ** number of frames in the WAL at the point of the last commit since
46265: ** sqlite3WalCallback() was called.  If no commits have occurred since
46266: ** the last call, then return 0.
46267: */
46268: SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
46269: 
46270: /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
46271: ** by the pager layer on the database file.
46272: */
46273: SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
46274: 
46275: /* Return true if the argument is non-NULL and the WAL module is using
46276: ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
46277: ** WAL module is using shared-memory, return false. 
46278: */
46279: SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
46280: 
46281: #ifdef SQLITE_ENABLE_SNAPSHOT
46282: SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
46283: SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
46284: #endif
46285: 
46286: #ifdef SQLITE_ENABLE_ZIPVFS
46287: /* If the WAL file is not empty, return the number of bytes of content
46288: ** stored in each frame (i.e. the db page-size when the WAL was created).
46289: */
46290: SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
46291: #endif
46292: 
46293: /* Return the sqlite3_file object for the WAL file */
46294: SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
46295: 
46296: #endif /* ifndef SQLITE_OMIT_WAL */
46297: #endif /* SQLITE_WAL_H */
46298: 
46299: /************** End of wal.h *************************************************/
46300: /************** Continuing where we left off in pager.c **********************/
46301: 
46302: 
46303: /******************* NOTES ON THE DESIGN OF THE PAGER ************************
46304: **
46305: ** This comment block describes invariants that hold when using a rollback
46306: ** journal.  These invariants do not apply for journal_mode=WAL,
46307: ** journal_mode=MEMORY, or journal_mode=OFF.
46308: **
46309: ** Within this comment block, a page is deemed to have been synced
46310: ** automatically as soon as it is written when PRAGMA synchronous=OFF.
46311: ** Otherwise, the page is not synced until the xSync method of the VFS
46312: ** is called successfully on the file containing the page.
46313: **
46314: ** Definition:  A page of the database file is said to be "overwriteable" if
46315: ** one or more of the following are true about the page:
46316: ** 
46317: **     (a)  The original content of the page as it was at the beginning of
46318: **          the transaction has been written into the rollback journal and
46319: **          synced.
46320: ** 
46321: **     (b)  The page was a freelist leaf page at the start of the transaction.
46322: ** 
46323: **     (c)  The page number is greater than the largest page that existed in
46324: **          the database file at the start of the transaction.
46325: ** 
46326: ** (1) A page of the database file is never overwritten unless one of the
46327: **     following are true:
46328: ** 
46329: **     (a) The page and all other pages on the same sector are overwriteable.
46330: ** 
46331: **     (b) The atomic page write optimization is enabled, and the entire
46332: **         transaction other than the update of the transaction sequence
46333: **         number consists of a single page change.
46334: ** 
46335: ** (2) The content of a page written into the rollback journal exactly matches
46336: **     both the content in the database when the rollback journal was written
46337: **     and the content in the database at the beginning of the current
46338: **     transaction.
46339: ** 
46340: ** (3) Writes to the database file are an integer multiple of the page size
46341: **     in length and are aligned on a page boundary.
46342: ** 
46343: ** (4) Reads from the database file are either aligned on a page boundary and
46344: **     an integer multiple of the page size in length or are taken from the
46345: **     first 100 bytes of the database file.
46346: ** 
46347: ** (5) All writes to the database file are synced prior to the rollback journal
46348: **     being deleted, truncated, or zeroed.
46349: ** 
46350: ** (6) If a master journal file is used, then all writes to the database file
46351: **     are synced prior to the master journal being deleted.
46352: ** 
46353: ** Definition: Two databases (or the same database at two points it time)
46354: ** are said to be "logically equivalent" if they give the same answer to
46355: ** all queries.  Note in particular the content of freelist leaf
46356: ** pages can be changed arbitrarily without affecting the logical equivalence
46357: ** of the database.
46358: ** 
46359: ** (7) At any time, if any subset, including the empty set and the total set,
46360: **     of the unsynced changes to a rollback journal are removed and the 
46361: **     journal is rolled back, the resulting database file will be logically
46362: **     equivalent to the database file at the beginning of the transaction.
46363: ** 
46364: ** (8) When a transaction is rolled back, the xTruncate method of the VFS
46365: **     is called to restore the database file to the same size it was at
46366: **     the beginning of the transaction.  (In some VFSes, the xTruncate
46367: **     method is a no-op, but that does not change the fact the SQLite will
46368: **     invoke it.)
46369: ** 
46370: ** (9) Whenever the database file is modified, at least one bit in the range
46371: **     of bytes from 24 through 39 inclusive will be changed prior to releasing
46372: **     the EXCLUSIVE lock, thus signaling other connections on the same
46373: **     database to flush their caches.
46374: **
46375: ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
46376: **      than one billion transactions.
46377: **
46378: ** (11) A database file is well-formed at the beginning and at the conclusion
46379: **      of every transaction.
46380: **
46381: ** (12) An EXCLUSIVE lock is held on the database file when writing to
46382: **      the database file.
46383: **
46384: ** (13) A SHARED lock is held on the database file while reading any
46385: **      content out of the database file.
46386: **
46387: ******************************************************************************/
46388: 
46389: /*
46390: ** Macros for troubleshooting.  Normally turned off
46391: */
46392: #if 0
46393: int sqlite3PagerTrace=1;  /* True to enable tracing */
46394: #define sqlite3DebugPrintf printf
46395: #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
46396: #else
46397: #define PAGERTRACE(X)
46398: #endif
46399: 
46400: /*
46401: ** The following two macros are used within the PAGERTRACE() macros above
46402: ** to print out file-descriptors. 
46403: **
46404: ** PAGERID() takes a pointer to a Pager struct as its argument. The
46405: ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
46406: ** struct as its argument.
46407: */
46408: #define PAGERID(p) ((int)(p->fd))
46409: #define FILEHANDLEID(fd) ((int)fd)
46410: 
46411: /*
46412: ** The Pager.eState variable stores the current 'state' of a pager. A
46413: ** pager may be in any one of the seven states shown in the following
46414: ** state diagram.
46415: **
46416: **                            OPEN <------+------+
46417: **                              |         |      |
46418: **                              V         |      |
46419: **               +---------> READER-------+      |
46420: **               |              |                |
46421: **               |              V                |
46422: **               |<-------WRITER_LOCKED------> ERROR
46423: **               |              |                ^  
46424: **               |              V                |
46425: **               |<------WRITER_CACHEMOD-------->|
46426: **               |              |                |
46427: **               |              V                |
46428: **               |<-------WRITER_DBMOD---------->|
46429: **               |              |                |
46430: **               |              V                |
46431: **               +<------WRITER_FINISHED-------->+
46432: **
46433: **
46434: ** List of state transitions and the C [function] that performs each:
46435: ** 
46436: **   OPEN              -> READER              [sqlite3PagerSharedLock]
46437: **   READER            -> OPEN                [pager_unlock]
46438: **
46439: **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
46440: **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
46441: **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
46442: **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
46443: **   WRITER_***        -> READER              [pager_end_transaction]
46444: **
46445: **   WRITER_***        -> ERROR               [pager_error]
46446: **   ERROR             -> OPEN                [pager_unlock]
46447: ** 
46448: **
46449: **  OPEN:
46450: **
46451: **    The pager starts up in this state. Nothing is guaranteed in this
46452: **    state - the file may or may not be locked and the database size is
46453: **    unknown. The database may not be read or written.
46454: **
46455: **    * No read or write transaction is active.
46456: **    * Any lock, or no lock at all, may be held on the database file.
46457: **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
46458: **
46459: **  READER:
46460: **
46461: **    In this state all the requirements for reading the database in 
46462: **    rollback (non-WAL) mode are met. Unless the pager is (or recently
46463: **    was) in exclusive-locking mode, a user-level read transaction is 
46464: **    open. The database size is known in this state.
46465: **
46466: **    A connection running with locking_mode=normal enters this state when
46467: **    it opens a read-transaction on the database and returns to state
46468: **    OPEN after the read-transaction is completed. However a connection
46469: **    running in locking_mode=exclusive (including temp databases) remains in
46470: **    this state even after the read-transaction is closed. The only way
46471: **    a locking_mode=exclusive connection can transition from READER to OPEN
46472: **    is via the ERROR state (see below).
46473: ** 
46474: **    * A read transaction may be active (but a write-transaction cannot).
46475: **    * A SHARED or greater lock is held on the database file.
46476: **    * The dbSize variable may be trusted (even if a user-level read 
46477: **      transaction is not active). The dbOrigSize and dbFileSize variables
46478: **      may not be trusted at this point.
46479: **    * If the database is a WAL database, then the WAL connection is open.
46480: **    * Even if a read-transaction is not open, it is guaranteed that 
46481: **      there is no hot-journal in the file-system.
46482: **
46483: **  WRITER_LOCKED:
46484: **
46485: **    The pager moves to this state from READER when a write-transaction
46486: **    is first opened on the database. In WRITER_LOCKED state, all locks 
46487: **    required to start a write-transaction are held, but no actual 
46488: **    modifications to the cache or database have taken place.
46489: **
46490: **    In rollback mode, a RESERVED or (if the transaction was opened with 
46491: **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
46492: **    moving to this state, but the journal file is not written to or opened 
46493: **    to in this state. If the transaction is committed or rolled back while 
46494: **    in WRITER_LOCKED state, all that is required is to unlock the database 
46495: **    file.
46496: **
46497: **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
46498: **    If the connection is running with locking_mode=exclusive, an attempt
46499: **    is made to obtain an EXCLUSIVE lock on the database file.
46500: **
46501: **    * A write transaction is active.
46502: **    * If the connection is open in rollback-mode, a RESERVED or greater 
46503: **      lock is held on the database file.
46504: **    * If the connection is open in WAL-mode, a WAL write transaction
46505: **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
46506: **      called).
46507: **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
46508: **    * The contents of the pager cache have not been modified.
46509: **    * The journal file may or may not be open.
46510: **    * Nothing (not even the first header) has been written to the journal.
46511: **
46512: **  WRITER_CACHEMOD:
46513: **
46514: **    A pager moves from WRITER_LOCKED state to this state when a page is
46515: **    first modified by the upper layer. In rollback mode the journal file
46516: **    is opened (if it is not already open) and a header written to the
46517: **    start of it. The database file on disk has not been modified.
46518: **
46519: **    * A write transaction is active.
46520: **    * A RESERVED or greater lock is held on the database file.
46521: **    * The journal file is open and the first header has been written 
46522: **      to it, but the header has not been synced to disk.
46523: **    * The contents of the page cache have been modified.
46524: **
46525: **  WRITER_DBMOD:
46526: **
46527: **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
46528: **    when it modifies the contents of the database file. WAL connections
46529: **    never enter this state (since they do not modify the database file,
46530: **    just the log file).
46531: **
46532: **    * A write transaction is active.
46533: **    * An EXCLUSIVE or greater lock is held on the database file.
46534: **    * The journal file is open and the first header has been written 
46535: **      and synced to disk.
46536: **    * The contents of the page cache have been modified (and possibly
46537: **      written to disk).
46538: **
46539: **  WRITER_FINISHED:
46540: **
46541: **    It is not possible for a WAL connection to enter this state.
46542: **
46543: **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
46544: **    state after the entire transaction has been successfully written into the
46545: **    database file. In this state the transaction may be committed simply
46546: **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
46547: **    not possible to modify the database further. At this point, the upper 
46548: **    layer must either commit or rollback the transaction.
46549: **
46550: **    * A write transaction is active.
46551: **    * An EXCLUSIVE or greater lock is held on the database file.
46552: **    * All writing and syncing of journal and database data has finished.
46553: **      If no error occurred, all that remains is to finalize the journal to
46554: **      commit the transaction. If an error did occur, the caller will need
46555: **      to rollback the transaction. 
46556: **
46557: **  ERROR:
46558: **
46559: **    The ERROR state is entered when an IO or disk-full error (including
46560: **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
46561: **    difficult to be sure that the in-memory pager state (cache contents, 
46562: **    db size etc.) are consistent with the contents of the file-system.
46563: **
46564: **    Temporary pager files may enter the ERROR state, but in-memory pagers
46565: **    cannot.
46566: **
46567: **    For example, if an IO error occurs while performing a rollback, 
46568: **    the contents of the page-cache may be left in an inconsistent state.
46569: **    At this point it would be dangerous to change back to READER state
46570: **    (as usually happens after a rollback). Any subsequent readers might
46571: **    report database corruption (due to the inconsistent cache), and if
46572: **    they upgrade to writers, they may inadvertently corrupt the database
46573: **    file. To avoid this hazard, the pager switches into the ERROR state
46574: **    instead of READER following such an error.
46575: **
46576: **    Once it has entered the ERROR state, any attempt to use the pager
46577: **    to read or write data returns an error. Eventually, once all 
46578: **    outstanding transactions have been abandoned, the pager is able to
46579: **    transition back to OPEN state, discarding the contents of the 
46580: **    page-cache and any other in-memory state at the same time. Everything
46581: **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
46582: **    when a read-transaction is next opened on the pager (transitioning
46583: **    the pager into READER state). At that point the system has recovered 
46584: **    from the error.
46585: **
46586: **    Specifically, the pager jumps into the ERROR state if:
46587: **
46588: **      1. An error occurs while attempting a rollback. This happens in
46589: **         function sqlite3PagerRollback().
46590: **
46591: **      2. An error occurs while attempting to finalize a journal file
46592: **         following a commit in function sqlite3PagerCommitPhaseTwo().
46593: **
46594: **      3. An error occurs while attempting to write to the journal or
46595: **         database file in function pagerStress() in order to free up
46596: **         memory.
46597: **
46598: **    In other cases, the error is returned to the b-tree layer. The b-tree
46599: **    layer then attempts a rollback operation. If the error condition 
46600: **    persists, the pager enters the ERROR state via condition (1) above.
46601: **
46602: **    Condition (3) is necessary because it can be triggered by a read-only
46603: **    statement executed within a transaction. In this case, if the error
46604: **    code were simply returned to the user, the b-tree layer would not
46605: **    automatically attempt a rollback, as it assumes that an error in a
46606: **    read-only statement cannot leave the pager in an internally inconsistent 
46607: **    state.
46608: **
46609: **    * The Pager.errCode variable is set to something other than SQLITE_OK.
46610: **    * There are one or more outstanding references to pages (after the
46611: **      last reference is dropped the pager should move back to OPEN state).
46612: **    * The pager is not an in-memory pager.
46613: **    
46614: **
46615: ** Notes:
46616: **
46617: **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
46618: **     connection is open in WAL mode. A WAL connection is always in one
46619: **     of the first four states.
46620: **
46621: **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
46622: **     state. There are two exceptions: immediately after exclusive-mode has
46623: **     been turned on (and before any read or write transactions are 
46624: **     executed), and when the pager is leaving the "error state".
46625: **
46626: **   * See also: assert_pager_state().
46627: */
46628: #define PAGER_OPEN                  0
46629: #define PAGER_READER                1
46630: #define PAGER_WRITER_LOCKED         2
46631: #define PAGER_WRITER_CACHEMOD       3
46632: #define PAGER_WRITER_DBMOD          4
46633: #define PAGER_WRITER_FINISHED       5
46634: #define PAGER_ERROR                 6
46635: 
46636: /*
46637: ** The Pager.eLock variable is almost always set to one of the 
46638: ** following locking-states, according to the lock currently held on
46639: ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46640: ** This variable is kept up to date as locks are taken and released by
46641: ** the pagerLockDb() and pagerUnlockDb() wrappers.
46642: **
46643: ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
46644: ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
46645: ** the operation was successful. In these circumstances pagerLockDb() and
46646: ** pagerUnlockDb() take a conservative approach - eLock is always updated
46647: ** when unlocking the file, and only updated when locking the file if the
46648: ** VFS call is successful. This way, the Pager.eLock variable may be set
46649: ** to a less exclusive (lower) value than the lock that is actually held
46650: ** at the system level, but it is never set to a more exclusive value.
46651: **
46652: ** This is usually safe. If an xUnlock fails or appears to fail, there may 
46653: ** be a few redundant xLock() calls or a lock may be held for longer than
46654: ** required, but nothing really goes wrong.
46655: **
46656: ** The exception is when the database file is unlocked as the pager moves
46657: ** from ERROR to OPEN state. At this point there may be a hot-journal file 
46658: ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
46659: ** transition, by the same pager or any other). If the call to xUnlock()
46660: ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
46661: ** can confuse the call to xCheckReservedLock() call made later as part
46662: ** of hot-journal detection.
46663: **
46664: ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
46665: ** lock held by this process or any others". So xCheckReservedLock may 
46666: ** return true because the caller itself is holding an EXCLUSIVE lock (but
46667: ** doesn't know it because of a previous error in xUnlock). If this happens
46668: ** a hot-journal may be mistaken for a journal being created by an active
46669: ** transaction in another process, causing SQLite to read from the database
46670: ** without rolling it back.
46671: **
46672: ** To work around this, if a call to xUnlock() fails when unlocking the
46673: ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
46674: ** is only changed back to a real locking state after a successful call
46675: ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
46676: ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
46677: ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
46678: ** lock on the database file before attempting to roll it back. See function
46679: ** PagerSharedLock() for more detail.
46680: **
46681: ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
46682: ** PAGER_OPEN state.
46683: */
46684: #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
46685: 
46686: /*
46687: ** A macro used for invoking the codec if there is one
46688: */
46689: #ifdef SQLITE_HAS_CODEC
46690: # define CODEC1(P,D,N,X,E) \
46691:     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
46692: # define CODEC2(P,D,N,X,E,O) \
46693:     if( P->xCodec==0 ){ O=(char*)D; }else \
46694:     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
46695: #else
46696: # define CODEC1(P,D,N,X,E)   /* NO-OP */
46697: # define CODEC2(P,D,N,X,E,O) O=(char*)D
46698: #endif
46699: 
46700: /*
46701: ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
46702: ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
46703: ** This could conceivably cause corruption following a power failure on
46704: ** such a system. This is currently an undocumented limit.
46705: */
46706: #define MAX_SECTOR_SIZE 0x10000
46707: 
46708: 
46709: /*
46710: ** An instance of the following structure is allocated for each active
46711: ** savepoint and statement transaction in the system. All such structures
46712: ** are stored in the Pager.aSavepoint[] array, which is allocated and
46713: ** resized using sqlite3Realloc().
46714: **
46715: ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
46716: ** set to 0. If a journal-header is written into the main journal while
46717: ** the savepoint is active, then iHdrOffset is set to the byte offset 
46718: ** immediately following the last journal record written into the main
46719: ** journal before the journal-header. This is required during savepoint
46720: ** rollback (see pagerPlaybackSavepoint()).
46721: */
46722: typedef struct PagerSavepoint PagerSavepoint;
46723: struct PagerSavepoint {
46724:   i64 iOffset;                 /* Starting offset in main journal */
46725:   i64 iHdrOffset;              /* See above */
46726:   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
46727:   Pgno nOrig;                  /* Original number of pages in file */
46728:   Pgno iSubRec;                /* Index of first record in sub-journal */
46729: #ifndef SQLITE_OMIT_WAL
46730:   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
46731: #endif
46732: };
46733: 
46734: /*
46735: ** Bits of the Pager.doNotSpill flag.  See further description below.
46736: */
46737: #define SPILLFLAG_OFF         0x01 /* Never spill cache.  Set via pragma */
46738: #define SPILLFLAG_ROLLBACK    0x02 /* Current rolling back, so do not spill */
46739: #define SPILLFLAG_NOSYNC      0x04 /* Spill is ok, but do not sync */
46740: 
46741: /*
46742: ** An open page cache is an instance of struct Pager. A description of
46743: ** some of the more important member variables follows:
46744: **
46745: ** eState
46746: **
46747: **   The current 'state' of the pager object. See the comment and state
46748: **   diagram above for a description of the pager state.
46749: **
46750: ** eLock
46751: **
46752: **   For a real on-disk database, the current lock held on the database file -
46753: **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46754: **
46755: **   For a temporary or in-memory database (neither of which require any
46756: **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
46757: **   databases always have Pager.exclusiveMode==1, this tricks the pager
46758: **   logic into thinking that it already has all the locks it will ever
46759: **   need (and no reason to release them).
46760: **
46761: **   In some (obscure) circumstances, this variable may also be set to
46762: **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
46763: **   details.
46764: **
46765: ** changeCountDone
46766: **
46767: **   This boolean variable is used to make sure that the change-counter 
46768: **   (the 4-byte header field at byte offset 24 of the database file) is 
46769: **   not updated more often than necessary. 
46770: **
46771: **   It is set to true when the change-counter field is updated, which 
46772: **   can only happen if an exclusive lock is held on the database file.
46773: **   It is cleared (set to false) whenever an exclusive lock is 
46774: **   relinquished on the database file. Each time a transaction is committed,
46775: **   The changeCountDone flag is inspected. If it is true, the work of
46776: **   updating the change-counter is omitted for the current transaction.
46777: **
46778: **   This mechanism means that when running in exclusive mode, a connection 
46779: **   need only update the change-counter once, for the first transaction
46780: **   committed.
46781: **
46782: ** setMaster
46783: **
46784: **   When PagerCommitPhaseOne() is called to commit a transaction, it may
46785: **   (or may not) specify a master-journal name to be written into the 
46786: **   journal file before it is synced to disk.
46787: **
46788: **   Whether or not a journal file contains a master-journal pointer affects 
46789: **   the way in which the journal file is finalized after the transaction is 
46790: **   committed or rolled back when running in "journal_mode=PERSIST" mode.
46791: **   If a journal file does not contain a master-journal pointer, it is
46792: **   finalized by overwriting the first journal header with zeroes. If
46793: **   it does contain a master-journal pointer the journal file is finalized 
46794: **   by truncating it to zero bytes, just as if the connection were 
46795: **   running in "journal_mode=truncate" mode.
46796: **
46797: **   Journal files that contain master journal pointers cannot be finalized
46798: **   simply by overwriting the first journal-header with zeroes, as the
46799: **   master journal pointer could interfere with hot-journal rollback of any
46800: **   subsequently interrupted transaction that reuses the journal file.
46801: **
46802: **   The flag is cleared as soon as the journal file is finalized (either
46803: **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
46804: **   journal file from being successfully finalized, the setMaster flag
46805: **   is cleared anyway (and the pager will move to ERROR state).
46806: **
46807: ** doNotSpill
46808: **
46809: **   This variables control the behavior of cache-spills  (calls made by
46810: **   the pcache module to the pagerStress() routine to write cached data
46811: **   to the file-system in order to free up memory).
46812: **
46813: **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
46814: **   writing to the database from pagerStress() is disabled altogether.
46815: **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
46816: **   comes up during savepoint rollback that requires the pcache module
46817: **   to allocate a new page to prevent the journal file from being written
46818: **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
46819: **   case is a user preference.
46820: ** 
46821: **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from
46822: **   pagerStress() is permitted, but syncing the journal file is not.
46823: **   This flag is set by sqlite3PagerWrite() when the file-system sector-size
46824: **   is larger than the database page-size in order to prevent a journal sync
46825: **   from happening in between the journalling of two pages on the same sector. 
46826: **
46827: ** subjInMemory
46828: **
46829: **   This is a boolean variable. If true, then any required sub-journal
46830: **   is opened as an in-memory journal file. If false, then in-memory
46831: **   sub-journals are only used for in-memory pager files.
46832: **
46833: **   This variable is updated by the upper layer each time a new 
46834: **   write-transaction is opened.
46835: **
46836: ** dbSize, dbOrigSize, dbFileSize
46837: **
46838: **   Variable dbSize is set to the number of pages in the database file.
46839: **   It is valid in PAGER_READER and higher states (all states except for
46840: **   OPEN and ERROR). 
46841: **
46842: **   dbSize is set based on the size of the database file, which may be 
46843: **   larger than the size of the database (the value stored at offset
46844: **   28 of the database header by the btree). If the size of the file
46845: **   is not an integer multiple of the page-size, the value stored in
46846: **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
46847: **   Except, any file that is greater than 0 bytes in size is considered
46848: **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
46849: **   to dbSize==1).
46850: **
46851: **   During a write-transaction, if pages with page-numbers greater than
46852: **   dbSize are modified in the cache, dbSize is updated accordingly.
46853: **   Similarly, if the database is truncated using PagerTruncateImage(), 
46854: **   dbSize is updated.
46855: **
46856: **   Variables dbOrigSize and dbFileSize are valid in states 
46857: **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
46858: **   variable at the start of the transaction. It is used during rollback,
46859: **   and to determine whether or not pages need to be journalled before
46860: **   being modified.
46861: **
46862: **   Throughout a write-transaction, dbFileSize contains the size of
46863: **   the file on disk in pages. It is set to a copy of dbSize when the
46864: **   write-transaction is first opened, and updated when VFS calls are made
46865: **   to write or truncate the database file on disk. 
46866: **
46867: **   The only reason the dbFileSize variable is required is to suppress 
46868: **   unnecessary calls to xTruncate() after committing a transaction. If, 
46869: **   when a transaction is committed, the dbFileSize variable indicates 
46870: **   that the database file is larger than the database image (Pager.dbSize), 
46871: **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
46872: **   to measure the database file on disk, and then truncates it if required.
46873: **   dbFileSize is not used when rolling back a transaction. In this case
46874: **   pager_truncate() is called unconditionally (which means there may be
46875: **   a call to xFilesize() that is not strictly required). In either case,
46876: **   pager_truncate() may cause the file to become smaller or larger.
46877: **
46878: ** dbHintSize
46879: **
46880: **   The dbHintSize variable is used to limit the number of calls made to
46881: **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
46882: **
46883: **   dbHintSize is set to a copy of the dbSize variable when a
46884: **   write-transaction is opened (at the same time as dbFileSize and
46885: **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
46886: **   dbHintSize is increased to the number of pages that correspond to the
46887: **   size-hint passed to the method call. See pager_write_pagelist() for 
46888: **   details.
46889: **
46890: ** errCode
46891: **
46892: **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
46893: **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
46894: **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
46895: **   sub-codes.
46896: */
46897: struct Pager {
46898:   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
46899:   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
46900:   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
46901:   u8 useJournal;              /* Use a rollback journal on this file */
46902:   u8 noSync;                  /* Do not sync the journal if true */
46903:   u8 fullSync;                /* Do extra syncs of the journal for robustness */
46904:   u8 extraSync;               /* sync directory after journal delete */
46905:   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
46906:   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
46907:   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
46908:   u8 tempFile;                /* zFilename is a temporary or immutable file */
46909:   u8 noLock;                  /* Do not lock (except in WAL mode) */
46910:   u8 readOnly;                /* True for a read-only database */
46911:   u8 memDb;                   /* True to inhibit all file I/O */
46912: 
46913:   /**************************************************************************
46914:   ** The following block contains those class members that change during
46915:   ** routine operation.  Class members not in this block are either fixed
46916:   ** when the pager is first created or else only change when there is a
46917:   ** significant mode change (such as changing the page_size, locking_mode,
46918:   ** or the journal_mode).  From another view, these class members describe
46919:   ** the "state" of the pager, while other class members describe the
46920:   ** "configuration" of the pager.
46921:   */
46922:   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
46923:   u8 eLock;                   /* Current lock held on database file */
46924:   u8 changeCountDone;         /* Set after incrementing the change-counter */
46925:   u8 setMaster;               /* True if a m-j name has been written to jrnl */
46926:   u8 doNotSpill;              /* Do not spill the cache when non-zero */
46927:   u8 subjInMemory;            /* True to use in-memory sub-journals */
46928:   u8 bUseFetch;               /* True to use xFetch() */
46929:   u8 hasHeldSharedLock;       /* True if a shared lock has ever been held */
46930:   Pgno dbSize;                /* Number of pages in the database */
46931:   Pgno dbOrigSize;            /* dbSize before the current transaction */
46932:   Pgno dbFileSize;            /* Number of pages in the database file */
46933:   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
46934:   int errCode;                /* One of several kinds of errors */
46935:   int nRec;                   /* Pages journalled since last j-header written */
46936:   u32 cksumInit;              /* Quasi-random value added to every checksum */
46937:   u32 nSubRec;                /* Number of records written to sub-journal */
46938:   Bitvec *pInJournal;         /* One bit for each page in the database file */
46939:   sqlite3_file *fd;           /* File descriptor for database */
46940:   sqlite3_file *jfd;          /* File descriptor for main journal */
46941:   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
46942:   i64 journalOff;             /* Current write offset in the journal file */
46943:   i64 journalHdr;             /* Byte offset to previous journal header */
46944:   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
46945:   PagerSavepoint *aSavepoint; /* Array of active savepoints */
46946:   int nSavepoint;             /* Number of elements in aSavepoint[] */
46947:   u32 iDataVersion;           /* Changes whenever database content changes */
46948:   char dbFileVers[16];        /* Changes whenever database file changes */
46949: 
46950:   int nMmapOut;               /* Number of mmap pages currently outstanding */
46951:   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
46952:   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
46953:   /*
46954:   ** End of the routinely-changing class members
46955:   ***************************************************************************/
46956: 
46957:   u16 nExtra;                 /* Add this many bytes to each in-memory page */
46958:   i16 nReserve;               /* Number of unused bytes at end of each page */
46959:   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
46960:   u32 sectorSize;             /* Assumed sector size during rollback */
46961:   int pageSize;               /* Number of bytes in a page */
46962:   Pgno mxPgno;                /* Maximum allowed size of the database */
46963:   i64 journalSizeLimit;       /* Size limit for persistent journal files */
46964:   char *zFilename;            /* Name of the database file */
46965:   char *zJournal;             /* Name of the journal file */
46966:   int (*xBusyHandler)(void*); /* Function to call when busy */
46967:   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
46968:   int aStat[3];               /* Total cache hits, misses and writes */
46969: #ifdef SQLITE_TEST
46970:   int nRead;                  /* Database pages read */
46971: #endif
46972:   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
46973: #ifdef SQLITE_HAS_CODEC
46974:   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
46975:   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
46976:   void (*xCodecFree)(void*);             /* Destructor for the codec */
46977:   void *pCodec;               /* First argument to xCodec... methods */
46978: #endif
46979:   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
46980:   PCache *pPCache;            /* Pointer to page cache object */
46981: #ifndef SQLITE_OMIT_WAL
46982:   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
46983:   char *zWal;                 /* File name for write-ahead log */
46984: #endif
46985: };
46986: 
46987: /*
46988: ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
46989: ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
46990: ** or CACHE_WRITE to sqlite3_db_status().
46991: */
46992: #define PAGER_STAT_HIT   0
46993: #define PAGER_STAT_MISS  1
46994: #define PAGER_STAT_WRITE 2
46995: 
46996: /*
46997: ** The following global variables hold counters used for
46998: ** testing purposes only.  These variables do not exist in
46999: ** a non-testing build.  These variables are not thread-safe.
47000: */
47001: #ifdef SQLITE_TEST
47002: SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
47003: SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
47004: SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
47005: # define PAGER_INCR(v)  v++
47006: #else
47007: # define PAGER_INCR(v)
47008: #endif
47009: 
47010: 
47011: 
47012: /*
47013: ** Journal files begin with the following magic string.  The data
47014: ** was obtained from /dev/random.  It is used only as a sanity check.
47015: **
47016: ** Since version 2.8.0, the journal format contains additional sanity
47017: ** checking information.  If the power fails while the journal is being
47018: ** written, semi-random garbage data might appear in the journal
47019: ** file after power is restored.  If an attempt is then made
47020: ** to roll the journal back, the database could be corrupted.  The additional
47021: ** sanity checking data is an attempt to discover the garbage in the
47022: ** journal and ignore it.
47023: **
47024: ** The sanity checking information for the new journal format consists
47025: ** of a 32-bit checksum on each page of data.  The checksum covers both
47026: ** the page number and the pPager->pageSize bytes of data for the page.
47027: ** This cksum is initialized to a 32-bit random value that appears in the
47028: ** journal file right after the header.  The random initializer is important,
47029: ** because garbage data that appears at the end of a journal is likely
47030: ** data that was once in other files that have now been deleted.  If the
47031: ** garbage data came from an obsolete journal file, the checksums might
47032: ** be correct.  But by initializing the checksum to random value which
47033: ** is different for every journal, we minimize that risk.
47034: */
47035: static const unsigned char aJournalMagic[] = {
47036:   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
47037: };
47038: 
47039: /*
47040: ** The size of the of each page record in the journal is given by
47041: ** the following macro.
47042: */
47043: #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
47044: 
47045: /*
47046: ** The journal header size for this pager. This is usually the same 
47047: ** size as a single disk sector. See also setSectorSize().
47048: */
47049: #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
47050: 
47051: /*
47052: ** The macro MEMDB is true if we are dealing with an in-memory database.
47053: ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
47054: ** the value of MEMDB will be a constant and the compiler will optimize
47055: ** out code that would never execute.
47056: */
47057: #ifdef SQLITE_OMIT_MEMORYDB
47058: # define MEMDB 0
47059: #else
47060: # define MEMDB pPager->memDb
47061: #endif
47062: 
47063: /*
47064: ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
47065: ** interfaces to access the database using memory-mapped I/O.
47066: */
47067: #if SQLITE_MAX_MMAP_SIZE>0
47068: # define USEFETCH(x) ((x)->bUseFetch)
47069: #else
47070: # define USEFETCH(x) 0
47071: #endif
47072: 
47073: /*
47074: ** The maximum legal page number is (2^31 - 1).
47075: */
47076: #define PAGER_MAX_PGNO 2147483647
47077: 
47078: /*
47079: ** The argument to this macro is a file descriptor (type sqlite3_file*).
47080: ** Return 0 if it is not open, or non-zero (but not 1) if it is.
47081: **
47082: ** This is so that expressions can be written as:
47083: **
47084: **   if( isOpen(pPager->jfd) ){ ...
47085: **
47086: ** instead of
47087: **
47088: **   if( pPager->jfd->pMethods ){ ...
47089: */
47090: #define isOpen(pFd) ((pFd)->pMethods!=0)
47091: 
47092: /*
47093: ** Return true if this pager uses a write-ahead log instead of the usual
47094: ** rollback journal. Otherwise false.
47095: */
47096: #ifndef SQLITE_OMIT_WAL
47097: static int pagerUseWal(Pager *pPager){
47098:   return (pPager->pWal!=0);
47099: }
47100: #else
47101: # define pagerUseWal(x) 0
47102: # define pagerRollbackWal(x) 0
47103: # define pagerWalFrames(v,w,x,y) 0
47104: # define pagerOpenWalIfPresent(z) SQLITE_OK
47105: # define pagerBeginReadTransaction(z) SQLITE_OK
47106: #endif
47107: 
47108: #ifndef NDEBUG 
47109: /*
47110: ** Usage:
47111: **
47112: **   assert( assert_pager_state(pPager) );
47113: **
47114: ** This function runs many asserts to try to find inconsistencies in
47115: ** the internal state of the Pager object.
47116: */
47117: static int assert_pager_state(Pager *p){
47118:   Pager *pPager = p;
47119: 
47120:   /* State must be valid. */
47121:   assert( p->eState==PAGER_OPEN
47122:        || p->eState==PAGER_READER
47123:        || p->eState==PAGER_WRITER_LOCKED
47124:        || p->eState==PAGER_WRITER_CACHEMOD
47125:        || p->eState==PAGER_WRITER_DBMOD
47126:        || p->eState==PAGER_WRITER_FINISHED
47127:        || p->eState==PAGER_ERROR
47128:   );
47129: 
47130:   /* Regardless of the current state, a temp-file connection always behaves
47131:   ** as if it has an exclusive lock on the database file. It never updates
47132:   ** the change-counter field, so the changeCountDone flag is always set.
47133:   */
47134:   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
47135:   assert( p->tempFile==0 || pPager->changeCountDone );
47136: 
47137:   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
47138:   ** And if the journal-mode is "OFF", the journal file must not be open.
47139:   */
47140:   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
47141:   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
47142: 
47143:   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
47144:   ** this means an in-memory pager performs no IO at all, it cannot encounter 
47145:   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
47146:   ** a journal file. (although the in-memory journal implementation may 
47147:   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
47148:   ** is therefore not possible for an in-memory pager to enter the ERROR 
47149:   ** state.
47150:   */
47151:   if( MEMDB ){
47152:     assert( !isOpen(p->fd) );
47153:     assert( p->noSync );
47154:     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
47155:          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
47156:     );
47157:     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
47158:     assert( pagerUseWal(p)==0 );
47159:   }
47160: 
47161:   /* If changeCountDone is set, a RESERVED lock or greater must be held
47162:   ** on the file.
47163:   */
47164:   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
47165:   assert( p->eLock!=PENDING_LOCK );
47166: 
47167:   switch( p->eState ){
47168:     case PAGER_OPEN:
47169:       assert( !MEMDB );
47170:       assert( pPager->errCode==SQLITE_OK );
47171:       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
47172:       break;
47173: 
47174:     case PAGER_READER:
47175:       assert( pPager->errCode==SQLITE_OK );
47176:       assert( p->eLock!=UNKNOWN_LOCK );
47177:       assert( p->eLock>=SHARED_LOCK );
47178:       break;
47179: 
47180:     case PAGER_WRITER_LOCKED:
47181:       assert( p->eLock!=UNKNOWN_LOCK );
47182:       assert( pPager->errCode==SQLITE_OK );
47183:       if( !pagerUseWal(pPager) ){
47184:         assert( p->eLock>=RESERVED_LOCK );
47185:       }
47186:       assert( pPager->dbSize==pPager->dbOrigSize );
47187:       assert( pPager->dbOrigSize==pPager->dbFileSize );
47188:       assert( pPager->dbOrigSize==pPager->dbHintSize );
47189:       assert( pPager->setMaster==0 );
47190:       break;
47191: 
47192:     case PAGER_WRITER_CACHEMOD:
47193:       assert( p->eLock!=UNKNOWN_LOCK );
47194:       assert( pPager->errCode==SQLITE_OK );
47195:       if( !pagerUseWal(pPager) ){
47196:         /* It is possible that if journal_mode=wal here that neither the
47197:         ** journal file nor the WAL file are open. This happens during
47198:         ** a rollback transaction that switches from journal_mode=off
47199:         ** to journal_mode=wal.
47200:         */
47201:         assert( p->eLock>=RESERVED_LOCK );
47202:         assert( isOpen(p->jfd) 
47203:              || p->journalMode==PAGER_JOURNALMODE_OFF 
47204:              || p->journalMode==PAGER_JOURNALMODE_WAL 
47205:         );
47206:       }
47207:       assert( pPager->dbOrigSize==pPager->dbFileSize );
47208:       assert( pPager->dbOrigSize==pPager->dbHintSize );
47209:       break;
47210: 
47211:     case PAGER_WRITER_DBMOD:
47212:       assert( p->eLock==EXCLUSIVE_LOCK );
47213:       assert( pPager->errCode==SQLITE_OK );
47214:       assert( !pagerUseWal(pPager) );
47215:       assert( p->eLock>=EXCLUSIVE_LOCK );
47216:       assert( isOpen(p->jfd) 
47217:            || p->journalMode==PAGER_JOURNALMODE_OFF 
47218:            || p->journalMode==PAGER_JOURNALMODE_WAL 
47219:       );
47220:       assert( pPager->dbOrigSize<=pPager->dbHintSize );
47221:       break;
47222: 
47223:     case PAGER_WRITER_FINISHED:
47224:       assert( p->eLock==EXCLUSIVE_LOCK );
47225:       assert( pPager->errCode==SQLITE_OK );
47226:       assert( !pagerUseWal(pPager) );
47227:       assert( isOpen(p->jfd) 
47228:            || p->journalMode==PAGER_JOURNALMODE_OFF 
47229:            || p->journalMode==PAGER_JOURNALMODE_WAL 
47230:       );
47231:       break;
47232: 
47233:     case PAGER_ERROR:
47234:       /* There must be at least one outstanding reference to the pager if
47235:       ** in ERROR state. Otherwise the pager should have already dropped
47236:       ** back to OPEN state.
47237:       */
47238:       assert( pPager->errCode!=SQLITE_OK );
47239:       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
47240:       break;
47241:   }
47242: 
47243:   return 1;
47244: }
47245: #endif /* ifndef NDEBUG */
47246: 
47247: #ifdef SQLITE_DEBUG 
47248: /*
47249: ** Return a pointer to a human readable string in a static buffer
47250: ** containing the state of the Pager object passed as an argument. This
47251: ** is intended to be used within debuggers. For example, as an alternative
47252: ** to "print *pPager" in gdb:
47253: **
47254: ** (gdb) printf "%s", print_pager_state(pPager)
47255: */
47256: static char *print_pager_state(Pager *p){
47257:   static char zRet[1024];
47258: 
47259:   sqlite3_snprintf(1024, zRet,
47260:       "Filename:      %s\n"
47261:       "State:         %s errCode=%d\n"
47262:       "Lock:          %s\n"
47263:       "Locking mode:  locking_mode=%s\n"
47264:       "Journal mode:  journal_mode=%s\n"
47265:       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
47266:       "Journal:       journalOff=%lld journalHdr=%lld\n"
47267:       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
47268:       , p->zFilename
47269:       , p->eState==PAGER_OPEN            ? "OPEN" :
47270:         p->eState==PAGER_READER          ? "READER" :
47271:         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
47272:         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
47273:         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
47274:         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
47275:         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
47276:       , (int)p->errCode
47277:       , p->eLock==NO_LOCK         ? "NO_LOCK" :
47278:         p->eLock==RESERVED_LOCK   ? "RESERVED" :
47279:         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
47280:         p->eLock==SHARED_LOCK     ? "SHARED" :
47281:         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
47282:       , p->exclusiveMode ? "exclusive" : "normal"
47283:       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
47284:         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
47285:         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
47286:         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
47287:         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
47288:         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
47289:       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
47290:       , p->journalOff, p->journalHdr
47291:       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
47292:   );
47293: 
47294:   return zRet;
47295: }
47296: #endif
47297: 
47298: /*
47299: ** Return true if it is necessary to write page *pPg into the sub-journal.
47300: ** A page needs to be written into the sub-journal if there exists one
47301: ** or more open savepoints for which:
47302: **
47303: **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
47304: **   * The bit corresponding to the page-number is not set in
47305: **     PagerSavepoint.pInSavepoint.
47306: */
47307: static int subjRequiresPage(PgHdr *pPg){
47308:   Pager *pPager = pPg->pPager;
47309:   PagerSavepoint *p;
47310:   Pgno pgno = pPg->pgno;
47311:   int i;
47312:   for(i=0; i<pPager->nSavepoint; i++){
47313:     p = &pPager->aSavepoint[i];
47314:     if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
47315:       return 1;
47316:     }
47317:   }
47318:   return 0;
47319: }
47320: 
47321: #ifdef SQLITE_DEBUG
47322: /*
47323: ** Return true if the page is already in the journal file.
47324: */
47325: static int pageInJournal(Pager *pPager, PgHdr *pPg){
47326:   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
47327: }
47328: #endif
47329: 
47330: /*
47331: ** Read a 32-bit integer from the given file descriptor.  Store the integer
47332: ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
47333: ** error code is something goes wrong.
47334: **
47335: ** All values are stored on disk as big-endian.
47336: */
47337: static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
47338:   unsigned char ac[4];
47339:   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
47340:   if( rc==SQLITE_OK ){
47341:     *pRes = sqlite3Get4byte(ac);
47342:   }
47343:   return rc;
47344: }
47345: 
47346: /*
47347: ** Write a 32-bit integer into a string buffer in big-endian byte order.
47348: */
47349: #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
47350: 
47351: 
47352: /*
47353: ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
47354: ** on success or an error code is something goes wrong.
47355: */
47356: static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
47357:   char ac[4];
47358:   put32bits(ac, val);
47359:   return sqlite3OsWrite(fd, ac, 4, offset);
47360: }
47361: 
47362: /*
47363: ** Unlock the database file to level eLock, which must be either NO_LOCK
47364: ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
47365: ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
47366: **
47367: ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
47368: ** called, do not modify it. See the comment above the #define of 
47369: ** UNKNOWN_LOCK for an explanation of this.
47370: */
47371: static int pagerUnlockDb(Pager *pPager, int eLock){
47372:   int rc = SQLITE_OK;
47373: 
47374:   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
47375:   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
47376:   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
47377:   if( isOpen(pPager->fd) ){
47378:     assert( pPager->eLock>=eLock );
47379:     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
47380:     if( pPager->eLock!=UNKNOWN_LOCK ){
47381:       pPager->eLock = (u8)eLock;
47382:     }
47383:     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
47384:   }
47385:   return rc;
47386: }
47387: 
47388: /*
47389: ** Lock the database file to level eLock, which must be either SHARED_LOCK,
47390: ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
47391: ** Pager.eLock variable to the new locking state. 
47392: **
47393: ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
47394: ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
47395: ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
47396: ** of this.
47397: */
47398: static int pagerLockDb(Pager *pPager, int eLock){
47399:   int rc = SQLITE_OK;
47400: 
47401:   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
47402:   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
47403:     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
47404:     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
47405:       pPager->eLock = (u8)eLock;
47406:       IOTRACE(("LOCK %p %d\n", pPager, eLock))
47407:     }
47408:   }
47409:   return rc;
47410: }
47411: 
47412: /*
47413: ** This function determines whether or not the atomic-write optimization
47414: ** can be used with this pager. The optimization can be used if:
47415: **
47416: **  (a) the value returned by OsDeviceCharacteristics() indicates that
47417: **      a database page may be written atomically, and
47418: **  (b) the value returned by OsSectorSize() is less than or equal
47419: **      to the page size.
47420: **
47421: ** The optimization is also always enabled for temporary files. It is
47422: ** an error to call this function if pPager is opened on an in-memory
47423: ** database.
47424: **
47425: ** If the optimization cannot be used, 0 is returned. If it can be used,
47426: ** then the value returned is the size of the journal file when it
47427: ** contains rollback data for exactly one page.
47428: */
47429: #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47430: static int jrnlBufferSize(Pager *pPager){
47431:   assert( !MEMDB );
47432:   if( !pPager->tempFile ){
47433:     int dc;                           /* Device characteristics */
47434:     int nSector;                      /* Sector size */
47435:     int szPage;                       /* Page size */
47436: 
47437:     assert( isOpen(pPager->fd) );
47438:     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
47439:     nSector = pPager->sectorSize;
47440:     szPage = pPager->pageSize;
47441: 
47442:     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
47443:     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
47444:     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
47445:       return 0;
47446:     }
47447:   }
47448: 
47449:   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
47450: }
47451: #else
47452: # define jrnlBufferSize(x) 0
47453: #endif
47454: 
47455: /*
47456: ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
47457: ** on the cache using a hash function.  This is used for testing
47458: ** and debugging only.
47459: */
47460: #ifdef SQLITE_CHECK_PAGES
47461: /*
47462: ** Return a 32-bit hash of the page data for pPage.
47463: */
47464: static u32 pager_datahash(int nByte, unsigned char *pData){
47465:   u32 hash = 0;
47466:   int i;
47467:   for(i=0; i<nByte; i++){
47468:     hash = (hash*1039) + pData[i];
47469:   }
47470:   return hash;
47471: }
47472: static u32 pager_pagehash(PgHdr *pPage){
47473:   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
47474: }
47475: static void pager_set_pagehash(PgHdr *pPage){
47476:   pPage->pageHash = pager_pagehash(pPage);
47477: }
47478: 
47479: /*
47480: ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
47481: ** is defined, and NDEBUG is not defined, an assert() statement checks
47482: ** that the page is either dirty or still matches the calculated page-hash.
47483: */
47484: #define CHECK_PAGE(x) checkPage(x)
47485: static void checkPage(PgHdr *pPg){
47486:   Pager *pPager = pPg->pPager;
47487:   assert( pPager->eState!=PAGER_ERROR );
47488:   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
47489: }
47490: 
47491: #else
47492: #define pager_datahash(X,Y)  0
47493: #define pager_pagehash(X)  0
47494: #define pager_set_pagehash(X)
47495: #define CHECK_PAGE(x)
47496: #endif  /* SQLITE_CHECK_PAGES */
47497: 
47498: /*
47499: ** When this is called the journal file for pager pPager must be open.
47500: ** This function attempts to read a master journal file name from the 
47501: ** end of the file and, if successful, copies it into memory supplied 
47502: ** by the caller. See comments above writeMasterJournal() for the format
47503: ** used to store a master journal file name at the end of a journal file.
47504: **
47505: ** zMaster must point to a buffer of at least nMaster bytes allocated by
47506: ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
47507: ** enough space to write the master journal name). If the master journal
47508: ** name in the journal is longer than nMaster bytes (including a
47509: ** nul-terminator), then this is handled as if no master journal name
47510: ** were present in the journal.
47511: **
47512: ** If a master journal file name is present at the end of the journal
47513: ** file, then it is copied into the buffer pointed to by zMaster. A
47514: ** nul-terminator byte is appended to the buffer following the master
47515: ** journal file name.
47516: **
47517: ** If it is determined that no master journal file name is present 
47518: ** zMaster[0] is set to 0 and SQLITE_OK returned.
47519: **
47520: ** If an error occurs while reading from the journal file, an SQLite
47521: ** error code is returned.
47522: */
47523: static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
47524:   int rc;                    /* Return code */
47525:   u32 len;                   /* Length in bytes of master journal name */
47526:   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
47527:   u32 cksum;                 /* MJ checksum value read from journal */
47528:   u32 u;                     /* Unsigned loop counter */
47529:   unsigned char aMagic[8];   /* A buffer to hold the magic header */
47530:   zMaster[0] = '\0';
47531: 
47532:   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
47533:    || szJ<16
47534:    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
47535:    || len>=nMaster 
47536:    || len==0 
47537:    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
47538:    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
47539:    || memcmp(aMagic, aJournalMagic, 8)
47540:    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
47541:   ){
47542:     return rc;
47543:   }
47544: 
47545:   /* See if the checksum matches the master journal name */
47546:   for(u=0; u<len; u++){
47547:     cksum -= zMaster[u];
47548:   }
47549:   if( cksum ){
47550:     /* If the checksum doesn't add up, then one or more of the disk sectors
47551:     ** containing the master journal filename is corrupted. This means
47552:     ** definitely roll back, so just return SQLITE_OK and report a (nul)
47553:     ** master-journal filename.
47554:     */
47555:     len = 0;
47556:   }
47557:   zMaster[len] = '\0';
47558:    
47559:   return SQLITE_OK;
47560: }
47561: 
47562: /*
47563: ** Return the offset of the sector boundary at or immediately 
47564: ** following the value in pPager->journalOff, assuming a sector 
47565: ** size of pPager->sectorSize bytes.
47566: **
47567: ** i.e for a sector size of 512:
47568: **
47569: **   Pager.journalOff          Return value
47570: **   ---------------------------------------
47571: **   0                         0
47572: **   512                       512
47573: **   100                       512
47574: **   2000                      2048
47575: ** 
47576: */
47577: static i64 journalHdrOffset(Pager *pPager){
47578:   i64 offset = 0;
47579:   i64 c = pPager->journalOff;
47580:   if( c ){
47581:     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
47582:   }
47583:   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
47584:   assert( offset>=c );
47585:   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
47586:   return offset;
47587: }
47588: 
47589: /*
47590: ** The journal file must be open when this function is called.
47591: **
47592: ** This function is a no-op if the journal file has not been written to
47593: ** within the current transaction (i.e. if Pager.journalOff==0).
47594: **
47595: ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
47596: ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
47597: ** zero the 28-byte header at the start of the journal file. In either case, 
47598: ** if the pager is not in no-sync mode, sync the journal file immediately 
47599: ** after writing or truncating it.
47600: **
47601: ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
47602: ** following the truncation or zeroing described above the size of the 
47603: ** journal file in bytes is larger than this value, then truncate the
47604: ** journal file to Pager.journalSizeLimit bytes. The journal file does
47605: ** not need to be synced following this operation.
47606: **
47607: ** If an IO error occurs, abandon processing and return the IO error code.
47608: ** Otherwise, return SQLITE_OK.
47609: */
47610: static int zeroJournalHdr(Pager *pPager, int doTruncate){
47611:   int rc = SQLITE_OK;                               /* Return code */
47612:   assert( isOpen(pPager->jfd) );
47613:   assert( !sqlite3JournalIsInMemory(pPager->jfd) );
47614:   if( pPager->journalOff ){
47615:     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
47616: 
47617:     IOTRACE(("JZEROHDR %p\n", pPager))
47618:     if( doTruncate || iLimit==0 ){
47619:       rc = sqlite3OsTruncate(pPager->jfd, 0);
47620:     }else{
47621:       static const char zeroHdr[28] = {0};
47622:       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
47623:     }
47624:     if( rc==SQLITE_OK && !pPager->noSync ){
47625:       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
47626:     }
47627: 
47628:     /* At this point the transaction is committed but the write lock 
47629:     ** is still held on the file. If there is a size limit configured for 
47630:     ** the persistent journal and the journal file currently consumes more
47631:     ** space than that limit allows for, truncate it now. There is no need
47632:     ** to sync the file following this operation.
47633:     */
47634:     if( rc==SQLITE_OK && iLimit>0 ){
47635:       i64 sz;
47636:       rc = sqlite3OsFileSize(pPager->jfd, &sz);
47637:       if( rc==SQLITE_OK && sz>iLimit ){
47638:         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
47639:       }
47640:     }
47641:   }
47642:   return rc;
47643: }
47644: 
47645: /*
47646: ** The journal file must be open when this routine is called. A journal
47647: ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
47648: ** current location.
47649: **
47650: ** The format for the journal header is as follows:
47651: ** - 8 bytes: Magic identifying journal format.
47652: ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
47653: ** - 4 bytes: Random number used for page hash.
47654: ** - 4 bytes: Initial database page count.
47655: ** - 4 bytes: Sector size used by the process that wrote this journal.
47656: ** - 4 bytes: Database page size.
47657: ** 
47658: ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
47659: */
47660: static int writeJournalHdr(Pager *pPager){
47661:   int rc = SQLITE_OK;                 /* Return code */
47662:   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
47663:   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
47664:   u32 nWrite;                         /* Bytes of header sector written */
47665:   int ii;                             /* Loop counter */
47666: 
47667:   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
47668: 
47669:   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
47670:     nHeader = JOURNAL_HDR_SZ(pPager);
47671:   }
47672: 
47673:   /* If there are active savepoints and any of them were created 
47674:   ** since the most recent journal header was written, update the 
47675:   ** PagerSavepoint.iHdrOffset fields now.
47676:   */
47677:   for(ii=0; ii<pPager->nSavepoint; ii++){
47678:     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
47679:       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
47680:     }
47681:   }
47682: 
47683:   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
47684: 
47685:   /* 
47686:   ** Write the nRec Field - the number of page records that follow this
47687:   ** journal header. Normally, zero is written to this value at this time.
47688:   ** After the records are added to the journal (and the journal synced, 
47689:   ** if in full-sync mode), the zero is overwritten with the true number
47690:   ** of records (see syncJournal()).
47691:   **
47692:   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
47693:   ** reading the journal this value tells SQLite to assume that the
47694:   ** rest of the journal file contains valid page records. This assumption
47695:   ** is dangerous, as if a failure occurred whilst writing to the journal
47696:   ** file it may contain some garbage data. There are two scenarios
47697:   ** where this risk can be ignored:
47698:   **
47699:   **   * When the pager is in no-sync mode. Corruption can follow a
47700:   **     power failure in this case anyway.
47701:   **
47702:   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
47703:   **     that garbage data is never appended to the journal file.
47704:   */
47705:   assert( isOpen(pPager->fd) || pPager->noSync );
47706:   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
47707:    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
47708:   ){
47709:     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47710:     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
47711:   }else{
47712:     memset(zHeader, 0, sizeof(aJournalMagic)+4);
47713:   }
47714: 
47715:   /* The random check-hash initializer */ 
47716:   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
47717:   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
47718:   /* The initial database size */
47719:   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
47720:   /* The assumed sector size for this process */
47721:   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
47722: 
47723:   /* The page size */
47724:   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
47725: 
47726:   /* Initializing the tail of the buffer is not necessary.  Everything
47727:   ** works find if the following memset() is omitted.  But initializing
47728:   ** the memory prevents valgrind from complaining, so we are willing to
47729:   ** take the performance hit.
47730:   */
47731:   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
47732:          nHeader-(sizeof(aJournalMagic)+20));
47733: 
47734:   /* In theory, it is only necessary to write the 28 bytes that the 
47735:   ** journal header consumes to the journal file here. Then increment the 
47736:   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
47737:   ** record is written to the following sector (leaving a gap in the file
47738:   ** that will be implicitly filled in by the OS).
47739:   **
47740:   ** However it has been discovered that on some systems this pattern can 
47741:   ** be significantly slower than contiguously writing data to the file,
47742:   ** even if that means explicitly writing data to the block of 
47743:   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
47744:   ** is done. 
47745:   **
47746:   ** The loop is required here in case the sector-size is larger than the 
47747:   ** database page size. Since the zHeader buffer is only Pager.pageSize
47748:   ** bytes in size, more than one call to sqlite3OsWrite() may be required
47749:   ** to populate the entire journal header sector.
47750:   */ 
47751:   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
47752:     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
47753:     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
47754:     assert( pPager->journalHdr <= pPager->journalOff );
47755:     pPager->journalOff += nHeader;
47756:   }
47757: 
47758:   return rc;
47759: }
47760: 
47761: /*
47762: ** The journal file must be open when this is called. A journal header file
47763: ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
47764: ** file. The current location in the journal file is given by
47765: ** pPager->journalOff. See comments above function writeJournalHdr() for
47766: ** a description of the journal header format.
47767: **
47768: ** If the header is read successfully, *pNRec is set to the number of
47769: ** page records following this header and *pDbSize is set to the size of the
47770: ** database before the transaction began, in pages. Also, pPager->cksumInit
47771: ** is set to the value read from the journal header. SQLITE_OK is returned
47772: ** in this case.
47773: **
47774: ** If the journal header file appears to be corrupted, SQLITE_DONE is
47775: ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
47776: ** cannot be read from the journal file an error code is returned.
47777: */
47778: static int readJournalHdr(
47779:   Pager *pPager,               /* Pager object */
47780:   int isHot,
47781:   i64 journalSize,             /* Size of the open journal file in bytes */
47782:   u32 *pNRec,                  /* OUT: Value read from the nRec field */
47783:   u32 *pDbSize                 /* OUT: Value of original database size field */
47784: ){
47785:   int rc;                      /* Return code */
47786:   unsigned char aMagic[8];     /* A buffer to hold the magic header */
47787:   i64 iHdrOff;                 /* Offset of journal header being read */
47788: 
47789:   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
47790: 
47791:   /* Advance Pager.journalOff to the start of the next sector. If the
47792:   ** journal file is too small for there to be a header stored at this
47793:   ** point, return SQLITE_DONE.
47794:   */
47795:   pPager->journalOff = journalHdrOffset(pPager);
47796:   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
47797:     return SQLITE_DONE;
47798:   }
47799:   iHdrOff = pPager->journalOff;
47800: 
47801:   /* Read in the first 8 bytes of the journal header. If they do not match
47802:   ** the  magic string found at the start of each journal header, return
47803:   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
47804:   ** proceed.
47805:   */
47806:   if( isHot || iHdrOff!=pPager->journalHdr ){
47807:     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
47808:     if( rc ){
47809:       return rc;
47810:     }
47811:     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
47812:       return SQLITE_DONE;
47813:     }
47814:   }
47815: 
47816:   /* Read the first three 32-bit fields of the journal header: The nRec
47817:   ** field, the checksum-initializer and the database size at the start
47818:   ** of the transaction. Return an error code if anything goes wrong.
47819:   */
47820:   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
47821:    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
47822:    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
47823:   ){
47824:     return rc;
47825:   }
47826: 
47827:   if( pPager->journalOff==0 ){
47828:     u32 iPageSize;               /* Page-size field of journal header */
47829:     u32 iSectorSize;             /* Sector-size field of journal header */
47830: 
47831:     /* Read the page-size and sector-size journal header fields. */
47832:     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
47833:      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
47834:     ){
47835:       return rc;
47836:     }
47837: 
47838:     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
47839:     ** journal header to zero. In this case, assume that the Pager.pageSize
47840:     ** variable is already set to the correct page size.
47841:     */
47842:     if( iPageSize==0 ){
47843:       iPageSize = pPager->pageSize;
47844:     }
47845: 
47846:     /* Check that the values read from the page-size and sector-size fields
47847:     ** are within range. To be 'in range', both values need to be a power
47848:     ** of two greater than or equal to 512 or 32, and not greater than their 
47849:     ** respective compile time maximum limits.
47850:     */
47851:     if( iPageSize<512                  || iSectorSize<32
47852:      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
47853:      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
47854:     ){
47855:       /* If the either the page-size or sector-size in the journal-header is 
47856:       ** invalid, then the process that wrote the journal-header must have 
47857:       ** crashed before the header was synced. In this case stop reading 
47858:       ** the journal file here.
47859:       */
47860:       return SQLITE_DONE;
47861:     }
47862: 
47863:     /* Update the page-size to match the value read from the journal. 
47864:     ** Use a testcase() macro to make sure that malloc failure within 
47865:     ** PagerSetPagesize() is tested.
47866:     */
47867:     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
47868:     testcase( rc!=SQLITE_OK );
47869: 
47870:     /* Update the assumed sector-size to match the value used by 
47871:     ** the process that created this journal. If this journal was
47872:     ** created by a process other than this one, then this routine
47873:     ** is being called from within pager_playback(). The local value
47874:     ** of Pager.sectorSize is restored at the end of that routine.
47875:     */
47876:     pPager->sectorSize = iSectorSize;
47877:   }
47878: 
47879:   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
47880:   return rc;
47881: }
47882: 
47883: 
47884: /*
47885: ** Write the supplied master journal name into the journal file for pager
47886: ** pPager at the current location. The master journal name must be the last
47887: ** thing written to a journal file. If the pager is in full-sync mode, the
47888: ** journal file descriptor is advanced to the next sector boundary before
47889: ** anything is written. The format is:
47890: **
47891: **   + 4 bytes: PAGER_MJ_PGNO.
47892: **   + N bytes: Master journal filename in utf-8.
47893: **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
47894: **   + 4 bytes: Master journal name checksum.
47895: **   + 8 bytes: aJournalMagic[].
47896: **
47897: ** The master journal page checksum is the sum of the bytes in the master
47898: ** journal name, where each byte is interpreted as a signed 8-bit integer.
47899: **
47900: ** If zMaster is a NULL pointer (occurs for a single database transaction), 
47901: ** this call is a no-op.
47902: */
47903: static int writeMasterJournal(Pager *pPager, const char *zMaster){
47904:   int rc;                          /* Return code */
47905:   int nMaster;                     /* Length of string zMaster */
47906:   i64 iHdrOff;                     /* Offset of header in journal file */
47907:   i64 jrnlSize;                    /* Size of journal file on disk */
47908:   u32 cksum = 0;                   /* Checksum of string zMaster */
47909: 
47910:   assert( pPager->setMaster==0 );
47911:   assert( !pagerUseWal(pPager) );
47912: 
47913:   if( !zMaster 
47914:    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
47915:    || !isOpen(pPager->jfd)
47916:   ){
47917:     return SQLITE_OK;
47918:   }
47919:   pPager->setMaster = 1;
47920:   assert( pPager->journalHdr <= pPager->journalOff );
47921: 
47922:   /* Calculate the length in bytes and the checksum of zMaster */
47923:   for(nMaster=0; zMaster[nMaster]; nMaster++){
47924:     cksum += zMaster[nMaster];
47925:   }
47926: 
47927:   /* If in full-sync mode, advance to the next disk sector before writing
47928:   ** the master journal name. This is in case the previous page written to
47929:   ** the journal has already been synced.
47930:   */
47931:   if( pPager->fullSync ){
47932:     pPager->journalOff = journalHdrOffset(pPager);
47933:   }
47934:   iHdrOff = pPager->journalOff;
47935: 
47936:   /* Write the master journal data to the end of the journal file. If
47937:   ** an error occurs, return the error code to the caller.
47938:   */
47939:   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
47940:    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
47941:    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
47942:    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
47943:    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
47944:                                  iHdrOff+4+nMaster+8)))
47945:   ){
47946:     return rc;
47947:   }
47948:   pPager->journalOff += (nMaster+20);
47949: 
47950:   /* If the pager is in peristent-journal mode, then the physical 
47951:   ** journal-file may extend past the end of the master-journal name
47952:   ** and 8 bytes of magic data just written to the file. This is 
47953:   ** dangerous because the code to rollback a hot-journal file
47954:   ** will not be able to find the master-journal name to determine 
47955:   ** whether or not the journal is hot. 
47956:   **
47957:   ** Easiest thing to do in this scenario is to truncate the journal 
47958:   ** file to the required size.
47959:   */ 
47960:   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
47961:    && jrnlSize>pPager->journalOff
47962:   ){
47963:     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
47964:   }
47965:   return rc;
47966: }
47967: 
47968: /*
47969: ** Discard the entire contents of the in-memory page-cache.
47970: */
47971: static void pager_reset(Pager *pPager){
47972:   pPager->iDataVersion++;
47973:   sqlite3BackupRestart(pPager->pBackup);
47974:   sqlite3PcacheClear(pPager->pPCache);
47975: }
47976: 
47977: /*
47978: ** Return the pPager->iDataVersion value
47979: */
47980: SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
47981:   assert( pPager->eState>PAGER_OPEN );
47982:   return pPager->iDataVersion;
47983: }
47984: 
47985: /*
47986: ** Free all structures in the Pager.aSavepoint[] array and set both
47987: ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
47988: ** if it is open and the pager is not in exclusive mode.
47989: */
47990: static void releaseAllSavepoints(Pager *pPager){
47991:   int ii;               /* Iterator for looping through Pager.aSavepoint */
47992:   for(ii=0; ii<pPager->nSavepoint; ii++){
47993:     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
47994:   }
47995:   if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
47996:     sqlite3OsClose(pPager->sjfd);
47997:   }
47998:   sqlite3_free(pPager->aSavepoint);
47999:   pPager->aSavepoint = 0;
48000:   pPager->nSavepoint = 0;
48001:   pPager->nSubRec = 0;
48002: }
48003: 
48004: /*
48005: ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
48006: ** bitvecs of all open savepoints. Return SQLITE_OK if successful
48007: ** or SQLITE_NOMEM if a malloc failure occurs.
48008: */
48009: static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
48010:   int ii;                   /* Loop counter */
48011:   int rc = SQLITE_OK;       /* Result code */
48012: 
48013:   for(ii=0; ii<pPager->nSavepoint; ii++){
48014:     PagerSavepoint *p = &pPager->aSavepoint[ii];
48015:     if( pgno<=p->nOrig ){
48016:       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
48017:       testcase( rc==SQLITE_NOMEM );
48018:       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
48019:     }
48020:   }
48021:   return rc;
48022: }
48023: 
48024: /*
48025: ** This function is a no-op if the pager is in exclusive mode and not
48026: ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
48027: ** state.
48028: **
48029: ** If the pager is not in exclusive-access mode, the database file is
48030: ** completely unlocked. If the file is unlocked and the file-system does
48031: ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
48032: ** closed (if it is open).
48033: **
48034: ** If the pager is in ERROR state when this function is called, the 
48035: ** contents of the pager cache are discarded before switching back to 
48036: ** the OPEN state. Regardless of whether the pager is in exclusive-mode
48037: ** or not, any journal file left in the file-system will be treated
48038: ** as a hot-journal and rolled back the next time a read-transaction
48039: ** is opened (by this or by any other connection).
48040: */
48041: static void pager_unlock(Pager *pPager){
48042: 
48043:   assert( pPager->eState==PAGER_READER 
48044:        || pPager->eState==PAGER_OPEN 
48045:        || pPager->eState==PAGER_ERROR 
48046:   );
48047: 
48048:   sqlite3BitvecDestroy(pPager->pInJournal);
48049:   pPager->pInJournal = 0;
48050:   releaseAllSavepoints(pPager);
48051: 
48052:   if( pagerUseWal(pPager) ){
48053:     assert( !isOpen(pPager->jfd) );
48054:     sqlite3WalEndReadTransaction(pPager->pWal);
48055:     pPager->eState = PAGER_OPEN;
48056:   }else if( !pPager->exclusiveMode ){
48057:     int rc;                       /* Error code returned by pagerUnlockDb() */
48058:     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
48059: 
48060:     /* If the operating system support deletion of open files, then
48061:     ** close the journal file when dropping the database lock.  Otherwise
48062:     ** another connection with journal_mode=delete might delete the file
48063:     ** out from under us.
48064:     */
48065:     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
48066:     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
48067:     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
48068:     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
48069:     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48070:     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
48071:     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
48072:      || 1!=(pPager->journalMode & 5)
48073:     ){
48074:       sqlite3OsClose(pPager->jfd);
48075:     }
48076: 
48077:     /* If the pager is in the ERROR state and the call to unlock the database
48078:     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
48079:     ** above the #define for UNKNOWN_LOCK for an explanation of why this
48080:     ** is necessary.
48081:     */
48082:     rc = pagerUnlockDb(pPager, NO_LOCK);
48083:     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
48084:       pPager->eLock = UNKNOWN_LOCK;
48085:     }
48086: 
48087:     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
48088:     ** without clearing the error code. This is intentional - the error
48089:     ** code is cleared and the cache reset in the block below.
48090:     */
48091:     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
48092:     pPager->changeCountDone = 0;
48093:     pPager->eState = PAGER_OPEN;
48094:   }
48095: 
48096:   /* If Pager.errCode is set, the contents of the pager cache cannot be
48097:   ** trusted. Now that there are no outstanding references to the pager,
48098:   ** it can safely move back to PAGER_OPEN state. This happens in both
48099:   ** normal and exclusive-locking mode.
48100:   */
48101:   assert( pPager->errCode==SQLITE_OK || !MEMDB );
48102:   if( pPager->errCode ){
48103:     if( pPager->tempFile==0 ){
48104:       pager_reset(pPager);
48105:       pPager->changeCountDone = 0;
48106:       pPager->eState = PAGER_OPEN;
48107:     }else{
48108:       pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
48109:     }
48110:     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
48111:     pPager->errCode = SQLITE_OK;
48112:   }
48113: 
48114:   pPager->journalOff = 0;
48115:   pPager->journalHdr = 0;
48116:   pPager->setMaster = 0;
48117: }
48118: 
48119: /*
48120: ** This function is called whenever an IOERR or FULL error that requires
48121: ** the pager to transition into the ERROR state may ahve occurred.
48122: ** The first argument is a pointer to the pager structure, the second 
48123: ** the error-code about to be returned by a pager API function. The 
48124: ** value returned is a copy of the second argument to this function. 
48125: **
48126: ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
48127: ** IOERR sub-codes, the pager enters the ERROR state and the error code
48128: ** is stored in Pager.errCode. While the pager remains in the ERROR state,
48129: ** all major API calls on the Pager will immediately return Pager.errCode.
48130: **
48131: ** The ERROR state indicates that the contents of the pager-cache 
48132: ** cannot be trusted. This state can be cleared by completely discarding 
48133: ** the contents of the pager-cache. If a transaction was active when
48134: ** the persistent error occurred, then the rollback journal may need
48135: ** to be replayed to restore the contents of the database file (as if
48136: ** it were a hot-journal).
48137: */
48138: static int pager_error(Pager *pPager, int rc){
48139:   int rc2 = rc & 0xff;
48140:   assert( rc==SQLITE_OK || !MEMDB );
48141:   assert(
48142:        pPager->errCode==SQLITE_FULL ||
48143:        pPager->errCode==SQLITE_OK ||
48144:        (pPager->errCode & 0xff)==SQLITE_IOERR
48145:   );
48146:   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
48147:     pPager->errCode = rc;
48148:     pPager->eState = PAGER_ERROR;
48149:   }
48150:   return rc;
48151: }
48152: 
48153: static int pager_truncate(Pager *pPager, Pgno nPage);
48154: 
48155: /*
48156: ** The write transaction open on pPager is being committed (bCommit==1)
48157: ** or rolled back (bCommit==0).
48158: **
48159: ** Return TRUE if and only if all dirty pages should be flushed to disk.
48160: **
48161: ** Rules:
48162: **
48163: **   *  For non-TEMP databases, always sync to disk.  This is necessary
48164: **      for transactions to be durable.
48165: **
48166: **   *  Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
48167: **      file has been created already (via a spill on pagerStress()) and
48168: **      when the number of dirty pages in memory exceeds 25% of the total
48169: **      cache size.
48170: */
48171: static int pagerFlushOnCommit(Pager *pPager, int bCommit){
48172:   if( pPager->tempFile==0 ) return 1;
48173:   if( !bCommit ) return 0;
48174:   if( !isOpen(pPager->fd) ) return 0;
48175:   return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
48176: }
48177: 
48178: /*
48179: ** This routine ends a transaction. A transaction is usually ended by 
48180: ** either a COMMIT or a ROLLBACK operation. This routine may be called 
48181: ** after rollback of a hot-journal, or if an error occurs while opening
48182: ** the journal file or writing the very first journal-header of a
48183: ** database transaction.
48184: ** 
48185: ** This routine is never called in PAGER_ERROR state. If it is called
48186: ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
48187: ** exclusive than a RESERVED lock, it is a no-op.
48188: **
48189: ** Otherwise, any active savepoints are released.
48190: **
48191: ** If the journal file is open, then it is "finalized". Once a journal 
48192: ** file has been finalized it is not possible to use it to roll back a 
48193: ** transaction. Nor will it be considered to be a hot-journal by this
48194: ** or any other database connection. Exactly how a journal is finalized
48195: ** depends on whether or not the pager is running in exclusive mode and
48196: ** the current journal-mode (Pager.journalMode value), as follows:
48197: **
48198: **   journalMode==MEMORY
48199: **     Journal file descriptor is simply closed. This destroys an 
48200: **     in-memory journal.
48201: **
48202: **   journalMode==TRUNCATE
48203: **     Journal file is truncated to zero bytes in size.
48204: **
48205: **   journalMode==PERSIST
48206: **     The first 28 bytes of the journal file are zeroed. This invalidates
48207: **     the first journal header in the file, and hence the entire journal
48208: **     file. An invalid journal file cannot be rolled back.
48209: **
48210: **   journalMode==DELETE
48211: **     The journal file is closed and deleted using sqlite3OsDelete().
48212: **
48213: **     If the pager is running in exclusive mode, this method of finalizing
48214: **     the journal file is never used. Instead, if the journalMode is
48215: **     DELETE and the pager is in exclusive mode, the method described under
48216: **     journalMode==PERSIST is used instead.
48217: **
48218: ** After the journal is finalized, the pager moves to PAGER_READER state.
48219: ** If running in non-exclusive rollback mode, the lock on the file is 
48220: ** downgraded to a SHARED_LOCK.
48221: **
48222: ** SQLITE_OK is returned if no error occurs. If an error occurs during
48223: ** any of the IO operations to finalize the journal file or unlock the
48224: ** database then the IO error code is returned to the user. If the 
48225: ** operation to finalize the journal file fails, then the code still
48226: ** tries to unlock the database file if not in exclusive mode. If the
48227: ** unlock operation fails as well, then the first error code related
48228: ** to the first error encountered (the journal finalization one) is
48229: ** returned.
48230: */
48231: static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
48232:   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
48233:   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
48234: 
48235:   /* Do nothing if the pager does not have an open write transaction
48236:   ** or at least a RESERVED lock. This function may be called when there
48237:   ** is no write-transaction active but a RESERVED or greater lock is
48238:   ** held under two circumstances:
48239:   **
48240:   **   1. After a successful hot-journal rollback, it is called with
48241:   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
48242:   **
48243:   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
48244:   **      lock switches back to locking_mode=normal and then executes a
48245:   **      read-transaction, this function is called with eState==PAGER_READER 
48246:   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
48247:   */
48248:   assert( assert_pager_state(pPager) );
48249:   assert( pPager->eState!=PAGER_ERROR );
48250:   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
48251:     return SQLITE_OK;
48252:   }
48253: 
48254:   releaseAllSavepoints(pPager);
48255:   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
48256:   if( isOpen(pPager->jfd) ){
48257:     assert( !pagerUseWal(pPager) );
48258: 
48259:     /* Finalize the journal file. */
48260:     if( sqlite3JournalIsInMemory(pPager->jfd) ){
48261:       /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
48262:       sqlite3OsClose(pPager->jfd);
48263:     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
48264:       if( pPager->journalOff==0 ){
48265:         rc = SQLITE_OK;
48266:       }else{
48267:         rc = sqlite3OsTruncate(pPager->jfd, 0);
48268:         if( rc==SQLITE_OK && pPager->fullSync ){
48269:           /* Make sure the new file size is written into the inode right away.
48270:           ** Otherwise the journal might resurrect following a power loss and
48271:           ** cause the last transaction to roll back.  See
48272:           ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
48273:           */
48274:           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
48275:         }
48276:       }
48277:       pPager->journalOff = 0;
48278:     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
48279:       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
48280:     ){
48281:       rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
48282:       pPager->journalOff = 0;
48283:     }else{
48284:       /* This branch may be executed with Pager.journalMode==MEMORY if
48285:       ** a hot-journal was just rolled back. In this case the journal
48286:       ** file should be closed and deleted. If this connection writes to
48287:       ** the database file, it will do so using an in-memory journal.
48288:       */
48289:       int bDelete = !pPager->tempFile;
48290:       assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
48291:       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
48292:            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
48293:            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
48294:       );
48295:       sqlite3OsClose(pPager->jfd);
48296:       if( bDelete ){
48297:         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
48298:       }
48299:     }
48300:   }
48301: 
48302: #ifdef SQLITE_CHECK_PAGES
48303:   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
48304:   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
48305:     PgHdr *p = sqlite3PagerLookup(pPager, 1);
48306:     if( p ){
48307:       p->pageHash = 0;
48308:       sqlite3PagerUnrefNotNull(p);
48309:     }
48310:   }
48311: #endif
48312: 
48313:   sqlite3BitvecDestroy(pPager->pInJournal);
48314:   pPager->pInJournal = 0;
48315:   pPager->nRec = 0;
48316:   if( rc==SQLITE_OK ){
48317:     if( pagerFlushOnCommit(pPager, bCommit) ){
48318:       sqlite3PcacheCleanAll(pPager->pPCache);
48319:     }else{
48320:       sqlite3PcacheClearWritable(pPager->pPCache);
48321:     }
48322:     sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
48323:   }
48324: 
48325:   if( pagerUseWal(pPager) ){
48326:     /* Drop the WAL write-lock, if any. Also, if the connection was in 
48327:     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
48328:     ** lock held on the database file.
48329:     */
48330:     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
48331:     assert( rc2==SQLITE_OK );
48332:   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
48333:     /* This branch is taken when committing a transaction in rollback-journal
48334:     ** mode if the database file on disk is larger than the database image.
48335:     ** At this point the journal has been finalized and the transaction 
48336:     ** successfully committed, but the EXCLUSIVE lock is still held on the
48337:     ** file. So it is safe to truncate the database file to its minimum
48338:     ** required size.  */
48339:     assert( pPager->eLock==EXCLUSIVE_LOCK );
48340:     rc = pager_truncate(pPager, pPager->dbSize);
48341:   }
48342: 
48343:   if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
48344:     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
48345:     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
48346:   }
48347: 
48348:   if( !pPager->exclusiveMode 
48349:    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
48350:   ){
48351:     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
48352:     pPager->changeCountDone = 0;
48353:   }
48354:   pPager->eState = PAGER_READER;
48355:   pPager->setMaster = 0;
48356: 
48357:   return (rc==SQLITE_OK?rc2:rc);
48358: }
48359: 
48360: /*
48361: ** Execute a rollback if a transaction is active and unlock the 
48362: ** database file. 
48363: **
48364: ** If the pager has already entered the ERROR state, do not attempt 
48365: ** the rollback at this time. Instead, pager_unlock() is called. The
48366: ** call to pager_unlock() will discard all in-memory pages, unlock
48367: ** the database file and move the pager back to OPEN state. If this 
48368: ** means that there is a hot-journal left in the file-system, the next 
48369: ** connection to obtain a shared lock on the pager (which may be this one) 
48370: ** will roll it back.
48371: **
48372: ** If the pager has not already entered the ERROR state, but an IO or
48373: ** malloc error occurs during a rollback, then this will itself cause 
48374: ** the pager to enter the ERROR state. Which will be cleared by the
48375: ** call to pager_unlock(), as described above.
48376: */
48377: static void pagerUnlockAndRollback(Pager *pPager){
48378:   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
48379:     assert( assert_pager_state(pPager) );
48380:     if( pPager->eState>=PAGER_WRITER_LOCKED ){
48381:       sqlite3BeginBenignMalloc();
48382:       sqlite3PagerRollback(pPager);
48383:       sqlite3EndBenignMalloc();
48384:     }else if( !pPager->exclusiveMode ){
48385:       assert( pPager->eState==PAGER_READER );
48386:       pager_end_transaction(pPager, 0, 0);
48387:     }
48388:   }
48389:   pager_unlock(pPager);
48390: }
48391: 
48392: /*
48393: ** Parameter aData must point to a buffer of pPager->pageSize bytes
48394: ** of data. Compute and return a checksum based ont the contents of the 
48395: ** page of data and the current value of pPager->cksumInit.
48396: **
48397: ** This is not a real checksum. It is really just the sum of the 
48398: ** random initial value (pPager->cksumInit) and every 200th byte
48399: ** of the page data, starting with byte offset (pPager->pageSize%200).
48400: ** Each byte is interpreted as an 8-bit unsigned integer.
48401: **
48402: ** Changing the formula used to compute this checksum results in an
48403: ** incompatible journal file format.
48404: **
48405: ** If journal corruption occurs due to a power failure, the most likely 
48406: ** scenario is that one end or the other of the record will be changed. 
48407: ** It is much less likely that the two ends of the journal record will be
48408: ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
48409: ** though fast and simple, catches the mostly likely kind of corruption.
48410: */
48411: static u32 pager_cksum(Pager *pPager, const u8 *aData){
48412:   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
48413:   int i = pPager->pageSize-200;          /* Loop counter */
48414:   while( i>0 ){
48415:     cksum += aData[i];
48416:     i -= 200;
48417:   }
48418:   return cksum;
48419: }
48420: 
48421: /*
48422: ** Report the current page size and number of reserved bytes back
48423: ** to the codec.
48424: */
48425: #ifdef SQLITE_HAS_CODEC
48426: static void pagerReportSize(Pager *pPager){
48427:   if( pPager->xCodecSizeChng ){
48428:     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
48429:                            (int)pPager->nReserve);
48430:   }
48431: }
48432: #else
48433: # define pagerReportSize(X)     /* No-op if we do not support a codec */
48434: #endif
48435: 
48436: #ifdef SQLITE_HAS_CODEC
48437: /*
48438: ** Make sure the number of reserved bits is the same in the destination
48439: ** pager as it is in the source.  This comes up when a VACUUM changes the
48440: ** number of reserved bits to the "optimal" amount.
48441: */
48442: SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
48443:   if( pDest->nReserve!=pSrc->nReserve ){
48444:     pDest->nReserve = pSrc->nReserve;
48445:     pagerReportSize(pDest);
48446:   }
48447: }
48448: #endif
48449: 
48450: /*
48451: ** Read a single page from either the journal file (if isMainJrnl==1) or
48452: ** from the sub-journal (if isMainJrnl==0) and playback that page.
48453: ** The page begins at offset *pOffset into the file. The *pOffset
48454: ** value is increased to the start of the next page in the journal.
48455: **
48456: ** The main rollback journal uses checksums - the statement journal does 
48457: ** not.
48458: **
48459: ** If the page number of the page record read from the (sub-)journal file
48460: ** is greater than the current value of Pager.dbSize, then playback is
48461: ** skipped and SQLITE_OK is returned.
48462: **
48463: ** If pDone is not NULL, then it is a record of pages that have already
48464: ** been played back.  If the page at *pOffset has already been played back
48465: ** (if the corresponding pDone bit is set) then skip the playback.
48466: ** Make sure the pDone bit corresponding to the *pOffset page is set
48467: ** prior to returning.
48468: **
48469: ** If the page record is successfully read from the (sub-)journal file
48470: ** and played back, then SQLITE_OK is returned. If an IO error occurs
48471: ** while reading the record from the (sub-)journal file or while writing
48472: ** to the database file, then the IO error code is returned. If data
48473: ** is successfully read from the (sub-)journal file but appears to be
48474: ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
48475: ** two circumstances:
48476: ** 
48477: **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
48478: **   * If the record is being rolled back from the main journal file
48479: **     and the checksum field does not match the record content.
48480: **
48481: ** Neither of these two scenarios are possible during a savepoint rollback.
48482: **
48483: ** If this is a savepoint rollback, then memory may have to be dynamically
48484: ** allocated by this function. If this is the case and an allocation fails,
48485: ** SQLITE_NOMEM is returned.
48486: */
48487: static int pager_playback_one_page(
48488:   Pager *pPager,                /* The pager being played back */
48489:   i64 *pOffset,                 /* Offset of record to playback */
48490:   Bitvec *pDone,                /* Bitvec of pages already played back */
48491:   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
48492:   int isSavepnt                 /* True for a savepoint rollback */
48493: ){
48494:   int rc;
48495:   PgHdr *pPg;                   /* An existing page in the cache */
48496:   Pgno pgno;                    /* The page number of a page in journal */
48497:   u32 cksum;                    /* Checksum used for sanity checking */
48498:   char *aData;                  /* Temporary storage for the page */
48499:   sqlite3_file *jfd;            /* The file descriptor for the journal file */
48500:   int isSynced;                 /* True if journal page is synced */
48501: 
48502:   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
48503:   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
48504:   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
48505:   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
48506: 
48507:   aData = pPager->pTmpSpace;
48508:   assert( aData );         /* Temp storage must have already been allocated */
48509:   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
48510: 
48511:   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
48512:   ** or savepoint rollback done at the request of the caller) or this is
48513:   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
48514:   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
48515:   ** only reads from the main journal, not the sub-journal.
48516:   */
48517:   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
48518:        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
48519:   );
48520:   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
48521: 
48522:   /* Read the page number and page data from the journal or sub-journal
48523:   ** file. Return an error code to the caller if an IO error occurs.
48524:   */
48525:   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
48526:   rc = read32bits(jfd, *pOffset, &pgno);
48527:   if( rc!=SQLITE_OK ) return rc;
48528:   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
48529:   if( rc!=SQLITE_OK ) return rc;
48530:   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
48531: 
48532:   /* Sanity checking on the page.  This is more important that I originally
48533:   ** thought.  If a power failure occurs while the journal is being written,
48534:   ** it could cause invalid data to be written into the journal.  We need to
48535:   ** detect this invalid data (with high probability) and ignore it.
48536:   */
48537:   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
48538:     assert( !isSavepnt );
48539:     return SQLITE_DONE;
48540:   }
48541:   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
48542:     return SQLITE_OK;
48543:   }
48544:   if( isMainJrnl ){
48545:     rc = read32bits(jfd, (*pOffset)-4, &cksum);
48546:     if( rc ) return rc;
48547:     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
48548:       return SQLITE_DONE;
48549:     }
48550:   }
48551: 
48552:   /* If this page has already been played back before during the current
48553:   ** rollback, then don't bother to play it back again.
48554:   */
48555:   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
48556:     return rc;
48557:   }
48558: 
48559:   /* When playing back page 1, restore the nReserve setting
48560:   */
48561:   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
48562:     pPager->nReserve = ((u8*)aData)[20];
48563:     pagerReportSize(pPager);
48564:   }
48565: 
48566:   /* If the pager is in CACHEMOD state, then there must be a copy of this
48567:   ** page in the pager cache. In this case just update the pager cache,
48568:   ** not the database file. The page is left marked dirty in this case.
48569:   **
48570:   ** An exception to the above rule: If the database is in no-sync mode
48571:   ** and a page is moved during an incremental vacuum then the page may
48572:   ** not be in the pager cache. Later: if a malloc() or IO error occurs
48573:   ** during a Movepage() call, then the page may not be in the cache
48574:   ** either. So the condition described in the above paragraph is not
48575:   ** assert()able.
48576:   **
48577:   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
48578:   ** pager cache if it exists and the main file. The page is then marked 
48579:   ** not dirty. Since this code is only executed in PAGER_OPEN state for
48580:   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
48581:   ** if the pager is in OPEN state.
48582:   **
48583:   ** Ticket #1171:  The statement journal might contain page content that is
48584:   ** different from the page content at the start of the transaction.
48585:   ** This occurs when a page is changed prior to the start of a statement
48586:   ** then changed again within the statement.  When rolling back such a
48587:   ** statement we must not write to the original database unless we know
48588:   ** for certain that original page contents are synced into the main rollback
48589:   ** journal.  Otherwise, a power loss might leave modified data in the
48590:   ** database file without an entry in the rollback journal that can
48591:   ** restore the database to its original form.  Two conditions must be
48592:   ** met before writing to the database files. (1) the database must be
48593:   ** locked.  (2) we know that the original page content is fully synced
48594:   ** in the main journal either because the page is not in cache or else
48595:   ** the page is marked as needSync==0.
48596:   **
48597:   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
48598:   ** is possible to fail a statement on a database that does not yet exist.
48599:   ** Do not attempt to write if database file has never been opened.
48600:   */
48601:   if( pagerUseWal(pPager) ){
48602:     pPg = 0;
48603:   }else{
48604:     pPg = sqlite3PagerLookup(pPager, pgno);
48605:   }
48606:   assert( pPg || !MEMDB );
48607:   assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
48608:   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
48609:            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
48610:            (isMainJrnl?"main-journal":"sub-journal")
48611:   ));
48612:   if( isMainJrnl ){
48613:     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
48614:   }else{
48615:     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
48616:   }
48617:   if( isOpen(pPager->fd)
48618:    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48619:    && isSynced
48620:   ){
48621:     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
48622:     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
48623:     assert( !pagerUseWal(pPager) );
48624:     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
48625:     if( pgno>pPager->dbFileSize ){
48626:       pPager->dbFileSize = pgno;
48627:     }
48628:     if( pPager->pBackup ){
48629:       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
48630:       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
48631:       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
48632:     }
48633:   }else if( !isMainJrnl && pPg==0 ){
48634:     /* If this is a rollback of a savepoint and data was not written to
48635:     ** the database and the page is not in-memory, there is a potential
48636:     ** problem. When the page is next fetched by the b-tree layer, it 
48637:     ** will be read from the database file, which may or may not be 
48638:     ** current. 
48639:     **
48640:     ** There are a couple of different ways this can happen. All are quite
48641:     ** obscure. When running in synchronous mode, this can only happen 
48642:     ** if the page is on the free-list at the start of the transaction, then
48643:     ** populated, then moved using sqlite3PagerMovepage().
48644:     **
48645:     ** The solution is to add an in-memory page to the cache containing
48646:     ** the data just read from the sub-journal. Mark the page as dirty 
48647:     ** and if the pager requires a journal-sync, then mark the page as 
48648:     ** requiring a journal-sync before it is written.
48649:     */
48650:     assert( isSavepnt );
48651:     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
48652:     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
48653:     rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
48654:     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
48655:     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
48656:     if( rc!=SQLITE_OK ) return rc;
48657:     sqlite3PcacheMakeDirty(pPg);
48658:   }
48659:   if( pPg ){
48660:     /* No page should ever be explicitly rolled back that is in use, except
48661:     ** for page 1 which is held in use in order to keep the lock on the
48662:     ** database active. However such a page may be rolled back as a result
48663:     ** of an internal error resulting in an automatic call to
48664:     ** sqlite3PagerRollback().
48665:     */
48666:     void *pData;
48667:     pData = pPg->pData;
48668:     memcpy(pData, (u8*)aData, pPager->pageSize);
48669:     pPager->xReiniter(pPg);
48670:     /* It used to be that sqlite3PcacheMakeClean(pPg) was called here.  But
48671:     ** that call was dangerous and had no detectable benefit since the cache
48672:     ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48673:     ** has been removed. */
48674:     pager_set_pagehash(pPg);
48675: 
48676:     /* If this was page 1, then restore the value of Pager.dbFileVers.
48677:     ** Do this before any decoding. */
48678:     if( pgno==1 ){
48679:       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
48680:     }
48681: 
48682:     /* Decode the page just read from disk */
48683:     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
48684:     sqlite3PcacheRelease(pPg);
48685:   }
48686:   return rc;
48687: }
48688: 
48689: /*
48690: ** Parameter zMaster is the name of a master journal file. A single journal
48691: ** file that referred to the master journal file has just been rolled back.
48692: ** This routine checks if it is possible to delete the master journal file,
48693: ** and does so if it is.
48694: **
48695: ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
48696: ** available for use within this function.
48697: **
48698: ** When a master journal file is created, it is populated with the names 
48699: ** of all of its child journals, one after another, formatted as utf-8 
48700: ** encoded text. The end of each child journal file is marked with a 
48701: ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
48702: ** file for a transaction involving two databases might be:
48703: **
48704: **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
48705: **
48706: ** A master journal file may only be deleted once all of its child 
48707: ** journals have been rolled back.
48708: **
48709: ** This function reads the contents of the master-journal file into 
48710: ** memory and loops through each of the child journal names. For
48711: ** each child journal, it checks if:
48712: **
48713: **   * if the child journal exists, and if so
48714: **   * if the child journal contains a reference to master journal 
48715: **     file zMaster
48716: **
48717: ** If a child journal can be found that matches both of the criteria
48718: ** above, this function returns without doing anything. Otherwise, if
48719: ** no such child journal can be found, file zMaster is deleted from
48720: ** the file-system using sqlite3OsDelete().
48721: **
48722: ** If an IO error within this function, an error code is returned. This
48723: ** function allocates memory by calling sqlite3Malloc(). If an allocation
48724: ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
48725: ** occur, SQLITE_OK is returned.
48726: **
48727: ** TODO: This function allocates a single block of memory to load
48728: ** the entire contents of the master journal file. This could be
48729: ** a couple of kilobytes or so - potentially larger than the page 
48730: ** size.
48731: */
48732: static int pager_delmaster(Pager *pPager, const char *zMaster){
48733:   sqlite3_vfs *pVfs = pPager->pVfs;
48734:   int rc;                   /* Return code */
48735:   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
48736:   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
48737:   char *zMasterJournal = 0; /* Contents of master journal file */
48738:   i64 nMasterJournal;       /* Size of master journal file */
48739:   char *zJournal;           /* Pointer to one journal within MJ file */
48740:   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
48741:   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
48742: 
48743:   /* Allocate space for both the pJournal and pMaster file descriptors.
48744:   ** If successful, open the master journal file for reading.
48745:   */
48746:   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
48747:   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
48748:   if( !pMaster ){
48749:     rc = SQLITE_NOMEM_BKPT;
48750:   }else{
48751:     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
48752:     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
48753:   }
48754:   if( rc!=SQLITE_OK ) goto delmaster_out;
48755: 
48756:   /* Load the entire master journal file into space obtained from
48757:   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
48758:   ** sufficient space (in zMasterPtr) to hold the names of master
48759:   ** journal files extracted from regular rollback-journals.
48760:   */
48761:   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
48762:   if( rc!=SQLITE_OK ) goto delmaster_out;
48763:   nMasterPtr = pVfs->mxPathname+1;
48764:   zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
48765:   if( !zMasterJournal ){
48766:     rc = SQLITE_NOMEM_BKPT;
48767:     goto delmaster_out;
48768:   }
48769:   zMasterPtr = &zMasterJournal[nMasterJournal+1];
48770:   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
48771:   if( rc!=SQLITE_OK ) goto delmaster_out;
48772:   zMasterJournal[nMasterJournal] = 0;
48773: 
48774:   zJournal = zMasterJournal;
48775:   while( (zJournal-zMasterJournal)<nMasterJournal ){
48776:     int exists;
48777:     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
48778:     if( rc!=SQLITE_OK ){
48779:       goto delmaster_out;
48780:     }
48781:     if( exists ){
48782:       /* One of the journals pointed to by the master journal exists.
48783:       ** Open it and check if it points at the master journal. If
48784:       ** so, return without deleting the master journal file.
48785:       */
48786:       int c;
48787:       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
48788:       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
48789:       if( rc!=SQLITE_OK ){
48790:         goto delmaster_out;
48791:       }
48792: 
48793:       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
48794:       sqlite3OsClose(pJournal);
48795:       if( rc!=SQLITE_OK ){
48796:         goto delmaster_out;
48797:       }
48798: 
48799:       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
48800:       if( c ){
48801:         /* We have a match. Do not delete the master journal file. */
48802:         goto delmaster_out;
48803:       }
48804:     }
48805:     zJournal += (sqlite3Strlen30(zJournal)+1);
48806:   }
48807:  
48808:   sqlite3OsClose(pMaster);
48809:   rc = sqlite3OsDelete(pVfs, zMaster, 0);
48810: 
48811: delmaster_out:
48812:   sqlite3_free(zMasterJournal);
48813:   if( pMaster ){
48814:     sqlite3OsClose(pMaster);
48815:     assert( !isOpen(pJournal) );
48816:     sqlite3_free(pMaster);
48817:   }
48818:   return rc;
48819: }
48820: 
48821: 
48822: /*
48823: ** This function is used to change the actual size of the database 
48824: ** file in the file-system. This only happens when committing a transaction,
48825: ** or rolling back a transaction (including rolling back a hot-journal).
48826: **
48827: ** If the main database file is not open, or the pager is not in either
48828: ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
48829: ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
48830: ** If the file on disk is currently larger than nPage pages, then use the VFS
48831: ** xTruncate() method to truncate it.
48832: **
48833: ** Or, it might be the case that the file on disk is smaller than 
48834: ** nPage pages. Some operating system implementations can get confused if 
48835: ** you try to truncate a file to some size that is larger than it 
48836: ** currently is, so detect this case and write a single zero byte to 
48837: ** the end of the new file instead.
48838: **
48839: ** If successful, return SQLITE_OK. If an IO error occurs while modifying
48840: ** the database file, return the error code to the caller.
48841: */
48842: static int pager_truncate(Pager *pPager, Pgno nPage){
48843:   int rc = SQLITE_OK;
48844:   assert( pPager->eState!=PAGER_ERROR );
48845:   assert( pPager->eState!=PAGER_READER );
48846:   
48847:   if( isOpen(pPager->fd) 
48848:    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
48849:   ){
48850:     i64 currentSize, newSize;
48851:     int szPage = pPager->pageSize;
48852:     assert( pPager->eLock==EXCLUSIVE_LOCK );
48853:     /* TODO: Is it safe to use Pager.dbFileSize here? */
48854:     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
48855:     newSize = szPage*(i64)nPage;
48856:     if( rc==SQLITE_OK && currentSize!=newSize ){
48857:       if( currentSize>newSize ){
48858:         rc = sqlite3OsTruncate(pPager->fd, newSize);
48859:       }else if( (currentSize+szPage)<=newSize ){
48860:         char *pTmp = pPager->pTmpSpace;
48861:         memset(pTmp, 0, szPage);
48862:         testcase( (newSize-szPage) == currentSize );
48863:         testcase( (newSize-szPage) >  currentSize );
48864:         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
48865:       }
48866:       if( rc==SQLITE_OK ){
48867:         pPager->dbFileSize = nPage;
48868:       }
48869:     }
48870:   }
48871:   return rc;
48872: }
48873: 
48874: /*
48875: ** Return a sanitized version of the sector-size of OS file pFile. The
48876: ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
48877: */
48878: SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
48879:   int iRet = sqlite3OsSectorSize(pFile);
48880:   if( iRet<32 ){
48881:     iRet = 512;
48882:   }else if( iRet>MAX_SECTOR_SIZE ){
48883:     assert( MAX_SECTOR_SIZE>=512 );
48884:     iRet = MAX_SECTOR_SIZE;
48885:   }
48886:   return iRet;
48887: }
48888: 
48889: /*
48890: ** Set the value of the Pager.sectorSize variable for the given
48891: ** pager based on the value returned by the xSectorSize method
48892: ** of the open database file. The sector size will be used 
48893: ** to determine the size and alignment of journal header and 
48894: ** master journal pointers within created journal files.
48895: **
48896: ** For temporary files the effective sector size is always 512 bytes.
48897: **
48898: ** Otherwise, for non-temporary files, the effective sector size is
48899: ** the value returned by the xSectorSize() method rounded up to 32 if
48900: ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
48901: ** is greater than MAX_SECTOR_SIZE.
48902: **
48903: ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
48904: ** the effective sector size to its minimum value (512).  The purpose of
48905: ** pPager->sectorSize is to define the "blast radius" of bytes that
48906: ** might change if a crash occurs while writing to a single byte in
48907: ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
48908: ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
48909: ** size.  For backwards compatibility of the rollback journal file format,
48910: ** we cannot reduce the effective sector size below 512.
48911: */
48912: static void setSectorSize(Pager *pPager){
48913:   assert( isOpen(pPager->fd) || pPager->tempFile );
48914: 
48915:   if( pPager->tempFile
48916:    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
48917:               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
48918:   ){
48919:     /* Sector size doesn't matter for temporary files. Also, the file
48920:     ** may not have been opened yet, in which case the OsSectorSize()
48921:     ** call will segfault. */
48922:     pPager->sectorSize = 512;
48923:   }else{
48924:     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
48925:   }
48926: }
48927: 
48928: /*
48929: ** Playback the journal and thus restore the database file to
48930: ** the state it was in before we started making changes.  
48931: **
48932: ** The journal file format is as follows: 
48933: **
48934: **  (1)  8 byte prefix.  A copy of aJournalMagic[].
48935: **  (2)  4 byte big-endian integer which is the number of valid page records
48936: **       in the journal.  If this value is 0xffffffff, then compute the
48937: **       number of page records from the journal size.
48938: **  (3)  4 byte big-endian integer which is the initial value for the 
48939: **       sanity checksum.
48940: **  (4)  4 byte integer which is the number of pages to truncate the
48941: **       database to during a rollback.
48942: **  (5)  4 byte big-endian integer which is the sector size.  The header
48943: **       is this many bytes in size.
48944: **  (6)  4 byte big-endian integer which is the page size.
48945: **  (7)  zero padding out to the next sector size.
48946: **  (8)  Zero or more pages instances, each as follows:
48947: **        +  4 byte page number.
48948: **        +  pPager->pageSize bytes of data.
48949: **        +  4 byte checksum
48950: **
48951: ** When we speak of the journal header, we mean the first 7 items above.
48952: ** Each entry in the journal is an instance of the 8th item.
48953: **
48954: ** Call the value from the second bullet "nRec".  nRec is the number of
48955: ** valid page entries in the journal.  In most cases, you can compute the
48956: ** value of nRec from the size of the journal file.  But if a power
48957: ** failure occurred while the journal was being written, it could be the
48958: ** case that the size of the journal file had already been increased but
48959: ** the extra entries had not yet made it safely to disk.  In such a case,
48960: ** the value of nRec computed from the file size would be too large.  For
48961: ** that reason, we always use the nRec value in the header.
48962: **
48963: ** If the nRec value is 0xffffffff it means that nRec should be computed
48964: ** from the file size.  This value is used when the user selects the
48965: ** no-sync option for the journal.  A power failure could lead to corruption
48966: ** in this case.  But for things like temporary table (which will be
48967: ** deleted when the power is restored) we don't care.  
48968: **
48969: ** If the file opened as the journal file is not a well-formed
48970: ** journal file then all pages up to the first corrupted page are rolled
48971: ** back (or no pages if the journal header is corrupted). The journal file
48972: ** is then deleted and SQLITE_OK returned, just as if no corruption had
48973: ** been encountered.
48974: **
48975: ** If an I/O or malloc() error occurs, the journal-file is not deleted
48976: ** and an error code is returned.
48977: **
48978: ** The isHot parameter indicates that we are trying to rollback a journal
48979: ** that might be a hot journal.  Or, it could be that the journal is 
48980: ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
48981: ** If the journal really is hot, reset the pager cache prior rolling
48982: ** back any content.  If the journal is merely persistent, no reset is
48983: ** needed.
48984: */
48985: static int pager_playback(Pager *pPager, int isHot){
48986:   sqlite3_vfs *pVfs = pPager->pVfs;
48987:   i64 szJ;                 /* Size of the journal file in bytes */
48988:   u32 nRec;                /* Number of Records in the journal */
48989:   u32 u;                   /* Unsigned loop counter */
48990:   Pgno mxPg = 0;           /* Size of the original file in pages */
48991:   int rc;                  /* Result code of a subroutine */
48992:   int res = 1;             /* Value returned by sqlite3OsAccess() */
48993:   char *zMaster = 0;       /* Name of master journal file if any */
48994:   int needPagerReset;      /* True to reset page prior to first page rollback */
48995:   int nPlayback = 0;       /* Total number of pages restored from journal */
48996: 
48997:   /* Figure out how many records are in the journal.  Abort early if
48998:   ** the journal is empty.
48999:   */
49000:   assert( isOpen(pPager->jfd) );
49001:   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
49002:   if( rc!=SQLITE_OK ){
49003:     goto end_playback;
49004:   }
49005: 
49006:   /* Read the master journal name from the journal, if it is present.
49007:   ** If a master journal file name is specified, but the file is not
49008:   ** present on disk, then the journal is not hot and does not need to be
49009:   ** played back.
49010:   **
49011:   ** TODO: Technically the following is an error because it assumes that
49012:   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
49013:   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
49014:   ** mxPathname is 512, which is the same as the minimum allowable value
49015:   ** for pageSize.
49016:   */
49017:   zMaster = pPager->pTmpSpace;
49018:   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49019:   if( rc==SQLITE_OK && zMaster[0] ){
49020:     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49021:   }
49022:   zMaster = 0;
49023:   if( rc!=SQLITE_OK || !res ){
49024:     goto end_playback;
49025:   }
49026:   pPager->journalOff = 0;
49027:   needPagerReset = isHot;
49028: 
49029:   /* This loop terminates either when a readJournalHdr() or 
49030:   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
49031:   ** occurs. 
49032:   */
49033:   while( 1 ){
49034:     /* Read the next journal header from the journal file.  If there are
49035:     ** not enough bytes left in the journal file for a complete header, or
49036:     ** it is corrupted, then a process must have failed while writing it.
49037:     ** This indicates nothing more needs to be rolled back.
49038:     */
49039:     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
49040:     if( rc!=SQLITE_OK ){ 
49041:       if( rc==SQLITE_DONE ){
49042:         rc = SQLITE_OK;
49043:       }
49044:       goto end_playback;
49045:     }
49046: 
49047:     /* If nRec is 0xffffffff, then this journal was created by a process
49048:     ** working in no-sync mode. This means that the rest of the journal
49049:     ** file consists of pages, there are no more journal headers. Compute
49050:     ** the value of nRec based on this assumption.
49051:     */
49052:     if( nRec==0xffffffff ){
49053:       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
49054:       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
49055:     }
49056: 
49057:     /* If nRec is 0 and this rollback is of a transaction created by this
49058:     ** process and if this is the final header in the journal, then it means
49059:     ** that this part of the journal was being filled but has not yet been
49060:     ** synced to disk.  Compute the number of pages based on the remaining
49061:     ** size of the file.
49062:     **
49063:     ** The third term of the test was added to fix ticket #2565.
49064:     ** When rolling back a hot journal, nRec==0 always means that the next
49065:     ** chunk of the journal contains zero pages to be rolled back.  But
49066:     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
49067:     ** the journal, it means that the journal might contain additional
49068:     ** pages that need to be rolled back and that the number of pages 
49069:     ** should be computed based on the journal file size.
49070:     */
49071:     if( nRec==0 && !isHot &&
49072:         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
49073:       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
49074:     }
49075: 
49076:     /* If this is the first header read from the journal, truncate the
49077:     ** database file back to its original size.
49078:     */
49079:     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
49080:       rc = pager_truncate(pPager, mxPg);
49081:       if( rc!=SQLITE_OK ){
49082:         goto end_playback;
49083:       }
49084:       pPager->dbSize = mxPg;
49085:     }
49086: 
49087:     /* Copy original pages out of the journal and back into the 
49088:     ** database file and/or page cache.
49089:     */
49090:     for(u=0; u<nRec; u++){
49091:       if( needPagerReset ){
49092:         pager_reset(pPager);
49093:         needPagerReset = 0;
49094:       }
49095:       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
49096:       if( rc==SQLITE_OK ){
49097:         nPlayback++;
49098:       }else{
49099:         if( rc==SQLITE_DONE ){
49100:           pPager->journalOff = szJ;
49101:           break;
49102:         }else if( rc==SQLITE_IOERR_SHORT_READ ){
49103:           /* If the journal has been truncated, simply stop reading and
49104:           ** processing the journal. This might happen if the journal was
49105:           ** not completely written and synced prior to a crash.  In that
49106:           ** case, the database should have never been written in the
49107:           ** first place so it is OK to simply abandon the rollback. */
49108:           rc = SQLITE_OK;
49109:           goto end_playback;
49110:         }else{
49111:           /* If we are unable to rollback, quit and return the error
49112:           ** code.  This will cause the pager to enter the error state
49113:           ** so that no further harm will be done.  Perhaps the next
49114:           ** process to come along will be able to rollback the database.
49115:           */
49116:           goto end_playback;
49117:         }
49118:       }
49119:     }
49120:   }
49121:   /*NOTREACHED*/
49122:   assert( 0 );
49123: 
49124: end_playback:
49125:   /* Following a rollback, the database file should be back in its original
49126:   ** state prior to the start of the transaction, so invoke the
49127:   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
49128:   ** assertion that the transaction counter was modified.
49129:   */
49130: #ifdef SQLITE_DEBUG
49131:   if( pPager->fd->pMethods ){
49132:     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
49133:   }
49134: #endif
49135: 
49136:   /* If this playback is happening automatically as a result of an IO or 
49137:   ** malloc error that occurred after the change-counter was updated but 
49138:   ** before the transaction was committed, then the change-counter 
49139:   ** modification may just have been reverted. If this happens in exclusive 
49140:   ** mode, then subsequent transactions performed by the connection will not
49141:   ** update the change-counter at all. This may lead to cache inconsistency
49142:   ** problems for other processes at some point in the future. So, just
49143:   ** in case this has happened, clear the changeCountDone flag now.
49144:   */
49145:   pPager->changeCountDone = pPager->tempFile;
49146: 
49147:   if( rc==SQLITE_OK ){
49148:     zMaster = pPager->pTmpSpace;
49149:     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
49150:     testcase( rc!=SQLITE_OK );
49151:   }
49152:   if( rc==SQLITE_OK
49153:    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
49154:   ){
49155:     rc = sqlite3PagerSync(pPager, 0);
49156:   }
49157:   if( rc==SQLITE_OK ){
49158:     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
49159:     testcase( rc!=SQLITE_OK );
49160:   }
49161:   if( rc==SQLITE_OK && zMaster[0] && res ){
49162:     /* If there was a master journal and this routine will return success,
49163:     ** see if it is possible to delete the master journal.
49164:     */
49165:     rc = pager_delmaster(pPager, zMaster);
49166:     testcase( rc!=SQLITE_OK );
49167:   }
49168:   if( isHot && nPlayback ){
49169:     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
49170:                 nPlayback, pPager->zJournal);
49171:   }
49172: 
49173:   /* The Pager.sectorSize variable may have been updated while rolling
49174:   ** back a journal created by a process with a different sector size
49175:   ** value. Reset it to the correct value for this process.
49176:   */
49177:   setSectorSize(pPager);
49178:   return rc;
49179: }
49180: 
49181: 
49182: /*
49183: ** Read the content for page pPg out of the database file and into 
49184: ** pPg->pData. A shared lock or greater must be held on the database
49185: ** file before this function is called.
49186: **
49187: ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
49188: ** the value read from the database file.
49189: **
49190: ** If an IO error occurs, then the IO error is returned to the caller.
49191: ** Otherwise, SQLITE_OK is returned.
49192: */
49193: static int readDbPage(PgHdr *pPg, u32 iFrame){
49194:   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
49195:   Pgno pgno = pPg->pgno;       /* Page number to read */
49196:   int rc = SQLITE_OK;          /* Return code */
49197:   int pgsz = pPager->pageSize; /* Number of bytes to read */
49198: 
49199:   assert( pPager->eState>=PAGER_READER && !MEMDB );
49200:   assert( isOpen(pPager->fd) );
49201: 
49202: #ifndef SQLITE_OMIT_WAL
49203:   if( iFrame ){
49204:     /* Try to pull the page from the write-ahead log. */
49205:     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
49206:   }else
49207: #endif
49208:   {
49209:     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
49210:     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
49211:     if( rc==SQLITE_IOERR_SHORT_READ ){
49212:       rc = SQLITE_OK;
49213:     }
49214:   }
49215: 
49216:   if( pgno==1 ){
49217:     if( rc ){
49218:       /* If the read is unsuccessful, set the dbFileVers[] to something
49219:       ** that will never be a valid file version.  dbFileVers[] is a copy
49220:       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
49221:       ** zero or the size of the database in page. Bytes 32..35 and 35..39
49222:       ** should be page numbers which are never 0xffffffff.  So filling
49223:       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
49224:       **
49225:       ** For an encrypted database, the situation is more complex:  bytes
49226:       ** 24..39 of the database are white noise.  But the probability of
49227:       ** white noise equaling 16 bytes of 0xff is vanishingly small so
49228:       ** we should still be ok.
49229:       */
49230:       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
49231:     }else{
49232:       u8 *dbFileVers = &((u8*)pPg->pData)[24];
49233:       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
49234:     }
49235:   }
49236:   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
49237: 
49238:   PAGER_INCR(sqlite3_pager_readdb_count);
49239:   PAGER_INCR(pPager->nRead);
49240:   IOTRACE(("PGIN %p %d\n", pPager, pgno));
49241:   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
49242:                PAGERID(pPager), pgno, pager_pagehash(pPg)));
49243: 
49244:   return rc;
49245: }
49246: 
49247: /*
49248: ** Update the value of the change-counter at offsets 24 and 92 in
49249: ** the header and the sqlite version number at offset 96.
49250: **
49251: ** This is an unconditional update.  See also the pager_incr_changecounter()
49252: ** routine which only updates the change-counter if the update is actually
49253: ** needed, as determined by the pPager->changeCountDone state variable.
49254: */
49255: static void pager_write_changecounter(PgHdr *pPg){
49256:   u32 change_counter;
49257: 
49258:   /* Increment the value just read and write it back to byte 24. */
49259:   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
49260:   put32bits(((char*)pPg->pData)+24, change_counter);
49261: 
49262:   /* Also store the SQLite version number in bytes 96..99 and in
49263:   ** bytes 92..95 store the change counter for which the version number
49264:   ** is valid. */
49265:   put32bits(((char*)pPg->pData)+92, change_counter);
49266:   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
49267: }
49268: 
49269: #ifndef SQLITE_OMIT_WAL
49270: /*
49271: ** This function is invoked once for each page that has already been 
49272: ** written into the log file when a WAL transaction is rolled back.
49273: ** Parameter iPg is the page number of said page. The pCtx argument 
49274: ** is actually a pointer to the Pager structure.
49275: **
49276: ** If page iPg is present in the cache, and has no outstanding references,
49277: ** it is discarded. Otherwise, if there are one or more outstanding
49278: ** references, the page content is reloaded from the database. If the
49279: ** attempt to reload content from the database is required and fails, 
49280: ** return an SQLite error code. Otherwise, SQLITE_OK.
49281: */
49282: static int pagerUndoCallback(void *pCtx, Pgno iPg){
49283:   int rc = SQLITE_OK;
49284:   Pager *pPager = (Pager *)pCtx;
49285:   PgHdr *pPg;
49286: 
49287:   assert( pagerUseWal(pPager) );
49288:   pPg = sqlite3PagerLookup(pPager, iPg);
49289:   if( pPg ){
49290:     if( sqlite3PcachePageRefcount(pPg)==1 ){
49291:       sqlite3PcacheDrop(pPg);
49292:     }else{
49293:       u32 iFrame = 0;
49294:       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
49295:       if( rc==SQLITE_OK ){
49296:         rc = readDbPage(pPg, iFrame);
49297:       }
49298:       if( rc==SQLITE_OK ){
49299:         pPager->xReiniter(pPg);
49300:       }
49301:       sqlite3PagerUnrefNotNull(pPg);
49302:     }
49303:   }
49304: 
49305:   /* Normally, if a transaction is rolled back, any backup processes are
49306:   ** updated as data is copied out of the rollback journal and into the
49307:   ** database. This is not generally possible with a WAL database, as
49308:   ** rollback involves simply truncating the log file. Therefore, if one
49309:   ** or more frames have already been written to the log (and therefore 
49310:   ** also copied into the backup databases) as part of this transaction,
49311:   ** the backups must be restarted.
49312:   */
49313:   sqlite3BackupRestart(pPager->pBackup);
49314: 
49315:   return rc;
49316: }
49317: 
49318: /*
49319: ** This function is called to rollback a transaction on a WAL database.
49320: */
49321: static int pagerRollbackWal(Pager *pPager){
49322:   int rc;                         /* Return Code */
49323:   PgHdr *pList;                   /* List of dirty pages to revert */
49324: 
49325:   /* For all pages in the cache that are currently dirty or have already
49326:   ** been written (but not committed) to the log file, do one of the 
49327:   ** following:
49328:   **
49329:   **   + Discard the cached page (if refcount==0), or
49330:   **   + Reload page content from the database (if refcount>0).
49331:   */
49332:   pPager->dbSize = pPager->dbOrigSize;
49333:   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
49334:   pList = sqlite3PcacheDirtyList(pPager->pPCache);
49335:   while( pList && rc==SQLITE_OK ){
49336:     PgHdr *pNext = pList->pDirty;
49337:     rc = pagerUndoCallback((void *)pPager, pList->pgno);
49338:     pList = pNext;
49339:   }
49340: 
49341:   return rc;
49342: }
49343: 
49344: /*
49345: ** This function is a wrapper around sqlite3WalFrames(). As well as logging
49346: ** the contents of the list of pages headed by pList (connected by pDirty),
49347: ** this function notifies any active backup processes that the pages have
49348: ** changed. 
49349: **
49350: ** The list of pages passed into this routine is always sorted by page number.
49351: ** Hence, if page 1 appears anywhere on the list, it will be the first page.
49352: */ 
49353: static int pagerWalFrames(
49354:   Pager *pPager,                  /* Pager object */
49355:   PgHdr *pList,                   /* List of frames to log */
49356:   Pgno nTruncate,                 /* Database size after this commit */
49357:   int isCommit                    /* True if this is a commit */
49358: ){
49359:   int rc;                         /* Return code */
49360:   int nList;                      /* Number of pages in pList */
49361:   PgHdr *p;                       /* For looping over pages */
49362: 
49363:   assert( pPager->pWal );
49364:   assert( pList );
49365: #ifdef SQLITE_DEBUG
49366:   /* Verify that the page list is in accending order */
49367:   for(p=pList; p && p->pDirty; p=p->pDirty){
49368:     assert( p->pgno < p->pDirty->pgno );
49369:   }
49370: #endif
49371: 
49372:   assert( pList->pDirty==0 || isCommit );
49373:   if( isCommit ){
49374:     /* If a WAL transaction is being committed, there is no point in writing
49375:     ** any pages with page numbers greater than nTruncate into the WAL file.
49376:     ** They will never be read by any client. So remove them from the pDirty
49377:     ** list here. */
49378:     PgHdr **ppNext = &pList;
49379:     nList = 0;
49380:     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
49381:       if( p->pgno<=nTruncate ){
49382:         ppNext = &p->pDirty;
49383:         nList++;
49384:       }
49385:     }
49386:     assert( pList );
49387:   }else{
49388:     nList = 1;
49389:   }
49390:   pPager->aStat[PAGER_STAT_WRITE] += nList;
49391: 
49392:   if( pList->pgno==1 ) pager_write_changecounter(pList);
49393:   rc = sqlite3WalFrames(pPager->pWal, 
49394:       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
49395:   );
49396:   if( rc==SQLITE_OK && pPager->pBackup ){
49397:     for(p=pList; p; p=p->pDirty){
49398:       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
49399:     }
49400:   }
49401: 
49402: #ifdef SQLITE_CHECK_PAGES
49403:   pList = sqlite3PcacheDirtyList(pPager->pPCache);
49404:   for(p=pList; p; p=p->pDirty){
49405:     pager_set_pagehash(p);
49406:   }
49407: #endif
49408: 
49409:   return rc;
49410: }
49411: 
49412: /*
49413: ** Begin a read transaction on the WAL.
49414: **
49415: ** This routine used to be called "pagerOpenSnapshot()" because it essentially
49416: ** makes a snapshot of the database at the current point in time and preserves
49417: ** that snapshot for use by the reader in spite of concurrently changes by
49418: ** other writers or checkpointers.
49419: */
49420: static int pagerBeginReadTransaction(Pager *pPager){
49421:   int rc;                         /* Return code */
49422:   int changed = 0;                /* True if cache must be reset */
49423: 
49424:   assert( pagerUseWal(pPager) );
49425:   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
49426: 
49427:   /* sqlite3WalEndReadTransaction() was not called for the previous
49428:   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
49429:   ** are in locking_mode=NORMAL and EndRead() was previously called,
49430:   ** the duplicate call is harmless.
49431:   */
49432:   sqlite3WalEndReadTransaction(pPager->pWal);
49433: 
49434:   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
49435:   if( rc!=SQLITE_OK || changed ){
49436:     pager_reset(pPager);
49437:     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
49438:   }
49439: 
49440:   return rc;
49441: }
49442: #endif
49443: 
49444: /*
49445: ** This function is called as part of the transition from PAGER_OPEN
49446: ** to PAGER_READER state to determine the size of the database file
49447: ** in pages (assuming the page size currently stored in Pager.pageSize).
49448: **
49449: ** If no error occurs, SQLITE_OK is returned and the size of the database
49450: ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
49451: ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
49452: */
49453: static int pagerPagecount(Pager *pPager, Pgno *pnPage){
49454:   Pgno nPage;                     /* Value to return via *pnPage */
49455: 
49456:   /* Query the WAL sub-system for the database size. The WalDbsize()
49457:   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
49458:   ** if the database size is not available. The database size is not
49459:   ** available from the WAL sub-system if the log file is empty or
49460:   ** contains no valid committed transactions.
49461:   */
49462:   assert( pPager->eState==PAGER_OPEN );
49463:   assert( pPager->eLock>=SHARED_LOCK );
49464:   assert( isOpen(pPager->fd) );
49465:   assert( pPager->tempFile==0 );
49466:   nPage = sqlite3WalDbsize(pPager->pWal);
49467: 
49468:   /* If the number of pages in the database is not available from the
49469:   ** WAL sub-system, determine the page counte based on the size of
49470:   ** the database file.  If the size of the database file is not an
49471:   ** integer multiple of the page-size, round up the result.
49472:   */
49473:   if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
49474:     i64 n = 0;                    /* Size of db file in bytes */
49475:     int rc = sqlite3OsFileSize(pPager->fd, &n);
49476:     if( rc!=SQLITE_OK ){
49477:       return rc;
49478:     }
49479:     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
49480:   }
49481: 
49482:   /* If the current number of pages in the file is greater than the
49483:   ** configured maximum pager number, increase the allowed limit so
49484:   ** that the file can be read.
49485:   */
49486:   if( nPage>pPager->mxPgno ){
49487:     pPager->mxPgno = (Pgno)nPage;
49488:   }
49489: 
49490:   *pnPage = nPage;
49491:   return SQLITE_OK;
49492: }
49493: 
49494: #ifndef SQLITE_OMIT_WAL
49495: /*
49496: ** Check if the *-wal file that corresponds to the database opened by pPager
49497: ** exists if the database is not empy, or verify that the *-wal file does
49498: ** not exist (by deleting it) if the database file is empty.
49499: **
49500: ** If the database is not empty and the *-wal file exists, open the pager
49501: ** in WAL mode.  If the database is empty or if no *-wal file exists and
49502: ** if no error occurs, make sure Pager.journalMode is not set to
49503: ** PAGER_JOURNALMODE_WAL.
49504: **
49505: ** Return SQLITE_OK or an error code.
49506: **
49507: ** The caller must hold a SHARED lock on the database file to call this
49508: ** function. Because an EXCLUSIVE lock on the db file is required to delete 
49509: ** a WAL on a none-empty database, this ensures there is no race condition 
49510: ** between the xAccess() below and an xDelete() being executed by some 
49511: ** other connection.
49512: */
49513: static int pagerOpenWalIfPresent(Pager *pPager){
49514:   int rc = SQLITE_OK;
49515:   assert( pPager->eState==PAGER_OPEN );
49516:   assert( pPager->eLock>=SHARED_LOCK );
49517: 
49518:   if( !pPager->tempFile ){
49519:     int isWal;                    /* True if WAL file exists */
49520:     Pgno nPage;                   /* Size of the database file */
49521: 
49522:     rc = pagerPagecount(pPager, &nPage);
49523:     if( rc ) return rc;
49524:     if( nPage==0 ){
49525:       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
49526:       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
49527:       isWal = 0;
49528:     }else{
49529:       rc = sqlite3OsAccess(
49530:           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
49531:       );
49532:     }
49533:     if( rc==SQLITE_OK ){
49534:       if( isWal ){
49535:         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
49536:         rc = sqlite3PagerOpenWal(pPager, 0);
49537:       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
49538:         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
49539:       }
49540:     }
49541:   }
49542:   return rc;
49543: }
49544: #endif
49545: 
49546: /*
49547: ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
49548: ** the entire master journal file. The case pSavepoint==NULL occurs when 
49549: ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
49550: ** savepoint.
49551: **
49552: ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
49553: ** being rolled back), then the rollback consists of up to three stages,
49554: ** performed in the order specified:
49555: **
49556: **   * Pages are played back from the main journal starting at byte
49557: **     offset PagerSavepoint.iOffset and continuing to 
49558: **     PagerSavepoint.iHdrOffset, or to the end of the main journal
49559: **     file if PagerSavepoint.iHdrOffset is zero.
49560: **
49561: **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
49562: **     back starting from the journal header immediately following 
49563: **     PagerSavepoint.iHdrOffset to the end of the main journal file.
49564: **
49565: **   * Pages are then played back from the sub-journal file, starting
49566: **     with the PagerSavepoint.iSubRec and continuing to the end of
49567: **     the journal file.
49568: **
49569: ** Throughout the rollback process, each time a page is rolled back, the
49570: ** corresponding bit is set in a bitvec structure (variable pDone in the
49571: ** implementation below). This is used to ensure that a page is only
49572: ** rolled back the first time it is encountered in either journal.
49573: **
49574: ** If pSavepoint is NULL, then pages are only played back from the main
49575: ** journal file. There is no need for a bitvec in this case.
49576: **
49577: ** In either case, before playback commences the Pager.dbSize variable
49578: ** is reset to the value that it held at the start of the savepoint 
49579: ** (or transaction). No page with a page-number greater than this value
49580: ** is played back. If one is encountered it is simply skipped.
49581: */
49582: static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
49583:   i64 szJ;                 /* Effective size of the main journal */
49584:   i64 iHdrOff;             /* End of first segment of main-journal records */
49585:   int rc = SQLITE_OK;      /* Return code */
49586:   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
49587: 
49588:   assert( pPager->eState!=PAGER_ERROR );
49589:   assert( pPager->eState>=PAGER_WRITER_LOCKED );
49590: 
49591:   /* Allocate a bitvec to use to store the set of pages rolled back */
49592:   if( pSavepoint ){
49593:     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
49594:     if( !pDone ){
49595:       return SQLITE_NOMEM_BKPT;
49596:     }
49597:   }
49598: 
49599:   /* Set the database size back to the value it was before the savepoint 
49600:   ** being reverted was opened.
49601:   */
49602:   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
49603:   pPager->changeCountDone = pPager->tempFile;
49604: 
49605:   if( !pSavepoint && pagerUseWal(pPager) ){
49606:     return pagerRollbackWal(pPager);
49607:   }
49608: 
49609:   /* Use pPager->journalOff as the effective size of the main rollback
49610:   ** journal.  The actual file might be larger than this in
49611:   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
49612:   ** past pPager->journalOff is off-limits to us.
49613:   */
49614:   szJ = pPager->journalOff;
49615:   assert( pagerUseWal(pPager)==0 || szJ==0 );
49616: 
49617:   /* Begin by rolling back records from the main journal starting at
49618:   ** PagerSavepoint.iOffset and continuing to the next journal header.
49619:   ** There might be records in the main journal that have a page number
49620:   ** greater than the current database size (pPager->dbSize) but those
49621:   ** will be skipped automatically.  Pages are added to pDone as they
49622:   ** are played back.
49623:   */
49624:   if( pSavepoint && !pagerUseWal(pPager) ){
49625:     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
49626:     pPager->journalOff = pSavepoint->iOffset;
49627:     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
49628:       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49629:     }
49630:     assert( rc!=SQLITE_DONE );
49631:   }else{
49632:     pPager->journalOff = 0;
49633:   }
49634: 
49635:   /* Continue rolling back records out of the main journal starting at
49636:   ** the first journal header seen and continuing until the effective end
49637:   ** of the main journal file.  Continue to skip out-of-range pages and
49638:   ** continue adding pages rolled back to pDone.
49639:   */
49640:   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
49641:     u32 ii;            /* Loop counter */
49642:     u32 nJRec = 0;     /* Number of Journal Records */
49643:     u32 dummy;
49644:     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
49645:     assert( rc!=SQLITE_DONE );
49646: 
49647:     /*
49648:     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
49649:     ** test is related to ticket #2565.  See the discussion in the
49650:     ** pager_playback() function for additional information.
49651:     */
49652:     if( nJRec==0 
49653:      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
49654:     ){
49655:       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
49656:     }
49657:     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
49658:       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49659:     }
49660:     assert( rc!=SQLITE_DONE );
49661:   }
49662:   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
49663: 
49664:   /* Finally,  rollback pages from the sub-journal.  Page that were
49665:   ** previously rolled back out of the main journal (and are hence in pDone)
49666:   ** will be skipped.  Out-of-range pages are also skipped.
49667:   */
49668:   if( pSavepoint ){
49669:     u32 ii;            /* Loop counter */
49670:     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
49671: 
49672:     if( pagerUseWal(pPager) ){
49673:       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
49674:     }
49675:     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
49676:       assert( offset==(i64)ii*(4+pPager->pageSize) );
49677:       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
49678:     }
49679:     assert( rc!=SQLITE_DONE );
49680:   }
49681: 
49682:   sqlite3BitvecDestroy(pDone);
49683:   if( rc==SQLITE_OK ){
49684:     pPager->journalOff = szJ;
49685:   }
49686: 
49687:   return rc;
49688: }
49689: 
49690: /*
49691: ** Change the maximum number of in-memory pages that are allowed
49692: ** before attempting to recycle clean and unused pages.
49693: */
49694: SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
49695:   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
49696: }
49697: 
49698: /*
49699: ** Change the maximum number of in-memory pages that are allowed
49700: ** before attempting to spill pages to journal.
49701: */
49702: SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
49703:   return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
49704: }
49705: 
49706: /*
49707: ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
49708: */
49709: static void pagerFixMaplimit(Pager *pPager){
49710: #if SQLITE_MAX_MMAP_SIZE>0
49711:   sqlite3_file *fd = pPager->fd;
49712:   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
49713:     sqlite3_int64 sz;
49714:     sz = pPager->szMmap;
49715:     pPager->bUseFetch = (sz>0);
49716:     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
49717:   }
49718: #endif
49719: }
49720: 
49721: /*
49722: ** Change the maximum size of any memory mapping made of the database file.
49723: */
49724: SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
49725:   pPager->szMmap = szMmap;
49726:   pagerFixMaplimit(pPager);
49727: }
49728: 
49729: /*
49730: ** Free as much memory as possible from the pager.
49731: */
49732: SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
49733:   sqlite3PcacheShrink(pPager->pPCache);
49734: }
49735: 
49736: /*
49737: ** Adjust settings of the pager to those specified in the pgFlags parameter.
49738: **
49739: ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
49740: ** of the database to damage due to OS crashes or power failures by
49741: ** changing the number of syncs()s when writing the journals.
49742: ** There are four levels:
49743: **
49744: **    OFF       sqlite3OsSync() is never called.  This is the default
49745: **              for temporary and transient files.
49746: **
49747: **    NORMAL    The journal is synced once before writes begin on the
49748: **              database.  This is normally adequate protection, but
49749: **              it is theoretically possible, though very unlikely,
49750: **              that an inopertune power failure could leave the journal
49751: **              in a state which would cause damage to the database
49752: **              when it is rolled back.
49753: **
49754: **    FULL      The journal is synced twice before writes begin on the
49755: **              database (with some additional information - the nRec field
49756: **              of the journal header - being written in between the two
49757: **              syncs).  If we assume that writing a
49758: **              single disk sector is atomic, then this mode provides
49759: **              assurance that the journal will not be corrupted to the
49760: **              point of causing damage to the database during rollback.
49761: **
49762: **    EXTRA     This is like FULL except that is also syncs the directory
49763: **              that contains the rollback journal after the rollback
49764: **              journal is unlinked.
49765: **
49766: ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
49767: ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
49768: ** prior to the start of checkpoint and that the database file is synced
49769: ** at the conclusion of the checkpoint if the entire content of the WAL
49770: ** was written back into the database.  But no sync operations occur for
49771: ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
49772: ** file is synced following each commit operation, in addition to the
49773: ** syncs associated with NORMAL.  There is no difference between FULL
49774: ** and EXTRA for WAL mode.
49775: **
49776: ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
49777: ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
49778: ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
49779: ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
49780: ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
49781: ** synchronous=FULL versus synchronous=NORMAL setting determines when
49782: ** the xSync primitive is called and is relevant to all platforms.
49783: **
49784: ** Numeric values associated with these states are OFF==1, NORMAL=2,
49785: ** and FULL=3.
49786: */
49787: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49788: SQLITE_PRIVATE void sqlite3PagerSetFlags(
49789:   Pager *pPager,        /* The pager to set safety level for */
49790:   unsigned pgFlags      /* Various flags */
49791: ){
49792:   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
49793:   if( pPager->tempFile ){
49794:     pPager->noSync = 1;
49795:     pPager->fullSync = 0;
49796:     pPager->extraSync = 0;
49797:   }else{
49798:     pPager->noSync =  level==PAGER_SYNCHRONOUS_OFF ?1:0;
49799:     pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
49800:     pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
49801:   }
49802:   if( pPager->noSync ){
49803:     pPager->syncFlags = 0;
49804:     pPager->ckptSyncFlags = 0;
49805:   }else if( pgFlags & PAGER_FULLFSYNC ){
49806:     pPager->syncFlags = SQLITE_SYNC_FULL;
49807:     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49808:   }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
49809:     pPager->syncFlags = SQLITE_SYNC_NORMAL;
49810:     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49811:   }else{
49812:     pPager->syncFlags = SQLITE_SYNC_NORMAL;
49813:     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
49814:   }
49815:   pPager->walSyncFlags = pPager->syncFlags;
49816:   if( pPager->fullSync ){
49817:     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
49818:   }
49819:   if( pgFlags & PAGER_CACHESPILL ){
49820:     pPager->doNotSpill &= ~SPILLFLAG_OFF;
49821:   }else{
49822:     pPager->doNotSpill |= SPILLFLAG_OFF;
49823:   }
49824: }
49825: #endif
49826: 
49827: /*
49828: ** The following global variable is incremented whenever the library
49829: ** attempts to open a temporary file.  This information is used for
49830: ** testing and analysis only.  
49831: */
49832: #ifdef SQLITE_TEST
49833: SQLITE_API int sqlite3_opentemp_count = 0;
49834: #endif
49835: 
49836: /*
49837: ** Open a temporary file.
49838: **
49839: ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
49840: ** or some other error code if we fail. The OS will automatically 
49841: ** delete the temporary file when it is closed.
49842: **
49843: ** The flags passed to the VFS layer xOpen() call are those specified
49844: ** by parameter vfsFlags ORed with the following:
49845: **
49846: **     SQLITE_OPEN_READWRITE
49847: **     SQLITE_OPEN_CREATE
49848: **     SQLITE_OPEN_EXCLUSIVE
49849: **     SQLITE_OPEN_DELETEONCLOSE
49850: */
49851: static int pagerOpentemp(
49852:   Pager *pPager,        /* The pager object */
49853:   sqlite3_file *pFile,  /* Write the file descriptor here */
49854:   int vfsFlags          /* Flags passed through to the VFS */
49855: ){
49856:   int rc;               /* Return code */
49857: 
49858: #ifdef SQLITE_TEST
49859:   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
49860: #endif
49861: 
49862:   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
49863:             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
49864:   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
49865:   assert( rc!=SQLITE_OK || isOpen(pFile) );
49866:   return rc;
49867: }
49868: 
49869: /*
49870: ** Set the busy handler function.
49871: **
49872: ** The pager invokes the busy-handler if sqlite3OsLock() returns 
49873: ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
49874: ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
49875: ** lock. It does *not* invoke the busy handler when upgrading from
49876: ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
49877: ** (which occurs during hot-journal rollback). Summary:
49878: **
49879: **   Transition                        | Invokes xBusyHandler
49880: **   --------------------------------------------------------
49881: **   NO_LOCK       -> SHARED_LOCK      | Yes
49882: **   SHARED_LOCK   -> RESERVED_LOCK    | No
49883: **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
49884: **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
49885: **
49886: ** If the busy-handler callback returns non-zero, the lock is 
49887: ** retried. If it returns zero, then the SQLITE_BUSY error is
49888: ** returned to the caller of the pager API function.
49889: */
49890: SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
49891:   Pager *pPager,                       /* Pager object */
49892:   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
49893:   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
49894: ){
49895:   pPager->xBusyHandler = xBusyHandler;
49896:   pPager->pBusyHandlerArg = pBusyHandlerArg;
49897: 
49898:   if( isOpen(pPager->fd) ){
49899:     void **ap = (void **)&pPager->xBusyHandler;
49900:     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
49901:     assert( ap[1]==pBusyHandlerArg );
49902:     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
49903:   }
49904: }
49905: 
49906: /*
49907: ** Change the page size used by the Pager object. The new page size 
49908: ** is passed in *pPageSize.
49909: **
49910: ** If the pager is in the error state when this function is called, it
49911: ** is a no-op. The value returned is the error state error code (i.e. 
49912: ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
49913: **
49914: ** Otherwise, if all of the following are true:
49915: **
49916: **   * the new page size (value of *pPageSize) is valid (a power 
49917: **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
49918: **
49919: **   * there are no outstanding page references, and
49920: **
49921: **   * the database is either not an in-memory database or it is
49922: **     an in-memory database that currently consists of zero pages.
49923: **
49924: ** then the pager object page size is set to *pPageSize.
49925: **
49926: ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
49927: ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
49928: ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
49929: ** In all other cases, SQLITE_OK is returned.
49930: **
49931: ** If the page size is not changed, either because one of the enumerated
49932: ** conditions above is not true, the pager was in error state when this
49933: ** function was called, or because the memory allocation attempt failed, 
49934: ** then *pPageSize is set to the old, retained page size before returning.
49935: */
49936: SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
49937:   int rc = SQLITE_OK;
49938: 
49939:   /* It is not possible to do a full assert_pager_state() here, as this
49940:   ** function may be called from within PagerOpen(), before the state
49941:   ** of the Pager object is internally consistent.
49942:   **
49943:   ** At one point this function returned an error if the pager was in 
49944:   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
49945:   ** there is at least one outstanding page reference, this function
49946:   ** is a no-op for that case anyhow.
49947:   */
49948: 
49949:   u32 pageSize = *pPageSize;
49950:   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
49951:   if( (pPager->memDb==0 || pPager->dbSize==0)
49952:    && sqlite3PcacheRefCount(pPager->pPCache)==0 
49953:    && pageSize && pageSize!=(u32)pPager->pageSize 
49954:   ){
49955:     char *pNew = NULL;             /* New temp space */
49956:     i64 nByte = 0;
49957: 
49958:     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
49959:       rc = sqlite3OsFileSize(pPager->fd, &nByte);
49960:     }
49961:     if( rc==SQLITE_OK ){
49962:       pNew = (char *)sqlite3PageMalloc(pageSize);
49963:       if( !pNew ) rc = SQLITE_NOMEM_BKPT;
49964:     }
49965: 
49966:     if( rc==SQLITE_OK ){
49967:       pager_reset(pPager);
49968:       rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
49969:     }
49970:     if( rc==SQLITE_OK ){
49971:       sqlite3PageFree(pPager->pTmpSpace);
49972:       pPager->pTmpSpace = pNew;
49973:       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
49974:       pPager->pageSize = pageSize;
49975:     }else{
49976:       sqlite3PageFree(pNew);
49977:     }
49978:   }
49979: 
49980:   *pPageSize = pPager->pageSize;
49981:   if( rc==SQLITE_OK ){
49982:     if( nReserve<0 ) nReserve = pPager->nReserve;
49983:     assert( nReserve>=0 && nReserve<1000 );
49984:     pPager->nReserve = (i16)nReserve;
49985:     pagerReportSize(pPager);
49986:     pagerFixMaplimit(pPager);
49987:   }
49988:   return rc;
49989: }
49990: 
49991: /*
49992: ** Return a pointer to the "temporary page" buffer held internally
49993: ** by the pager.  This is a buffer that is big enough to hold the
49994: ** entire content of a database page.  This buffer is used internally
49995: ** during rollback and will be overwritten whenever a rollback
49996: ** occurs.  But other modules are free to use it too, as long as
49997: ** no rollbacks are happening.
49998: */
49999: SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
50000:   return pPager->pTmpSpace;
50001: }
50002: 
50003: /*
50004: ** Attempt to set the maximum database page count if mxPage is positive. 
50005: ** Make no changes if mxPage is zero or negative.  And never reduce the
50006: ** maximum page count below the current size of the database.
50007: **
50008: ** Regardless of mxPage, return the current maximum page count.
50009: */
50010: SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
50011:   if( mxPage>0 ){
50012:     pPager->mxPgno = mxPage;
50013:   }
50014:   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
50015:   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
50016:   return pPager->mxPgno;
50017: }
50018: 
50019: /*
50020: ** The following set of routines are used to disable the simulated
50021: ** I/O error mechanism.  These routines are used to avoid simulated
50022: ** errors in places where we do not care about errors.
50023: **
50024: ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
50025: ** and generate no code.
50026: */
50027: #ifdef SQLITE_TEST
50028: SQLITE_API extern int sqlite3_io_error_pending;
50029: SQLITE_API extern int sqlite3_io_error_hit;
50030: static int saved_cnt;
50031: void disable_simulated_io_errors(void){
50032:   saved_cnt = sqlite3_io_error_pending;
50033:   sqlite3_io_error_pending = -1;
50034: }
50035: void enable_simulated_io_errors(void){
50036:   sqlite3_io_error_pending = saved_cnt;
50037: }
50038: #else
50039: # define disable_simulated_io_errors()
50040: # define enable_simulated_io_errors()
50041: #endif
50042: 
50043: /*
50044: ** Read the first N bytes from the beginning of the file into memory
50045: ** that pDest points to. 
50046: **
50047: ** If the pager was opened on a transient file (zFilename==""), or
50048: ** opened on a file less than N bytes in size, the output buffer is
50049: ** zeroed and SQLITE_OK returned. The rationale for this is that this 
50050: ** function is used to read database headers, and a new transient or
50051: ** zero sized database has a header than consists entirely of zeroes.
50052: **
50053: ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
50054: ** the error code is returned to the caller and the contents of the
50055: ** output buffer undefined.
50056: */
50057: SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
50058:   int rc = SQLITE_OK;
50059:   memset(pDest, 0, N);
50060:   assert( isOpen(pPager->fd) || pPager->tempFile );
50061: 
50062:   /* This routine is only called by btree immediately after creating
50063:   ** the Pager object.  There has not been an opportunity to transition
50064:   ** to WAL mode yet.
50065:   */
50066:   assert( !pagerUseWal(pPager) );
50067: 
50068:   if( isOpen(pPager->fd) ){
50069:     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
50070:     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
50071:     if( rc==SQLITE_IOERR_SHORT_READ ){
50072:       rc = SQLITE_OK;
50073:     }
50074:   }
50075:   return rc;
50076: }
50077: 
50078: /*
50079: ** This function may only be called when a read-transaction is open on
50080: ** the pager. It returns the total number of pages in the database.
50081: **
50082: ** However, if the file is between 1 and <page-size> bytes in size, then 
50083: ** this is considered a 1 page file.
50084: */
50085: SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
50086:   assert( pPager->eState>=PAGER_READER );
50087:   assert( pPager->eState!=PAGER_WRITER_FINISHED );
50088:   *pnPage = (int)pPager->dbSize;
50089: }
50090: 
50091: 
50092: /*
50093: ** Try to obtain a lock of type locktype on the database file. If
50094: ** a similar or greater lock is already held, this function is a no-op
50095: ** (returning SQLITE_OK immediately).
50096: **
50097: ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
50098: ** the busy callback if the lock is currently not available. Repeat 
50099: ** until the busy callback returns false or until the attempt to 
50100: ** obtain the lock succeeds.
50101: **
50102: ** Return SQLITE_OK on success and an error code if we cannot obtain
50103: ** the lock. If the lock is obtained successfully, set the Pager.state 
50104: ** variable to locktype before returning.
50105: */
50106: static int pager_wait_on_lock(Pager *pPager, int locktype){
50107:   int rc;                              /* Return code */
50108: 
50109:   /* Check that this is either a no-op (because the requested lock is 
50110:   ** already held), or one of the transitions that the busy-handler
50111:   ** may be invoked during, according to the comment above
50112:   ** sqlite3PagerSetBusyhandler().
50113:   */
50114:   assert( (pPager->eLock>=locktype)
50115:        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
50116:        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
50117:   );
50118: 
50119:   do {
50120:     rc = pagerLockDb(pPager, locktype);
50121:   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
50122:   return rc;
50123: }
50124: 
50125: /*
50126: ** Function assertTruncateConstraint(pPager) checks that one of the 
50127: ** following is true for all dirty pages currently in the page-cache:
50128: **
50129: **   a) The page number is less than or equal to the size of the 
50130: **      current database image, in pages, OR
50131: **
50132: **   b) if the page content were written at this time, it would not
50133: **      be necessary to write the current content out to the sub-journal
50134: **      (as determined by function subjRequiresPage()).
50135: **
50136: ** If the condition asserted by this function were not true, and the
50137: ** dirty page were to be discarded from the cache via the pagerStress()
50138: ** routine, pagerStress() would not write the current page content to
50139: ** the database file. If a savepoint transaction were rolled back after
50140: ** this happened, the correct behavior would be to restore the current
50141: ** content of the page. However, since this content is not present in either
50142: ** the database file or the portion of the rollback journal and 
50143: ** sub-journal rolled back the content could not be restored and the
50144: ** database image would become corrupt. It is therefore fortunate that 
50145: ** this circumstance cannot arise.
50146: */
50147: #if defined(SQLITE_DEBUG)
50148: static void assertTruncateConstraintCb(PgHdr *pPg){
50149:   assert( pPg->flags&PGHDR_DIRTY );
50150:   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
50151: }
50152: static void assertTruncateConstraint(Pager *pPager){
50153:   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
50154: }
50155: #else
50156: # define assertTruncateConstraint(pPager)
50157: #endif
50158: 
50159: /*
50160: ** Truncate the in-memory database file image to nPage pages. This 
50161: ** function does not actually modify the database file on disk. It 
50162: ** just sets the internal state of the pager object so that the 
50163: ** truncation will be done when the current transaction is committed.
50164: **
50165: ** This function is only called right before committing a transaction.
50166: ** Once this function has been called, the transaction must either be
50167: ** rolled back or committed. It is not safe to call this function and
50168: ** then continue writing to the database.
50169: */
50170: SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
50171:   assert( pPager->dbSize>=nPage );
50172:   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
50173:   pPager->dbSize = nPage;
50174: 
50175:   /* At one point the code here called assertTruncateConstraint() to
50176:   ** ensure that all pages being truncated away by this operation are,
50177:   ** if one or more savepoints are open, present in the savepoint 
50178:   ** journal so that they can be restored if the savepoint is rolled
50179:   ** back. This is no longer necessary as this function is now only
50180:   ** called right before committing a transaction. So although the 
50181:   ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
50182:   ** they cannot be rolled back. So the assertTruncateConstraint() call
50183:   ** is no longer correct. */
50184: }
50185: 
50186: 
50187: /*
50188: ** This function is called before attempting a hot-journal rollback. It
50189: ** syncs the journal file to disk, then sets pPager->journalHdr to the
50190: ** size of the journal file so that the pager_playback() routine knows
50191: ** that the entire journal file has been synced.
50192: **
50193: ** Syncing a hot-journal to disk before attempting to roll it back ensures 
50194: ** that if a power-failure occurs during the rollback, the process that
50195: ** attempts rollback following system recovery sees the same journal
50196: ** content as this process.
50197: **
50198: ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
50199: ** an SQLite error code.
50200: */
50201: static int pagerSyncHotJournal(Pager *pPager){
50202:   int rc = SQLITE_OK;
50203:   if( !pPager->noSync ){
50204:     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
50205:   }
50206:   if( rc==SQLITE_OK ){
50207:     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
50208:   }
50209:   return rc;
50210: }
50211: 
50212: /*
50213: ** Obtain a reference to a memory mapped page object for page number pgno. 
50214: ** The new object will use the pointer pData, obtained from xFetch().
50215: ** If successful, set *ppPage to point to the new page reference
50216: ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
50217: ** *ppPage to zero.
50218: **
50219: ** Page references obtained by calling this function should be released
50220: ** by calling pagerReleaseMapPage().
50221: */
50222: static int pagerAcquireMapPage(
50223:   Pager *pPager,                  /* Pager object */
50224:   Pgno pgno,                      /* Page number */
50225:   void *pData,                    /* xFetch()'d data for this page */
50226:   PgHdr **ppPage                  /* OUT: Acquired page object */
50227: ){
50228:   PgHdr *p;                       /* Memory mapped page to return */
50229:   
50230:   if( pPager->pMmapFreelist ){
50231:     *ppPage = p = pPager->pMmapFreelist;
50232:     pPager->pMmapFreelist = p->pDirty;
50233:     p->pDirty = 0;
50234:     memset(p->pExtra, 0, pPager->nExtra);
50235:   }else{
50236:     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
50237:     if( p==0 ){
50238:       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
50239:       return SQLITE_NOMEM_BKPT;
50240:     }
50241:     p->pExtra = (void *)&p[1];
50242:     p->flags = PGHDR_MMAP;
50243:     p->nRef = 1;
50244:     p->pPager = pPager;
50245:   }
50246: 
50247:   assert( p->pExtra==(void *)&p[1] );
50248:   assert( p->pPage==0 );
50249:   assert( p->flags==PGHDR_MMAP );
50250:   assert( p->pPager==pPager );
50251:   assert( p->nRef==1 );
50252: 
50253:   p->pgno = pgno;
50254:   p->pData = pData;
50255:   pPager->nMmapOut++;
50256: 
50257:   return SQLITE_OK;
50258: }
50259: 
50260: /*
50261: ** Release a reference to page pPg. pPg must have been returned by an 
50262: ** earlier call to pagerAcquireMapPage().
50263: */
50264: static void pagerReleaseMapPage(PgHdr *pPg){
50265:   Pager *pPager = pPg->pPager;
50266:   pPager->nMmapOut--;
50267:   pPg->pDirty = pPager->pMmapFreelist;
50268:   pPager->pMmapFreelist = pPg;
50269: 
50270:   assert( pPager->fd->pMethods->iVersion>=3 );
50271:   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
50272: }
50273: 
50274: /*
50275: ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
50276: */
50277: static void pagerFreeMapHdrs(Pager *pPager){
50278:   PgHdr *p;
50279:   PgHdr *pNext;
50280:   for(p=pPager->pMmapFreelist; p; p=pNext){
50281:     pNext = p->pDirty;
50282:     sqlite3_free(p);
50283:   }
50284: }
50285: 
50286: 
50287: /*
50288: ** Shutdown the page cache.  Free all memory and close all files.
50289: **
50290: ** If a transaction was in progress when this routine is called, that
50291: ** transaction is rolled back.  All outstanding pages are invalidated
50292: ** and their memory is freed.  Any attempt to use a page associated
50293: ** with this page cache after this function returns will likely
50294: ** result in a coredump.
50295: **
50296: ** This function always succeeds. If a transaction is active an attempt
50297: ** is made to roll it back. If an error occurs during the rollback 
50298: ** a hot journal may be left in the filesystem but no error is returned
50299: ** to the caller.
50300: */
50301: SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
50302:   u8 *pTmp = (u8 *)pPager->pTmpSpace;
50303: 
50304:   assert( assert_pager_state(pPager) );
50305:   disable_simulated_io_errors();
50306:   sqlite3BeginBenignMalloc();
50307:   pagerFreeMapHdrs(pPager);
50308:   /* pPager->errCode = 0; */
50309:   pPager->exclusiveMode = 0;
50310: #ifndef SQLITE_OMIT_WAL
50311:   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
50312:   pPager->pWal = 0;
50313: #endif
50314:   pager_reset(pPager);
50315:   if( MEMDB ){
50316:     pager_unlock(pPager);
50317:   }else{
50318:     /* If it is open, sync the journal file before calling UnlockAndRollback.
50319:     ** If this is not done, then an unsynced portion of the open journal 
50320:     ** file may be played back into the database. If a power failure occurs 
50321:     ** while this is happening, the database could become corrupt.
50322:     **
50323:     ** If an error occurs while trying to sync the journal, shift the pager
50324:     ** into the ERROR state. This causes UnlockAndRollback to unlock the
50325:     ** database and close the journal file without attempting to roll it
50326:     ** back or finalize it. The next database user will have to do hot-journal
50327:     ** rollback before accessing the database file.
50328:     */
50329:     if( isOpen(pPager->jfd) ){
50330:       pager_error(pPager, pagerSyncHotJournal(pPager));
50331:     }
50332:     pagerUnlockAndRollback(pPager);
50333:   }
50334:   sqlite3EndBenignMalloc();
50335:   enable_simulated_io_errors();
50336:   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
50337:   IOTRACE(("CLOSE %p\n", pPager))
50338:   sqlite3OsClose(pPager->jfd);
50339:   sqlite3OsClose(pPager->fd);
50340:   sqlite3PageFree(pTmp);
50341:   sqlite3PcacheClose(pPager->pPCache);
50342: 
50343: #ifdef SQLITE_HAS_CODEC
50344:   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
50345: #endif
50346: 
50347:   assert( !pPager->aSavepoint && !pPager->pInJournal );
50348:   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
50349: 
50350:   sqlite3_free(pPager);
50351:   return SQLITE_OK;
50352: }
50353: 
50354: #if !defined(NDEBUG) || defined(SQLITE_TEST)
50355: /*
50356: ** Return the page number for page pPg.
50357: */
50358: SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
50359:   return pPg->pgno;
50360: }
50361: #endif
50362: 
50363: /*
50364: ** Increment the reference count for page pPg.
50365: */
50366: SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
50367:   sqlite3PcacheRef(pPg);
50368: }
50369: 
50370: /*
50371: ** Sync the journal. In other words, make sure all the pages that have
50372: ** been written to the journal have actually reached the surface of the
50373: ** disk and can be restored in the event of a hot-journal rollback.
50374: **
50375: ** If the Pager.noSync flag is set, then this function is a no-op.
50376: ** Otherwise, the actions required depend on the journal-mode and the 
50377: ** device characteristics of the file-system, as follows:
50378: **
50379: **   * If the journal file is an in-memory journal file, no action need
50380: **     be taken.
50381: **
50382: **   * Otherwise, if the device does not support the SAFE_APPEND property,
50383: **     then the nRec field of the most recently written journal header
50384: **     is updated to contain the number of journal records that have
50385: **     been written following it. If the pager is operating in full-sync
50386: **     mode, then the journal file is synced before this field is updated.
50387: **
50388: **   * If the device does not support the SEQUENTIAL property, then 
50389: **     journal file is synced.
50390: **
50391: ** Or, in pseudo-code:
50392: **
50393: **   if( NOT <in-memory journal> ){
50394: **     if( NOT SAFE_APPEND ){
50395: **       if( <full-sync mode> ) xSync(<journal file>);
50396: **       <update nRec field>
50397: **     } 
50398: **     if( NOT SEQUENTIAL ) xSync(<journal file>);
50399: **   }
50400: **
50401: ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
50402: ** page currently held in memory before returning SQLITE_OK. If an IO
50403: ** error is encountered, then the IO error code is returned to the caller.
50404: */
50405: static int syncJournal(Pager *pPager, int newHdr){
50406:   int rc;                         /* Return code */
50407: 
50408:   assert( pPager->eState==PAGER_WRITER_CACHEMOD
50409:        || pPager->eState==PAGER_WRITER_DBMOD
50410:   );
50411:   assert( assert_pager_state(pPager) );
50412:   assert( !pagerUseWal(pPager) );
50413: 
50414:   rc = sqlite3PagerExclusiveLock(pPager);
50415:   if( rc!=SQLITE_OK ) return rc;
50416: 
50417:   if( !pPager->noSync ){
50418:     assert( !pPager->tempFile );
50419:     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
50420:       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50421:       assert( isOpen(pPager->jfd) );
50422: 
50423:       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50424:         /* This block deals with an obscure problem. If the last connection
50425:         ** that wrote to this database was operating in persistent-journal
50426:         ** mode, then the journal file may at this point actually be larger
50427:         ** than Pager.journalOff bytes. If the next thing in the journal
50428:         ** file happens to be a journal-header (written as part of the
50429:         ** previous connection's transaction), and a crash or power-failure 
50430:         ** occurs after nRec is updated but before this connection writes 
50431:         ** anything else to the journal file (or commits/rolls back its 
50432:         ** transaction), then SQLite may become confused when doing the 
50433:         ** hot-journal rollback following recovery. It may roll back all
50434:         ** of this connections data, then proceed to rolling back the old,
50435:         ** out-of-date data that follows it. Database corruption.
50436:         **
50437:         ** To work around this, if the journal file does appear to contain
50438:         ** a valid header following Pager.journalOff, then write a 0x00
50439:         ** byte to the start of it to prevent it from being recognized.
50440:         **
50441:         ** Variable iNextHdrOffset is set to the offset at which this
50442:         ** problematic header will occur, if it exists. aMagic is used 
50443:         ** as a temporary buffer to inspect the first couple of bytes of
50444:         ** the potential journal header.
50445:         */
50446:         i64 iNextHdrOffset;
50447:         u8 aMagic[8];
50448:         u8 zHeader[sizeof(aJournalMagic)+4];
50449: 
50450:         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
50451:         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
50452: 
50453:         iNextHdrOffset = journalHdrOffset(pPager);
50454:         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
50455:         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
50456:           static const u8 zerobyte = 0;
50457:           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
50458:         }
50459:         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
50460:           return rc;
50461:         }
50462: 
50463:         /* Write the nRec value into the journal file header. If in
50464:         ** full-synchronous mode, sync the journal first. This ensures that
50465:         ** all data has really hit the disk before nRec is updated to mark
50466:         ** it as a candidate for rollback.
50467:         **
50468:         ** This is not required if the persistent media supports the
50469:         ** SAFE_APPEND property. Because in this case it is not possible 
50470:         ** for garbage data to be appended to the file, the nRec field
50471:         ** is populated with 0xFFFFFFFF when the journal header is written
50472:         ** and never needs to be updated.
50473:         */
50474:         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50475:           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50476:           IOTRACE(("JSYNC %p\n", pPager))
50477:           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
50478:           if( rc!=SQLITE_OK ) return rc;
50479:         }
50480:         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
50481:         rc = sqlite3OsWrite(
50482:             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
50483:         );
50484:         if( rc!=SQLITE_OK ) return rc;
50485:       }
50486:       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50487:         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50488:         IOTRACE(("JSYNC %p\n", pPager))
50489:         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
50490:           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
50491:         );
50492:         if( rc!=SQLITE_OK ) return rc;
50493:       }
50494: 
50495:       pPager->journalHdr = pPager->journalOff;
50496:       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50497:         pPager->nRec = 0;
50498:         rc = writeJournalHdr(pPager);
50499:         if( rc!=SQLITE_OK ) return rc;
50500:       }
50501:     }else{
50502:       pPager->journalHdr = pPager->journalOff;
50503:     }
50504:   }
50505: 
50506:   /* Unless the pager is in noSync mode, the journal file was just 
50507:   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
50508:   ** all pages.
50509:   */
50510:   sqlite3PcacheClearSyncFlags(pPager->pPCache);
50511:   pPager->eState = PAGER_WRITER_DBMOD;
50512:   assert( assert_pager_state(pPager) );
50513:   return SQLITE_OK;
50514: }
50515: 
50516: /*
50517: ** The argument is the first in a linked list of dirty pages connected
50518: ** by the PgHdr.pDirty pointer. This function writes each one of the
50519: ** in-memory pages in the list to the database file. The argument may
50520: ** be NULL, representing an empty list. In this case this function is
50521: ** a no-op.
50522: **
50523: ** The pager must hold at least a RESERVED lock when this function
50524: ** is called. Before writing anything to the database file, this lock
50525: ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
50526: ** SQLITE_BUSY is returned and no data is written to the database file.
50527: ** 
50528: ** If the pager is a temp-file pager and the actual file-system file
50529: ** is not yet open, it is created and opened before any data is 
50530: ** written out.
50531: **
50532: ** Once the lock has been upgraded and, if necessary, the file opened,
50533: ** the pages are written out to the database file in list order. Writing
50534: ** a page is skipped if it meets either of the following criteria:
50535: **
50536: **   * The page number is greater than Pager.dbSize, or
50537: **   * The PGHDR_DONT_WRITE flag is set on the page.
50538: **
50539: ** If writing out a page causes the database file to grow, Pager.dbFileSize
50540: ** is updated accordingly. If page 1 is written out, then the value cached
50541: ** in Pager.dbFileVers[] is updated to match the new value stored in
50542: ** the database file.
50543: **
50544: ** If everything is successful, SQLITE_OK is returned. If an IO error 
50545: ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
50546: ** be obtained, SQLITE_BUSY is returned.
50547: */
50548: static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
50549:   int rc = SQLITE_OK;                  /* Return code */
50550: 
50551:   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
50552:   assert( !pagerUseWal(pPager) );
50553:   assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
50554:   assert( pPager->eLock==EXCLUSIVE_LOCK );
50555:   assert( isOpen(pPager->fd) || pList->pDirty==0 );
50556: 
50557:   /* If the file is a temp-file has not yet been opened, open it now. It
50558:   ** is not possible for rc to be other than SQLITE_OK if this branch
50559:   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
50560:   */
50561:   if( !isOpen(pPager->fd) ){
50562:     assert( pPager->tempFile && rc==SQLITE_OK );
50563:     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
50564:   }
50565: 
50566:   /* Before the first write, give the VFS a hint of what the final
50567:   ** file size will be.
50568:   */
50569:   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
50570:   if( rc==SQLITE_OK 
50571:    && pPager->dbHintSize<pPager->dbSize
50572:    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
50573:   ){
50574:     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
50575:     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
50576:     pPager->dbHintSize = pPager->dbSize;
50577:   }
50578: 
50579:   while( rc==SQLITE_OK && pList ){
50580:     Pgno pgno = pList->pgno;
50581: 
50582:     /* If there are dirty pages in the page cache with page numbers greater
50583:     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
50584:     ** make the file smaller (presumably by auto-vacuum code). Do not write
50585:     ** any such pages to the file.
50586:     **
50587:     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
50588:     ** set (set by sqlite3PagerDontWrite()).
50589:     */
50590:     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
50591:       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
50592:       char *pData;                                   /* Data to write */    
50593: 
50594:       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
50595:       if( pList->pgno==1 ) pager_write_changecounter(pList);
50596: 
50597:       /* Encode the database */
50598:       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
50599: 
50600:       /* Write out the page data. */
50601:       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
50602: 
50603:       /* If page 1 was just written, update Pager.dbFileVers to match
50604:       ** the value now stored in the database file. If writing this 
50605:       ** page caused the database file to grow, update dbFileSize. 
50606:       */
50607:       if( pgno==1 ){
50608:         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
50609:       }
50610:       if( pgno>pPager->dbFileSize ){
50611:         pPager->dbFileSize = pgno;
50612:       }
50613:       pPager->aStat[PAGER_STAT_WRITE]++;
50614: 
50615:       /* Update any backup objects copying the contents of this pager. */
50616:       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
50617: 
50618:       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
50619:                    PAGERID(pPager), pgno, pager_pagehash(pList)));
50620:       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
50621:       PAGER_INCR(sqlite3_pager_writedb_count);
50622:     }else{
50623:       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
50624:     }
50625:     pager_set_pagehash(pList);
50626:     pList = pList->pDirty;
50627:   }
50628: 
50629:   return rc;
50630: }
50631: 
50632: /*
50633: ** Ensure that the sub-journal file is open. If it is already open, this 
50634: ** function is a no-op.
50635: **
50636: ** SQLITE_OK is returned if everything goes according to plan. An 
50637: ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
50638: ** fails.
50639: */
50640: static int openSubJournal(Pager *pPager){
50641:   int rc = SQLITE_OK;
50642:   if( !isOpen(pPager->sjfd) ){
50643:     const int flags =  SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE 
50644:       | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE 
50645:       | SQLITE_OPEN_DELETEONCLOSE;
50646:     int nStmtSpill = sqlite3Config.nStmtSpill;
50647:     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
50648:       nStmtSpill = -1;
50649:     }
50650:     rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
50651:   }
50652:   return rc;
50653: }
50654: 
50655: /*
50656: ** Append a record of the current state of page pPg to the sub-journal. 
50657: **
50658: ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
50659: ** for all open savepoints before returning.
50660: **
50661: ** This function returns SQLITE_OK if everything is successful, an IO
50662: ** error code if the attempt to write to the sub-journal fails, or 
50663: ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
50664: ** bitvec.
50665: */
50666: static int subjournalPage(PgHdr *pPg){
50667:   int rc = SQLITE_OK;
50668:   Pager *pPager = pPg->pPager;
50669:   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
50670: 
50671:     /* Open the sub-journal, if it has not already been opened */
50672:     assert( pPager->useJournal );
50673:     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
50674:     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
50675:     assert( pagerUseWal(pPager) 
50676:          || pageInJournal(pPager, pPg) 
50677:          || pPg->pgno>pPager->dbOrigSize 
50678:     );
50679:     rc = openSubJournal(pPager);
50680: 
50681:     /* If the sub-journal was opened successfully (or was already open),
50682:     ** write the journal record into the file.  */
50683:     if( rc==SQLITE_OK ){
50684:       void *pData = pPg->pData;
50685:       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
50686:       char *pData2;
50687:   
50688:       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
50689:       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
50690:       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
50691:       if( rc==SQLITE_OK ){
50692:         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
50693:       }
50694:     }
50695:   }
50696:   if( rc==SQLITE_OK ){
50697:     pPager->nSubRec++;
50698:     assert( pPager->nSavepoint>0 );
50699:     rc = addToSavepointBitvecs(pPager, pPg->pgno);
50700:   }
50701:   return rc;
50702: }
50703: static int subjournalPageIfRequired(PgHdr *pPg){
50704:   if( subjRequiresPage(pPg) ){
50705:     return subjournalPage(pPg);
50706:   }else{
50707:     return SQLITE_OK;
50708:   }
50709: }
50710: 
50711: /*
50712: ** This function is called by the pcache layer when it has reached some
50713: ** soft memory limit. The first argument is a pointer to a Pager object
50714: ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
50715: ** database). The second argument is a reference to a page that is 
50716: ** currently dirty but has no outstanding references. The page
50717: ** is always associated with the Pager object passed as the first 
50718: ** argument.
50719: **
50720: ** The job of this function is to make pPg clean by writing its contents
50721: ** out to the database file, if possible. This may involve syncing the
50722: ** journal file. 
50723: **
50724: ** If successful, sqlite3PcacheMakeClean() is called on the page and
50725: ** SQLITE_OK returned. If an IO error occurs while trying to make the
50726: ** page clean, the IO error code is returned. If the page cannot be
50727: ** made clean for some other reason, but no error occurs, then SQLITE_OK
50728: ** is returned by sqlite3PcacheMakeClean() is not called.
50729: */
50730: static int pagerStress(void *p, PgHdr *pPg){
50731:   Pager *pPager = (Pager *)p;
50732:   int rc = SQLITE_OK;
50733: 
50734:   assert( pPg->pPager==pPager );
50735:   assert( pPg->flags&PGHDR_DIRTY );
50736: 
50737:   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
50738:   ** journal (and adding a new header) is not allowed.  This occurs
50739:   ** during calls to sqlite3PagerWrite() while trying to journal multiple
50740:   ** pages belonging to the same sector.
50741:   **
50742:   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
50743:   ** regardless of whether or not a sync is required.  This is set during
50744:   ** a rollback or by user request, respectively.
50745:   **
50746:   ** Spilling is also prohibited when in an error state since that could
50747:   ** lead to database corruption.   In the current implementation it 
50748:   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
50749:   ** while in the error state, hence it is impossible for this routine to
50750:   ** be called in the error state.  Nevertheless, we include a NEVER()
50751:   ** test for the error state as a safeguard against future changes.
50752:   */
50753:   if( NEVER(pPager->errCode) ) return SQLITE_OK;
50754:   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
50755:   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
50756:   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
50757:   if( pPager->doNotSpill
50758:    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
50759:       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
50760:   ){
50761:     return SQLITE_OK;
50762:   }
50763: 
50764:   pPg->pDirty = 0;
50765:   if( pagerUseWal(pPager) ){
50766:     /* Write a single frame for this page to the log. */
50767:     rc = subjournalPageIfRequired(pPg); 
50768:     if( rc==SQLITE_OK ){
50769:       rc = pagerWalFrames(pPager, pPg, 0, 0);
50770:     }
50771:   }else{
50772:   
50773:     /* Sync the journal file if required. */
50774:     if( pPg->flags&PGHDR_NEED_SYNC 
50775:      || pPager->eState==PAGER_WRITER_CACHEMOD
50776:     ){
50777:       rc = syncJournal(pPager, 1);
50778:     }
50779:   
50780:     /* Write the contents of the page out to the database file. */
50781:     if( rc==SQLITE_OK ){
50782:       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
50783:       rc = pager_write_pagelist(pPager, pPg);
50784:     }
50785:   }
50786: 
50787:   /* Mark the page as clean. */
50788:   if( rc==SQLITE_OK ){
50789:     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
50790:     sqlite3PcacheMakeClean(pPg);
50791:   }
50792: 
50793:   return pager_error(pPager, rc); 
50794: }
50795: 
50796: /*
50797: ** Flush all unreferenced dirty pages to disk.
50798: */
50799: SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
50800:   int rc = pPager->errCode;
50801:   if( !MEMDB ){
50802:     PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
50803:     assert( assert_pager_state(pPager) );
50804:     while( rc==SQLITE_OK && pList ){
50805:       PgHdr *pNext = pList->pDirty;
50806:       if( pList->nRef==0 ){
50807:         rc = pagerStress((void*)pPager, pList);
50808:       }
50809:       pList = pNext;
50810:     }
50811:   }
50812: 
50813:   return rc;
50814: }
50815: 
50816: /*
50817: ** Allocate and initialize a new Pager object and put a pointer to it
50818: ** in *ppPager. The pager should eventually be freed by passing it
50819: ** to sqlite3PagerClose().
50820: **
50821: ** The zFilename argument is the path to the database file to open.
50822: ** If zFilename is NULL then a randomly-named temporary file is created
50823: ** and used as the file to be cached. Temporary files are be deleted
50824: ** automatically when they are closed. If zFilename is ":memory:" then 
50825: ** all information is held in cache. It is never written to disk. 
50826: ** This can be used to implement an in-memory database.
50827: **
50828: ** The nExtra parameter specifies the number of bytes of space allocated
50829: ** along with each page reference. This space is available to the user
50830: ** via the sqlite3PagerGetExtra() API.
50831: **
50832: ** The flags argument is used to specify properties that affect the
50833: ** operation of the pager. It should be passed some bitwise combination
50834: ** of the PAGER_* flags.
50835: **
50836: ** The vfsFlags parameter is a bitmask to pass to the flags parameter
50837: ** of the xOpen() method of the supplied VFS when opening files. 
50838: **
50839: ** If the pager object is allocated and the specified file opened 
50840: ** successfully, SQLITE_OK is returned and *ppPager set to point to
50841: ** the new pager object. If an error occurs, *ppPager is set to NULL
50842: ** and error code returned. This function may return SQLITE_NOMEM
50843: ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
50844: ** various SQLITE_IO_XXX errors.
50845: */
50846: SQLITE_PRIVATE int sqlite3PagerOpen(
50847:   sqlite3_vfs *pVfs,       /* The virtual file system to use */
50848:   Pager **ppPager,         /* OUT: Return the Pager structure here */
50849:   const char *zFilename,   /* Name of the database file to open */
50850:   int nExtra,              /* Extra bytes append to each in-memory page */
50851:   int flags,               /* flags controlling this file */
50852:   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
50853:   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
50854: ){
50855:   u8 *pPtr;
50856:   Pager *pPager = 0;       /* Pager object to allocate and return */
50857:   int rc = SQLITE_OK;      /* Return code */
50858:   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
50859:   int memDb = 0;           /* True if this is an in-memory file */
50860:   int readOnly = 0;        /* True if this is a read-only file */
50861:   int journalFileSize;     /* Bytes to allocate for each journal fd */
50862:   char *zPathname = 0;     /* Full path to database file */
50863:   int nPathname = 0;       /* Number of bytes in zPathname */
50864:   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
50865:   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
50866:   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
50867:   const char *zUri = 0;    /* URI args to copy */
50868:   int nUri = 0;            /* Number of bytes of URI args at *zUri */
50869: 
50870:   /* Figure out how much space is required for each journal file-handle
50871:   ** (there are two of them, the main journal and the sub-journal).  */
50872:   journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
50873: 
50874:   /* Set the output variable to NULL in case an error occurs. */
50875:   *ppPager = 0;
50876: 
50877: #ifndef SQLITE_OMIT_MEMORYDB
50878:   if( flags & PAGER_MEMORY ){
50879:     memDb = 1;
50880:     if( zFilename && zFilename[0] ){
50881:       zPathname = sqlite3DbStrDup(0, zFilename);
50882:       if( zPathname==0  ) return SQLITE_NOMEM_BKPT;
50883:       nPathname = sqlite3Strlen30(zPathname);
50884:       zFilename = 0;
50885:     }
50886:   }
50887: #endif
50888: 
50889:   /* Compute and store the full pathname in an allocated buffer pointed
50890:   ** to by zPathname, length nPathname. Or, if this is a temporary file,
50891:   ** leave both nPathname and zPathname set to 0.
50892:   */
50893:   if( zFilename && zFilename[0] ){
50894:     const char *z;
50895:     nPathname = pVfs->mxPathname+1;
50896:     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
50897:     if( zPathname==0 ){
50898:       return SQLITE_NOMEM_BKPT;
50899:     }
50900:     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
50901:     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
50902:     nPathname = sqlite3Strlen30(zPathname);
50903:     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
50904:     while( *z ){
50905:       z += sqlite3Strlen30(z)+1;
50906:       z += sqlite3Strlen30(z)+1;
50907:     }
50908:     nUri = (int)(&z[1] - zUri);
50909:     assert( nUri>=0 );
50910:     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
50911:       /* This branch is taken when the journal path required by
50912:       ** the database being opened will be more than pVfs->mxPathname
50913:       ** bytes in length. This means the database cannot be opened,
50914:       ** as it will not be possible to open the journal file or even
50915:       ** check for a hot-journal before reading.
50916:       */
50917:       rc = SQLITE_CANTOPEN_BKPT;
50918:     }
50919:     if( rc!=SQLITE_OK ){
50920:       sqlite3DbFree(0, zPathname);
50921:       return rc;
50922:     }
50923:   }
50924: 
50925:   /* Allocate memory for the Pager structure, PCache object, the
50926:   ** three file descriptors, the database file name and the journal 
50927:   ** file name. The layout in memory is as follows:
50928:   **
50929:   **     Pager object                    (sizeof(Pager) bytes)
50930:   **     PCache object                   (sqlite3PcacheSize() bytes)
50931:   **     Database file handle            (pVfs->szOsFile bytes)
50932:   **     Sub-journal file handle         (journalFileSize bytes)
50933:   **     Main journal file handle        (journalFileSize bytes)
50934:   **     Database file name              (nPathname+1 bytes)
50935:   **     Journal file name               (nPathname+8+1 bytes)
50936:   */
50937:   pPtr = (u8 *)sqlite3MallocZero(
50938:     ROUND8(sizeof(*pPager)) +      /* Pager structure */
50939:     ROUND8(pcacheSize) +           /* PCache object */
50940:     ROUND8(pVfs->szOsFile) +       /* The main db file */
50941:     journalFileSize * 2 +          /* The two journal files */ 
50942:     nPathname + 1 + nUri +         /* zFilename */
50943:     nPathname + 8 + 2              /* zJournal */
50944: #ifndef SQLITE_OMIT_WAL
50945:     + nPathname + 4 + 2            /* zWal */
50946: #endif
50947:   );
50948:   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
50949:   if( !pPtr ){
50950:     sqlite3DbFree(0, zPathname);
50951:     return SQLITE_NOMEM_BKPT;
50952:   }
50953:   pPager =              (Pager*)(pPtr);
50954:   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
50955:   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
50956:   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
50957:   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
50958:   pPager->zFilename =    (char*)(pPtr += journalFileSize);
50959:   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
50960: 
50961:   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
50962:   if( zPathname ){
50963:     assert( nPathname>0 );
50964:     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
50965:     memcpy(pPager->zFilename, zPathname, nPathname);
50966:     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
50967:     memcpy(pPager->zJournal, zPathname, nPathname);
50968:     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
50969:     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
50970: #ifndef SQLITE_OMIT_WAL
50971:     pPager->zWal = &pPager->zJournal[nPathname+8+1];
50972:     memcpy(pPager->zWal, zPathname, nPathname);
50973:     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
50974:     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
50975: #endif
50976:     sqlite3DbFree(0, zPathname);
50977:   }
50978:   pPager->pVfs = pVfs;
50979:   pPager->vfsFlags = vfsFlags;
50980: 
50981:   /* Open the pager file.
50982:   */
50983:   if( zFilename && zFilename[0] ){
50984:     int fout = 0;                    /* VFS flags returned by xOpen() */
50985:     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
50986:     assert( !memDb );
50987:     readOnly = (fout&SQLITE_OPEN_READONLY);
50988: 
50989:     /* If the file was successfully opened for read/write access,
50990:     ** choose a default page size in case we have to create the
50991:     ** database file. The default page size is the maximum of:
50992:     **
50993:     **    + SQLITE_DEFAULT_PAGE_SIZE,
50994:     **    + The value returned by sqlite3OsSectorSize()
50995:     **    + The largest page size that can be written atomically.
50996:     */
50997:     if( rc==SQLITE_OK ){
50998:       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50999:       if( !readOnly ){
51000:         setSectorSize(pPager);
51001:         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
51002:         if( szPageDflt<pPager->sectorSize ){
51003:           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
51004:             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
51005:           }else{
51006:             szPageDflt = (u32)pPager->sectorSize;
51007:           }
51008:         }
51009: #ifdef SQLITE_ENABLE_ATOMIC_WRITE
51010:         {
51011:           int ii;
51012:           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
51013:           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
51014:           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
51015:           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
51016:             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
51017:               szPageDflt = ii;
51018:             }
51019:           }
51020:         }
51021: #endif
51022:       }
51023:       pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
51024:       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
51025:        || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
51026:           vfsFlags |= SQLITE_OPEN_READONLY;
51027:           goto act_like_temp_file;
51028:       }
51029:     }
51030:   }else{
51031:     /* If a temporary file is requested, it is not opened immediately.
51032:     ** In this case we accept the default page size and delay actually
51033:     ** opening the file until the first call to OsWrite().
51034:     **
51035:     ** This branch is also run for an in-memory database. An in-memory
51036:     ** database is the same as a temp-file that is never written out to
51037:     ** disk and uses an in-memory rollback journal.
51038:     **
51039:     ** This branch also runs for files marked as immutable.
51040:     */ 
51041: act_like_temp_file:
51042:     tempFile = 1;
51043:     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
51044:     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE mode */
51045:     pPager->noLock = 1;                /* Do no locking */
51046:     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
51047:   }
51048: 
51049:   /* The following call to PagerSetPagesize() serves to set the value of 
51050:   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
51051:   */
51052:   if( rc==SQLITE_OK ){
51053:     assert( pPager->memDb==0 );
51054:     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
51055:     testcase( rc!=SQLITE_OK );
51056:   }
51057: 
51058:   /* Initialize the PCache object. */
51059:   if( rc==SQLITE_OK ){
51060:     assert( nExtra<1000 );
51061:     nExtra = ROUND8(nExtra);
51062:     rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
51063:                        !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
51064:   }
51065: 
51066:   /* If an error occurred above, free the  Pager structure and close the file.
51067:   */
51068:   if( rc!=SQLITE_OK ){
51069:     sqlite3OsClose(pPager->fd);
51070:     sqlite3PageFree(pPager->pTmpSpace);
51071:     sqlite3_free(pPager);
51072:     return rc;
51073:   }
51074: 
51075:   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
51076:   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
51077: 
51078:   pPager->useJournal = (u8)useJournal;
51079:   /* pPager->stmtOpen = 0; */
51080:   /* pPager->stmtInUse = 0; */
51081:   /* pPager->nRef = 0; */
51082:   /* pPager->stmtSize = 0; */
51083:   /* pPager->stmtJSize = 0; */
51084:   /* pPager->nPage = 0; */
51085:   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
51086:   /* pPager->state = PAGER_UNLOCK; */
51087:   /* pPager->errMask = 0; */
51088:   pPager->tempFile = (u8)tempFile;
51089:   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
51090:           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
51091:   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
51092:   pPager->exclusiveMode = (u8)tempFile; 
51093:   pPager->changeCountDone = pPager->tempFile;
51094:   pPager->memDb = (u8)memDb;
51095:   pPager->readOnly = (u8)readOnly;
51096:   assert( useJournal || pPager->tempFile );
51097:   pPager->noSync = pPager->tempFile;
51098:   if( pPager->noSync ){
51099:     assert( pPager->fullSync==0 );
51100:     assert( pPager->extraSync==0 );
51101:     assert( pPager->syncFlags==0 );
51102:     assert( pPager->walSyncFlags==0 );
51103:     assert( pPager->ckptSyncFlags==0 );
51104:   }else{
51105:     pPager->fullSync = 1;
51106:     pPager->extraSync = 0;
51107:     pPager->syncFlags = SQLITE_SYNC_NORMAL;
51108:     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
51109:     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
51110:   }
51111:   /* pPager->pFirst = 0; */
51112:   /* pPager->pFirstSynced = 0; */
51113:   /* pPager->pLast = 0; */
51114:   pPager->nExtra = (u16)nExtra;
51115:   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
51116:   assert( isOpen(pPager->fd) || tempFile );
51117:   setSectorSize(pPager);
51118:   if( !useJournal ){
51119:     pPager->journalMode = PAGER_JOURNALMODE_OFF;
51120:   }else if( memDb ){
51121:     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
51122:   }
51123:   /* pPager->xBusyHandler = 0; */
51124:   /* pPager->pBusyHandlerArg = 0; */
51125:   pPager->xReiniter = xReinit;
51126:   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
51127:   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
51128: 
51129:   *ppPager = pPager;
51130:   return SQLITE_OK;
51131: }
51132: 
51133: 
51134: /* Verify that the database file has not be deleted or renamed out from
51135: ** under the pager.  Return SQLITE_OK if the database is still were it ought
51136: ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
51137: ** code from sqlite3OsAccess()) if the database has gone missing.
51138: */
51139: static int databaseIsUnmoved(Pager *pPager){
51140:   int bHasMoved = 0;
51141:   int rc;
51142: 
51143:   if( pPager->tempFile ) return SQLITE_OK;
51144:   if( pPager->dbSize==0 ) return SQLITE_OK;
51145:   assert( pPager->zFilename && pPager->zFilename[0] );
51146:   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
51147:   if( rc==SQLITE_NOTFOUND ){
51148:     /* If the HAS_MOVED file-control is unimplemented, assume that the file
51149:     ** has not been moved.  That is the historical behavior of SQLite: prior to
51150:     ** version 3.8.3, it never checked */
51151:     rc = SQLITE_OK;
51152:   }else if( rc==SQLITE_OK && bHasMoved ){
51153:     rc = SQLITE_READONLY_DBMOVED;
51154:   }
51155:   return rc;
51156: }
51157: 
51158: 
51159: /*
51160: ** This function is called after transitioning from PAGER_UNLOCK to
51161: ** PAGER_SHARED state. It tests if there is a hot journal present in
51162: ** the file-system for the given pager. A hot journal is one that 
51163: ** needs to be played back. According to this function, a hot-journal
51164: ** file exists if the following criteria are met:
51165: **
51166: **   * The journal file exists in the file system, and
51167: **   * No process holds a RESERVED or greater lock on the database file, and
51168: **   * The database file itself is greater than 0 bytes in size, and
51169: **   * The first byte of the journal file exists and is not 0x00.
51170: **
51171: ** If the current size of the database file is 0 but a journal file
51172: ** exists, that is probably an old journal left over from a prior
51173: ** database with the same name. In this case the journal file is
51174: ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
51175: ** is returned.
51176: **
51177: ** This routine does not check if there is a master journal filename
51178: ** at the end of the file. If there is, and that master journal file
51179: ** does not exist, then the journal file is not really hot. In this
51180: ** case this routine will return a false-positive. The pager_playback()
51181: ** routine will discover that the journal file is not really hot and 
51182: ** will not roll it back. 
51183: **
51184: ** If a hot-journal file is found to exist, *pExists is set to 1 and 
51185: ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
51186: ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
51187: ** to determine whether or not a hot-journal file exists, the IO error
51188: ** code is returned and the value of *pExists is undefined.
51189: */
51190: static int hasHotJournal(Pager *pPager, int *pExists){
51191:   sqlite3_vfs * const pVfs = pPager->pVfs;
51192:   int rc = SQLITE_OK;           /* Return code */
51193:   int exists = 1;               /* True if a journal file is present */
51194:   int jrnlOpen = !!isOpen(pPager->jfd);
51195: 
51196:   assert( pPager->useJournal );
51197:   assert( isOpen(pPager->fd) );
51198:   assert( pPager->eState==PAGER_OPEN );
51199: 
51200:   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
51201:     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
51202:   ));
51203: 
51204:   *pExists = 0;
51205:   if( !jrnlOpen ){
51206:     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
51207:   }
51208:   if( rc==SQLITE_OK && exists ){
51209:     int locked = 0;             /* True if some process holds a RESERVED lock */
51210: 
51211:     /* Race condition here:  Another process might have been holding the
51212:     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
51213:     ** call above, but then delete the journal and drop the lock before
51214:     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
51215:     ** is the case, this routine might think there is a hot journal when
51216:     ** in fact there is none.  This results in a false-positive which will
51217:     ** be dealt with by the playback routine.  Ticket #3883.
51218:     */
51219:     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
51220:     if( rc==SQLITE_OK && !locked ){
51221:       Pgno nPage;                 /* Number of pages in database file */
51222: 
51223:       assert( pPager->tempFile==0 );
51224:       rc = pagerPagecount(pPager, &nPage);
51225:       if( rc==SQLITE_OK ){
51226:         /* If the database is zero pages in size, that means that either (1) the
51227:         ** journal is a remnant from a prior database with the same name where
51228:         ** the database file but not the journal was deleted, or (2) the initial
51229:         ** transaction that populates a new database is being rolled back.
51230:         ** In either case, the journal file can be deleted.  However, take care
51231:         ** not to delete the journal file if it is already open due to
51232:         ** journal_mode=PERSIST.
51233:         */
51234:         if( nPage==0 && !jrnlOpen ){
51235:           sqlite3BeginBenignMalloc();
51236:           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
51237:             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
51238:             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
51239:           }
51240:           sqlite3EndBenignMalloc();
51241:         }else{
51242:           /* The journal file exists and no other connection has a reserved
51243:           ** or greater lock on the database file. Now check that there is
51244:           ** at least one non-zero bytes at the start of the journal file.
51245:           ** If there is, then we consider this journal to be hot. If not, 
51246:           ** it can be ignored.
51247:           */
51248:           if( !jrnlOpen ){
51249:             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
51250:             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
51251:           }
51252:           if( rc==SQLITE_OK ){
51253:             u8 first = 0;
51254:             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
51255:             if( rc==SQLITE_IOERR_SHORT_READ ){
51256:               rc = SQLITE_OK;
51257:             }
51258:             if( !jrnlOpen ){
51259:               sqlite3OsClose(pPager->jfd);
51260:             }
51261:             *pExists = (first!=0);
51262:           }else if( rc==SQLITE_CANTOPEN ){
51263:             /* If we cannot open the rollback journal file in order to see if
51264:             ** it has a zero header, that might be due to an I/O error, or
51265:             ** it might be due to the race condition described above and in
51266:             ** ticket #3883.  Either way, assume that the journal is hot.
51267:             ** This might be a false positive.  But if it is, then the
51268:             ** automatic journal playback and recovery mechanism will deal
51269:             ** with it under an EXCLUSIVE lock where we do not need to
51270:             ** worry so much with race conditions.
51271:             */
51272:             *pExists = 1;
51273:             rc = SQLITE_OK;
51274:           }
51275:         }
51276:       }
51277:     }
51278:   }
51279: 
51280:   return rc;
51281: }
51282: 
51283: /*
51284: ** This function is called to obtain a shared lock on the database file.
51285: ** It is illegal to call sqlite3PagerGet() until after this function
51286: ** has been successfully called. If a shared-lock is already held when
51287: ** this function is called, it is a no-op.
51288: **
51289: ** The following operations are also performed by this function.
51290: **
51291: **   1) If the pager is currently in PAGER_OPEN state (no lock held
51292: **      on the database file), then an attempt is made to obtain a
51293: **      SHARED lock on the database file. Immediately after obtaining
51294: **      the SHARED lock, the file-system is checked for a hot-journal,
51295: **      which is played back if present. Following any hot-journal 
51296: **      rollback, the contents of the cache are validated by checking
51297: **      the 'change-counter' field of the database file header and
51298: **      discarded if they are found to be invalid.
51299: **
51300: **   2) If the pager is running in exclusive-mode, and there are currently
51301: **      no outstanding references to any pages, and is in the error state,
51302: **      then an attempt is made to clear the error state by discarding
51303: **      the contents of the page cache and rolling back any open journal
51304: **      file.
51305: **
51306: ** If everything is successful, SQLITE_OK is returned. If an IO error 
51307: ** occurs while locking the database, checking for a hot-journal file or 
51308: ** rolling back a journal file, the IO error code is returned.
51309: */
51310: SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
51311:   int rc = SQLITE_OK;                /* Return code */
51312: 
51313:   /* This routine is only called from b-tree and only when there are no
51314:   ** outstanding pages. This implies that the pager state should either
51315:   ** be OPEN or READER. READER is only possible if the pager is or was in 
51316:   ** exclusive access mode.  */
51317:   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
51318:   assert( assert_pager_state(pPager) );
51319:   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
51320:   assert( pPager->errCode==SQLITE_OK );
51321: 
51322:   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
51323:     int bHotJournal = 1;          /* True if there exists a hot journal-file */
51324: 
51325:     assert( !MEMDB );
51326:     assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
51327: 
51328:     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
51329:     if( rc!=SQLITE_OK ){
51330:       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
51331:       goto failed;
51332:     }
51333: 
51334:     /* If a journal file exists, and there is no RESERVED lock on the
51335:     ** database file, then it either needs to be played back or deleted.
51336:     */
51337:     if( pPager->eLock<=SHARED_LOCK ){
51338:       rc = hasHotJournal(pPager, &bHotJournal);
51339:     }
51340:     if( rc!=SQLITE_OK ){
51341:       goto failed;
51342:     }
51343:     if( bHotJournal ){
51344:       if( pPager->readOnly ){
51345:         rc = SQLITE_READONLY_ROLLBACK;
51346:         goto failed;
51347:       }
51348: 
51349:       /* Get an EXCLUSIVE lock on the database file. At this point it is
51350:       ** important that a RESERVED lock is not obtained on the way to the
51351:       ** EXCLUSIVE lock. If it were, another process might open the
51352:       ** database file, detect the RESERVED lock, and conclude that the
51353:       ** database is safe to read while this process is still rolling the 
51354:       ** hot-journal back.
51355:       ** 
51356:       ** Because the intermediate RESERVED lock is not requested, any
51357:       ** other process attempting to access the database file will get to 
51358:       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
51359:       ** on the database file.
51360:       **
51361:       ** Unless the pager is in locking_mode=exclusive mode, the lock is
51362:       ** downgraded to SHARED_LOCK before this function returns.
51363:       */
51364:       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51365:       if( rc!=SQLITE_OK ){
51366:         goto failed;
51367:       }
51368:  
51369:       /* If it is not already open and the file exists on disk, open the 
51370:       ** journal for read/write access. Write access is required because 
51371:       ** in exclusive-access mode the file descriptor will be kept open 
51372:       ** and possibly used for a transaction later on. Also, write-access 
51373:       ** is usually required to finalize the journal in journal_mode=persist 
51374:       ** mode (and also for journal_mode=truncate on some systems).
51375:       **
51376:       ** If the journal does not exist, it usually means that some 
51377:       ** other connection managed to get in and roll it back before 
51378:       ** this connection obtained the exclusive lock above. Or, it 
51379:       ** may mean that the pager was in the error-state when this
51380:       ** function was called and the journal file does not exist.
51381:       */
51382:       if( !isOpen(pPager->jfd) ){
51383:         sqlite3_vfs * const pVfs = pPager->pVfs;
51384:         int bExists;              /* True if journal file exists */
51385:         rc = sqlite3OsAccess(
51386:             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
51387:         if( rc==SQLITE_OK && bExists ){
51388:           int fout = 0;
51389:           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
51390:           assert( !pPager->tempFile );
51391:           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
51392:           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51393:           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
51394:             rc = SQLITE_CANTOPEN_BKPT;
51395:             sqlite3OsClose(pPager->jfd);
51396:           }
51397:         }
51398:       }
51399:  
51400:       /* Playback and delete the journal.  Drop the database write
51401:       ** lock and reacquire the read lock. Purge the cache before
51402:       ** playing back the hot-journal so that we don't end up with
51403:       ** an inconsistent cache.  Sync the hot journal before playing
51404:       ** it back since the process that crashed and left the hot journal
51405:       ** probably did not sync it and we are required to always sync
51406:       ** the journal before playing it back.
51407:       */
51408:       if( isOpen(pPager->jfd) ){
51409:         assert( rc==SQLITE_OK );
51410:         rc = pagerSyncHotJournal(pPager);
51411:         if( rc==SQLITE_OK ){
51412:           rc = pager_playback(pPager, !pPager->tempFile);
51413:           pPager->eState = PAGER_OPEN;
51414:         }
51415:       }else if( !pPager->exclusiveMode ){
51416:         pagerUnlockDb(pPager, SHARED_LOCK);
51417:       }
51418: 
51419:       if( rc!=SQLITE_OK ){
51420:         /* This branch is taken if an error occurs while trying to open
51421:         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
51422:         ** pager_unlock() routine will be called before returning to unlock
51423:         ** the file. If the unlock attempt fails, then Pager.eLock must be
51424:         ** set to UNKNOWN_LOCK (see the comment above the #define for 
51425:         ** UNKNOWN_LOCK above for an explanation). 
51426:         **
51427:         ** In order to get pager_unlock() to do this, set Pager.eState to
51428:         ** PAGER_ERROR now. This is not actually counted as a transition
51429:         ** to ERROR state in the state diagram at the top of this file,
51430:         ** since we know that the same call to pager_unlock() will very
51431:         ** shortly transition the pager object to the OPEN state. Calling
51432:         ** assert_pager_state() would fail now, as it should not be possible
51433:         ** to be in ERROR state when there are zero outstanding page 
51434:         ** references.
51435:         */
51436:         pager_error(pPager, rc);
51437:         goto failed;
51438:       }
51439: 
51440:       assert( pPager->eState==PAGER_OPEN );
51441:       assert( (pPager->eLock==SHARED_LOCK)
51442:            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
51443:       );
51444:     }
51445: 
51446:     if( !pPager->tempFile && pPager->hasHeldSharedLock ){
51447:       /* The shared-lock has just been acquired then check to
51448:       ** see if the database has been modified.  If the database has changed,
51449:       ** flush the cache.  The hasHeldSharedLock flag prevents this from
51450:       ** occurring on the very first access to a file, in order to save a
51451:       ** single unnecessary sqlite3OsRead() call at the start-up.
51452:       **
51453:       ** Database changes are detected by looking at 15 bytes beginning
51454:       ** at offset 24 into the file.  The first 4 of these 16 bytes are
51455:       ** a 32-bit counter that is incremented with each change.  The
51456:       ** other bytes change randomly with each file change when
51457:       ** a codec is in use.
51458:       ** 
51459:       ** There is a vanishingly small chance that a change will not be 
51460:       ** detected.  The chance of an undetected change is so small that
51461:       ** it can be neglected.
51462:       */
51463:       Pgno nPage = 0;
51464:       char dbFileVers[sizeof(pPager->dbFileVers)];
51465: 
51466:       rc = pagerPagecount(pPager, &nPage);
51467:       if( rc ) goto failed;
51468: 
51469:       if( nPage>0 ){
51470:         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
51471:         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
51472:         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51473:           goto failed;
51474:         }
51475:       }else{
51476:         memset(dbFileVers, 0, sizeof(dbFileVers));
51477:       }
51478: 
51479:       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
51480:         pager_reset(pPager);
51481: 
51482:         /* Unmap the database file. It is possible that external processes
51483:         ** may have truncated the database file and then extended it back
51484:         ** to its original size while this process was not holding a lock.
51485:         ** In this case there may exist a Pager.pMap mapping that appears
51486:         ** to be the right size but is not actually valid. Avoid this
51487:         ** possibility by unmapping the db here. */
51488:         if( USEFETCH(pPager) ){
51489:           sqlite3OsUnfetch(pPager->fd, 0, 0);
51490:         }
51491:       }
51492:     }
51493: 
51494:     /* If there is a WAL file in the file-system, open this database in WAL
51495:     ** mode. Otherwise, the following function call is a no-op.
51496:     */
51497:     rc = pagerOpenWalIfPresent(pPager);
51498: #ifndef SQLITE_OMIT_WAL
51499:     assert( pPager->pWal==0 || rc==SQLITE_OK );
51500: #endif
51501:   }
51502: 
51503:   if( pagerUseWal(pPager) ){
51504:     assert( rc==SQLITE_OK );
51505:     rc = pagerBeginReadTransaction(pPager);
51506:   }
51507: 
51508:   if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51509:     rc = pagerPagecount(pPager, &pPager->dbSize);
51510:   }
51511: 
51512:  failed:
51513:   if( rc!=SQLITE_OK ){
51514:     assert( !MEMDB );
51515:     pager_unlock(pPager);
51516:     assert( pPager->eState==PAGER_OPEN );
51517:   }else{
51518:     pPager->eState = PAGER_READER;
51519:     pPager->hasHeldSharedLock = 1;
51520:   }
51521:   return rc;
51522: }
51523: 
51524: /*
51525: ** If the reference count has reached zero, rollback any active
51526: ** transaction and unlock the pager.
51527: **
51528: ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
51529: ** the rollback journal, the unlock is not performed and there is
51530: ** nothing to rollback, so this routine is a no-op.
51531: */ 
51532: static void pagerUnlockIfUnused(Pager *pPager){
51533:   if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
51534:     pagerUnlockAndRollback(pPager);
51535:   }
51536: }
51537: 
51538: /*
51539: ** Acquire a reference to page number pgno in pager pPager (a page
51540: ** reference has type DbPage*). If the requested reference is 
51541: ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
51542: **
51543: ** If the requested page is already in the cache, it is returned. 
51544: ** Otherwise, a new page object is allocated and populated with data
51545: ** read from the database file. In some cases, the pcache module may
51546: ** choose not to allocate a new page object and may reuse an existing
51547: ** object with no outstanding references.
51548: **
51549: ** The extra data appended to a page is always initialized to zeros the 
51550: ** first time a page is loaded into memory. If the page requested is 
51551: ** already in the cache when this function is called, then the extra
51552: ** data is left as it was when the page object was last used.
51553: **
51554: ** If the database image is smaller than the requested page or if a 
51555: ** non-zero value is passed as the noContent parameter and the 
51556: ** requested page is not already stored in the cache, then no 
51557: ** actual disk read occurs. In this case the memory image of the 
51558: ** page is initialized to all zeros. 
51559: **
51560: ** If noContent is true, it means that we do not care about the contents
51561: ** of the page. This occurs in two scenarios:
51562: **
51563: **   a) When reading a free-list leaf page from the database, and
51564: **
51565: **   b) When a savepoint is being rolled back and we need to load
51566: **      a new page into the cache to be filled with the data read
51567: **      from the savepoint journal.
51568: **
51569: ** If noContent is true, then the data returned is zeroed instead of
51570: ** being read from the database. Additionally, the bits corresponding
51571: ** to pgno in Pager.pInJournal (bitvec of pages already written to the
51572: ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
51573: ** savepoints are set. This means if the page is made writable at any
51574: ** point in the future, using a call to sqlite3PagerWrite(), its contents
51575: ** will not be journaled. This saves IO.
51576: **
51577: ** The acquisition might fail for several reasons.  In all cases,
51578: ** an appropriate error code is returned and *ppPage is set to NULL.
51579: **
51580: ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
51581: ** to find a page in the in-memory cache first.  If the page is not already
51582: ** in memory, this routine goes to disk to read it in whereas Lookup()
51583: ** just returns 0.  This routine acquires a read-lock the first time it
51584: ** has to go to disk, and could also playback an old journal if necessary.
51585: ** Since Lookup() never goes to disk, it never has to deal with locks
51586: ** or journal files.
51587: */
51588: SQLITE_PRIVATE int sqlite3PagerGet(
51589:   Pager *pPager,      /* The pager open on the database file */
51590:   Pgno pgno,          /* Page number to fetch */
51591:   DbPage **ppPage,    /* Write a pointer to the page here */
51592:   int flags           /* PAGER_GET_XXX flags */
51593: ){
51594:   int rc = SQLITE_OK;
51595:   PgHdr *pPg = 0;
51596:   u32 iFrame = 0;                 /* Frame to read from WAL file */
51597:   const int noContent = (flags & PAGER_GET_NOCONTENT);
51598: 
51599:   /* It is acceptable to use a read-only (mmap) page for any page except
51600:   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
51601:   ** flag was specified by the caller. And so long as the db is not a 
51602:   ** temporary or in-memory database.  */
51603:   const int bMmapOk = (pgno>1 && USEFETCH(pPager)
51604:    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
51605: #ifdef SQLITE_HAS_CODEC
51606:    && pPager->xCodec==0
51607: #endif
51608:   );
51609: 
51610:   /* Optimization note:  Adding the "pgno<=1" term before "pgno==0" here
51611:   ** allows the compiler optimizer to reuse the results of the "pgno>1"
51612:   ** test in the previous statement, and avoid testing pgno==0 in the
51613:   ** common case where pgno is large. */
51614:   if( pgno<=1 && pgno==0 ){
51615:     return SQLITE_CORRUPT_BKPT;
51616:   }
51617:   assert( pPager->eState>=PAGER_READER );
51618:   assert( assert_pager_state(pPager) );
51619:   assert( noContent==0 || bMmapOk==0 );
51620: 
51621:   assert( pPager->hasHeldSharedLock==1 );
51622: 
51623:   /* If the pager is in the error state, return an error immediately. 
51624:   ** Otherwise, request the page from the PCache layer. */
51625:   if( pPager->errCode!=SQLITE_OK ){
51626:     rc = pPager->errCode;
51627:   }else{
51628:     if( bMmapOk && pagerUseWal(pPager) ){
51629:       rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51630:       if( rc!=SQLITE_OK ) goto pager_acquire_err;
51631:     }
51632: 
51633:     if( bMmapOk && iFrame==0 ){
51634:       void *pData = 0;
51635: 
51636:       rc = sqlite3OsFetch(pPager->fd, 
51637:           (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
51638:       );
51639: 
51640:       if( rc==SQLITE_OK && pData ){
51641:         if( pPager->eState>PAGER_READER || pPager->tempFile ){
51642:           pPg = sqlite3PagerLookup(pPager, pgno);
51643:         }
51644:         if( pPg==0 ){
51645:           rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
51646:         }else{
51647:           sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
51648:         }
51649:         if( pPg ){
51650:           assert( rc==SQLITE_OK );
51651:           *ppPage = pPg;
51652:           return SQLITE_OK;
51653:         }
51654:       }
51655:       if( rc!=SQLITE_OK ){
51656:         goto pager_acquire_err;
51657:       }
51658:     }
51659: 
51660:     {
51661:       sqlite3_pcache_page *pBase;
51662:       pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
51663:       if( pBase==0 ){
51664:         rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
51665:         if( rc!=SQLITE_OK ) goto pager_acquire_err;
51666:         if( pBase==0 ){
51667:           pPg = *ppPage = 0;
51668:           rc = SQLITE_NOMEM_BKPT;
51669:           goto pager_acquire_err;
51670:         }
51671:       }
51672:       pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
51673:       assert( pPg!=0 );
51674:     }
51675:   }
51676: 
51677:   if( rc!=SQLITE_OK ){
51678:     /* Either the call to sqlite3PcacheFetch() returned an error or the
51679:     ** pager was already in the error-state when this function was called.
51680:     ** Set pPg to 0 and jump to the exception handler.  */
51681:     pPg = 0;
51682:     goto pager_acquire_err;
51683:   }
51684:   assert( pPg==(*ppPage) );
51685:   assert( pPg->pgno==pgno );
51686:   assert( pPg->pPager==pPager || pPg->pPager==0 );
51687: 
51688:   if( pPg->pPager && !noContent ){
51689:     /* In this case the pcache already contains an initialized copy of
51690:     ** the page. Return without further ado.  */
51691:     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
51692:     pPager->aStat[PAGER_STAT_HIT]++;
51693:     return SQLITE_OK;
51694: 
51695:   }else{
51696:     /* The pager cache has created a new page. Its content needs to 
51697:     ** be initialized.  */
51698: 
51699:     pPg->pPager = pPager;
51700: 
51701:     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
51702:     ** number greater than this, or the unused locking-page, is requested. */
51703:     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
51704:       rc = SQLITE_CORRUPT_BKPT;
51705:       goto pager_acquire_err;
51706:     }
51707: 
51708:     assert( !isOpen(pPager->fd) || !MEMDB );
51709:     if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
51710:       if( pgno>pPager->mxPgno ){
51711:         rc = SQLITE_FULL;
51712:         goto pager_acquire_err;
51713:       }
51714:       if( noContent ){
51715:         /* Failure to set the bits in the InJournal bit-vectors is benign.
51716:         ** It merely means that we might do some extra work to journal a 
51717:         ** page that does not need to be journaled.  Nevertheless, be sure 
51718:         ** to test the case where a malloc error occurs while trying to set 
51719:         ** a bit in a bit vector.
51720:         */
51721:         sqlite3BeginBenignMalloc();
51722:         if( pgno<=pPager->dbOrigSize ){
51723:           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
51724:           testcase( rc==SQLITE_NOMEM );
51725:         }
51726:         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
51727:         testcase( rc==SQLITE_NOMEM );
51728:         sqlite3EndBenignMalloc();
51729:       }
51730:       memset(pPg->pData, 0, pPager->pageSize);
51731:       IOTRACE(("ZERO %p %d\n", pPager, pgno));
51732:     }else{
51733:       if( pagerUseWal(pPager) && bMmapOk==0 ){
51734:         rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51735:         if( rc!=SQLITE_OK ) goto pager_acquire_err;
51736:       }
51737:       assert( pPg->pPager==pPager );
51738:       pPager->aStat[PAGER_STAT_MISS]++;
51739:       rc = readDbPage(pPg, iFrame);
51740:       if( rc!=SQLITE_OK ){
51741:         goto pager_acquire_err;
51742:       }
51743:     }
51744:     pager_set_pagehash(pPg);
51745:   }
51746: 
51747:   return SQLITE_OK;
51748: 
51749: pager_acquire_err:
51750:   assert( rc!=SQLITE_OK );
51751:   if( pPg ){
51752:     sqlite3PcacheDrop(pPg);
51753:   }
51754:   pagerUnlockIfUnused(pPager);
51755: 
51756:   *ppPage = 0;
51757:   return rc;
51758: }
51759: 
51760: /*
51761: ** Acquire a page if it is already in the in-memory cache.  Do
51762: ** not read the page from disk.  Return a pointer to the page,
51763: ** or 0 if the page is not in cache. 
51764: **
51765: ** See also sqlite3PagerGet().  The difference between this routine
51766: ** and sqlite3PagerGet() is that _get() will go to the disk and read
51767: ** in the page if the page is not already in cache.  This routine
51768: ** returns NULL if the page is not in cache or if a disk I/O error 
51769: ** has ever happened.
51770: */
51771: SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
51772:   sqlite3_pcache_page *pPage;
51773:   assert( pPager!=0 );
51774:   assert( pgno!=0 );
51775:   assert( pPager->pPCache!=0 );
51776:   pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
51777:   assert( pPage==0 || pPager->hasHeldSharedLock );
51778:   if( pPage==0 ) return 0;
51779:   return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
51780: }
51781: 
51782: /*
51783: ** Release a page reference.
51784: **
51785: ** If the number of references to the page drop to zero, then the
51786: ** page is added to the LRU list.  When all references to all pages
51787: ** are released, a rollback occurs and the lock on the database is
51788: ** removed.
51789: */
51790: SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
51791:   Pager *pPager;
51792:   assert( pPg!=0 );
51793:   pPager = pPg->pPager;
51794:   if( pPg->flags & PGHDR_MMAP ){
51795:     pagerReleaseMapPage(pPg);
51796:   }else{
51797:     sqlite3PcacheRelease(pPg);
51798:   }
51799:   pagerUnlockIfUnused(pPager);
51800: }
51801: SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
51802:   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
51803: }
51804: 
51805: /*
51806: ** This function is called at the start of every write transaction.
51807: ** There must already be a RESERVED or EXCLUSIVE lock on the database 
51808: ** file when this routine is called.
51809: **
51810: ** Open the journal file for pager pPager and write a journal header
51811: ** to the start of it. If there are active savepoints, open the sub-journal
51812: ** as well. This function is only used when the journal file is being 
51813: ** opened to write a rollback log for a transaction. It is not used 
51814: ** when opening a hot journal file to roll it back.
51815: **
51816: ** If the journal file is already open (as it may be in exclusive mode),
51817: ** then this function just writes a journal header to the start of the
51818: ** already open file. 
51819: **
51820: ** Whether or not the journal file is opened by this function, the
51821: ** Pager.pInJournal bitvec structure is allocated.
51822: **
51823: ** Return SQLITE_OK if everything is successful. Otherwise, return 
51824: ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
51825: ** an IO error code if opening or writing the journal file fails.
51826: */
51827: static int pager_open_journal(Pager *pPager){
51828:   int rc = SQLITE_OK;                        /* Return code */
51829:   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
51830: 
51831:   assert( pPager->eState==PAGER_WRITER_LOCKED );
51832:   assert( assert_pager_state(pPager) );
51833:   assert( pPager->pInJournal==0 );
51834:   
51835:   /* If already in the error state, this function is a no-op.  But on
51836:   ** the other hand, this routine is never called if we are already in
51837:   ** an error state. */
51838:   if( NEVER(pPager->errCode) ) return pPager->errCode;
51839: 
51840:   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51841:     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
51842:     if( pPager->pInJournal==0 ){
51843:       return SQLITE_NOMEM_BKPT;
51844:     }
51845:   
51846:     /* Open the journal file if it is not already open. */
51847:     if( !isOpen(pPager->jfd) ){
51848:       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
51849:         sqlite3MemJournalOpen(pPager->jfd);
51850:       }else{
51851:         int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
51852:         int nSpill;
51853: 
51854:         if( pPager->tempFile ){
51855:           flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
51856:           nSpill = sqlite3Config.nStmtSpill;
51857:         }else{
51858:           flags |= SQLITE_OPEN_MAIN_JOURNAL;
51859:           nSpill = jrnlBufferSize(pPager);
51860:         }
51861:           
51862:         /* Verify that the database still has the same name as it did when
51863:         ** it was originally opened. */
51864:         rc = databaseIsUnmoved(pPager);
51865:         if( rc==SQLITE_OK ){
51866:           rc = sqlite3JournalOpen (
51867:               pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
51868:           );
51869:         }
51870:       }
51871:       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51872:     }
51873:   
51874:   
51875:     /* Write the first journal header to the journal file and open 
51876:     ** the sub-journal if necessary.
51877:     */
51878:     if( rc==SQLITE_OK ){
51879:       /* TODO: Check if all of these are really required. */
51880:       pPager->nRec = 0;
51881:       pPager->journalOff = 0;
51882:       pPager->setMaster = 0;
51883:       pPager->journalHdr = 0;
51884:       rc = writeJournalHdr(pPager);
51885:     }
51886:   }
51887: 
51888:   if( rc!=SQLITE_OK ){
51889:     sqlite3BitvecDestroy(pPager->pInJournal);
51890:     pPager->pInJournal = 0;
51891:   }else{
51892:     assert( pPager->eState==PAGER_WRITER_LOCKED );
51893:     pPager->eState = PAGER_WRITER_CACHEMOD;
51894:   }
51895: 
51896:   return rc;
51897: }
51898: 
51899: /*
51900: ** Begin a write-transaction on the specified pager object. If a 
51901: ** write-transaction has already been opened, this function is a no-op.
51902: **
51903: ** If the exFlag argument is false, then acquire at least a RESERVED
51904: ** lock on the database file. If exFlag is true, then acquire at least
51905: ** an EXCLUSIVE lock. If such a lock is already held, no locking 
51906: ** functions need be called.
51907: **
51908: ** If the subjInMemory argument is non-zero, then any sub-journal opened
51909: ** within this transaction will be opened as an in-memory file. This
51910: ** has no effect if the sub-journal is already opened (as it may be when
51911: ** running in exclusive mode) or if the transaction does not require a
51912: ** sub-journal. If the subjInMemory argument is zero, then any required
51913: ** sub-journal is implemented in-memory if pPager is an in-memory database, 
51914: ** or using a temporary file otherwise.
51915: */
51916: SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
51917:   int rc = SQLITE_OK;
51918: 
51919:   if( pPager->errCode ) return pPager->errCode;
51920:   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
51921:   pPager->subjInMemory = (u8)subjInMemory;
51922: 
51923:   if( ALWAYS(pPager->eState==PAGER_READER) ){
51924:     assert( pPager->pInJournal==0 );
51925: 
51926:     if( pagerUseWal(pPager) ){
51927:       /* If the pager is configured to use locking_mode=exclusive, and an
51928:       ** exclusive lock on the database is not already held, obtain it now.
51929:       */
51930:       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
51931:         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51932:         if( rc!=SQLITE_OK ){
51933:           return rc;
51934:         }
51935:         (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
51936:       }
51937: 
51938:       /* Grab the write lock on the log file. If successful, upgrade to
51939:       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
51940:       ** The busy-handler is not invoked if another connection already
51941:       ** holds the write-lock. If possible, the upper layer will call it.
51942:       */
51943:       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
51944:     }else{
51945:       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
51946:       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
51947:       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
51948:       ** lock, but not when obtaining the RESERVED lock.
51949:       */
51950:       rc = pagerLockDb(pPager, RESERVED_LOCK);
51951:       if( rc==SQLITE_OK && exFlag ){
51952:         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
51953:       }
51954:     }
51955: 
51956:     if( rc==SQLITE_OK ){
51957:       /* Change to WRITER_LOCKED state.
51958:       **
51959:       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
51960:       ** when it has an open transaction, but never to DBMOD or FINISHED.
51961:       ** This is because in those states the code to roll back savepoint 
51962:       ** transactions may copy data from the sub-journal into the database 
51963:       ** file as well as into the page cache. Which would be incorrect in 
51964:       ** WAL mode.
51965:       */
51966:       pPager->eState = PAGER_WRITER_LOCKED;
51967:       pPager->dbHintSize = pPager->dbSize;
51968:       pPager->dbFileSize = pPager->dbSize;
51969:       pPager->dbOrigSize = pPager->dbSize;
51970:       pPager->journalOff = 0;
51971:     }
51972: 
51973:     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
51974:     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
51975:     assert( assert_pager_state(pPager) );
51976:   }
51977: 
51978:   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
51979:   return rc;
51980: }
51981: 
51982: /*
51983: ** Write page pPg onto the end of the rollback journal.
51984: */
51985: static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
51986:   Pager *pPager = pPg->pPager;
51987:   int rc;
51988:   u32 cksum;
51989:   char *pData2;
51990:   i64 iOff = pPager->journalOff;
51991: 
51992:   /* We should never write to the journal file the page that
51993:   ** contains the database locks.  The following assert verifies
51994:   ** that we do not. */
51995:   assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
51996: 
51997:   assert( pPager->journalHdr<=pPager->journalOff );
51998:   CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
51999:   cksum = pager_cksum(pPager, (u8*)pData2);
52000: 
52001:   /* Even if an IO or diskfull error occurs while journalling the
52002:   ** page in the block above, set the need-sync flag for the page.
52003:   ** Otherwise, when the transaction is rolled back, the logic in
52004:   ** playback_one_page() will think that the page needs to be restored
52005:   ** in the database file. And if an IO error occurs while doing so,
52006:   ** then corruption may follow.
52007:   */
52008:   pPg->flags |= PGHDR_NEED_SYNC;
52009: 
52010:   rc = write32bits(pPager->jfd, iOff, pPg->pgno);
52011:   if( rc!=SQLITE_OK ) return rc;
52012:   rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
52013:   if( rc!=SQLITE_OK ) return rc;
52014:   rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
52015:   if( rc!=SQLITE_OK ) return rc;
52016: 
52017:   IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
52018:            pPager->journalOff, pPager->pageSize));
52019:   PAGER_INCR(sqlite3_pager_writej_count);
52020:   PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
52021:        PAGERID(pPager), pPg->pgno, 
52022:        ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
52023: 
52024:   pPager->journalOff += 8 + pPager->pageSize;
52025:   pPager->nRec++;
52026:   assert( pPager->pInJournal!=0 );
52027:   rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
52028:   testcase( rc==SQLITE_NOMEM );
52029:   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52030:   rc |= addToSavepointBitvecs(pPager, pPg->pgno);
52031:   assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
52032:   return rc;
52033: }
52034: 
52035: /*
52036: ** Mark a single data page as writeable. The page is written into the 
52037: ** main journal or sub-journal as required. If the page is written into
52038: ** one of the journals, the corresponding bit is set in the 
52039: ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
52040: ** of any open savepoints as appropriate.
52041: */
52042: static int pager_write(PgHdr *pPg){
52043:   Pager *pPager = pPg->pPager;
52044:   int rc = SQLITE_OK;
52045: 
52046:   /* This routine is not called unless a write-transaction has already 
52047:   ** been started. The journal file may or may not be open at this point.
52048:   ** It is never called in the ERROR state.
52049:   */
52050:   assert( pPager->eState==PAGER_WRITER_LOCKED
52051:        || pPager->eState==PAGER_WRITER_CACHEMOD
52052:        || pPager->eState==PAGER_WRITER_DBMOD
52053:   );
52054:   assert( assert_pager_state(pPager) );
52055:   assert( pPager->errCode==0 );
52056:   assert( pPager->readOnly==0 );
52057:   CHECK_PAGE(pPg);
52058: 
52059:   /* The journal file needs to be opened. Higher level routines have already
52060:   ** obtained the necessary locks to begin the write-transaction, but the
52061:   ** rollback journal might not yet be open. Open it now if this is the case.
52062:   **
52063:   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
52064:   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
52065:   ** an error might occur and the pager would end up in WRITER_LOCKED state
52066:   ** with pages marked as dirty in the cache.
52067:   */
52068:   if( pPager->eState==PAGER_WRITER_LOCKED ){
52069:     rc = pager_open_journal(pPager);
52070:     if( rc!=SQLITE_OK ) return rc;
52071:   }
52072:   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
52073:   assert( assert_pager_state(pPager) );
52074: 
52075:   /* Mark the page that is about to be modified as dirty. */
52076:   sqlite3PcacheMakeDirty(pPg);
52077: 
52078:   /* If a rollback journal is in use, them make sure the page that is about
52079:   ** to change is in the rollback journal, or if the page is a new page off
52080:   ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
52081:   */
52082:   assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
52083:   if( pPager->pInJournal!=0
52084:    && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
52085:   ){
52086:     assert( pagerUseWal(pPager)==0 );
52087:     if( pPg->pgno<=pPager->dbOrigSize ){
52088:       rc = pagerAddPageToRollbackJournal(pPg);
52089:       if( rc!=SQLITE_OK ){
52090:         return rc;
52091:       }
52092:     }else{
52093:       if( pPager->eState!=PAGER_WRITER_DBMOD ){
52094:         pPg->flags |= PGHDR_NEED_SYNC;
52095:       }
52096:       PAGERTRACE(("APPEND %d page %d needSync=%d\n",
52097:               PAGERID(pPager), pPg->pgno,
52098:              ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
52099:     }
52100:   }
52101: 
52102:   /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
52103:   ** and before writing the page into the rollback journal.  Wait until now,
52104:   ** after the page has been successfully journalled, before setting the
52105:   ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
52106:   */
52107:   pPg->flags |= PGHDR_WRITEABLE;
52108:   
52109:   /* If the statement journal is open and the page is not in it,
52110:   ** then write the page into the statement journal.
52111:   */
52112:   if( pPager->nSavepoint>0 ){
52113:     rc = subjournalPageIfRequired(pPg);
52114:   }
52115: 
52116:   /* Update the database size and return. */
52117:   if( pPager->dbSize<pPg->pgno ){
52118:     pPager->dbSize = pPg->pgno;
52119:   }
52120:   return rc;
52121: }
52122: 
52123: /*
52124: ** This is a variant of sqlite3PagerWrite() that runs when the sector size
52125: ** is larger than the page size.  SQLite makes the (reasonable) assumption that
52126: ** all bytes of a sector are written together by hardware.  Hence, all bytes of
52127: ** a sector need to be journalled in case of a power loss in the middle of
52128: ** a write.
52129: **
52130: ** Usually, the sector size is less than or equal to the page size, in which
52131: ** case pages can be individually written.  This routine only runs in the
52132: ** exceptional case where the page size is smaller than the sector size.
52133: */
52134: static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
52135:   int rc = SQLITE_OK;          /* Return code */
52136:   Pgno nPageCount;             /* Total number of pages in database file */
52137:   Pgno pg1;                    /* First page of the sector pPg is located on. */
52138:   int nPage = 0;               /* Number of pages starting at pg1 to journal */
52139:   int ii;                      /* Loop counter */
52140:   int needSync = 0;            /* True if any page has PGHDR_NEED_SYNC */
52141:   Pager *pPager = pPg->pPager; /* The pager that owns pPg */
52142:   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
52143: 
52144:   /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
52145:   ** a journal header to be written between the pages journaled by
52146:   ** this function.
52147:   */
52148:   assert( !MEMDB );
52149:   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
52150:   pPager->doNotSpill |= SPILLFLAG_NOSYNC;
52151: 
52152:   /* This trick assumes that both the page-size and sector-size are
52153:   ** an integer power of 2. It sets variable pg1 to the identifier
52154:   ** of the first page of the sector pPg is located on.
52155:   */
52156:   pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
52157: 
52158:   nPageCount = pPager->dbSize;
52159:   if( pPg->pgno>nPageCount ){
52160:     nPage = (pPg->pgno - pg1)+1;
52161:   }else if( (pg1+nPagePerSector-1)>nPageCount ){
52162:     nPage = nPageCount+1-pg1;
52163:   }else{
52164:     nPage = nPagePerSector;
52165:   }
52166:   assert(nPage>0);
52167:   assert(pg1<=pPg->pgno);
52168:   assert((pg1+nPage)>pPg->pgno);
52169: 
52170:   for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
52171:     Pgno pg = pg1+ii;
52172:     PgHdr *pPage;
52173:     if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
52174:       if( pg!=PAGER_MJ_PGNO(pPager) ){
52175:         rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
52176:         if( rc==SQLITE_OK ){
52177:           rc = pager_write(pPage);
52178:           if( pPage->flags&PGHDR_NEED_SYNC ){
52179:             needSync = 1;
52180:           }
52181:           sqlite3PagerUnrefNotNull(pPage);
52182:         }
52183:       }
52184:     }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
52185:       if( pPage->flags&PGHDR_NEED_SYNC ){
52186:         needSync = 1;
52187:       }
52188:       sqlite3PagerUnrefNotNull(pPage);
52189:     }
52190:   }
52191: 
52192:   /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
52193:   ** starting at pg1, then it needs to be set for all of them. Because
52194:   ** writing to any of these nPage pages may damage the others, the
52195:   ** journal file must contain sync()ed copies of all of them
52196:   ** before any of them can be written out to the database file.
52197:   */
52198:   if( rc==SQLITE_OK && needSync ){
52199:     assert( !MEMDB );
52200:     for(ii=0; ii<nPage; ii++){
52201:       PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
52202:       if( pPage ){
52203:         pPage->flags |= PGHDR_NEED_SYNC;
52204:         sqlite3PagerUnrefNotNull(pPage);
52205:       }
52206:     }
52207:   }
52208: 
52209:   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
52210:   pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
52211:   return rc;
52212: }
52213: 
52214: /*
52215: ** Mark a data page as writeable. This routine must be called before 
52216: ** making changes to a page. The caller must check the return value 
52217: ** of this function and be careful not to change any page data unless 
52218: ** this routine returns SQLITE_OK.
52219: **
52220: ** The difference between this function and pager_write() is that this
52221: ** function also deals with the special case where 2 or more pages
52222: ** fit on a single disk sector. In this case all co-resident pages
52223: ** must have been written to the journal file before returning.
52224: **
52225: ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
52226: ** as appropriate. Otherwise, SQLITE_OK.
52227: */
52228: SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
52229:   Pager *pPager = pPg->pPager;
52230:   assert( (pPg->flags & PGHDR_MMAP)==0 );
52231:   assert( pPager->eState>=PAGER_WRITER_LOCKED );
52232:   assert( assert_pager_state(pPager) );
52233:   if( pPager->errCode ){
52234:     return pPager->errCode;
52235:   }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
52236:     if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
52237:     return SQLITE_OK;
52238:   }else if( pPager->sectorSize > (u32)pPager->pageSize ){
52239:     assert( pPager->tempFile==0 );
52240:     return pagerWriteLargeSector(pPg);
52241:   }else{
52242:     return pager_write(pPg);
52243:   }
52244: }
52245: 
52246: /*
52247: ** Return TRUE if the page given in the argument was previously passed
52248: ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
52249: ** to change the content of the page.
52250: */
52251: #ifndef NDEBUG
52252: SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
52253:   return pPg->flags & PGHDR_WRITEABLE;
52254: }
52255: #endif
52256: 
52257: /*
52258: ** A call to this routine tells the pager that it is not necessary to
52259: ** write the information on page pPg back to the disk, even though
52260: ** that page might be marked as dirty.  This happens, for example, when
52261: ** the page has been added as a leaf of the freelist and so its
52262: ** content no longer matters.
52263: **
52264: ** The overlying software layer calls this routine when all of the data
52265: ** on the given page is unused. The pager marks the page as clean so
52266: ** that it does not get written to disk.
52267: **
52268: ** Tests show that this optimization can quadruple the speed of large 
52269: ** DELETE operations.
52270: **
52271: ** This optimization cannot be used with a temp-file, as the page may
52272: ** have been dirty at the start of the transaction. In that case, if
52273: ** memory pressure forces page pPg out of the cache, the data does need 
52274: ** to be written out to disk so that it may be read back in if the 
52275: ** current transaction is rolled back.
52276: */
52277: SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
52278:   Pager *pPager = pPg->pPager;
52279:   if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
52280:     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
52281:     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
52282:     pPg->flags |= PGHDR_DONT_WRITE;
52283:     pPg->flags &= ~PGHDR_WRITEABLE;
52284:     testcase( pPg->flags & PGHDR_NEED_SYNC );
52285:     pager_set_pagehash(pPg);
52286:   }
52287: }
52288: 
52289: /*
52290: ** This routine is called to increment the value of the database file 
52291: ** change-counter, stored as a 4-byte big-endian integer starting at 
52292: ** byte offset 24 of the pager file.  The secondary change counter at
52293: ** 92 is also updated, as is the SQLite version number at offset 96.
52294: **
52295: ** But this only happens if the pPager->changeCountDone flag is false.
52296: ** To avoid excess churning of page 1, the update only happens once.
52297: ** See also the pager_write_changecounter() routine that does an 
52298: ** unconditional update of the change counters.
52299: **
52300: ** If the isDirectMode flag is zero, then this is done by calling 
52301: ** sqlite3PagerWrite() on page 1, then modifying the contents of the
52302: ** page data. In this case the file will be updated when the current
52303: ** transaction is committed.
52304: **
52305: ** The isDirectMode flag may only be non-zero if the library was compiled
52306: ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
52307: ** if isDirect is non-zero, then the database file is updated directly
52308: ** by writing an updated version of page 1 using a call to the 
52309: ** sqlite3OsWrite() function.
52310: */
52311: static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
52312:   int rc = SQLITE_OK;
52313: 
52314:   assert( pPager->eState==PAGER_WRITER_CACHEMOD
52315:        || pPager->eState==PAGER_WRITER_DBMOD
52316:   );
52317:   assert( assert_pager_state(pPager) );
52318: 
52319:   /* Declare and initialize constant integer 'isDirect'. If the
52320:   ** atomic-write optimization is enabled in this build, then isDirect
52321:   ** is initialized to the value passed as the isDirectMode parameter
52322:   ** to this function. Otherwise, it is always set to zero.
52323:   **
52324:   ** The idea is that if the atomic-write optimization is not
52325:   ** enabled at compile time, the compiler can omit the tests of
52326:   ** 'isDirect' below, as well as the block enclosed in the
52327:   ** "if( isDirect )" condition.
52328:   */
52329: #ifndef SQLITE_ENABLE_ATOMIC_WRITE
52330: # define DIRECT_MODE 0
52331:   assert( isDirectMode==0 );
52332:   UNUSED_PARAMETER(isDirectMode);
52333: #else
52334: # define DIRECT_MODE isDirectMode
52335: #endif
52336: 
52337:   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
52338:     PgHdr *pPgHdr;                /* Reference to page 1 */
52339: 
52340:     assert( !pPager->tempFile && isOpen(pPager->fd) );
52341: 
52342:     /* Open page 1 of the file for writing. */
52343:     rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
52344:     assert( pPgHdr==0 || rc==SQLITE_OK );
52345: 
52346:     /* If page one was fetched successfully, and this function is not
52347:     ** operating in direct-mode, make page 1 writable.  When not in 
52348:     ** direct mode, page 1 is always held in cache and hence the PagerGet()
52349:     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
52350:     */
52351:     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
52352:       rc = sqlite3PagerWrite(pPgHdr);
52353:     }
52354: 
52355:     if( rc==SQLITE_OK ){
52356:       /* Actually do the update of the change counter */
52357:       pager_write_changecounter(pPgHdr);
52358: 
52359:       /* If running in direct mode, write the contents of page 1 to the file. */
52360:       if( DIRECT_MODE ){
52361:         const void *zBuf;
52362:         assert( pPager->dbFileSize>0 );
52363:         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
52364:         if( rc==SQLITE_OK ){
52365:           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
52366:           pPager->aStat[PAGER_STAT_WRITE]++;
52367:         }
52368:         if( rc==SQLITE_OK ){
52369:           /* Update the pager's copy of the change-counter. Otherwise, the
52370:           ** next time a read transaction is opened the cache will be
52371:           ** flushed (as the change-counter values will not match).  */
52372:           const void *pCopy = (const void *)&((const char *)zBuf)[24];
52373:           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
52374:           pPager->changeCountDone = 1;
52375:         }
52376:       }else{
52377:         pPager->changeCountDone = 1;
52378:       }
52379:     }
52380: 
52381:     /* Release the page reference. */
52382:     sqlite3PagerUnref(pPgHdr);
52383:   }
52384:   return rc;
52385: }
52386: 
52387: /*
52388: ** Sync the database file to disk. This is a no-op for in-memory databases
52389: ** or pages with the Pager.noSync flag set.
52390: **
52391: ** If successful, or if called on a pager for which it is a no-op, this
52392: ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
52393: */
52394: SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
52395:   int rc = SQLITE_OK;
52396: 
52397:   if( isOpen(pPager->fd) ){
52398:     void *pArg = (void*)zMaster;
52399:     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
52400:     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
52401:   }
52402:   if( rc==SQLITE_OK && !pPager->noSync ){
52403:     assert( !MEMDB );
52404:     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
52405:   }
52406:   return rc;
52407: }
52408: 
52409: /*
52410: ** This function may only be called while a write-transaction is active in
52411: ** rollback. If the connection is in WAL mode, this call is a no-op. 
52412: ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
52413: ** the database file, an attempt is made to obtain one.
52414: **
52415: ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
52416: ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
52417: ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
52418: ** returned.
52419: */
52420: SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
52421:   int rc = pPager->errCode;
52422:   assert( assert_pager_state(pPager) );
52423:   if( rc==SQLITE_OK ){
52424:     assert( pPager->eState==PAGER_WRITER_CACHEMOD 
52425:          || pPager->eState==PAGER_WRITER_DBMOD 
52426:          || pPager->eState==PAGER_WRITER_LOCKED 
52427:     );
52428:     assert( assert_pager_state(pPager) );
52429:     if( 0==pagerUseWal(pPager) ){
52430:       rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
52431:     }
52432:   }
52433:   return rc;
52434: }
52435: 
52436: /*
52437: ** Sync the database file for the pager pPager. zMaster points to the name
52438: ** of a master journal file that should be written into the individual
52439: ** journal file. zMaster may be NULL, which is interpreted as no master
52440: ** journal (a single database transaction).
52441: **
52442: ** This routine ensures that:
52443: **
52444: **   * The database file change-counter is updated,
52445: **   * the journal is synced (unless the atomic-write optimization is used),
52446: **   * all dirty pages are written to the database file, 
52447: **   * the database file is truncated (if required), and
52448: **   * the database file synced. 
52449: **
52450: ** The only thing that remains to commit the transaction is to finalize 
52451: ** (delete, truncate or zero the first part of) the journal file (or 
52452: ** delete the master journal file if specified).
52453: **
52454: ** Note that if zMaster==NULL, this does not overwrite a previous value
52455: ** passed to an sqlite3PagerCommitPhaseOne() call.
52456: **
52457: ** If the final parameter - noSync - is true, then the database file itself
52458: ** is not synced. The caller must call sqlite3PagerSync() directly to
52459: ** sync the database file before calling CommitPhaseTwo() to delete the
52460: ** journal file in this case.
52461: */
52462: SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
52463:   Pager *pPager,                  /* Pager object */
52464:   const char *zMaster,            /* If not NULL, the master journal name */
52465:   int noSync                      /* True to omit the xSync on the db file */
52466: ){
52467:   int rc = SQLITE_OK;             /* Return code */
52468: 
52469:   assert( pPager->eState==PAGER_WRITER_LOCKED
52470:        || pPager->eState==PAGER_WRITER_CACHEMOD
52471:        || pPager->eState==PAGER_WRITER_DBMOD
52472:        || pPager->eState==PAGER_ERROR
52473:   );
52474:   assert( assert_pager_state(pPager) );
52475: 
52476:   /* If a prior error occurred, report that error again. */
52477:   if( NEVER(pPager->errCode) ) return pPager->errCode;
52478: 
52479:   /* Provide the ability to easily simulate an I/O error during testing */
52480:   if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
52481: 
52482:   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
52483:       pPager->zFilename, zMaster, pPager->dbSize));
52484: 
52485:   /* If no database changes have been made, return early. */
52486:   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
52487: 
52488:   assert( MEMDB==0 || pPager->tempFile );
52489:   assert( isOpen(pPager->fd) || pPager->tempFile );
52490:   if( 0==pagerFlushOnCommit(pPager, 1) ){
52491:     /* If this is an in-memory db, or no pages have been written to, or this
52492:     ** function has already been called, it is mostly a no-op.  However, any
52493:     ** backup in progress needs to be restarted.  */
52494:     sqlite3BackupRestart(pPager->pBackup);
52495:   }else{
52496:     if( pagerUseWal(pPager) ){
52497:       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52498:       PgHdr *pPageOne = 0;
52499:       if( pList==0 ){
52500:         /* Must have at least one page for the WAL commit flag.
52501:         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
52502:         rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
52503:         pList = pPageOne;
52504:         pList->pDirty = 0;
52505:       }
52506:       assert( rc==SQLITE_OK );
52507:       if( ALWAYS(pList) ){
52508:         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
52509:       }
52510:       sqlite3PagerUnref(pPageOne);
52511:       if( rc==SQLITE_OK ){
52512:         sqlite3PcacheCleanAll(pPager->pPCache);
52513:       }
52514:     }else{
52515:       /* The following block updates the change-counter. Exactly how it
52516:       ** does this depends on whether or not the atomic-update optimization
52517:       ** was enabled at compile time, and if this transaction meets the 
52518:       ** runtime criteria to use the operation: 
52519:       **
52520:       **    * The file-system supports the atomic-write property for
52521:       **      blocks of size page-size, and 
52522:       **    * This commit is not part of a multi-file transaction, and
52523:       **    * Exactly one page has been modified and store in the journal file.
52524:       **
52525:       ** If the optimization was not enabled at compile time, then the
52526:       ** pager_incr_changecounter() function is called to update the change
52527:       ** counter in 'indirect-mode'. If the optimization is compiled in but
52528:       ** is not applicable to this transaction, call sqlite3JournalCreate()
52529:       ** to make sure the journal file has actually been created, then call
52530:       ** pager_incr_changecounter() to update the change-counter in indirect
52531:       ** mode. 
52532:       **
52533:       ** Otherwise, if the optimization is both enabled and applicable,
52534:       ** then call pager_incr_changecounter() to update the change-counter
52535:       ** in 'direct' mode. In this case the journal file will never be
52536:       ** created for this transaction.
52537:       */
52538:   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
52539:       PgHdr *pPg;
52540:       assert( isOpen(pPager->jfd) 
52541:            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
52542:            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
52543:       );
52544:       if( !zMaster && isOpen(pPager->jfd) 
52545:        && pPager->journalOff==jrnlBufferSize(pPager) 
52546:        && pPager->dbSize>=pPager->dbOrigSize
52547:        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
52548:       ){
52549:         /* Update the db file change counter via the direct-write method. The 
52550:         ** following call will modify the in-memory representation of page 1 
52551:         ** to include the updated change counter and then write page 1 
52552:         ** directly to the database file. Because of the atomic-write 
52553:         ** property of the host file-system, this is safe.
52554:         */
52555:         rc = pager_incr_changecounter(pPager, 1);
52556:       }else{
52557:         rc = sqlite3JournalCreate(pPager->jfd);
52558:         if( rc==SQLITE_OK ){
52559:           rc = pager_incr_changecounter(pPager, 0);
52560:         }
52561:       }
52562:   #else
52563:       rc = pager_incr_changecounter(pPager, 0);
52564:   #endif
52565:       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52566:   
52567:       /* Write the master journal name into the journal file. If a master 
52568:       ** journal file name has already been written to the journal file, 
52569:       ** or if zMaster is NULL (no master journal), then this call is a no-op.
52570:       */
52571:       rc = writeMasterJournal(pPager, zMaster);
52572:       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52573:   
52574:       /* Sync the journal file and write all dirty pages to the database.
52575:       ** If the atomic-update optimization is being used, this sync will not 
52576:       ** create the journal file or perform any real IO.
52577:       **
52578:       ** Because the change-counter page was just modified, unless the
52579:       ** atomic-update optimization is used it is almost certain that the
52580:       ** journal requires a sync here. However, in locking_mode=exclusive
52581:       ** on a system under memory pressure it is just possible that this is 
52582:       ** not the case. In this case it is likely enough that the redundant
52583:       ** xSync() call will be changed to a no-op by the OS anyhow. 
52584:       */
52585:       rc = syncJournal(pPager, 0);
52586:       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52587:   
52588:       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
52589:       if( rc!=SQLITE_OK ){
52590:         assert( rc!=SQLITE_IOERR_BLOCKED );
52591:         goto commit_phase_one_exit;
52592:       }
52593:       sqlite3PcacheCleanAll(pPager->pPCache);
52594: 
52595:       /* If the file on disk is smaller than the database image, use 
52596:       ** pager_truncate to grow the file here. This can happen if the database
52597:       ** image was extended as part of the current transaction and then the
52598:       ** last page in the db image moved to the free-list. In this case the
52599:       ** last page is never written out to disk, leaving the database file
52600:       ** undersized. Fix this now if it is the case.  */
52601:       if( pPager->dbSize>pPager->dbFileSize ){
52602:         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
52603:         assert( pPager->eState==PAGER_WRITER_DBMOD );
52604:         rc = pager_truncate(pPager, nNew);
52605:         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52606:       }
52607:   
52608:       /* Finally, sync the database file. */
52609:       if( !noSync ){
52610:         rc = sqlite3PagerSync(pPager, zMaster);
52611:       }
52612:       IOTRACE(("DBSYNC %p\n", pPager))
52613:     }
52614:   }
52615: 
52616: commit_phase_one_exit:
52617:   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
52618:     pPager->eState = PAGER_WRITER_FINISHED;
52619:   }
52620:   return rc;
52621: }
52622: 
52623: 
52624: /*
52625: ** When this function is called, the database file has been completely
52626: ** updated to reflect the changes made by the current transaction and
52627: ** synced to disk. The journal file still exists in the file-system 
52628: ** though, and if a failure occurs at this point it will eventually
52629: ** be used as a hot-journal and the current transaction rolled back.
52630: **
52631: ** This function finalizes the journal file, either by deleting, 
52632: ** truncating or partially zeroing it, so that it cannot be used 
52633: ** for hot-journal rollback. Once this is done the transaction is
52634: ** irrevocably committed.
52635: **
52636: ** If an error occurs, an IO error code is returned and the pager
52637: ** moves into the error state. Otherwise, SQLITE_OK is returned.
52638: */
52639: SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
52640:   int rc = SQLITE_OK;                  /* Return code */
52641: 
52642:   /* This routine should not be called if a prior error has occurred.
52643:   ** But if (due to a coding error elsewhere in the system) it does get
52644:   ** called, just return the same error code without doing anything. */
52645:   if( NEVER(pPager->errCode) ) return pPager->errCode;
52646: 
52647:   assert( pPager->eState==PAGER_WRITER_LOCKED
52648:        || pPager->eState==PAGER_WRITER_FINISHED
52649:        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
52650:   );
52651:   assert( assert_pager_state(pPager) );
52652: 
52653:   /* An optimization. If the database was not actually modified during
52654:   ** this transaction, the pager is running in exclusive-mode and is
52655:   ** using persistent journals, then this function is a no-op.
52656:   **
52657:   ** The start of the journal file currently contains a single journal 
52658:   ** header with the nRec field set to 0. If such a journal is used as
52659:   ** a hot-journal during hot-journal rollback, 0 changes will be made
52660:   ** to the database file. So there is no need to zero the journal 
52661:   ** header. Since the pager is in exclusive mode, there is no need
52662:   ** to drop any locks either.
52663:   */
52664:   if( pPager->eState==PAGER_WRITER_LOCKED 
52665:    && pPager->exclusiveMode 
52666:    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
52667:   ){
52668:     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
52669:     pPager->eState = PAGER_READER;
52670:     return SQLITE_OK;
52671:   }
52672: 
52673:   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
52674:   pPager->iDataVersion++;
52675:   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
52676:   return pager_error(pPager, rc);
52677: }
52678: 
52679: /*
52680: ** If a write transaction is open, then all changes made within the 
52681: ** transaction are reverted and the current write-transaction is closed.
52682: ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
52683: ** state if an error occurs.
52684: **
52685: ** If the pager is already in PAGER_ERROR state when this function is called,
52686: ** it returns Pager.errCode immediately. No work is performed in this case.
52687: **
52688: ** Otherwise, in rollback mode, this function performs two functions:
52689: **
52690: **   1) It rolls back the journal file, restoring all database file and 
52691: **      in-memory cache pages to the state they were in when the transaction
52692: **      was opened, and
52693: **
52694: **   2) It finalizes the journal file, so that it is not used for hot
52695: **      rollback at any point in the future.
52696: **
52697: ** Finalization of the journal file (task 2) is only performed if the 
52698: ** rollback is successful.
52699: **
52700: ** In WAL mode, all cache-entries containing data modified within the
52701: ** current transaction are either expelled from the cache or reverted to
52702: ** their pre-transaction state by re-reading data from the database or
52703: ** WAL files. The WAL transaction is then closed.
52704: */
52705: SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
52706:   int rc = SQLITE_OK;                  /* Return code */
52707:   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
52708: 
52709:   /* PagerRollback() is a no-op if called in READER or OPEN state. If
52710:   ** the pager is already in the ERROR state, the rollback is not 
52711:   ** attempted here. Instead, the error code is returned to the caller.
52712:   */
52713:   assert( assert_pager_state(pPager) );
52714:   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
52715:   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
52716: 
52717:   if( pagerUseWal(pPager) ){
52718:     int rc2;
52719:     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
52720:     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
52721:     if( rc==SQLITE_OK ) rc = rc2;
52722:   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
52723:     int eState = pPager->eState;
52724:     rc = pager_end_transaction(pPager, 0, 0);
52725:     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
52726:       /* This can happen using journal_mode=off. Move the pager to the error 
52727:       ** state to indicate that the contents of the cache may not be trusted.
52728:       ** Any active readers will get SQLITE_ABORT.
52729:       */
52730:       pPager->errCode = SQLITE_ABORT;
52731:       pPager->eState = PAGER_ERROR;
52732:       return rc;
52733:     }
52734:   }else{
52735:     rc = pager_playback(pPager, 0);
52736:   }
52737: 
52738:   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
52739:   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
52740:           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR 
52741:           || rc==SQLITE_CANTOPEN
52742:   );
52743: 
52744:   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
52745:   ** cache. So call pager_error() on the way out to make any error persistent.
52746:   */
52747:   return pager_error(pPager, rc);
52748: }
52749: 
52750: /*
52751: ** Return TRUE if the database file is opened read-only.  Return FALSE
52752: ** if the database is (in theory) writable.
52753: */
52754: SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
52755:   return pPager->readOnly;
52756: }
52757: 
52758: #ifdef SQLITE_DEBUG
52759: /*
52760: ** Return the sum of the reference counts for all pages held by pPager.
52761: */
52762: SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
52763:   return sqlite3PcacheRefCount(pPager->pPCache);
52764: }
52765: #endif
52766: 
52767: /*
52768: ** Return the approximate number of bytes of memory currently
52769: ** used by the pager and its associated cache.
52770: */
52771: SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
52772:   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
52773:                                      + 5*sizeof(void*);
52774:   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
52775:            + sqlite3MallocSize(pPager)
52776:            + pPager->pageSize;
52777: }
52778: 
52779: /*
52780: ** Return the number of references to the specified page.
52781: */
52782: SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
52783:   return sqlite3PcachePageRefcount(pPage);
52784: }
52785: 
52786: #ifdef SQLITE_TEST
52787: /*
52788: ** This routine is used for testing and analysis only.
52789: */
52790: SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
52791:   static int a[11];
52792:   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
52793:   a[1] = sqlite3PcachePagecount(pPager->pPCache);
52794:   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
52795:   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
52796:   a[4] = pPager->eState;
52797:   a[5] = pPager->errCode;
52798:   a[6] = pPager->aStat[PAGER_STAT_HIT];
52799:   a[7] = pPager->aStat[PAGER_STAT_MISS];
52800:   a[8] = 0;  /* Used to be pPager->nOvfl */
52801:   a[9] = pPager->nRead;
52802:   a[10] = pPager->aStat[PAGER_STAT_WRITE];
52803:   return a;
52804: }
52805: #endif
52806: 
52807: /*
52808: ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
52809: ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
52810: ** current cache hit or miss count, according to the value of eStat. If the 
52811: ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
52812: ** returning.
52813: */
52814: SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
52815: 
52816:   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
52817:        || eStat==SQLITE_DBSTATUS_CACHE_MISS
52818:        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
52819:   );
52820: 
52821:   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
52822:   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
52823:   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
52824: 
52825:   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
52826:   if( reset ){
52827:     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
52828:   }
52829: }
52830: 
52831: /*
52832: ** Return true if this is an in-memory or temp-file backed pager.
52833: */
52834: SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
52835:   return pPager->tempFile;
52836: }
52837: 
52838: /*
52839: ** Check that there are at least nSavepoint savepoints open. If there are
52840: ** currently less than nSavepoints open, then open one or more savepoints
52841: ** to make up the difference. If the number of savepoints is already
52842: ** equal to nSavepoint, then this function is a no-op.
52843: **
52844: ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
52845: ** occurs while opening the sub-journal file, then an IO error code is
52846: ** returned. Otherwise, SQLITE_OK.
52847: */
52848: static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
52849:   int rc = SQLITE_OK;                       /* Return code */
52850:   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
52851:   int ii;                                   /* Iterator variable */
52852:   PagerSavepoint *aNew;                     /* New Pager.aSavepoint array */
52853: 
52854:   assert( pPager->eState>=PAGER_WRITER_LOCKED );
52855:   assert( assert_pager_state(pPager) );
52856:   assert( nSavepoint>nCurrent && pPager->useJournal );
52857: 
52858:   /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
52859:   ** if the allocation fails. Otherwise, zero the new portion in case a 
52860:   ** malloc failure occurs while populating it in the for(...) loop below.
52861:   */
52862:   aNew = (PagerSavepoint *)sqlite3Realloc(
52863:       pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
52864:   );
52865:   if( !aNew ){
52866:     return SQLITE_NOMEM_BKPT;
52867:   }
52868:   memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
52869:   pPager->aSavepoint = aNew;
52870: 
52871:   /* Populate the PagerSavepoint structures just allocated. */
52872:   for(ii=nCurrent; ii<nSavepoint; ii++){
52873:     aNew[ii].nOrig = pPager->dbSize;
52874:     if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
52875:       aNew[ii].iOffset = pPager->journalOff;
52876:     }else{
52877:       aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
52878:     }
52879:     aNew[ii].iSubRec = pPager->nSubRec;
52880:     aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
52881:     if( !aNew[ii].pInSavepoint ){
52882:       return SQLITE_NOMEM_BKPT;
52883:     }
52884:     if( pagerUseWal(pPager) ){
52885:       sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
52886:     }
52887:     pPager->nSavepoint = ii+1;
52888:   }
52889:   assert( pPager->nSavepoint==nSavepoint );
52890:   assertTruncateConstraint(pPager);
52891:   return rc;
52892: }
52893: SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
52894:   assert( pPager->eState>=PAGER_WRITER_LOCKED );
52895:   assert( assert_pager_state(pPager) );
52896: 
52897:   if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
52898:     return pagerOpenSavepoint(pPager, nSavepoint);
52899:   }else{
52900:     return SQLITE_OK;
52901:   }
52902: }
52903: 
52904: 
52905: /*
52906: ** This function is called to rollback or release (commit) a savepoint.
52907: ** The savepoint to release or rollback need not be the most recently 
52908: ** created savepoint.
52909: **
52910: ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
52911: ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
52912: ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
52913: ** that have occurred since the specified savepoint was created.
52914: **
52915: ** The savepoint to rollback or release is identified by parameter 
52916: ** iSavepoint. A value of 0 means to operate on the outermost savepoint
52917: ** (the first created). A value of (Pager.nSavepoint-1) means operate
52918: ** on the most recently created savepoint. If iSavepoint is greater than
52919: ** (Pager.nSavepoint-1), then this function is a no-op.
52920: **
52921: ** If a negative value is passed to this function, then the current
52922: ** transaction is rolled back. This is different to calling 
52923: ** sqlite3PagerRollback() because this function does not terminate
52924: ** the transaction or unlock the database, it just restores the 
52925: ** contents of the database to its original state. 
52926: **
52927: ** In any case, all savepoints with an index greater than iSavepoint 
52928: ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
52929: ** then savepoint iSavepoint is also destroyed.
52930: **
52931: ** This function may return SQLITE_NOMEM if a memory allocation fails,
52932: ** or an IO error code if an IO error occurs while rolling back a 
52933: ** savepoint. If no errors occur, SQLITE_OK is returned.
52934: */ 
52935: SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
52936:   int rc = pPager->errCode;       /* Return code */
52937: 
52938:   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
52939:   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
52940: 
52941:   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
52942:     int ii;            /* Iterator variable */
52943:     int nNew;          /* Number of remaining savepoints after this op. */
52944: 
52945:     /* Figure out how many savepoints will still be active after this
52946:     ** operation. Store this value in nNew. Then free resources associated 
52947:     ** with any savepoints that are destroyed by this operation.
52948:     */
52949:     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
52950:     for(ii=nNew; ii<pPager->nSavepoint; ii++){
52951:       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
52952:     }
52953:     pPager->nSavepoint = nNew;
52954: 
52955:     /* If this is a release of the outermost savepoint, truncate 
52956:     ** the sub-journal to zero bytes in size. */
52957:     if( op==SAVEPOINT_RELEASE ){
52958:       if( nNew==0 && isOpen(pPager->sjfd) ){
52959:         /* Only truncate if it is an in-memory sub-journal. */
52960:         if( sqlite3JournalIsInMemory(pPager->sjfd) ){
52961:           rc = sqlite3OsTruncate(pPager->sjfd, 0);
52962:           assert( rc==SQLITE_OK );
52963:         }
52964:         pPager->nSubRec = 0;
52965:       }
52966:     }
52967:     /* Else this is a rollback operation, playback the specified savepoint.
52968:     ** If this is a temp-file, it is possible that the journal file has
52969:     ** not yet been opened. In this case there have been no changes to
52970:     ** the database file, so the playback operation can be skipped.
52971:     */
52972:     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
52973:       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
52974:       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
52975:       assert(rc!=SQLITE_DONE);
52976:     }
52977:   }
52978: 
52979:   return rc;
52980: }
52981: 
52982: /*
52983: ** Return the full pathname of the database file.
52984: **
52985: ** Except, if the pager is in-memory only, then return an empty string if
52986: ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
52987: ** used to report the filename to the user, for compatibility with legacy
52988: ** behavior.  But when the Btree needs to know the filename for matching to
52989: ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
52990: ** participate in shared-cache.
52991: */
52992: SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
52993:   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
52994: }
52995: 
52996: /*
52997: ** Return the VFS structure for the pager.
52998: */
52999: SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
53000:   return pPager->pVfs;
53001: }
53002: 
53003: /*
53004: ** Return the file handle for the database file associated
53005: ** with the pager.  This might return NULL if the file has
53006: ** not yet been opened.
53007: */
53008: SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
53009:   return pPager->fd;
53010: }
53011: 
53012: /*
53013: ** Return the file handle for the journal file (if it exists).
53014: ** This will be either the rollback journal or the WAL file.
53015: */
53016: SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
53017: #if SQLITE_OMIT_WAL
53018:   return pPager->jfd;
53019: #else
53020:   return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
53021: #endif
53022: }
53023: 
53024: /*
53025: ** Return the full pathname of the journal file.
53026: */
53027: SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
53028:   return pPager->zJournal;
53029: }
53030: 
53031: #ifdef SQLITE_HAS_CODEC
53032: /*
53033: ** Set or retrieve the codec for this pager
53034: */
53035: SQLITE_PRIVATE void sqlite3PagerSetCodec(
53036:   Pager *pPager,
53037:   void *(*xCodec)(void*,void*,Pgno,int),
53038:   void (*xCodecSizeChng)(void*,int,int),
53039:   void (*xCodecFree)(void*),
53040:   void *pCodec
53041: ){
53042:   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
53043:   pPager->xCodec = pPager->memDb ? 0 : xCodec;
53044:   pPager->xCodecSizeChng = xCodecSizeChng;
53045:   pPager->xCodecFree = xCodecFree;
53046:   pPager->pCodec = pCodec;
53047:   pagerReportSize(pPager);
53048: }
53049: SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
53050:   return pPager->pCodec;
53051: }
53052: 
53053: /*
53054: ** This function is called by the wal module when writing page content
53055: ** into the log file.
53056: **
53057: ** This function returns a pointer to a buffer containing the encrypted
53058: ** page content. If a malloc fails, this function may return NULL.
53059: */
53060: SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
53061:   void *aData = 0;
53062:   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
53063:   return aData;
53064: }
53065: 
53066: /*
53067: ** Return the current pager state
53068: */
53069: SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
53070:   return pPager->eState;
53071: }
53072: #endif /* SQLITE_HAS_CODEC */
53073: 
53074: #ifndef SQLITE_OMIT_AUTOVACUUM
53075: /*
53076: ** Move the page pPg to location pgno in the file.
53077: **
53078: ** There must be no references to the page previously located at
53079: ** pgno (which we call pPgOld) though that page is allowed to be
53080: ** in cache.  If the page previously located at pgno is not already
53081: ** in the rollback journal, it is not put there by by this routine.
53082: **
53083: ** References to the page pPg remain valid. Updating any
53084: ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
53085: ** allocated along with the page) is the responsibility of the caller.
53086: **
53087: ** A transaction must be active when this routine is called. It used to be
53088: ** required that a statement transaction was not active, but this restriction
53089: ** has been removed (CREATE INDEX needs to move a page when a statement
53090: ** transaction is active).
53091: **
53092: ** If the fourth argument, isCommit, is non-zero, then this page is being
53093: ** moved as part of a database reorganization just before the transaction 
53094: ** is being committed. In this case, it is guaranteed that the database page 
53095: ** pPg refers to will not be written to again within this transaction.
53096: **
53097: ** This function may return SQLITE_NOMEM or an IO error code if an error
53098: ** occurs. Otherwise, it returns SQLITE_OK.
53099: */
53100: SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
53101:   PgHdr *pPgOld;               /* The page being overwritten. */
53102:   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
53103:   int rc;                      /* Return code */
53104:   Pgno origPgno;               /* The original page number */
53105: 
53106:   assert( pPg->nRef>0 );
53107:   assert( pPager->eState==PAGER_WRITER_CACHEMOD
53108:        || pPager->eState==PAGER_WRITER_DBMOD
53109:   );
53110:   assert( assert_pager_state(pPager) );
53111: 
53112:   /* In order to be able to rollback, an in-memory database must journal
53113:   ** the page we are moving from.
53114:   */
53115:   assert( pPager->tempFile || !MEMDB );
53116:   if( pPager->tempFile ){
53117:     rc = sqlite3PagerWrite(pPg);
53118:     if( rc ) return rc;
53119:   }
53120: 
53121:   /* If the page being moved is dirty and has not been saved by the latest
53122:   ** savepoint, then save the current contents of the page into the 
53123:   ** sub-journal now. This is required to handle the following scenario:
53124:   **
53125:   **   BEGIN;
53126:   **     <journal page X, then modify it in memory>
53127:   **     SAVEPOINT one;
53128:   **       <Move page X to location Y>
53129:   **     ROLLBACK TO one;
53130:   **
53131:   ** If page X were not written to the sub-journal here, it would not
53132:   ** be possible to restore its contents when the "ROLLBACK TO one"
53133:   ** statement were is processed.
53134:   **
53135:   ** subjournalPage() may need to allocate space to store pPg->pgno into
53136:   ** one or more savepoint bitvecs. This is the reason this function
53137:   ** may return SQLITE_NOMEM.
53138:   */
53139:   if( (pPg->flags & PGHDR_DIRTY)!=0
53140:    && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
53141:   ){
53142:     return rc;
53143:   }
53144: 
53145:   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
53146:       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
53147:   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
53148: 
53149:   /* If the journal needs to be sync()ed before page pPg->pgno can
53150:   ** be written to, store pPg->pgno in local variable needSyncPgno.
53151:   **
53152:   ** If the isCommit flag is set, there is no need to remember that
53153:   ** the journal needs to be sync()ed before database page pPg->pgno 
53154:   ** can be written to. The caller has already promised not to write to it.
53155:   */
53156:   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
53157:     needSyncPgno = pPg->pgno;
53158:     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
53159:             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
53160:     assert( pPg->flags&PGHDR_DIRTY );
53161:   }
53162: 
53163:   /* If the cache contains a page with page-number pgno, remove it
53164:   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
53165:   ** page pgno before the 'move' operation, it needs to be retained 
53166:   ** for the page moved there.
53167:   */
53168:   pPg->flags &= ~PGHDR_NEED_SYNC;
53169:   pPgOld = sqlite3PagerLookup(pPager, pgno);
53170:   assert( !pPgOld || pPgOld->nRef==1 );
53171:   if( pPgOld ){
53172:     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
53173:     if( pPager->tempFile ){
53174:       /* Do not discard pages from an in-memory database since we might
53175:       ** need to rollback later.  Just move the page out of the way. */
53176:       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
53177:     }else{
53178:       sqlite3PcacheDrop(pPgOld);
53179:     }
53180:   }
53181: 
53182:   origPgno = pPg->pgno;
53183:   sqlite3PcacheMove(pPg, pgno);
53184:   sqlite3PcacheMakeDirty(pPg);
53185: 
53186:   /* For an in-memory database, make sure the original page continues
53187:   ** to exist, in case the transaction needs to roll back.  Use pPgOld
53188:   ** as the original page since it has already been allocated.
53189:   */
53190:   if( pPager->tempFile && pPgOld ){
53191:     sqlite3PcacheMove(pPgOld, origPgno);
53192:     sqlite3PagerUnrefNotNull(pPgOld);
53193:   }
53194: 
53195:   if( needSyncPgno ){
53196:     /* If needSyncPgno is non-zero, then the journal file needs to be 
53197:     ** sync()ed before any data is written to database file page needSyncPgno.
53198:     ** Currently, no such page exists in the page-cache and the 
53199:     ** "is journaled" bitvec flag has been set. This needs to be remedied by
53200:     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
53201:     ** flag.
53202:     **
53203:     ** If the attempt to load the page into the page-cache fails, (due
53204:     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
53205:     ** array. Otherwise, if the page is loaded and written again in
53206:     ** this transaction, it may be written to the database file before
53207:     ** it is synced into the journal file. This way, it may end up in
53208:     ** the journal file twice, but that is not a problem.
53209:     */
53210:     PgHdr *pPgHdr;
53211:     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
53212:     if( rc!=SQLITE_OK ){
53213:       if( needSyncPgno<=pPager->dbOrigSize ){
53214:         assert( pPager->pTmpSpace!=0 );
53215:         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
53216:       }
53217:       return rc;
53218:     }
53219:     pPgHdr->flags |= PGHDR_NEED_SYNC;
53220:     sqlite3PcacheMakeDirty(pPgHdr);
53221:     sqlite3PagerUnrefNotNull(pPgHdr);
53222:   }
53223: 
53224:   return SQLITE_OK;
53225: }
53226: #endif
53227: 
53228: /*
53229: ** The page handle passed as the first argument refers to a dirty page 
53230: ** with a page number other than iNew. This function changes the page's 
53231: ** page number to iNew and sets the value of the PgHdr.flags field to 
53232: ** the value passed as the third parameter.
53233: */
53234: SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
53235:   assert( pPg->pgno!=iNew );
53236:   pPg->flags = flags;
53237:   sqlite3PcacheMove(pPg, iNew);
53238: }
53239: 
53240: /*
53241: ** Return a pointer to the data for the specified page.
53242: */
53243: SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
53244:   assert( pPg->nRef>0 || pPg->pPager->memDb );
53245:   return pPg->pData;
53246: }
53247: 
53248: /*
53249: ** Return a pointer to the Pager.nExtra bytes of "extra" space 
53250: ** allocated along with the specified page.
53251: */
53252: SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
53253:   return pPg->pExtra;
53254: }
53255: 
53256: /*
53257: ** Get/set the locking-mode for this pager. Parameter eMode must be one
53258: ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
53259: ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
53260: ** the locking-mode is set to the value specified.
53261: **
53262: ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
53263: ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
53264: ** locking-mode.
53265: */
53266: SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
53267:   assert( eMode==PAGER_LOCKINGMODE_QUERY
53268:             || eMode==PAGER_LOCKINGMODE_NORMAL
53269:             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
53270:   assert( PAGER_LOCKINGMODE_QUERY<0 );
53271:   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
53272:   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
53273:   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
53274:     pPager->exclusiveMode = (u8)eMode;
53275:   }
53276:   return (int)pPager->exclusiveMode;
53277: }
53278: 
53279: /*
53280: ** Set the journal-mode for this pager. Parameter eMode must be one of:
53281: **
53282: **    PAGER_JOURNALMODE_DELETE
53283: **    PAGER_JOURNALMODE_TRUNCATE
53284: **    PAGER_JOURNALMODE_PERSIST
53285: **    PAGER_JOURNALMODE_OFF
53286: **    PAGER_JOURNALMODE_MEMORY
53287: **    PAGER_JOURNALMODE_WAL
53288: **
53289: ** The journalmode is set to the value specified if the change is allowed.
53290: ** The change may be disallowed for the following reasons:
53291: **
53292: **   *  An in-memory database can only have its journal_mode set to _OFF
53293: **      or _MEMORY.
53294: **
53295: **   *  Temporary databases cannot have _WAL journalmode.
53296: **
53297: ** The returned indicate the current (possibly updated) journal-mode.
53298: */
53299: SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
53300:   u8 eOld = pPager->journalMode;    /* Prior journalmode */
53301: 
53302: #ifdef SQLITE_DEBUG
53303:   /* The print_pager_state() routine is intended to be used by the debugger
53304:   ** only.  We invoke it once here to suppress a compiler warning. */
53305:   print_pager_state(pPager);
53306: #endif
53307: 
53308: 
53309:   /* The eMode parameter is always valid */
53310:   assert(      eMode==PAGER_JOURNALMODE_DELETE
53311:             || eMode==PAGER_JOURNALMODE_TRUNCATE
53312:             || eMode==PAGER_JOURNALMODE_PERSIST
53313:             || eMode==PAGER_JOURNALMODE_OFF 
53314:             || eMode==PAGER_JOURNALMODE_WAL 
53315:             || eMode==PAGER_JOURNALMODE_MEMORY );
53316: 
53317:   /* This routine is only called from the OP_JournalMode opcode, and
53318:   ** the logic there will never allow a temporary file to be changed
53319:   ** to WAL mode.
53320:   */
53321:   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
53322: 
53323:   /* Do allow the journalmode of an in-memory database to be set to
53324:   ** anything other than MEMORY or OFF
53325:   */
53326:   if( MEMDB ){
53327:     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
53328:     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
53329:       eMode = eOld;
53330:     }
53331:   }
53332: 
53333:   if( eMode!=eOld ){
53334: 
53335:     /* Change the journal mode. */
53336:     assert( pPager->eState!=PAGER_ERROR );
53337:     pPager->journalMode = (u8)eMode;
53338: 
53339:     /* When transistioning from TRUNCATE or PERSIST to any other journal
53340:     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
53341:     ** delete the journal file.
53342:     */
53343:     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
53344:     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
53345:     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
53346:     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
53347:     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
53348:     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
53349: 
53350:     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
53351:     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
53352: 
53353:       /* In this case we would like to delete the journal file. If it is
53354:       ** not possible, then that is not a problem. Deleting the journal file
53355:       ** here is an optimization only.
53356:       **
53357:       ** Before deleting the journal file, obtain a RESERVED lock on the
53358:       ** database file. This ensures that the journal file is not deleted
53359:       ** while it is in use by some other client.
53360:       */
53361:       sqlite3OsClose(pPager->jfd);
53362:       if( pPager->eLock>=RESERVED_LOCK ){
53363:         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53364:       }else{
53365:         int rc = SQLITE_OK;
53366:         int state = pPager->eState;
53367:         assert( state==PAGER_OPEN || state==PAGER_READER );
53368:         if( state==PAGER_OPEN ){
53369:           rc = sqlite3PagerSharedLock(pPager);
53370:         }
53371:         if( pPager->eState==PAGER_READER ){
53372:           assert( rc==SQLITE_OK );
53373:           rc = pagerLockDb(pPager, RESERVED_LOCK);
53374:         }
53375:         if( rc==SQLITE_OK ){
53376:           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
53377:         }
53378:         if( rc==SQLITE_OK && state==PAGER_READER ){
53379:           pagerUnlockDb(pPager, SHARED_LOCK);
53380:         }else if( state==PAGER_OPEN ){
53381:           pager_unlock(pPager);
53382:         }
53383:         assert( state==pPager->eState );
53384:       }
53385:     }else if( eMode==PAGER_JOURNALMODE_OFF ){
53386:       sqlite3OsClose(pPager->jfd);
53387:     }
53388:   }
53389: 
53390:   /* Return the new journal mode */
53391:   return (int)pPager->journalMode;
53392: }
53393: 
53394: /*
53395: ** Return the current journal mode.
53396: */
53397: SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
53398:   return (int)pPager->journalMode;
53399: }
53400: 
53401: /*
53402: ** Return TRUE if the pager is in a state where it is OK to change the
53403: ** journalmode.  Journalmode changes can only happen when the database
53404: ** is unmodified.
53405: */
53406: SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
53407:   assert( assert_pager_state(pPager) );
53408:   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
53409:   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
53410:   return 1;
53411: }
53412: 
53413: /*
53414: ** Get/set the size-limit used for persistent journal files.
53415: **
53416: ** Setting the size limit to -1 means no limit is enforced.
53417: ** An attempt to set a limit smaller than -1 is a no-op.
53418: */
53419: SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
53420:   if( iLimit>=-1 ){
53421:     pPager->journalSizeLimit = iLimit;
53422:     sqlite3WalLimit(pPager->pWal, iLimit);
53423:   }
53424:   return pPager->journalSizeLimit;
53425: }
53426: 
53427: /*
53428: ** Return a pointer to the pPager->pBackup variable. The backup module
53429: ** in backup.c maintains the content of this variable. This module
53430: ** uses it opaquely as an argument to sqlite3BackupRestart() and
53431: ** sqlite3BackupUpdate() only.
53432: */
53433: SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
53434:   return &pPager->pBackup;
53435: }
53436: 
53437: #ifndef SQLITE_OMIT_VACUUM
53438: /*
53439: ** Unless this is an in-memory or temporary database, clear the pager cache.
53440: */
53441: SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
53442:   assert( MEMDB==0 || pPager->tempFile );
53443:   if( pPager->tempFile==0 ) pager_reset(pPager);
53444: }
53445: #endif
53446: 
53447: 
53448: #ifndef SQLITE_OMIT_WAL
53449: /*
53450: ** This function is called when the user invokes "PRAGMA wal_checkpoint",
53451: ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
53452: ** or wal_blocking_checkpoint() API functions.
53453: **
53454: ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
53455: */
53456: SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
53457:   int rc = SQLITE_OK;
53458:   if( pPager->pWal ){
53459:     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
53460:         (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
53461:         pPager->pBusyHandlerArg,
53462:         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
53463:         pnLog, pnCkpt
53464:     );
53465:   }
53466:   return rc;
53467: }
53468: 
53469: SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
53470:   return sqlite3WalCallback(pPager->pWal);
53471: }
53472: 
53473: /*
53474: ** Return true if the underlying VFS for the given pager supports the
53475: ** primitives necessary for write-ahead logging.
53476: */
53477: SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
53478:   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
53479:   if( pPager->noLock ) return 0;
53480:   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
53481: }
53482: 
53483: /*
53484: ** Attempt to take an exclusive lock on the database file. If a PENDING lock
53485: ** is obtained instead, immediately release it.
53486: */
53487: static int pagerExclusiveLock(Pager *pPager){
53488:   int rc;                         /* Return code */
53489: 
53490:   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53491:   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53492:   if( rc!=SQLITE_OK ){
53493:     /* If the attempt to grab the exclusive lock failed, release the 
53494:     ** pending lock that may have been obtained instead.  */
53495:     pagerUnlockDb(pPager, SHARED_LOCK);
53496:   }
53497: 
53498:   return rc;
53499: }
53500: 
53501: /*
53502: ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
53503: ** exclusive-locking mode when this function is called, take an EXCLUSIVE
53504: ** lock on the database file and use heap-memory to store the wal-index
53505: ** in. Otherwise, use the normal shared-memory.
53506: */
53507: static int pagerOpenWal(Pager *pPager){
53508:   int rc = SQLITE_OK;
53509: 
53510:   assert( pPager->pWal==0 && pPager->tempFile==0 );
53511:   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53512: 
53513:   /* If the pager is already in exclusive-mode, the WAL module will use 
53514:   ** heap-memory for the wal-index instead of the VFS shared-memory 
53515:   ** implementation. Take the exclusive lock now, before opening the WAL
53516:   ** file, to make sure this is safe.
53517:   */
53518:   if( pPager->exclusiveMode ){
53519:     rc = pagerExclusiveLock(pPager);
53520:   }
53521: 
53522:   /* Open the connection to the log file. If this operation fails, 
53523:   ** (e.g. due to malloc() failure), return an error code.
53524:   */
53525:   if( rc==SQLITE_OK ){
53526:     rc = sqlite3WalOpen(pPager->pVfs,
53527:         pPager->fd, pPager->zWal, pPager->exclusiveMode,
53528:         pPager->journalSizeLimit, &pPager->pWal
53529:     );
53530:   }
53531:   pagerFixMaplimit(pPager);
53532: 
53533:   return rc;
53534: }
53535: 
53536: 
53537: /*
53538: ** The caller must be holding a SHARED lock on the database file to call
53539: ** this function.
53540: **
53541: ** If the pager passed as the first argument is open on a real database
53542: ** file (not a temp file or an in-memory database), and the WAL file
53543: ** is not already open, make an attempt to open it now. If successful,
53544: ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
53545: ** not support the xShmXXX() methods, return an error code. *pbOpen is
53546: ** not modified in either case.
53547: **
53548: ** If the pager is open on a temp-file (or in-memory database), or if
53549: ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
53550: ** without doing anything.
53551: */
53552: SQLITE_PRIVATE int sqlite3PagerOpenWal(
53553:   Pager *pPager,                  /* Pager object */
53554:   int *pbOpen                     /* OUT: Set to true if call is a no-op */
53555: ){
53556:   int rc = SQLITE_OK;             /* Return code */
53557: 
53558:   assert( assert_pager_state(pPager) );
53559:   assert( pPager->eState==PAGER_OPEN   || pbOpen );
53560:   assert( pPager->eState==PAGER_READER || !pbOpen );
53561:   assert( pbOpen==0 || *pbOpen==0 );
53562:   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
53563: 
53564:   if( !pPager->tempFile && !pPager->pWal ){
53565:     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
53566: 
53567:     /* Close any rollback journal previously open */
53568:     sqlite3OsClose(pPager->jfd);
53569: 
53570:     rc = pagerOpenWal(pPager);
53571:     if( rc==SQLITE_OK ){
53572:       pPager->journalMode = PAGER_JOURNALMODE_WAL;
53573:       pPager->eState = PAGER_OPEN;
53574:     }
53575:   }else{
53576:     *pbOpen = 1;
53577:   }
53578: 
53579:   return rc;
53580: }
53581: 
53582: /*
53583: ** This function is called to close the connection to the log file prior
53584: ** to switching from WAL to rollback mode.
53585: **
53586: ** Before closing the log file, this function attempts to take an 
53587: ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
53588: ** error (SQLITE_BUSY) is returned and the log connection is not closed.
53589: ** If successful, the EXCLUSIVE lock is not released before returning.
53590: */
53591: SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
53592:   int rc = SQLITE_OK;
53593: 
53594:   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
53595: 
53596:   /* If the log file is not already open, but does exist in the file-system,
53597:   ** it may need to be checkpointed before the connection can switch to
53598:   ** rollback mode. Open it now so this can happen.
53599:   */
53600:   if( !pPager->pWal ){
53601:     int logexists = 0;
53602:     rc = pagerLockDb(pPager, SHARED_LOCK);
53603:     if( rc==SQLITE_OK ){
53604:       rc = sqlite3OsAccess(
53605:           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
53606:       );
53607:     }
53608:     if( rc==SQLITE_OK && logexists ){
53609:       rc = pagerOpenWal(pPager);
53610:     }
53611:   }
53612:     
53613:   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
53614:   ** the database file, the log and log-summary files will be deleted.
53615:   */
53616:   if( rc==SQLITE_OK && pPager->pWal ){
53617:     rc = pagerExclusiveLock(pPager);
53618:     if( rc==SQLITE_OK ){
53619:       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
53620:                            pPager->pageSize, (u8*)pPager->pTmpSpace);
53621:       pPager->pWal = 0;
53622:       pagerFixMaplimit(pPager);
53623:       if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
53624:     }
53625:   }
53626:   return rc;
53627: }
53628: 
53629: #ifdef SQLITE_ENABLE_SNAPSHOT
53630: /*
53631: ** If this is a WAL database, obtain a snapshot handle for the snapshot
53632: ** currently open. Otherwise, return an error.
53633: */
53634: SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
53635:   int rc = SQLITE_ERROR;
53636:   if( pPager->pWal ){
53637:     rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
53638:   }
53639:   return rc;
53640: }
53641: 
53642: /*
53643: ** If this is a WAL database, store a pointer to pSnapshot. Next time a
53644: ** read transaction is opened, attempt to read from the snapshot it 
53645: ** identifies. If this is not a WAL database, return an error.
53646: */
53647: SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
53648:   int rc = SQLITE_OK;
53649:   if( pPager->pWal ){
53650:     sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
53651:   }else{
53652:     rc = SQLITE_ERROR;
53653:   }
53654:   return rc;
53655: }
53656: #endif /* SQLITE_ENABLE_SNAPSHOT */
53657: #endif /* !SQLITE_OMIT_WAL */
53658: 
53659: #ifdef SQLITE_ENABLE_ZIPVFS
53660: /*
53661: ** A read-lock must be held on the pager when this function is called. If
53662: ** the pager is in WAL mode and the WAL file currently contains one or more
53663: ** frames, return the size in bytes of the page images stored within the
53664: ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
53665: ** is empty, return 0.
53666: */
53667: SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
53668:   assert( pPager->eState>=PAGER_READER );
53669:   return sqlite3WalFramesize(pPager->pWal);
53670: }
53671: #endif
53672: 
53673: #endif /* SQLITE_OMIT_DISKIO */
53674: 
53675: /************** End of pager.c ***********************************************/
53676: /************** Begin file wal.c *********************************************/
53677: /*
53678: ** 2010 February 1
53679: **
53680: ** The author disclaims copyright to this source code.  In place of
53681: ** a legal notice, here is a blessing:
53682: **
53683: **    May you do good and not evil.
53684: **    May you find forgiveness for yourself and forgive others.
53685: **    May you share freely, never taking more than you give.
53686: **
53687: *************************************************************************
53688: **
53689: ** This file contains the implementation of a write-ahead log (WAL) used in 
53690: ** "journal_mode=WAL" mode.
53691: **
53692: ** WRITE-AHEAD LOG (WAL) FILE FORMAT
53693: **
53694: ** A WAL file consists of a header followed by zero or more "frames".
53695: ** Each frame records the revised content of a single page from the
53696: ** database file.  All changes to the database are recorded by writing
53697: ** frames into the WAL.  Transactions commit when a frame is written that
53698: ** contains a commit marker.  A single WAL can and usually does record 
53699: ** multiple transactions.  Periodically, the content of the WAL is
53700: ** transferred back into the database file in an operation called a
53701: ** "checkpoint".
53702: **
53703: ** A single WAL file can be used multiple times.  In other words, the
53704: ** WAL can fill up with frames and then be checkpointed and then new
53705: ** frames can overwrite the old ones.  A WAL always grows from beginning
53706: ** toward the end.  Checksums and counters attached to each frame are
53707: ** used to determine which frames within the WAL are valid and which
53708: ** are leftovers from prior checkpoints.
53709: **
53710: ** The WAL header is 32 bytes in size and consists of the following eight
53711: ** big-endian 32-bit unsigned integer values:
53712: **
53713: **     0: Magic number.  0x377f0682 or 0x377f0683
53714: **     4: File format version.  Currently 3007000
53715: **     8: Database page size.  Example: 1024
53716: **    12: Checkpoint sequence number
53717: **    16: Salt-1, random integer incremented with each checkpoint
53718: **    20: Salt-2, a different random integer changing with each ckpt
53719: **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
53720: **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
53721: **
53722: ** Immediately following the wal-header are zero or more frames. Each
53723: ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
53724: ** of page data. The frame-header is six big-endian 32-bit unsigned 
53725: ** integer values, as follows:
53726: **
53727: **     0: Page number.
53728: **     4: For commit records, the size of the database image in pages 
53729: **        after the commit. For all other records, zero.
53730: **     8: Salt-1 (copied from the header)
53731: **    12: Salt-2 (copied from the header)
53732: **    16: Checksum-1.
53733: **    20: Checksum-2.
53734: **
53735: ** A frame is considered valid if and only if the following conditions are
53736: ** true:
53737: **
53738: **    (1) The salt-1 and salt-2 values in the frame-header match
53739: **        salt values in the wal-header
53740: **
53741: **    (2) The checksum values in the final 8 bytes of the frame-header
53742: **        exactly match the checksum computed consecutively on the
53743: **        WAL header and the first 8 bytes and the content of all frames
53744: **        up to and including the current frame.
53745: **
53746: ** The checksum is computed using 32-bit big-endian integers if the
53747: ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
53748: ** is computed using little-endian if the magic number is 0x377f0682.
53749: ** The checksum values are always stored in the frame header in a
53750: ** big-endian format regardless of which byte order is used to compute
53751: ** the checksum.  The checksum is computed by interpreting the input as
53752: ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
53753: ** algorithm used for the checksum is as follows:
53754: ** 
53755: **   for i from 0 to n-1 step 2:
53756: **     s0 += x[i] + s1;
53757: **     s1 += x[i+1] + s0;
53758: **   endfor
53759: **
53760: ** Note that s0 and s1 are both weighted checksums using fibonacci weights
53761: ** in reverse order (the largest fibonacci weight occurs on the first element
53762: ** of the sequence being summed.)  The s1 value spans all 32-bit 
53763: ** terms of the sequence whereas s0 omits the final term.
53764: **
53765: ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
53766: ** WAL is transferred into the database, then the database is VFS.xSync-ed.
53767: ** The VFS.xSync operations serve as write barriers - all writes launched
53768: ** before the xSync must complete before any write that launches after the
53769: ** xSync begins.
53770: **
53771: ** After each checkpoint, the salt-1 value is incremented and the salt-2
53772: ** value is randomized.  This prevents old and new frames in the WAL from
53773: ** being considered valid at the same time and being checkpointing together
53774: ** following a crash.
53775: **
53776: ** READER ALGORITHM
53777: **
53778: ** To read a page from the database (call it page number P), a reader
53779: ** first checks the WAL to see if it contains page P.  If so, then the
53780: ** last valid instance of page P that is a followed by a commit frame
53781: ** or is a commit frame itself becomes the value read.  If the WAL
53782: ** contains no copies of page P that are valid and which are a commit
53783: ** frame or are followed by a commit frame, then page P is read from
53784: ** the database file.
53785: **
53786: ** To start a read transaction, the reader records the index of the last
53787: ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
53788: ** for all subsequent read operations.  New transactions can be appended
53789: ** to the WAL, but as long as the reader uses its original mxFrame value
53790: ** and ignores the newly appended content, it will see a consistent snapshot
53791: ** of the database from a single point in time.  This technique allows
53792: ** multiple concurrent readers to view different versions of the database
53793: ** content simultaneously.
53794: **
53795: ** The reader algorithm in the previous paragraphs works correctly, but 
53796: ** because frames for page P can appear anywhere within the WAL, the
53797: ** reader has to scan the entire WAL looking for page P frames.  If the
53798: ** WAL is large (multiple megabytes is typical) that scan can be slow,
53799: ** and read performance suffers.  To overcome this problem, a separate
53800: ** data structure called the wal-index is maintained to expedite the
53801: ** search for frames of a particular page.
53802: ** 
53803: ** WAL-INDEX FORMAT
53804: **
53805: ** Conceptually, the wal-index is shared memory, though VFS implementations
53806: ** might choose to implement the wal-index using a mmapped file.  Because
53807: ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
53808: ** on a network filesystem.  All users of the database must be able to
53809: ** share memory.
53810: **
53811: ** The wal-index is transient.  After a crash, the wal-index can (and should
53812: ** be) reconstructed from the original WAL file.  In fact, the VFS is required
53813: ** to either truncate or zero the header of the wal-index when the last
53814: ** connection to it closes.  Because the wal-index is transient, it can
53815: ** use an architecture-specific format; it does not have to be cross-platform.
53816: ** Hence, unlike the database and WAL file formats which store all values
53817: ** as big endian, the wal-index can store multi-byte values in the native
53818: ** byte order of the host computer.
53819: **
53820: ** The purpose of the wal-index is to answer this question quickly:  Given
53821: ** a page number P and a maximum frame index M, return the index of the 
53822: ** last frame in the wal before frame M for page P in the WAL, or return
53823: ** NULL if there are no frames for page P in the WAL prior to M.
53824: **
53825: ** The wal-index consists of a header region, followed by an one or
53826: ** more index blocks.  
53827: **
53828: ** The wal-index header contains the total number of frames within the WAL
53829: ** in the mxFrame field.
53830: **
53831: ** Each index block except for the first contains information on 
53832: ** HASHTABLE_NPAGE frames. The first index block contains information on
53833: ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
53834: ** HASHTABLE_NPAGE are selected so that together the wal-index header and
53835: ** first index block are the same size as all other index blocks in the
53836: ** wal-index.
53837: **
53838: ** Each index block contains two sections, a page-mapping that contains the
53839: ** database page number associated with each wal frame, and a hash-table 
53840: ** that allows readers to query an index block for a specific page number.
53841: ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
53842: ** for the first index block) 32-bit page numbers. The first entry in the 
53843: ** first index-block contains the database page number corresponding to the
53844: ** first frame in the WAL file. The first entry in the second index block
53845: ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
53846: ** the log, and so on.
53847: **
53848: ** The last index block in a wal-index usually contains less than the full
53849: ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
53850: ** depending on the contents of the WAL file. This does not change the
53851: ** allocated size of the page-mapping array - the page-mapping array merely
53852: ** contains unused entries.
53853: **
53854: ** Even without using the hash table, the last frame for page P
53855: ** can be found by scanning the page-mapping sections of each index block
53856: ** starting with the last index block and moving toward the first, and
53857: ** within each index block, starting at the end and moving toward the
53858: ** beginning.  The first entry that equals P corresponds to the frame
53859: ** holding the content for that page.
53860: **
53861: ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
53862: ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
53863: ** hash table for each page number in the mapping section, so the hash 
53864: ** table is never more than half full.  The expected number of collisions 
53865: ** prior to finding a match is 1.  Each entry of the hash table is an
53866: ** 1-based index of an entry in the mapping section of the same
53867: ** index block.   Let K be the 1-based index of the largest entry in
53868: ** the mapping section.  (For index blocks other than the last, K will
53869: ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
53870: ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
53871: ** contain a value of 0.
53872: **
53873: ** To look for page P in the hash table, first compute a hash iKey on
53874: ** P as follows:
53875: **
53876: **      iKey = (P * 383) % HASHTABLE_NSLOT
53877: **
53878: ** Then start scanning entries of the hash table, starting with iKey
53879: ** (wrapping around to the beginning when the end of the hash table is
53880: ** reached) until an unused hash slot is found. Let the first unused slot
53881: ** be at index iUnused.  (iUnused might be less than iKey if there was
53882: ** wrap-around.) Because the hash table is never more than half full,
53883: ** the search is guaranteed to eventually hit an unused entry.  Let 
53884: ** iMax be the value between iKey and iUnused, closest to iUnused,
53885: ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
53886: ** no hash slot such that aHash[i]==p) then page P is not in the
53887: ** current index block.  Otherwise the iMax-th mapping entry of the
53888: ** current index block corresponds to the last entry that references 
53889: ** page P.
53890: **
53891: ** A hash search begins with the last index block and moves toward the
53892: ** first index block, looking for entries corresponding to page P.  On
53893: ** average, only two or three slots in each index block need to be
53894: ** examined in order to either find the last entry for page P, or to
53895: ** establish that no such entry exists in the block.  Each index block
53896: ** holds over 4000 entries.  So two or three index blocks are sufficient
53897: ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
53898: ** comparisons (on average) suffice to either locate a frame in the
53899: ** WAL or to establish that the frame does not exist in the WAL.  This
53900: ** is much faster than scanning the entire 10MB WAL.
53901: **
53902: ** Note that entries are added in order of increasing K.  Hence, one
53903: ** reader might be using some value K0 and a second reader that started
53904: ** at a later time (after additional transactions were added to the WAL
53905: ** and to the wal-index) might be using a different value K1, where K1>K0.
53906: ** Both readers can use the same hash table and mapping section to get
53907: ** the correct result.  There may be entries in the hash table with
53908: ** K>K0 but to the first reader, those entries will appear to be unused
53909: ** slots in the hash table and so the first reader will get an answer as
53910: ** if no values greater than K0 had ever been inserted into the hash table
53911: ** in the first place - which is what reader one wants.  Meanwhile, the
53912: ** second reader using K1 will see additional values that were inserted
53913: ** later, which is exactly what reader two wants.  
53914: **
53915: ** When a rollback occurs, the value of K is decreased. Hash table entries
53916: ** that correspond to frames greater than the new K value are removed
53917: ** from the hash table at this point.
53918: */
53919: #ifndef SQLITE_OMIT_WAL
53920: 
53921: /* #include "wal.h" */
53922: 
53923: /*
53924: ** Trace output macros
53925: */
53926: #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
53927: SQLITE_PRIVATE int sqlite3WalTrace = 0;
53928: # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
53929: #else
53930: # define WALTRACE(X)
53931: #endif
53932: 
53933: /*
53934: ** The maximum (and only) versions of the wal and wal-index formats
53935: ** that may be interpreted by this version of SQLite.
53936: **
53937: ** If a client begins recovering a WAL file and finds that (a) the checksum
53938: ** values in the wal-header are correct and (b) the version field is not
53939: ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
53940: **
53941: ** Similarly, if a client successfully reads a wal-index header (i.e. the 
53942: ** checksum test is successful) and finds that the version field is not
53943: ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
53944: ** returns SQLITE_CANTOPEN.
53945: */
53946: #define WAL_MAX_VERSION      3007000
53947: #define WALINDEX_MAX_VERSION 3007000
53948: 
53949: /*
53950: ** Indices of various locking bytes.   WAL_NREADER is the number
53951: ** of available reader locks and should be at least 3.  The default
53952: ** is SQLITE_SHM_NLOCK==8 and  WAL_NREADER==5.
53953: */
53954: #define WAL_WRITE_LOCK         0
53955: #define WAL_ALL_BUT_WRITE      1
53956: #define WAL_CKPT_LOCK          1
53957: #define WAL_RECOVER_LOCK       2
53958: #define WAL_READ_LOCK(I)       (3+(I))
53959: #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
53960: 
53961: 
53962: /* Object declarations */
53963: typedef struct WalIndexHdr WalIndexHdr;
53964: typedef struct WalIterator WalIterator;
53965: typedef struct WalCkptInfo WalCkptInfo;
53966: 
53967: 
53968: /*
53969: ** The following object holds a copy of the wal-index header content.
53970: **
53971: ** The actual header in the wal-index consists of two copies of this
53972: ** object followed by one instance of the WalCkptInfo object.
53973: ** For all versions of SQLite through 3.10.0 and probably beyond,
53974: ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
53975: ** the total header size is 136 bytes.
53976: **
53977: ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
53978: ** Or it can be 1 to represent a 65536-byte page.  The latter case was
53979: ** added in 3.7.1 when support for 64K pages was added.  
53980: */
53981: struct WalIndexHdr {
53982:   u32 iVersion;                   /* Wal-index version */
53983:   u32 unused;                     /* Unused (padding) field */
53984:   u32 iChange;                    /* Counter incremented each transaction */
53985:   u8 isInit;                      /* 1 when initialized */
53986:   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
53987:   u16 szPage;                     /* Database page size in bytes. 1==64K */
53988:   u32 mxFrame;                    /* Index of last valid frame in the WAL */
53989:   u32 nPage;                      /* Size of database in pages */
53990:   u32 aFrameCksum[2];             /* Checksum of last frame in log */
53991:   u32 aSalt[2];                   /* Two salt values copied from WAL header */
53992:   u32 aCksum[2];                  /* Checksum over all prior fields */
53993: };
53994: 
53995: /*
53996: ** A copy of the following object occurs in the wal-index immediately
53997: ** following the second copy of the WalIndexHdr.  This object stores
53998: ** information used by checkpoint.
53999: **
54000: ** nBackfill is the number of frames in the WAL that have been written
54001: ** back into the database. (We call the act of moving content from WAL to
54002: ** database "backfilling".)  The nBackfill number is never greater than
54003: ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
54004: ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
54005: ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
54006: ** mxFrame back to zero when the WAL is reset.
54007: **
54008: ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
54009: ** has attempted to achieve.  Normally nBackfill==nBackfillAtempted, however
54010: ** the nBackfillAttempted is set before any backfilling is done and the
54011: ** nBackfill is only set after all backfilling completes.  So if a checkpoint
54012: ** crashes, nBackfillAttempted might be larger than nBackfill.  The
54013: ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
54014: **
54015: ** The aLock[] field is a set of bytes used for locking.  These bytes should
54016: ** never be read or written.
54017: **
54018: ** There is one entry in aReadMark[] for each reader lock.  If a reader
54019: ** holds read-lock K, then the value in aReadMark[K] is no greater than
54020: ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
54021: ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
54022: ** a special case; its value is never used and it exists as a place-holder
54023: ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
54024: ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
54025: ** directly from the database.
54026: **
54027: ** The value of aReadMark[K] may only be changed by a thread that
54028: ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
54029: ** aReadMark[K] cannot changed while there is a reader is using that mark
54030: ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
54031: **
54032: ** The checkpointer may only transfer frames from WAL to database where
54033: ** the frame numbers are less than or equal to every aReadMark[] that is
54034: ** in use (that is, every aReadMark[j] for which there is a corresponding
54035: ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
54036: ** largest value and will increase an unused aReadMark[] to mxFrame if there
54037: ** is not already an aReadMark[] equal to mxFrame.  The exception to the
54038: ** previous sentence is when nBackfill equals mxFrame (meaning that everything
54039: ** in the WAL has been backfilled into the database) then new readers
54040: ** will choose aReadMark[0] which has value 0 and hence such reader will
54041: ** get all their all content directly from the database file and ignore 
54042: ** the WAL.
54043: **
54044: ** Writers normally append new frames to the end of the WAL.  However,
54045: ** if nBackfill equals mxFrame (meaning that all WAL content has been
54046: ** written back into the database) and if no readers are using the WAL
54047: ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
54048: ** the writer will first "reset" the WAL back to the beginning and start
54049: ** writing new content beginning at frame 1.
54050: **
54051: ** We assume that 32-bit loads are atomic and so no locks are needed in
54052: ** order to read from any aReadMark[] entries.
54053: */
54054: struct WalCkptInfo {
54055:   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
54056:   u32 aReadMark[WAL_NREADER];     /* Reader marks */
54057:   u8 aLock[SQLITE_SHM_NLOCK];     /* Reserved space for locks */
54058:   u32 nBackfillAttempted;         /* WAL frames perhaps written, or maybe not */
54059:   u32 notUsed0;                   /* Available for future enhancements */
54060: };
54061: #define READMARK_NOT_USED  0xffffffff
54062: 
54063: 
54064: /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
54065: ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
54066: ** only support mandatory file-locks, we do not read or write data
54067: ** from the region of the file on which locks are applied.
54068: */
54069: #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
54070: #define WALINDEX_HDR_SIZE    (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
54071: 
54072: /* Size of header before each frame in wal */
54073: #define WAL_FRAME_HDRSIZE 24
54074: 
54075: /* Size of write ahead log header, including checksum. */
54076: /* #define WAL_HDRSIZE 24 */
54077: #define WAL_HDRSIZE 32
54078: 
54079: /* WAL magic value. Either this value, or the same value with the least
54080: ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
54081: ** big-endian format in the first 4 bytes of a WAL file.
54082: **
54083: ** If the LSB is set, then the checksums for each frame within the WAL
54084: ** file are calculated by treating all data as an array of 32-bit 
54085: ** big-endian words. Otherwise, they are calculated by interpreting 
54086: ** all data as 32-bit little-endian words.
54087: */
54088: #define WAL_MAGIC 0x377f0682
54089: 
54090: /*
54091: ** Return the offset of frame iFrame in the write-ahead log file, 
54092: ** assuming a database page size of szPage bytes. The offset returned
54093: ** is to the start of the write-ahead log frame-header.
54094: */
54095: #define walFrameOffset(iFrame, szPage) (                               \
54096:   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
54097: )
54098: 
54099: /*
54100: ** An open write-ahead log file is represented by an instance of the
54101: ** following object.
54102: */
54103: struct Wal {
54104:   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
54105:   sqlite3_file *pDbFd;       /* File handle for the database file */
54106:   sqlite3_file *pWalFd;      /* File handle for WAL file */
54107:   u32 iCallback;             /* Value to pass to log callback (or 0) */
54108:   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
54109:   int nWiData;               /* Size of array apWiData */
54110:   int szFirstBlock;          /* Size of first block written to WAL file */
54111:   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
54112:   u32 szPage;                /* Database page size */
54113:   i16 readLock;              /* Which read lock is being held.  -1 for none */
54114:   u8 syncFlags;              /* Flags to use to sync header writes */
54115:   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
54116:   u8 writeLock;              /* True if in a write transaction */
54117:   u8 ckptLock;               /* True if holding a checkpoint lock */
54118:   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
54119:   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
54120:   u8 syncHeader;             /* Fsync the WAL header if true */
54121:   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
54122:   WalIndexHdr hdr;           /* Wal-index header for current transaction */
54123:   u32 minFrame;              /* Ignore wal frames before this one */
54124:   u32 iReCksum;              /* On commit, recalculate checksums from here */
54125:   const char *zWalName;      /* Name of WAL file */
54126:   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
54127: #ifdef SQLITE_DEBUG
54128:   u8 lockError;              /* True if a locking error has occurred */
54129: #endif
54130: #ifdef SQLITE_ENABLE_SNAPSHOT
54131:   WalIndexHdr *pSnapshot;    /* Start transaction here if not NULL */
54132: #endif
54133: };
54134: 
54135: /*
54136: ** Candidate values for Wal.exclusiveMode.
54137: */
54138: #define WAL_NORMAL_MODE     0
54139: #define WAL_EXCLUSIVE_MODE  1     
54140: #define WAL_HEAPMEMORY_MODE 2
54141: 
54142: /*
54143: ** Possible values for WAL.readOnly
54144: */
54145: #define WAL_RDWR        0    /* Normal read/write connection */
54146: #define WAL_RDONLY      1    /* The WAL file is readonly */
54147: #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
54148: 
54149: /*
54150: ** Each page of the wal-index mapping contains a hash-table made up of
54151: ** an array of HASHTABLE_NSLOT elements of the following type.
54152: */
54153: typedef u16 ht_slot;
54154: 
54155: /*
54156: ** This structure is used to implement an iterator that loops through
54157: ** all frames in the WAL in database page order. Where two or more frames
54158: ** correspond to the same database page, the iterator visits only the 
54159: ** frame most recently written to the WAL (in other words, the frame with
54160: ** the largest index).
54161: **
54162: ** The internals of this structure are only accessed by:
54163: **
54164: **   walIteratorInit() - Create a new iterator,
54165: **   walIteratorNext() - Step an iterator,
54166: **   walIteratorFree() - Free an iterator.
54167: **
54168: ** This functionality is used by the checkpoint code (see walCheckpoint()).
54169: */
54170: struct WalIterator {
54171:   int iPrior;                     /* Last result returned from the iterator */
54172:   int nSegment;                   /* Number of entries in aSegment[] */
54173:   struct WalSegment {
54174:     int iNext;                    /* Next slot in aIndex[] not yet returned */
54175:     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
54176:     u32 *aPgno;                   /* Array of page numbers. */
54177:     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
54178:     int iZero;                    /* Frame number associated with aPgno[0] */
54179:   } aSegment[1];                  /* One for every 32KB page in the wal-index */
54180: };
54181: 
54182: /*
54183: ** Define the parameters of the hash tables in the wal-index file. There
54184: ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
54185: ** wal-index.
54186: **
54187: ** Changing any of these constants will alter the wal-index format and
54188: ** create incompatibilities.
54189: */
54190: #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
54191: #define HASHTABLE_HASH_1     383                  /* Should be prime */
54192: #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
54193: 
54194: /* 
54195: ** The block of page numbers associated with the first hash-table in a
54196: ** wal-index is smaller than usual. This is so that there is a complete
54197: ** hash-table on each aligned 32KB page of the wal-index.
54198: */
54199: #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
54200: 
54201: /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
54202: #define WALINDEX_PGSZ   (                                         \
54203:     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
54204: )
54205: 
54206: /*
54207: ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
54208: ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
54209: ** numbered from zero.
54210: **
54211: ** If this call is successful, *ppPage is set to point to the wal-index
54212: ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
54213: ** then an SQLite error code is returned and *ppPage is set to 0.
54214: */
54215: static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
54216:   int rc = SQLITE_OK;
54217: 
54218:   /* Enlarge the pWal->apWiData[] array if required */
54219:   if( pWal->nWiData<=iPage ){
54220:     int nByte = sizeof(u32*)*(iPage+1);
54221:     volatile u32 **apNew;
54222:     apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
54223:     if( !apNew ){
54224:       *ppPage = 0;
54225:       return SQLITE_NOMEM_BKPT;
54226:     }
54227:     memset((void*)&apNew[pWal->nWiData], 0,
54228:            sizeof(u32*)*(iPage+1-pWal->nWiData));
54229:     pWal->apWiData = apNew;
54230:     pWal->nWiData = iPage+1;
54231:   }
54232: 
54233:   /* Request a pointer to the required page from the VFS */
54234:   if( pWal->apWiData[iPage]==0 ){
54235:     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54236:       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
54237:       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
54238:     }else{
54239:       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
54240:           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
54241:       );
54242:       if( rc==SQLITE_READONLY ){
54243:         pWal->readOnly |= WAL_SHM_RDONLY;
54244:         rc = SQLITE_OK;
54245:       }
54246:     }
54247:   }
54248: 
54249:   *ppPage = pWal->apWiData[iPage];
54250:   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
54251:   return rc;
54252: }
54253: 
54254: /*
54255: ** Return a pointer to the WalCkptInfo structure in the wal-index.
54256: */
54257: static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
54258:   assert( pWal->nWiData>0 && pWal->apWiData[0] );
54259:   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
54260: }
54261: 
54262: /*
54263: ** Return a pointer to the WalIndexHdr structure in the wal-index.
54264: */
54265: static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
54266:   assert( pWal->nWiData>0 && pWal->apWiData[0] );
54267:   return (volatile WalIndexHdr*)pWal->apWiData[0];
54268: }
54269: 
54270: /*
54271: ** The argument to this macro must be of type u32. On a little-endian
54272: ** architecture, it returns the u32 value that results from interpreting
54273: ** the 4 bytes as a big-endian value. On a big-endian architecture, it
54274: ** returns the value that would be produced by interpreting the 4 bytes
54275: ** of the input value as a little-endian integer.
54276: */
54277: #define BYTESWAP32(x) ( \
54278:     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
54279:   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
54280: )
54281: 
54282: /*
54283: ** Generate or extend an 8 byte checksum based on the data in 
54284: ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
54285: ** initial values of 0 and 0 if aIn==NULL).
54286: **
54287: ** The checksum is written back into aOut[] before returning.
54288: **
54289: ** nByte must be a positive multiple of 8.
54290: */
54291: static void walChecksumBytes(
54292:   int nativeCksum, /* True for native byte-order, false for non-native */
54293:   u8 *a,           /* Content to be checksummed */
54294:   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
54295:   const u32 *aIn,  /* Initial checksum value input */
54296:   u32 *aOut        /* OUT: Final checksum value output */
54297: ){
54298:   u32 s1, s2;
54299:   u32 *aData = (u32 *)a;
54300:   u32 *aEnd = (u32 *)&a[nByte];
54301: 
54302:   if( aIn ){
54303:     s1 = aIn[0];
54304:     s2 = aIn[1];
54305:   }else{
54306:     s1 = s2 = 0;
54307:   }
54308: 
54309:   assert( nByte>=8 );
54310:   assert( (nByte&0x00000007)==0 );
54311: 
54312:   if( nativeCksum ){
54313:     do {
54314:       s1 += *aData++ + s2;
54315:       s2 += *aData++ + s1;
54316:     }while( aData<aEnd );
54317:   }else{
54318:     do {
54319:       s1 += BYTESWAP32(aData[0]) + s2;
54320:       s2 += BYTESWAP32(aData[1]) + s1;
54321:       aData += 2;
54322:     }while( aData<aEnd );
54323:   }
54324: 
54325:   aOut[0] = s1;
54326:   aOut[1] = s2;
54327: }
54328: 
54329: static void walShmBarrier(Wal *pWal){
54330:   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
54331:     sqlite3OsShmBarrier(pWal->pDbFd);
54332:   }
54333: }
54334: 
54335: /*
54336: ** Write the header information in pWal->hdr into the wal-index.
54337: **
54338: ** The checksum on pWal->hdr is updated before it is written.
54339: */
54340: static void walIndexWriteHdr(Wal *pWal){
54341:   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
54342:   const int nCksum = offsetof(WalIndexHdr, aCksum);
54343: 
54344:   assert( pWal->writeLock );
54345:   pWal->hdr.isInit = 1;
54346:   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
54347:   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
54348:   memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54349:   walShmBarrier(pWal);
54350:   memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
54351: }
54352: 
54353: /*
54354: ** This function encodes a single frame header and writes it to a buffer
54355: ** supplied by the caller. A frame-header is made up of a series of 
54356: ** 4-byte big-endian integers, as follows:
54357: **
54358: **     0: Page number.
54359: **     4: For commit records, the size of the database image in pages 
54360: **        after the commit. For all other records, zero.
54361: **     8: Salt-1 (copied from the wal-header)
54362: **    12: Salt-2 (copied from the wal-header)
54363: **    16: Checksum-1.
54364: **    20: Checksum-2.
54365: */
54366: static void walEncodeFrame(
54367:   Wal *pWal,                      /* The write-ahead log */
54368:   u32 iPage,                      /* Database page number for frame */
54369:   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
54370:   u8 *aData,                      /* Pointer to page data */
54371:   u8 *aFrame                      /* OUT: Write encoded frame here */
54372: ){
54373:   int nativeCksum;                /* True for native byte-order checksums */
54374:   u32 *aCksum = pWal->hdr.aFrameCksum;
54375:   assert( WAL_FRAME_HDRSIZE==24 );
54376:   sqlite3Put4byte(&aFrame[0], iPage);
54377:   sqlite3Put4byte(&aFrame[4], nTruncate);
54378:   if( pWal->iReCksum==0 ){
54379:     memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
54380: 
54381:     nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54382:     walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54383:     walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54384: 
54385:     sqlite3Put4byte(&aFrame[16], aCksum[0]);
54386:     sqlite3Put4byte(&aFrame[20], aCksum[1]);
54387:   }else{
54388:     memset(&aFrame[8], 0, 16);
54389:   }
54390: }
54391: 
54392: /*
54393: ** Check to see if the frame with header in aFrame[] and content
54394: ** in aData[] is valid.  If it is a valid frame, fill *piPage and
54395: ** *pnTruncate and return true.  Return if the frame is not valid.
54396: */
54397: static int walDecodeFrame(
54398:   Wal *pWal,                      /* The write-ahead log */
54399:   u32 *piPage,                    /* OUT: Database page number for frame */
54400:   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
54401:   u8 *aData,                      /* Pointer to page data (for checksum) */
54402:   u8 *aFrame                      /* Frame data */
54403: ){
54404:   int nativeCksum;                /* True for native byte-order checksums */
54405:   u32 *aCksum = pWal->hdr.aFrameCksum;
54406:   u32 pgno;                       /* Page number of the frame */
54407:   assert( WAL_FRAME_HDRSIZE==24 );
54408: 
54409:   /* A frame is only valid if the salt values in the frame-header
54410:   ** match the salt values in the wal-header. 
54411:   */
54412:   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
54413:     return 0;
54414:   }
54415: 
54416:   /* A frame is only valid if the page number is creater than zero.
54417:   */
54418:   pgno = sqlite3Get4byte(&aFrame[0]);
54419:   if( pgno==0 ){
54420:     return 0;
54421:   }
54422: 
54423:   /* A frame is only valid if a checksum of the WAL header,
54424:   ** all prior frams, the first 16 bytes of this frame-header, 
54425:   ** and the frame-data matches the checksum in the last 8 
54426:   ** bytes of this frame-header.
54427:   */
54428:   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
54429:   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
54430:   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
54431:   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
54432:    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
54433:   ){
54434:     /* Checksum failed. */
54435:     return 0;
54436:   }
54437: 
54438:   /* If we reach this point, the frame is valid.  Return the page number
54439:   ** and the new database size.
54440:   */
54441:   *piPage = pgno;
54442:   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
54443:   return 1;
54444: }
54445: 
54446: 
54447: #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
54448: /*
54449: ** Names of locks.  This routine is used to provide debugging output and is not
54450: ** a part of an ordinary build.
54451: */
54452: static const char *walLockName(int lockIdx){
54453:   if( lockIdx==WAL_WRITE_LOCK ){
54454:     return "WRITE-LOCK";
54455:   }else if( lockIdx==WAL_CKPT_LOCK ){
54456:     return "CKPT-LOCK";
54457:   }else if( lockIdx==WAL_RECOVER_LOCK ){
54458:     return "RECOVER-LOCK";
54459:   }else{
54460:     static char zName[15];
54461:     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
54462:                      lockIdx-WAL_READ_LOCK(0));
54463:     return zName;
54464:   }
54465: }
54466: #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
54467:     
54468: 
54469: /*
54470: ** Set or release locks on the WAL.  Locks are either shared or exclusive.
54471: ** A lock cannot be moved directly between shared and exclusive - it must go
54472: ** through the unlocked state first.
54473: **
54474: ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
54475: */
54476: static int walLockShared(Wal *pWal, int lockIdx){
54477:   int rc;
54478:   if( pWal->exclusiveMode ) return SQLITE_OK;
54479:   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54480:                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
54481:   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
54482:             walLockName(lockIdx), rc ? "failed" : "ok"));
54483:   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54484:   return rc;
54485: }
54486: static void walUnlockShared(Wal *pWal, int lockIdx){
54487:   if( pWal->exclusiveMode ) return;
54488:   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54489:                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
54490:   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
54491: }
54492: static int walLockExclusive(Wal *pWal, int lockIdx, int n){
54493:   int rc;
54494:   if( pWal->exclusiveMode ) return SQLITE_OK;
54495:   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54496:                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
54497:   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
54498:             walLockName(lockIdx), n, rc ? "failed" : "ok"));
54499:   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54500:   return rc;
54501: }
54502: static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
54503:   if( pWal->exclusiveMode ) return;
54504:   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54505:                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
54506:   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
54507:              walLockName(lockIdx), n));
54508: }
54509: 
54510: /*
54511: ** Compute a hash on a page number.  The resulting hash value must land
54512: ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
54513: ** the hash to the next value in the event of a collision.
54514: */
54515: static int walHash(u32 iPage){
54516:   assert( iPage>0 );
54517:   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
54518:   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
54519: }
54520: static int walNextHash(int iPriorHash){
54521:   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
54522: }
54523: 
54524: /* 
54525: ** Return pointers to the hash table and page number array stored on
54526: ** page iHash of the wal-index. The wal-index is broken into 32KB pages
54527: ** numbered starting from 0.
54528: **
54529: ** Set output variable *paHash to point to the start of the hash table
54530: ** in the wal-index file. Set *piZero to one less than the frame 
54531: ** number of the first frame indexed by this hash table. If a
54532: ** slot in the hash table is set to N, it refers to frame number 
54533: ** (*piZero+N) in the log.
54534: **
54535: ** Finally, set *paPgno so that *paPgno[1] is the page number of the
54536: ** first frame indexed by the hash table, frame (*piZero+1).
54537: */
54538: static int walHashGet(
54539:   Wal *pWal,                      /* WAL handle */
54540:   int iHash,                      /* Find the iHash'th table */
54541:   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
54542:   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
54543:   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
54544: ){
54545:   int rc;                         /* Return code */
54546:   volatile u32 *aPgno;
54547: 
54548:   rc = walIndexPage(pWal, iHash, &aPgno);
54549:   assert( rc==SQLITE_OK || iHash>0 );
54550: 
54551:   if( rc==SQLITE_OK ){
54552:     u32 iZero;
54553:     volatile ht_slot *aHash;
54554: 
54555:     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
54556:     if( iHash==0 ){
54557:       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
54558:       iZero = 0;
54559:     }else{
54560:       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
54561:     }
54562:   
54563:     *paPgno = &aPgno[-1];
54564:     *paHash = aHash;
54565:     *piZero = iZero;
54566:   }
54567:   return rc;
54568: }
54569: 
54570: /*
54571: ** Return the number of the wal-index page that contains the hash-table
54572: ** and page-number array that contain entries corresponding to WAL frame
54573: ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
54574: ** are numbered starting from 0.
54575: */
54576: static int walFramePage(u32 iFrame){
54577:   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
54578:   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
54579:        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
54580:        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
54581:        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
54582:        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
54583:   );
54584:   return iHash;
54585: }
54586: 
54587: /*
54588: ** Return the page number associated with frame iFrame in this WAL.
54589: */
54590: static u32 walFramePgno(Wal *pWal, u32 iFrame){
54591:   int iHash = walFramePage(iFrame);
54592:   if( iHash==0 ){
54593:     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
54594:   }
54595:   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
54596: }
54597: 
54598: /*
54599: ** Remove entries from the hash table that point to WAL slots greater
54600: ** than pWal->hdr.mxFrame.
54601: **
54602: ** This function is called whenever pWal->hdr.mxFrame is decreased due
54603: ** to a rollback or savepoint.
54604: **
54605: ** At most only the hash table containing pWal->hdr.mxFrame needs to be
54606: ** updated.  Any later hash tables will be automatically cleared when
54607: ** pWal->hdr.mxFrame advances to the point where those hash tables are
54608: ** actually needed.
54609: */
54610: static void walCleanupHash(Wal *pWal){
54611:   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
54612:   volatile u32 *aPgno = 0;        /* Page number array for hash table */
54613:   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
54614:   int iLimit = 0;                 /* Zero values greater than this */
54615:   int nByte;                      /* Number of bytes to zero in aPgno[] */
54616:   int i;                          /* Used to iterate through aHash[] */
54617: 
54618:   assert( pWal->writeLock );
54619:   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
54620:   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
54621:   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
54622: 
54623:   if( pWal->hdr.mxFrame==0 ) return;
54624: 
54625:   /* Obtain pointers to the hash-table and page-number array containing 
54626:   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
54627:   ** that the page said hash-table and array reside on is already mapped.
54628:   */
54629:   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
54630:   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
54631:   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
54632: 
54633:   /* Zero all hash-table entries that correspond to frame numbers greater
54634:   ** than pWal->hdr.mxFrame.
54635:   */
54636:   iLimit = pWal->hdr.mxFrame - iZero;
54637:   assert( iLimit>0 );
54638:   for(i=0; i<HASHTABLE_NSLOT; i++){
54639:     if( aHash[i]>iLimit ){
54640:       aHash[i] = 0;
54641:     }
54642:   }
54643:   
54644:   /* Zero the entries in the aPgno array that correspond to frames with
54645:   ** frame numbers greater than pWal->hdr.mxFrame. 
54646:   */
54647:   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
54648:   memset((void *)&aPgno[iLimit+1], 0, nByte);
54649: 
54650: #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54651:   /* Verify that the every entry in the mapping region is still reachable
54652:   ** via the hash table even after the cleanup.
54653:   */
54654:   if( iLimit ){
54655:     int j;           /* Loop counter */
54656:     int iKey;        /* Hash key */
54657:     for(j=1; j<=iLimit; j++){
54658:       for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
54659:         if( aHash[iKey]==j ) break;
54660:       }
54661:       assert( aHash[iKey]==j );
54662:     }
54663:   }
54664: #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54665: }
54666: 
54667: 
54668: /*
54669: ** Set an entry in the wal-index that will map database page number
54670: ** pPage into WAL frame iFrame.
54671: */
54672: static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
54673:   int rc;                         /* Return code */
54674:   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
54675:   volatile u32 *aPgno = 0;        /* Page number array */
54676:   volatile ht_slot *aHash = 0;    /* Hash table */
54677: 
54678:   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
54679: 
54680:   /* Assuming the wal-index file was successfully mapped, populate the
54681:   ** page number array and hash table entry.
54682:   */
54683:   if( rc==SQLITE_OK ){
54684:     int iKey;                     /* Hash table key */
54685:     int idx;                      /* Value to write to hash-table slot */
54686:     int nCollide;                 /* Number of hash collisions */
54687: 
54688:     idx = iFrame - iZero;
54689:     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
54690:     
54691:     /* If this is the first entry to be added to this hash-table, zero the
54692:     ** entire hash table and aPgno[] array before proceeding. 
54693:     */
54694:     if( idx==1 ){
54695:       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
54696:       memset((void*)&aPgno[1], 0, nByte);
54697:     }
54698: 
54699:     /* If the entry in aPgno[] is already set, then the previous writer
54700:     ** must have exited unexpectedly in the middle of a transaction (after
54701:     ** writing one or more dirty pages to the WAL to free up memory). 
54702:     ** Remove the remnants of that writers uncommitted transaction from 
54703:     ** the hash-table before writing any new entries.
54704:     */
54705:     if( aPgno[idx] ){
54706:       walCleanupHash(pWal);
54707:       assert( !aPgno[idx] );
54708:     }
54709: 
54710:     /* Write the aPgno[] array entry and the hash-table slot. */
54711:     nCollide = idx;
54712:     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
54713:       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
54714:     }
54715:     aPgno[idx] = iPage;
54716:     aHash[iKey] = (ht_slot)idx;
54717: 
54718: #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54719:     /* Verify that the number of entries in the hash table exactly equals
54720:     ** the number of entries in the mapping region.
54721:     */
54722:     {
54723:       int i;           /* Loop counter */
54724:       int nEntry = 0;  /* Number of entries in the hash table */
54725:       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
54726:       assert( nEntry==idx );
54727:     }
54728: 
54729:     /* Verify that the every entry in the mapping region is reachable
54730:     ** via the hash table.  This turns out to be a really, really expensive
54731:     ** thing to check, so only do this occasionally - not on every
54732:     ** iteration.
54733:     */
54734:     if( (idx&0x3ff)==0 ){
54735:       int i;           /* Loop counter */
54736:       for(i=1; i<=idx; i++){
54737:         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
54738:           if( aHash[iKey]==i ) break;
54739:         }
54740:         assert( aHash[iKey]==i );
54741:       }
54742:     }
54743: #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54744:   }
54745: 
54746: 
54747:   return rc;
54748: }
54749: 
54750: 
54751: /*
54752: ** Recover the wal-index by reading the write-ahead log file. 
54753: **
54754: ** This routine first tries to establish an exclusive lock on the
54755: ** wal-index to prevent other threads/processes from doing anything
54756: ** with the WAL or wal-index while recovery is running.  The
54757: ** WAL_RECOVER_LOCK is also held so that other threads will know
54758: ** that this thread is running recovery.  If unable to establish
54759: ** the necessary locks, this routine returns SQLITE_BUSY.
54760: */
54761: static int walIndexRecover(Wal *pWal){
54762:   int rc;                         /* Return Code */
54763:   i64 nSize;                      /* Size of log file */
54764:   u32 aFrameCksum[2] = {0, 0};
54765:   int iLock;                      /* Lock offset to lock for checkpoint */
54766:   int nLock;                      /* Number of locks to hold */
54767: 
54768:   /* Obtain an exclusive lock on all byte in the locking range not already
54769:   ** locked by the caller. The caller is guaranteed to have locked the
54770:   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
54771:   ** If successful, the same bytes that are locked here are unlocked before
54772:   ** this function returns.
54773:   */
54774:   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
54775:   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
54776:   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
54777:   assert( pWal->writeLock );
54778:   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
54779:   nLock = SQLITE_SHM_NLOCK - iLock;
54780:   rc = walLockExclusive(pWal, iLock, nLock);
54781:   if( rc ){
54782:     return rc;
54783:   }
54784:   WALTRACE(("WAL%p: recovery begin...\n", pWal));
54785: 
54786:   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
54787: 
54788:   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
54789:   if( rc!=SQLITE_OK ){
54790:     goto recovery_error;
54791:   }
54792: 
54793:   if( nSize>WAL_HDRSIZE ){
54794:     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
54795:     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
54796:     int szFrame;                  /* Number of bytes in buffer aFrame[] */
54797:     u8 *aData;                    /* Pointer to data part of aFrame buffer */
54798:     int iFrame;                   /* Index of last frame read */
54799:     i64 iOffset;                  /* Next offset to read from log file */
54800:     int szPage;                   /* Page size according to the log */
54801:     u32 magic;                    /* Magic value read from WAL header */
54802:     u32 version;                  /* Magic value read from WAL header */
54803:     int isValid;                  /* True if this frame is valid */
54804: 
54805:     /* Read in the WAL header. */
54806:     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
54807:     if( rc!=SQLITE_OK ){
54808:       goto recovery_error;
54809:     }
54810: 
54811:     /* If the database page size is not a power of two, or is greater than
54812:     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
54813:     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
54814:     ** WAL file.
54815:     */
54816:     magic = sqlite3Get4byte(&aBuf[0]);
54817:     szPage = sqlite3Get4byte(&aBuf[8]);
54818:     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
54819:      || szPage&(szPage-1) 
54820:      || szPage>SQLITE_MAX_PAGE_SIZE 
54821:      || szPage<512 
54822:     ){
54823:       goto finished;
54824:     }
54825:     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
54826:     pWal->szPage = szPage;
54827:     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
54828:     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
54829: 
54830:     /* Verify that the WAL header checksum is correct */
54831:     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
54832:         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
54833:     );
54834:     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
54835:      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
54836:     ){
54837:       goto finished;
54838:     }
54839: 
54840:     /* Verify that the version number on the WAL format is one that
54841:     ** are able to understand */
54842:     version = sqlite3Get4byte(&aBuf[4]);
54843:     if( version!=WAL_MAX_VERSION ){
54844:       rc = SQLITE_CANTOPEN_BKPT;
54845:       goto finished;
54846:     }
54847: 
54848:     /* Malloc a buffer to read frames into. */
54849:     szFrame = szPage + WAL_FRAME_HDRSIZE;
54850:     aFrame = (u8 *)sqlite3_malloc64(szFrame);
54851:     if( !aFrame ){
54852:       rc = SQLITE_NOMEM_BKPT;
54853:       goto recovery_error;
54854:     }
54855:     aData = &aFrame[WAL_FRAME_HDRSIZE];
54856: 
54857:     /* Read all frames from the log file. */
54858:     iFrame = 0;
54859:     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
54860:       u32 pgno;                   /* Database page number for frame */
54861:       u32 nTruncate;              /* dbsize field from frame header */
54862: 
54863:       /* Read and decode the next log frame. */
54864:       iFrame++;
54865:       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
54866:       if( rc!=SQLITE_OK ) break;
54867:       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
54868:       if( !isValid ) break;
54869:       rc = walIndexAppend(pWal, iFrame, pgno);
54870:       if( rc!=SQLITE_OK ) break;
54871: 
54872:       /* If nTruncate is non-zero, this is a commit record. */
54873:       if( nTruncate ){
54874:         pWal->hdr.mxFrame = iFrame;
54875:         pWal->hdr.nPage = nTruncate;
54876:         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
54877:         testcase( szPage<=32768 );
54878:         testcase( szPage>=65536 );
54879:         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
54880:         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
54881:       }
54882:     }
54883: 
54884:     sqlite3_free(aFrame);
54885:   }
54886: 
54887: finished:
54888:   if( rc==SQLITE_OK ){
54889:     volatile WalCkptInfo *pInfo;
54890:     int i;
54891:     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
54892:     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
54893:     walIndexWriteHdr(pWal);
54894: 
54895:     /* Reset the checkpoint-header. This is safe because this thread is 
54896:     ** currently holding locks that exclude all other readers, writers and
54897:     ** checkpointers.
54898:     */
54899:     pInfo = walCkptInfo(pWal);
54900:     pInfo->nBackfill = 0;
54901:     pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
54902:     pInfo->aReadMark[0] = 0;
54903:     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
54904:     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
54905: 
54906:     /* If more than one frame was recovered from the log file, report an
54907:     ** event via sqlite3_log(). This is to help with identifying performance
54908:     ** problems caused by applications routinely shutting down without
54909:     ** checkpointing the log file.
54910:     */
54911:     if( pWal->hdr.nPage ){
54912:       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
54913:           "recovered %d frames from WAL file %s",
54914:           pWal->hdr.mxFrame, pWal->zWalName
54915:       );
54916:     }
54917:   }
54918: 
54919: recovery_error:
54920:   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
54921:   walUnlockExclusive(pWal, iLock, nLock);
54922:   return rc;
54923: }
54924: 
54925: /*
54926: ** Close an open wal-index.
54927: */
54928: static void walIndexClose(Wal *pWal, int isDelete){
54929:   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54930:     int i;
54931:     for(i=0; i<pWal->nWiData; i++){
54932:       sqlite3_free((void *)pWal->apWiData[i]);
54933:       pWal->apWiData[i] = 0;
54934:     }
54935:   }else{
54936:     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
54937:   }
54938: }
54939: 
54940: /* 
54941: ** Open a connection to the WAL file zWalName. The database file must 
54942: ** already be opened on connection pDbFd. The buffer that zWalName points
54943: ** to must remain valid for the lifetime of the returned Wal* handle.
54944: **
54945: ** A SHARED lock should be held on the database file when this function
54946: ** is called. The purpose of this SHARED lock is to prevent any other
54947: ** client from unlinking the WAL or wal-index file. If another process
54948: ** were to do this just after this client opened one of these files, the
54949: ** system would be badly broken.
54950: **
54951: ** If the log file is successfully opened, SQLITE_OK is returned and 
54952: ** *ppWal is set to point to a new WAL handle. If an error occurs,
54953: ** an SQLite error code is returned and *ppWal is left unmodified.
54954: */
54955: SQLITE_PRIVATE int sqlite3WalOpen(
54956:   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
54957:   sqlite3_file *pDbFd,            /* The open database file */
54958:   const char *zWalName,           /* Name of the WAL file */
54959:   int bNoShm,                     /* True to run in heap-memory mode */
54960:   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
54961:   Wal **ppWal                     /* OUT: Allocated Wal handle */
54962: ){
54963:   int rc;                         /* Return Code */
54964:   Wal *pRet;                      /* Object to allocate and return */
54965:   int flags;                      /* Flags passed to OsOpen() */
54966: 
54967:   assert( zWalName && zWalName[0] );
54968:   assert( pDbFd );
54969: 
54970:   /* In the amalgamation, the os_unix.c and os_win.c source files come before
54971:   ** this source file.  Verify that the #defines of the locking byte offsets
54972:   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
54973:   ** For that matter, if the lock offset ever changes from its initial design
54974:   ** value of 120, we need to know that so there is an assert() to check it.
54975:   */
54976:   assert( 120==WALINDEX_LOCK_OFFSET );
54977:   assert( 136==WALINDEX_HDR_SIZE );
54978: #ifdef WIN_SHM_BASE
54979:   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
54980: #endif
54981: #ifdef UNIX_SHM_BASE
54982:   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
54983: #endif
54984: 
54985: 
54986:   /* Allocate an instance of struct Wal to return. */
54987:   *ppWal = 0;
54988:   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
54989:   if( !pRet ){
54990:     return SQLITE_NOMEM_BKPT;
54991:   }
54992: 
54993:   pRet->pVfs = pVfs;
54994:   pRet->pWalFd = (sqlite3_file *)&pRet[1];
54995:   pRet->pDbFd = pDbFd;
54996:   pRet->readLock = -1;
54997:   pRet->mxWalSize = mxWalSize;
54998:   pRet->zWalName = zWalName;
54999:   pRet->syncHeader = 1;
55000:   pRet->padToSectorBoundary = 1;
55001:   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
55002: 
55003:   /* Open file handle on the write-ahead log file. */
55004:   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
55005:   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
55006:   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
55007:     pRet->readOnly = WAL_RDONLY;
55008:   }
55009: 
55010:   if( rc!=SQLITE_OK ){
55011:     walIndexClose(pRet, 0);
55012:     sqlite3OsClose(pRet->pWalFd);
55013:     sqlite3_free(pRet);
55014:   }else{
55015:     int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
55016:     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
55017:     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
55018:       pRet->padToSectorBoundary = 0;
55019:     }
55020:     *ppWal = pRet;
55021:     WALTRACE(("WAL%d: opened\n", pRet));
55022:   }
55023:   return rc;
55024: }
55025: 
55026: /*
55027: ** Change the size to which the WAL file is trucated on each reset.
55028: */
55029: SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
55030:   if( pWal ) pWal->mxWalSize = iLimit;
55031: }
55032: 
55033: /*
55034: ** Find the smallest page number out of all pages held in the WAL that
55035: ** has not been returned by any prior invocation of this method on the
55036: ** same WalIterator object.   Write into *piFrame the frame index where
55037: ** that page was last written into the WAL.  Write into *piPage the page
55038: ** number.
55039: **
55040: ** Return 0 on success.  If there are no pages in the WAL with a page
55041: ** number larger than *piPage, then return 1.
55042: */
55043: static int walIteratorNext(
55044:   WalIterator *p,               /* Iterator */
55045:   u32 *piPage,                  /* OUT: The page number of the next page */
55046:   u32 *piFrame                  /* OUT: Wal frame index of next page */
55047: ){
55048:   u32 iMin;                     /* Result pgno must be greater than iMin */
55049:   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
55050:   int i;                        /* For looping through segments */
55051: 
55052:   iMin = p->iPrior;
55053:   assert( iMin<0xffffffff );
55054:   for(i=p->nSegment-1; i>=0; i--){
55055:     struct WalSegment *pSegment = &p->aSegment[i];
55056:     while( pSegment->iNext<pSegment->nEntry ){
55057:       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
55058:       if( iPg>iMin ){
55059:         if( iPg<iRet ){
55060:           iRet = iPg;
55061:           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
55062:         }
55063:         break;
55064:       }
55065:       pSegment->iNext++;
55066:     }
55067:   }
55068: 
55069:   *piPage = p->iPrior = iRet;
55070:   return (iRet==0xFFFFFFFF);
55071: }
55072: 
55073: /*
55074: ** This function merges two sorted lists into a single sorted list.
55075: **
55076: ** aLeft[] and aRight[] are arrays of indices.  The sort key is
55077: ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
55078: ** is guaranteed for all J<K:
55079: **
55080: **        aContent[aLeft[J]] < aContent[aLeft[K]]
55081: **        aContent[aRight[J]] < aContent[aRight[K]]
55082: **
55083: ** This routine overwrites aRight[] with a new (probably longer) sequence
55084: ** of indices such that the aRight[] contains every index that appears in
55085: ** either aLeft[] or the old aRight[] and such that the second condition
55086: ** above is still met.
55087: **
55088: ** The aContent[aLeft[X]] values will be unique for all X.  And the
55089: ** aContent[aRight[X]] values will be unique too.  But there might be
55090: ** one or more combinations of X and Y such that
55091: **
55092: **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
55093: **
55094: ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
55095: */
55096: static void walMerge(
55097:   const u32 *aContent,            /* Pages in wal - keys for the sort */
55098:   ht_slot *aLeft,                 /* IN: Left hand input list */
55099:   int nLeft,                      /* IN: Elements in array *paLeft */
55100:   ht_slot **paRight,              /* IN/OUT: Right hand input list */
55101:   int *pnRight,                   /* IN/OUT: Elements in *paRight */
55102:   ht_slot *aTmp                   /* Temporary buffer */
55103: ){
55104:   int iLeft = 0;                  /* Current index in aLeft */
55105:   int iRight = 0;                 /* Current index in aRight */
55106:   int iOut = 0;                   /* Current index in output buffer */
55107:   int nRight = *pnRight;
55108:   ht_slot *aRight = *paRight;
55109: 
55110:   assert( nLeft>0 && nRight>0 );
55111:   while( iRight<nRight || iLeft<nLeft ){
55112:     ht_slot logpage;
55113:     Pgno dbpage;
55114: 
55115:     if( (iLeft<nLeft) 
55116:      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
55117:     ){
55118:       logpage = aLeft[iLeft++];
55119:     }else{
55120:       logpage = aRight[iRight++];
55121:     }
55122:     dbpage = aContent[logpage];
55123: 
55124:     aTmp[iOut++] = logpage;
55125:     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
55126: 
55127:     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
55128:     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
55129:   }
55130: 
55131:   *paRight = aLeft;
55132:   *pnRight = iOut;
55133:   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
55134: }
55135: 
55136: /*
55137: ** Sort the elements in list aList using aContent[] as the sort key.
55138: ** Remove elements with duplicate keys, preferring to keep the
55139: ** larger aList[] values.
55140: **
55141: ** The aList[] entries are indices into aContent[].  The values in
55142: ** aList[] are to be sorted so that for all J<K:
55143: **
55144: **      aContent[aList[J]] < aContent[aList[K]]
55145: **
55146: ** For any X and Y such that
55147: **
55148: **      aContent[aList[X]] == aContent[aList[Y]]
55149: **
55150: ** Keep the larger of the two values aList[X] and aList[Y] and discard
55151: ** the smaller.
55152: */
55153: static void walMergesort(
55154:   const u32 *aContent,            /* Pages in wal */
55155:   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
55156:   ht_slot *aList,                 /* IN/OUT: List to sort */
55157:   int *pnList                     /* IN/OUT: Number of elements in aList[] */
55158: ){
55159:   struct Sublist {
55160:     int nList;                    /* Number of elements in aList */
55161:     ht_slot *aList;               /* Pointer to sub-list content */
55162:   };
55163: 
55164:   const int nList = *pnList;      /* Size of input list */
55165:   int nMerge = 0;                 /* Number of elements in list aMerge */
55166:   ht_slot *aMerge = 0;            /* List to be merged */
55167:   int iList;                      /* Index into input list */
55168:   u32 iSub = 0;                   /* Index into aSub array */
55169:   struct Sublist aSub[13];        /* Array of sub-lists */
55170: 
55171:   memset(aSub, 0, sizeof(aSub));
55172:   assert( nList<=HASHTABLE_NPAGE && nList>0 );
55173:   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
55174: 
55175:   for(iList=0; iList<nList; iList++){
55176:     nMerge = 1;
55177:     aMerge = &aList[iList];
55178:     for(iSub=0; iList & (1<<iSub); iSub++){
55179:       struct Sublist *p;
55180:       assert( iSub<ArraySize(aSub) );
55181:       p = &aSub[iSub];
55182:       assert( p->aList && p->nList<=(1<<iSub) );
55183:       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
55184:       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55185:     }
55186:     aSub[iSub].aList = aMerge;
55187:     aSub[iSub].nList = nMerge;
55188:   }
55189: 
55190:   for(iSub++; iSub<ArraySize(aSub); iSub++){
55191:     if( nList & (1<<iSub) ){
55192:       struct Sublist *p;
55193:       assert( iSub<ArraySize(aSub) );
55194:       p = &aSub[iSub];
55195:       assert( p->nList<=(1<<iSub) );
55196:       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
55197:       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
55198:     }
55199:   }
55200:   assert( aMerge==aList );
55201:   *pnList = nMerge;
55202: 
55203: #ifdef SQLITE_DEBUG
55204:   {
55205:     int i;
55206:     for(i=1; i<*pnList; i++){
55207:       assert( aContent[aList[i]] > aContent[aList[i-1]] );
55208:     }
55209:   }
55210: #endif
55211: }
55212: 
55213: /* 
55214: ** Free an iterator allocated by walIteratorInit().
55215: */
55216: static void walIteratorFree(WalIterator *p){
55217:   sqlite3_free(p);
55218: }
55219: 
55220: /*
55221: ** Construct a WalInterator object that can be used to loop over all 
55222: ** pages in the WAL in ascending order. The caller must hold the checkpoint
55223: ** lock.
55224: **
55225: ** On success, make *pp point to the newly allocated WalInterator object
55226: ** return SQLITE_OK. Otherwise, return an error code. If this routine
55227: ** returns an error, the value of *pp is undefined.
55228: **
55229: ** The calling routine should invoke walIteratorFree() to destroy the
55230: ** WalIterator object when it has finished with it.
55231: */
55232: static int walIteratorInit(Wal *pWal, WalIterator **pp){
55233:   WalIterator *p;                 /* Return value */
55234:   int nSegment;                   /* Number of segments to merge */
55235:   u32 iLast;                      /* Last frame in log */
55236:   int nByte;                      /* Number of bytes to allocate */
55237:   int i;                          /* Iterator variable */
55238:   ht_slot *aTmp;                  /* Temp space used by merge-sort */
55239:   int rc = SQLITE_OK;             /* Return Code */
55240: 
55241:   /* This routine only runs while holding the checkpoint lock. And
55242:   ** it only runs if there is actually content in the log (mxFrame>0).
55243:   */
55244:   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
55245:   iLast = pWal->hdr.mxFrame;
55246: 
55247:   /* Allocate space for the WalIterator object. */
55248:   nSegment = walFramePage(iLast) + 1;
55249:   nByte = sizeof(WalIterator) 
55250:         + (nSegment-1)*sizeof(struct WalSegment)
55251:         + iLast*sizeof(ht_slot);
55252:   p = (WalIterator *)sqlite3_malloc64(nByte);
55253:   if( !p ){
55254:     return SQLITE_NOMEM_BKPT;
55255:   }
55256:   memset(p, 0, nByte);
55257:   p->nSegment = nSegment;
55258: 
55259:   /* Allocate temporary space used by the merge-sort routine. This block
55260:   ** of memory will be freed before this function returns.
55261:   */
55262:   aTmp = (ht_slot *)sqlite3_malloc64(
55263:       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
55264:   );
55265:   if( !aTmp ){
55266:     rc = SQLITE_NOMEM_BKPT;
55267:   }
55268: 
55269:   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
55270:     volatile ht_slot *aHash;
55271:     u32 iZero;
55272:     volatile u32 *aPgno;
55273: 
55274:     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
55275:     if( rc==SQLITE_OK ){
55276:       int j;                      /* Counter variable */
55277:       int nEntry;                 /* Number of entries in this segment */
55278:       ht_slot *aIndex;            /* Sorted index for this segment */
55279: 
55280:       aPgno++;
55281:       if( (i+1)==nSegment ){
55282:         nEntry = (int)(iLast - iZero);
55283:       }else{
55284:         nEntry = (int)((u32*)aHash - (u32*)aPgno);
55285:       }
55286:       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
55287:       iZero++;
55288:   
55289:       for(j=0; j<nEntry; j++){
55290:         aIndex[j] = (ht_slot)j;
55291:       }
55292:       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
55293:       p->aSegment[i].iZero = iZero;
55294:       p->aSegment[i].nEntry = nEntry;
55295:       p->aSegment[i].aIndex = aIndex;
55296:       p->aSegment[i].aPgno = (u32 *)aPgno;
55297:     }
55298:   }
55299:   sqlite3_free(aTmp);
55300: 
55301:   if( rc!=SQLITE_OK ){
55302:     walIteratorFree(p);
55303:   }
55304:   *pp = p;
55305:   return rc;
55306: }
55307: 
55308: /*
55309: ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
55310: ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
55311: ** busy-handler function. Invoke it and retry the lock until either the
55312: ** lock is successfully obtained or the busy-handler returns 0.
55313: */
55314: static int walBusyLock(
55315:   Wal *pWal,                      /* WAL connection */
55316:   int (*xBusy)(void*),            /* Function to call when busy */
55317:   void *pBusyArg,                 /* Context argument for xBusyHandler */
55318:   int lockIdx,                    /* Offset of first byte to lock */
55319:   int n                           /* Number of bytes to lock */
55320: ){
55321:   int rc;
55322:   do {
55323:     rc = walLockExclusive(pWal, lockIdx, n);
55324:   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
55325:   return rc;
55326: }
55327: 
55328: /*
55329: ** The cache of the wal-index header must be valid to call this function.
55330: ** Return the page-size in bytes used by the database.
55331: */
55332: static int walPagesize(Wal *pWal){
55333:   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55334: }
55335: 
55336: /*
55337: ** The following is guaranteed when this function is called:
55338: **
55339: **   a) the WRITER lock is held,
55340: **   b) the entire log file has been checkpointed, and
55341: **   c) any existing readers are reading exclusively from the database
55342: **      file - there are no readers that may attempt to read a frame from
55343: **      the log file.
55344: **
55345: ** This function updates the shared-memory structures so that the next
55346: ** client to write to the database (which may be this one) does so by
55347: ** writing frames into the start of the log file.
55348: **
55349: ** The value of parameter salt1 is used as the aSalt[1] value in the 
55350: ** new wal-index header. It should be passed a pseudo-random value (i.e. 
55351: ** one obtained from sqlite3_randomness()).
55352: */
55353: static void walRestartHdr(Wal *pWal, u32 salt1){
55354:   volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
55355:   int i;                          /* Loop counter */
55356:   u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
55357:   pWal->nCkpt++;
55358:   pWal->hdr.mxFrame = 0;
55359:   sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
55360:   memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
55361:   walIndexWriteHdr(pWal);
55362:   pInfo->nBackfill = 0;
55363:   pInfo->nBackfillAttempted = 0;
55364:   pInfo->aReadMark[1] = 0;
55365:   for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
55366:   assert( pInfo->aReadMark[0]==0 );
55367: }
55368: 
55369: /*
55370: ** Copy as much content as we can from the WAL back into the database file
55371: ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
55372: **
55373: ** The amount of information copies from WAL to database might be limited
55374: ** by active readers.  This routine will never overwrite a database page
55375: ** that a concurrent reader might be using.
55376: **
55377: ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
55378: ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
55379: ** checkpoints are always run by a background thread or background 
55380: ** process, foreground threads will never block on a lengthy fsync call.
55381: **
55382: ** Fsync is called on the WAL before writing content out of the WAL and
55383: ** into the database.  This ensures that if the new content is persistent
55384: ** in the WAL and can be recovered following a power-loss or hard reset.
55385: **
55386: ** Fsync is also called on the database file if (and only if) the entire
55387: ** WAL content is copied into the database file.  This second fsync makes
55388: ** it safe to delete the WAL since the new content will persist in the
55389: ** database file.
55390: **
55391: ** This routine uses and updates the nBackfill field of the wal-index header.
55392: ** This is the only routine that will increase the value of nBackfill.  
55393: ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
55394: ** its value.)
55395: **
55396: ** The caller must be holding sufficient locks to ensure that no other
55397: ** checkpoint is running (in any other thread or process) at the same
55398: ** time.
55399: */
55400: static int walCheckpoint(
55401:   Wal *pWal,                      /* Wal connection */
55402:   int eMode,                      /* One of PASSIVE, FULL or RESTART */
55403:   int (*xBusy)(void*),            /* Function to call when busy */
55404:   void *pBusyArg,                 /* Context argument for xBusyHandler */
55405:   int sync_flags,                 /* Flags for OsSync() (or 0) */
55406:   u8 *zBuf                        /* Temporary buffer to use */
55407: ){
55408:   int rc = SQLITE_OK;             /* Return code */
55409:   int szPage;                     /* Database page-size */
55410:   WalIterator *pIter = 0;         /* Wal iterator context */
55411:   u32 iDbpage = 0;                /* Next database page to write */
55412:   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
55413:   u32 mxSafeFrame;                /* Max frame that can be backfilled */
55414:   u32 mxPage;                     /* Max database page to write */
55415:   int i;                          /* Loop counter */
55416:   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
55417: 
55418:   szPage = walPagesize(pWal);
55419:   testcase( szPage<=32768 );
55420:   testcase( szPage>=65536 );
55421:   pInfo = walCkptInfo(pWal);
55422:   if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55423: 
55424:     /* Allocate the iterator */
55425:     rc = walIteratorInit(pWal, &pIter);
55426:     if( rc!=SQLITE_OK ){
55427:       return rc;
55428:     }
55429:     assert( pIter );
55430: 
55431:     /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
55432:     ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
55433:     assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
55434: 
55435:     /* Compute in mxSafeFrame the index of the last frame of the WAL that is
55436:     ** safe to write into the database.  Frames beyond mxSafeFrame might
55437:     ** overwrite database pages that are in use by active readers and thus
55438:     ** cannot be backfilled from the WAL.
55439:     */
55440:     mxSafeFrame = pWal->hdr.mxFrame;
55441:     mxPage = pWal->hdr.nPage;
55442:     for(i=1; i<WAL_NREADER; i++){
55443:       /* Thread-sanitizer reports that the following is an unsafe read,
55444:       ** as some other thread may be in the process of updating the value
55445:       ** of the aReadMark[] slot. The assumption here is that if that is
55446:       ** happening, the other client may only be increasing the value,
55447:       ** not decreasing it. So assuming either that either the "old" or
55448:       ** "new" version of the value is read, and not some arbitrary value
55449:       ** that would never be written by a real client, things are still 
55450:       ** safe.  */
55451:       u32 y = pInfo->aReadMark[i];
55452:       if( mxSafeFrame>y ){
55453:         assert( y<=pWal->hdr.mxFrame );
55454:         rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
55455:         if( rc==SQLITE_OK ){
55456:           pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
55457:           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55458:         }else if( rc==SQLITE_BUSY ){
55459:           mxSafeFrame = y;
55460:           xBusy = 0;
55461:         }else{
55462:           goto walcheckpoint_out;
55463:         }
55464:       }
55465:     }
55466: 
55467:     if( pInfo->nBackfill<mxSafeFrame
55468:      && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
55469:     ){
55470:       i64 nSize;                    /* Current size of database file */
55471:       u32 nBackfill = pInfo->nBackfill;
55472: 
55473:       pInfo->nBackfillAttempted = mxSafeFrame;
55474: 
55475:       /* Sync the WAL to disk */
55476:       if( sync_flags ){
55477:         rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
55478:       }
55479: 
55480:       /* If the database may grow as a result of this checkpoint, hint
55481:       ** about the eventual size of the db file to the VFS layer.
55482:       */
55483:       if( rc==SQLITE_OK ){
55484:         i64 nReq = ((i64)mxPage * szPage);
55485:         rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
55486:         if( rc==SQLITE_OK && nSize<nReq ){
55487:           sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
55488:         }
55489:       }
55490: 
55491: 
55492:       /* Iterate through the contents of the WAL, copying data to the db file */
55493:       while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
55494:         i64 iOffset;
55495:         assert( walFramePgno(pWal, iFrame)==iDbpage );
55496:         if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
55497:           continue;
55498:         }
55499:         iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
55500:         /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
55501:         rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
55502:         if( rc!=SQLITE_OK ) break;
55503:         iOffset = (iDbpage-1)*(i64)szPage;
55504:         testcase( IS_BIG_INT(iOffset) );
55505:         rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
55506:         if( rc!=SQLITE_OK ) break;
55507:       }
55508: 
55509:       /* If work was actually accomplished... */
55510:       if( rc==SQLITE_OK ){
55511:         if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
55512:           i64 szDb = pWal->hdr.nPage*(i64)szPage;
55513:           testcase( IS_BIG_INT(szDb) );
55514:           rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
55515:           if( rc==SQLITE_OK && sync_flags ){
55516:             rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
55517:           }
55518:         }
55519:         if( rc==SQLITE_OK ){
55520:           pInfo->nBackfill = mxSafeFrame;
55521:         }
55522:       }
55523: 
55524:       /* Release the reader lock held while backfilling */
55525:       walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
55526:     }
55527: 
55528:     if( rc==SQLITE_BUSY ){
55529:       /* Reset the return code so as not to report a checkpoint failure
55530:       ** just because there are active readers.  */
55531:       rc = SQLITE_OK;
55532:     }
55533:   }
55534: 
55535:   /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
55536:   ** entire wal file has been copied into the database file, then block 
55537:   ** until all readers have finished using the wal file. This ensures that 
55538:   ** the next process to write to the database restarts the wal file.
55539:   */
55540:   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
55541:     assert( pWal->writeLock );
55542:     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55543:       rc = SQLITE_BUSY;
55544:     }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
55545:       u32 salt1;
55546:       sqlite3_randomness(4, &salt1);
55547:       assert( pInfo->nBackfill==pWal->hdr.mxFrame );
55548:       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
55549:       if( rc==SQLITE_OK ){
55550:         if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
55551:           /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
55552:           ** SQLITE_CHECKPOINT_RESTART with the addition that it also
55553:           ** truncates the log file to zero bytes just prior to a
55554:           ** successful return.
55555:           **
55556:           ** In theory, it might be safe to do this without updating the
55557:           ** wal-index header in shared memory, as all subsequent reader or
55558:           ** writer clients should see that the entire log file has been
55559:           ** checkpointed and behave accordingly. This seems unsafe though,
55560:           ** as it would leave the system in a state where the contents of
55561:           ** the wal-index header do not match the contents of the 
55562:           ** file-system. To avoid this, update the wal-index header to
55563:           ** indicate that the log file contains zero valid frames.  */
55564:           walRestartHdr(pWal, salt1);
55565:           rc = sqlite3OsTruncate(pWal->pWalFd, 0);
55566:         }
55567:         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
55568:       }
55569:     }
55570:   }
55571: 
55572:  walcheckpoint_out:
55573:   walIteratorFree(pIter);
55574:   return rc;
55575: }
55576: 
55577: /*
55578: ** If the WAL file is currently larger than nMax bytes in size, truncate
55579: ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
55580: */
55581: static void walLimitSize(Wal *pWal, i64 nMax){
55582:   i64 sz;
55583:   int rx;
55584:   sqlite3BeginBenignMalloc();
55585:   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
55586:   if( rx==SQLITE_OK && (sz > nMax ) ){
55587:     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
55588:   }
55589:   sqlite3EndBenignMalloc();
55590:   if( rx ){
55591:     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
55592:   }
55593: }
55594: 
55595: /*
55596: ** Close a connection to a log file.
55597: */
55598: SQLITE_PRIVATE int sqlite3WalClose(
55599:   Wal *pWal,                      /* Wal to close */
55600:   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
55601:   int nBuf,
55602:   u8 *zBuf                        /* Buffer of at least nBuf bytes */
55603: ){
55604:   int rc = SQLITE_OK;
55605:   if( pWal ){
55606:     int isDelete = 0;             /* True to unlink wal and wal-index files */
55607: 
55608:     /* If an EXCLUSIVE lock can be obtained on the database file (using the
55609:     ** ordinary, rollback-mode locking methods, this guarantees that the
55610:     ** connection associated with this log file is the only connection to
55611:     ** the database. In this case checkpoint the database and unlink both
55612:     ** the wal and wal-index files.
55613:     **
55614:     ** The EXCLUSIVE lock is not released before returning.
55615:     */
55616:     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
55617:     if( rc==SQLITE_OK ){
55618:       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
55619:         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
55620:       }
55621:       rc = sqlite3WalCheckpoint(
55622:           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
55623:       );
55624:       if( rc==SQLITE_OK ){
55625:         int bPersist = -1;
55626:         sqlite3OsFileControlHint(
55627:             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
55628:         );
55629:         if( bPersist!=1 ){
55630:           /* Try to delete the WAL file if the checkpoint completed and
55631:           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
55632:           ** mode (!bPersist) */
55633:           isDelete = 1;
55634:         }else if( pWal->mxWalSize>=0 ){
55635:           /* Try to truncate the WAL file to zero bytes if the checkpoint
55636:           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
55637:           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
55638:           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
55639:           ** to zero bytes as truncating to the journal_size_limit might
55640:           ** leave a corrupt WAL file on disk. */
55641:           walLimitSize(pWal, 0);
55642:         }
55643:       }
55644:     }
55645: 
55646:     walIndexClose(pWal, isDelete);
55647:     sqlite3OsClose(pWal->pWalFd);
55648:     if( isDelete ){
55649:       sqlite3BeginBenignMalloc();
55650:       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
55651:       sqlite3EndBenignMalloc();
55652:     }
55653:     WALTRACE(("WAL%p: closed\n", pWal));
55654:     sqlite3_free((void *)pWal->apWiData);
55655:     sqlite3_free(pWal);
55656:   }
55657:   return rc;
55658: }
55659: 
55660: /*
55661: ** Try to read the wal-index header.  Return 0 on success and 1 if
55662: ** there is a problem.
55663: **
55664: ** The wal-index is in shared memory.  Another thread or process might
55665: ** be writing the header at the same time this procedure is trying to
55666: ** read it, which might result in inconsistency.  A dirty read is detected
55667: ** by verifying that both copies of the header are the same and also by
55668: ** a checksum on the header.
55669: **
55670: ** If and only if the read is consistent and the header is different from
55671: ** pWal->hdr, then pWal->hdr is updated to the content of the new header
55672: ** and *pChanged is set to 1.
55673: **
55674: ** If the checksum cannot be verified return non-zero. If the header
55675: ** is read successfully and the checksum verified, return zero.
55676: */
55677: static int walIndexTryHdr(Wal *pWal, int *pChanged){
55678:   u32 aCksum[2];                  /* Checksum on the header content */
55679:   WalIndexHdr h1, h2;             /* Two copies of the header content */
55680:   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
55681: 
55682:   /* The first page of the wal-index must be mapped at this point. */
55683:   assert( pWal->nWiData>0 && pWal->apWiData[0] );
55684: 
55685:   /* Read the header. This might happen concurrently with a write to the
55686:   ** same area of shared memory on a different CPU in a SMP,
55687:   ** meaning it is possible that an inconsistent snapshot is read
55688:   ** from the file. If this happens, return non-zero.
55689:   **
55690:   ** There are two copies of the header at the beginning of the wal-index.
55691:   ** When reading, read [0] first then [1].  Writes are in the reverse order.
55692:   ** Memory barriers are used to prevent the compiler or the hardware from
55693:   ** reordering the reads and writes.
55694:   */
55695:   aHdr = walIndexHdr(pWal);
55696:   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
55697:   walShmBarrier(pWal);
55698:   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
55699: 
55700:   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
55701:     return 1;   /* Dirty read */
55702:   }  
55703:   if( h1.isInit==0 ){
55704:     return 1;   /* Malformed header - probably all zeros */
55705:   }
55706:   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
55707:   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
55708:     return 1;   /* Checksum does not match */
55709:   }
55710: 
55711:   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
55712:     *pChanged = 1;
55713:     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
55714:     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55715:     testcase( pWal->szPage<=32768 );
55716:     testcase( pWal->szPage>=65536 );
55717:   }
55718: 
55719:   /* The header was successfully read. Return zero. */
55720:   return 0;
55721: }
55722: 
55723: /*
55724: ** Read the wal-index header from the wal-index and into pWal->hdr.
55725: ** If the wal-header appears to be corrupt, try to reconstruct the
55726: ** wal-index from the WAL before returning.
55727: **
55728: ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
55729: ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
55730: ** to 0.
55731: **
55732: ** If the wal-index header is successfully read, return SQLITE_OK. 
55733: ** Otherwise an SQLite error code.
55734: */
55735: static int walIndexReadHdr(Wal *pWal, int *pChanged){
55736:   int rc;                         /* Return code */
55737:   int badHdr;                     /* True if a header read failed */
55738:   volatile u32 *page0;            /* Chunk of wal-index containing header */
55739: 
55740:   /* Ensure that page 0 of the wal-index (the page that contains the 
55741:   ** wal-index header) is mapped. Return early if an error occurs here.
55742:   */
55743:   assert( pChanged );
55744:   rc = walIndexPage(pWal, 0, &page0);
55745:   if( rc!=SQLITE_OK ){
55746:     return rc;
55747:   };
55748:   assert( page0 || pWal->writeLock==0 );
55749: 
55750:   /* If the first page of the wal-index has been mapped, try to read the
55751:   ** wal-index header immediately, without holding any lock. This usually
55752:   ** works, but may fail if the wal-index header is corrupt or currently 
55753:   ** being modified by another thread or process.
55754:   */
55755:   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
55756: 
55757:   /* If the first attempt failed, it might have been due to a race
55758:   ** with a writer.  So get a WRITE lock and try again.
55759:   */
55760:   assert( badHdr==0 || pWal->writeLock==0 );
55761:   if( badHdr ){
55762:     if( pWal->readOnly & WAL_SHM_RDONLY ){
55763:       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
55764:         walUnlockShared(pWal, WAL_WRITE_LOCK);
55765:         rc = SQLITE_READONLY_RECOVERY;
55766:       }
55767:     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
55768:       pWal->writeLock = 1;
55769:       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
55770:         badHdr = walIndexTryHdr(pWal, pChanged);
55771:         if( badHdr ){
55772:           /* If the wal-index header is still malformed even while holding
55773:           ** a WRITE lock, it can only mean that the header is corrupted and
55774:           ** needs to be reconstructed.  So run recovery to do exactly that.
55775:           */
55776:           rc = walIndexRecover(pWal);
55777:           *pChanged = 1;
55778:         }
55779:       }
55780:       pWal->writeLock = 0;
55781:       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
55782:     }
55783:   }
55784: 
55785:   /* If the header is read successfully, check the version number to make
55786:   ** sure the wal-index was not constructed with some future format that
55787:   ** this version of SQLite cannot understand.
55788:   */
55789:   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
55790:     rc = SQLITE_CANTOPEN_BKPT;
55791:   }
55792: 
55793:   return rc;
55794: }
55795: 
55796: /*
55797: ** This is the value that walTryBeginRead returns when it needs to
55798: ** be retried.
55799: */
55800: #define WAL_RETRY  (-1)
55801: 
55802: /*
55803: ** Attempt to start a read transaction.  This might fail due to a race or
55804: ** other transient condition.  When that happens, it returns WAL_RETRY to
55805: ** indicate to the caller that it is safe to retry immediately.
55806: **
55807: ** On success return SQLITE_OK.  On a permanent failure (such an
55808: ** I/O error or an SQLITE_BUSY because another process is running
55809: ** recovery) return a positive error code.
55810: **
55811: ** The useWal parameter is true to force the use of the WAL and disable
55812: ** the case where the WAL is bypassed because it has been completely
55813: ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
55814: ** to make a copy of the wal-index header into pWal->hdr.  If the 
55815: ** wal-index header has changed, *pChanged is set to 1 (as an indication 
55816: ** to the caller that the local paget cache is obsolete and needs to be 
55817: ** flushed.)  When useWal==1, the wal-index header is assumed to already
55818: ** be loaded and the pChanged parameter is unused.
55819: **
55820: ** The caller must set the cnt parameter to the number of prior calls to
55821: ** this routine during the current read attempt that returned WAL_RETRY.
55822: ** This routine will start taking more aggressive measures to clear the
55823: ** race conditions after multiple WAL_RETRY returns, and after an excessive
55824: ** number of errors will ultimately return SQLITE_PROTOCOL.  The
55825: ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
55826: ** and is not honoring the locking protocol.  There is a vanishingly small
55827: ** chance that SQLITE_PROTOCOL could be returned because of a run of really
55828: ** bad luck when there is lots of contention for the wal-index, but that
55829: ** possibility is so small that it can be safely neglected, we believe.
55830: **
55831: ** On success, this routine obtains a read lock on 
55832: ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
55833: ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
55834: ** that means the Wal does not hold any read lock.  The reader must not
55835: ** access any database page that is modified by a WAL frame up to and
55836: ** including frame number aReadMark[pWal->readLock].  The reader will
55837: ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
55838: ** Or if pWal->readLock==0, then the reader will ignore the WAL
55839: ** completely and get all content directly from the database file.
55840: ** If the useWal parameter is 1 then the WAL will never be ignored and
55841: ** this routine will always set pWal->readLock>0 on success.
55842: ** When the read transaction is completed, the caller must release the
55843: ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
55844: **
55845: ** This routine uses the nBackfill and aReadMark[] fields of the header
55846: ** to select a particular WAL_READ_LOCK() that strives to let the
55847: ** checkpoint process do as much work as possible.  This routine might
55848: ** update values of the aReadMark[] array in the header, but if it does
55849: ** so it takes care to hold an exclusive lock on the corresponding
55850: ** WAL_READ_LOCK() while changing values.
55851: */
55852: static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
55853:   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
55854:   u32 mxReadMark;                 /* Largest aReadMark[] value */
55855:   int mxI;                        /* Index of largest aReadMark[] value */
55856:   int i;                          /* Loop counter */
55857:   int rc = SQLITE_OK;             /* Return code  */
55858:   u32 mxFrame;                    /* Wal frame to lock to */
55859: 
55860:   assert( pWal->readLock<0 );     /* Not currently locked */
55861: 
55862:   /* Take steps to avoid spinning forever if there is a protocol error.
55863:   **
55864:   ** Circumstances that cause a RETRY should only last for the briefest
55865:   ** instances of time.  No I/O or other system calls are done while the
55866:   ** locks are held, so the locks should not be held for very long. But 
55867:   ** if we are unlucky, another process that is holding a lock might get
55868:   ** paged out or take a page-fault that is time-consuming to resolve, 
55869:   ** during the few nanoseconds that it is holding the lock.  In that case,
55870:   ** it might take longer than normal for the lock to free.
55871:   **
55872:   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
55873:   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
55874:   ** is more of a scheduler yield than an actual delay.  But on the 10th
55875:   ** an subsequent retries, the delays start becoming longer and longer, 
55876:   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
55877:   ** The total delay time before giving up is less than 10 seconds.
55878:   */
55879:   if( cnt>5 ){
55880:     int nDelay = 1;                      /* Pause time in microseconds */
55881:     if( cnt>100 ){
55882:       VVA_ONLY( pWal->lockError = 1; )
55883:       return SQLITE_PROTOCOL;
55884:     }
55885:     if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
55886:     sqlite3OsSleep(pWal->pVfs, nDelay);
55887:   }
55888: 
55889:   if( !useWal ){
55890:     rc = walIndexReadHdr(pWal, pChanged);
55891:     if( rc==SQLITE_BUSY ){
55892:       /* If there is not a recovery running in another thread or process
55893:       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
55894:       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
55895:       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
55896:       ** would be technically correct.  But the race is benign since with
55897:       ** WAL_RETRY this routine will be called again and will probably be
55898:       ** right on the second iteration.
55899:       */
55900:       if( pWal->apWiData[0]==0 ){
55901:         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
55902:         ** We assume this is a transient condition, so return WAL_RETRY. The
55903:         ** xShmMap() implementation used by the default unix and win32 VFS 
55904:         ** modules may return SQLITE_BUSY due to a race condition in the 
55905:         ** code that determines whether or not the shared-memory region 
55906:         ** must be zeroed before the requested page is returned.
55907:         */
55908:         rc = WAL_RETRY;
55909:       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
55910:         walUnlockShared(pWal, WAL_RECOVER_LOCK);
55911:         rc = WAL_RETRY;
55912:       }else if( rc==SQLITE_BUSY ){
55913:         rc = SQLITE_BUSY_RECOVERY;
55914:       }
55915:     }
55916:     if( rc!=SQLITE_OK ){
55917:       return rc;
55918:     }
55919:   }
55920: 
55921:   pInfo = walCkptInfo(pWal);
55922:   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame 
55923: #ifdef SQLITE_ENABLE_SNAPSHOT
55924:    && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
55925:      || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
55926: #endif
55927:   ){
55928:     /* The WAL has been completely backfilled (or it is empty).
55929:     ** and can be safely ignored.
55930:     */
55931:     rc = walLockShared(pWal, WAL_READ_LOCK(0));
55932:     walShmBarrier(pWal);
55933:     if( rc==SQLITE_OK ){
55934:       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
55935:         /* It is not safe to allow the reader to continue here if frames
55936:         ** may have been appended to the log before READ_LOCK(0) was obtained.
55937:         ** When holding READ_LOCK(0), the reader ignores the entire log file,
55938:         ** which implies that the database file contains a trustworthy
55939:         ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
55940:         ** happening, this is usually correct.
55941:         **
55942:         ** However, if frames have been appended to the log (or if the log 
55943:         ** is wrapped and written for that matter) before the READ_LOCK(0)
55944:         ** is obtained, that is not necessarily true. A checkpointer may
55945:         ** have started to backfill the appended frames but crashed before
55946:         ** it finished. Leaving a corrupt image in the database file.
55947:         */
55948:         walUnlockShared(pWal, WAL_READ_LOCK(0));
55949:         return WAL_RETRY;
55950:       }
55951:       pWal->readLock = 0;
55952:       return SQLITE_OK;
55953:     }else if( rc!=SQLITE_BUSY ){
55954:       return rc;
55955:     }
55956:   }
55957: 
55958:   /* If we get this far, it means that the reader will want to use
55959:   ** the WAL to get at content from recent commits.  The job now is
55960:   ** to select one of the aReadMark[] entries that is closest to
55961:   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
55962:   */
55963:   mxReadMark = 0;
55964:   mxI = 0;
55965:   mxFrame = pWal->hdr.mxFrame;
55966: #ifdef SQLITE_ENABLE_SNAPSHOT
55967:   if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
55968:     mxFrame = pWal->pSnapshot->mxFrame;
55969:   }
55970: #endif
55971:   for(i=1; i<WAL_NREADER; i++){
55972:     u32 thisMark = pInfo->aReadMark[i];
55973:     if( mxReadMark<=thisMark && thisMark<=mxFrame ){
55974:       assert( thisMark!=READMARK_NOT_USED );
55975:       mxReadMark = thisMark;
55976:       mxI = i;
55977:     }
55978:   }
55979:   if( (pWal->readOnly & WAL_SHM_RDONLY)==0
55980:    && (mxReadMark<mxFrame || mxI==0)
55981:   ){
55982:     for(i=1; i<WAL_NREADER; i++){
55983:       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
55984:       if( rc==SQLITE_OK ){
55985:         mxReadMark = pInfo->aReadMark[i] = mxFrame;
55986:         mxI = i;
55987:         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55988:         break;
55989:       }else if( rc!=SQLITE_BUSY ){
55990:         return rc;
55991:       }
55992:     }
55993:   }
55994:   if( mxI==0 ){
55995:     assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
55996:     return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
55997:   }
55998: 
55999:   rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
56000:   if( rc ){
56001:     return rc==SQLITE_BUSY ? WAL_RETRY : rc;
56002:   }
56003:   /* Now that the read-lock has been obtained, check that neither the
56004:   ** value in the aReadMark[] array or the contents of the wal-index
56005:   ** header have changed.
56006:   **
56007:   ** It is necessary to check that the wal-index header did not change
56008:   ** between the time it was read and when the shared-lock was obtained
56009:   ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
56010:   ** that the log file may have been wrapped by a writer, or that frames
56011:   ** that occur later in the log than pWal->hdr.mxFrame may have been
56012:   ** copied into the database by a checkpointer. If either of these things
56013:   ** happened, then reading the database with the current value of
56014:   ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
56015:   ** instead.
56016:   **
56017:   ** Before checking that the live wal-index header has not changed
56018:   ** since it was read, set Wal.minFrame to the first frame in the wal
56019:   ** file that has not yet been checkpointed. This client will not need
56020:   ** to read any frames earlier than minFrame from the wal file - they
56021:   ** can be safely read directly from the database file.
56022:   **
56023:   ** Because a ShmBarrier() call is made between taking the copy of 
56024:   ** nBackfill and checking that the wal-header in shared-memory still
56025:   ** matches the one cached in pWal->hdr, it is guaranteed that the 
56026:   ** checkpointer that set nBackfill was not working with a wal-index
56027:   ** header newer than that cached in pWal->hdr. If it were, that could
56028:   ** cause a problem. The checkpointer could omit to checkpoint
56029:   ** a version of page X that lies before pWal->minFrame (call that version
56030:   ** A) on the basis that there is a newer version (version B) of the same
56031:   ** page later in the wal file. But if version B happens to like past
56032:   ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
56033:   ** that it can read version A from the database file. However, since
56034:   ** we can guarantee that the checkpointer that set nBackfill could not
56035:   ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
56036:   */
56037:   pWal->minFrame = pInfo->nBackfill+1;
56038:   walShmBarrier(pWal);
56039:   if( pInfo->aReadMark[mxI]!=mxReadMark
56040:    || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
56041:   ){
56042:     walUnlockShared(pWal, WAL_READ_LOCK(mxI));
56043:     return WAL_RETRY;
56044:   }else{
56045:     assert( mxReadMark<=pWal->hdr.mxFrame );
56046:     pWal->readLock = (i16)mxI;
56047:   }
56048:   return rc;
56049: }
56050: 
56051: /*
56052: ** Begin a read transaction on the database.
56053: **
56054: ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
56055: ** it takes a snapshot of the state of the WAL and wal-index for the current
56056: ** instant in time.  The current thread will continue to use this snapshot.
56057: ** Other threads might append new content to the WAL and wal-index but
56058: ** that extra content is ignored by the current thread.
56059: **
56060: ** If the database contents have changes since the previous read
56061: ** transaction, then *pChanged is set to 1 before returning.  The
56062: ** Pager layer will use this to know that is cache is stale and
56063: ** needs to be flushed.
56064: */
56065: SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
56066:   int rc;                         /* Return code */
56067:   int cnt = 0;                    /* Number of TryBeginRead attempts */
56068: 
56069: #ifdef SQLITE_ENABLE_SNAPSHOT
56070:   int bChanged = 0;
56071:   WalIndexHdr *pSnapshot = pWal->pSnapshot;
56072:   if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56073:     bChanged = 1;
56074:   }
56075: #endif
56076: 
56077:   do{
56078:     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
56079:   }while( rc==WAL_RETRY );
56080:   testcase( (rc&0xff)==SQLITE_BUSY );
56081:   testcase( (rc&0xff)==SQLITE_IOERR );
56082:   testcase( rc==SQLITE_PROTOCOL );
56083:   testcase( rc==SQLITE_OK );
56084: 
56085: #ifdef SQLITE_ENABLE_SNAPSHOT
56086:   if( rc==SQLITE_OK ){
56087:     if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
56088:       /* At this point the client has a lock on an aReadMark[] slot holding
56089:       ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
56090:       ** is populated with the wal-index header corresponding to the head
56091:       ** of the wal file. Verify that pSnapshot is still valid before
56092:       ** continuing.  Reasons why pSnapshot might no longer be valid:
56093:       **
56094:       **    (1)  The WAL file has been reset since the snapshot was taken.
56095:       **         In this case, the salt will have changed.
56096:       **
56097:       **    (2)  A checkpoint as been attempted that wrote frames past
56098:       **         pSnapshot->mxFrame into the database file.  Note that the
56099:       **         checkpoint need not have completed for this to cause problems.
56100:       */
56101:       volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56102: 
56103:       assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
56104:       assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
56105: 
56106:       /* It is possible that there is a checkpointer thread running 
56107:       ** concurrent with this code. If this is the case, it may be that the
56108:       ** checkpointer has already determined that it will checkpoint 
56109:       ** snapshot X, where X is later in the wal file than pSnapshot, but 
56110:       ** has not yet set the pInfo->nBackfillAttempted variable to indicate 
56111:       ** its intent. To avoid the race condition this leads to, ensure that
56112:       ** there is no checkpointer process by taking a shared CKPT lock 
56113:       ** before checking pInfo->nBackfillAttempted.  */
56114:       rc = walLockShared(pWal, WAL_CKPT_LOCK);
56115: 
56116:       if( rc==SQLITE_OK ){
56117:         /* Check that the wal file has not been wrapped. Assuming that it has
56118:         ** not, also check that no checkpointer has attempted to checkpoint any
56119:         ** frames beyond pSnapshot->mxFrame. If either of these conditions are
56120:         ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
56121:         ** with *pSnapshot and set *pChanged as appropriate for opening the
56122:         ** snapshot.  */
56123:         if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
56124:          && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
56125:         ){
56126:           assert( pWal->readLock>0 );
56127:           memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
56128:           *pChanged = bChanged;
56129:         }else{
56130:           rc = SQLITE_BUSY_SNAPSHOT;
56131:         }
56132: 
56133:         /* Release the shared CKPT lock obtained above. */
56134:         walUnlockShared(pWal, WAL_CKPT_LOCK);
56135:       }
56136: 
56137: 
56138:       if( rc!=SQLITE_OK ){
56139:         sqlite3WalEndReadTransaction(pWal);
56140:       }
56141:     }
56142:   }
56143: #endif
56144:   return rc;
56145: }
56146: 
56147: /*
56148: ** Finish with a read transaction.  All this does is release the
56149: ** read-lock.
56150: */
56151: SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
56152:   sqlite3WalEndWriteTransaction(pWal);
56153:   if( pWal->readLock>=0 ){
56154:     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
56155:     pWal->readLock = -1;
56156:   }
56157: }
56158: 
56159: /*
56160: ** Search the wal file for page pgno. If found, set *piRead to the frame that
56161: ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
56162: ** to zero.
56163: **
56164: ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
56165: ** error does occur, the final value of *piRead is undefined.
56166: */
56167: SQLITE_PRIVATE int sqlite3WalFindFrame(
56168:   Wal *pWal,                      /* WAL handle */
56169:   Pgno pgno,                      /* Database page number to read data for */
56170:   u32 *piRead                     /* OUT: Frame number (or zero) */
56171: ){
56172:   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
56173:   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
56174:   int iHash;                      /* Used to loop through N hash tables */
56175:   int iMinHash;
56176: 
56177:   /* This routine is only be called from within a read transaction. */
56178:   assert( pWal->readLock>=0 || pWal->lockError );
56179: 
56180:   /* If the "last page" field of the wal-index header snapshot is 0, then
56181:   ** no data will be read from the wal under any circumstances. Return early
56182:   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
56183:   ** then the WAL is ignored by the reader so return early, as if the 
56184:   ** WAL were empty.
56185:   */
56186:   if( iLast==0 || pWal->readLock==0 ){
56187:     *piRead = 0;
56188:     return SQLITE_OK;
56189:   }
56190: 
56191:   /* Search the hash table or tables for an entry matching page number
56192:   ** pgno. Each iteration of the following for() loop searches one
56193:   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
56194:   **
56195:   ** This code might run concurrently to the code in walIndexAppend()
56196:   ** that adds entries to the wal-index (and possibly to this hash 
56197:   ** table). This means the value just read from the hash 
56198:   ** slot (aHash[iKey]) may have been added before or after the 
56199:   ** current read transaction was opened. Values added after the
56200:   ** read transaction was opened may have been written incorrectly -
56201:   ** i.e. these slots may contain garbage data. However, we assume
56202:   ** that any slots written before the current read transaction was
56203:   ** opened remain unmodified.
56204:   **
56205:   ** For the reasons above, the if(...) condition featured in the inner
56206:   ** loop of the following block is more stringent that would be required 
56207:   ** if we had exclusive access to the hash-table:
56208:   **
56209:   **   (aPgno[iFrame]==pgno): 
56210:   **     This condition filters out normal hash-table collisions.
56211:   **
56212:   **   (iFrame<=iLast): 
56213:   **     This condition filters out entries that were added to the hash
56214:   **     table after the current read-transaction had started.
56215:   */
56216:   iMinHash = walFramePage(pWal->minFrame);
56217:   for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
56218:     volatile ht_slot *aHash;      /* Pointer to hash table */
56219:     volatile u32 *aPgno;          /* Pointer to array of page numbers */
56220:     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
56221:     int iKey;                     /* Hash slot index */
56222:     int nCollide;                 /* Number of hash collisions remaining */
56223:     int rc;                       /* Error code */
56224: 
56225:     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
56226:     if( rc!=SQLITE_OK ){
56227:       return rc;
56228:     }
56229:     nCollide = HASHTABLE_NSLOT;
56230:     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
56231:       u32 iFrame = aHash[iKey] + iZero;
56232:       if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
56233:         assert( iFrame>iRead || CORRUPT_DB );
56234:         iRead = iFrame;
56235:       }
56236:       if( (nCollide--)==0 ){
56237:         return SQLITE_CORRUPT_BKPT;
56238:       }
56239:     }
56240:   }
56241: 
56242: #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
56243:   /* If expensive assert() statements are available, do a linear search
56244:   ** of the wal-index file content. Make sure the results agree with the
56245:   ** result obtained using the hash indexes above.  */
56246:   {
56247:     u32 iRead2 = 0;
56248:     u32 iTest;
56249:     assert( pWal->minFrame>0 );
56250:     for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
56251:       if( walFramePgno(pWal, iTest)==pgno ){
56252:         iRead2 = iTest;
56253:         break;
56254:       }
56255:     }
56256:     assert( iRead==iRead2 );
56257:   }
56258: #endif
56259: 
56260:   *piRead = iRead;
56261:   return SQLITE_OK;
56262: }
56263: 
56264: /*
56265: ** Read the contents of frame iRead from the wal file into buffer pOut
56266: ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
56267: ** error code otherwise.
56268: */
56269: SQLITE_PRIVATE int sqlite3WalReadFrame(
56270:   Wal *pWal,                      /* WAL handle */
56271:   u32 iRead,                      /* Frame to read */
56272:   int nOut,                       /* Size of buffer pOut in bytes */
56273:   u8 *pOut                        /* Buffer to write page data to */
56274: ){
56275:   int sz;
56276:   i64 iOffset;
56277:   sz = pWal->hdr.szPage;
56278:   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
56279:   testcase( sz<=32768 );
56280:   testcase( sz>=65536 );
56281:   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
56282:   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
56283:   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
56284: }
56285: 
56286: /* 
56287: ** Return the size of the database in pages (or zero, if unknown).
56288: */
56289: SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
56290:   if( pWal && ALWAYS(pWal->readLock>=0) ){
56291:     return pWal->hdr.nPage;
56292:   }
56293:   return 0;
56294: }
56295: 
56296: 
56297: /* 
56298: ** This function starts a write transaction on the WAL.
56299: **
56300: ** A read transaction must have already been started by a prior call
56301: ** to sqlite3WalBeginReadTransaction().
56302: **
56303: ** If another thread or process has written into the database since
56304: ** the read transaction was started, then it is not possible for this
56305: ** thread to write as doing so would cause a fork.  So this routine
56306: ** returns SQLITE_BUSY in that case and no write transaction is started.
56307: **
56308: ** There can only be a single writer active at a time.
56309: */
56310: SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
56311:   int rc;
56312: 
56313:   /* Cannot start a write transaction without first holding a read
56314:   ** transaction. */
56315:   assert( pWal->readLock>=0 );
56316:   assert( pWal->writeLock==0 && pWal->iReCksum==0 );
56317: 
56318:   if( pWal->readOnly ){
56319:     return SQLITE_READONLY;
56320:   }
56321: 
56322:   /* Only one writer allowed at a time.  Get the write lock.  Return
56323:   ** SQLITE_BUSY if unable.
56324:   */
56325:   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
56326:   if( rc ){
56327:     return rc;
56328:   }
56329:   pWal->writeLock = 1;
56330: 
56331:   /* If another connection has written to the database file since the
56332:   ** time the read transaction on this connection was started, then
56333:   ** the write is disallowed.
56334:   */
56335:   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
56336:     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56337:     pWal->writeLock = 0;
56338:     rc = SQLITE_BUSY_SNAPSHOT;
56339:   }
56340: 
56341:   return rc;
56342: }
56343: 
56344: /*
56345: ** End a write transaction.  The commit has already been done.  This
56346: ** routine merely releases the lock.
56347: */
56348: SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
56349:   if( pWal->writeLock ){
56350:     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
56351:     pWal->writeLock = 0;
56352:     pWal->iReCksum = 0;
56353:     pWal->truncateOnCommit = 0;
56354:   }
56355:   return SQLITE_OK;
56356: }
56357: 
56358: /*
56359: ** If any data has been written (but not committed) to the log file, this
56360: ** function moves the write-pointer back to the start of the transaction.
56361: **
56362: ** Additionally, the callback function is invoked for each frame written
56363: ** to the WAL since the start of the transaction. If the callback returns
56364: ** other than SQLITE_OK, it is not invoked again and the error code is
56365: ** returned to the caller.
56366: **
56367: ** Otherwise, if the callback function does not return an error, this
56368: ** function returns SQLITE_OK.
56369: */
56370: SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
56371:   int rc = SQLITE_OK;
56372:   if( ALWAYS(pWal->writeLock) ){
56373:     Pgno iMax = pWal->hdr.mxFrame;
56374:     Pgno iFrame;
56375:   
56376:     /* Restore the clients cache of the wal-index header to the state it
56377:     ** was in before the client began writing to the database. 
56378:     */
56379:     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
56380: 
56381:     for(iFrame=pWal->hdr.mxFrame+1; 
56382:         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
56383:         iFrame++
56384:     ){
56385:       /* This call cannot fail. Unless the page for which the page number
56386:       ** is passed as the second argument is (a) in the cache and 
56387:       ** (b) has an outstanding reference, then xUndo is either a no-op
56388:       ** (if (a) is false) or simply expels the page from the cache (if (b)
56389:       ** is false).
56390:       **
56391:       ** If the upper layer is doing a rollback, it is guaranteed that there
56392:       ** are no outstanding references to any page other than page 1. And
56393:       ** page 1 is never written to the log until the transaction is
56394:       ** committed. As a result, the call to xUndo may not fail.
56395:       */
56396:       assert( walFramePgno(pWal, iFrame)!=1 );
56397:       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
56398:     }
56399:     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
56400:   }
56401:   return rc;
56402: }
56403: 
56404: /* 
56405: ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
56406: ** values. This function populates the array with values required to 
56407: ** "rollback" the write position of the WAL handle back to the current 
56408: ** point in the event of a savepoint rollback (via WalSavepointUndo()).
56409: */
56410: SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
56411:   assert( pWal->writeLock );
56412:   aWalData[0] = pWal->hdr.mxFrame;
56413:   aWalData[1] = pWal->hdr.aFrameCksum[0];
56414:   aWalData[2] = pWal->hdr.aFrameCksum[1];
56415:   aWalData[3] = pWal->nCkpt;
56416: }
56417: 
56418: /* 
56419: ** Move the write position of the WAL back to the point identified by
56420: ** the values in the aWalData[] array. aWalData must point to an array
56421: ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
56422: ** by a call to WalSavepoint().
56423: */
56424: SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
56425:   int rc = SQLITE_OK;
56426: 
56427:   assert( pWal->writeLock );
56428:   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
56429: 
56430:   if( aWalData[3]!=pWal->nCkpt ){
56431:     /* This savepoint was opened immediately after the write-transaction
56432:     ** was started. Right after that, the writer decided to wrap around
56433:     ** to the start of the log. Update the savepoint values to match.
56434:     */
56435:     aWalData[0] = 0;
56436:     aWalData[3] = pWal->nCkpt;
56437:   }
56438: 
56439:   if( aWalData[0]<pWal->hdr.mxFrame ){
56440:     pWal->hdr.mxFrame = aWalData[0];
56441:     pWal->hdr.aFrameCksum[0] = aWalData[1];
56442:     pWal->hdr.aFrameCksum[1] = aWalData[2];
56443:     walCleanupHash(pWal);
56444:   }
56445: 
56446:   return rc;
56447: }
56448: 
56449: /*
56450: ** This function is called just before writing a set of frames to the log
56451: ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
56452: ** to the current log file, it is possible to overwrite the start of the
56453: ** existing log file with the new frames (i.e. "reset" the log). If so,
56454: ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
56455: ** unchanged.
56456: **
56457: ** SQLITE_OK is returned if no error is encountered (regardless of whether
56458: ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
56459: ** if an error occurs.
56460: */
56461: static int walRestartLog(Wal *pWal){
56462:   int rc = SQLITE_OK;
56463:   int cnt;
56464: 
56465:   if( pWal->readLock==0 ){
56466:     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56467:     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56468:     if( pInfo->nBackfill>0 ){
56469:       u32 salt1;
56470:       sqlite3_randomness(4, &salt1);
56471:       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56472:       if( rc==SQLITE_OK ){
56473:         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
56474:         ** readers are currently using the WAL), then the transactions
56475:         ** frames will overwrite the start of the existing log. Update the
56476:         ** wal-index header to reflect this.
56477:         **
56478:         ** In theory it would be Ok to update the cache of the header only
56479:         ** at this point. But updating the actual wal-index header is also
56480:         ** safe and means there is no special case for sqlite3WalUndo()
56481:         ** to handle if this transaction is rolled back.  */
56482:         walRestartHdr(pWal, salt1);
56483:         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56484:       }else if( rc!=SQLITE_BUSY ){
56485:         return rc;
56486:       }
56487:     }
56488:     walUnlockShared(pWal, WAL_READ_LOCK(0));
56489:     pWal->readLock = -1;
56490:     cnt = 0;
56491:     do{
56492:       int notUsed;
56493:       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
56494:     }while( rc==WAL_RETRY );
56495:     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
56496:     testcase( (rc&0xff)==SQLITE_IOERR );
56497:     testcase( rc==SQLITE_PROTOCOL );
56498:     testcase( rc==SQLITE_OK );
56499:   }
56500:   return rc;
56501: }
56502: 
56503: /*
56504: ** Information about the current state of the WAL file and where
56505: ** the next fsync should occur - passed from sqlite3WalFrames() into
56506: ** walWriteToLog().
56507: */
56508: typedef struct WalWriter {
56509:   Wal *pWal;                   /* The complete WAL information */
56510:   sqlite3_file *pFd;           /* The WAL file to which we write */
56511:   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
56512:   int syncFlags;               /* Flags for the fsync */
56513:   int szPage;                  /* Size of one page */
56514: } WalWriter;
56515: 
56516: /*
56517: ** Write iAmt bytes of content into the WAL file beginning at iOffset.
56518: ** Do a sync when crossing the p->iSyncPoint boundary.
56519: **
56520: ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
56521: ** first write the part before iSyncPoint, then sync, then write the
56522: ** rest.
56523: */
56524: static int walWriteToLog(
56525:   WalWriter *p,              /* WAL to write to */
56526:   void *pContent,            /* Content to be written */
56527:   int iAmt,                  /* Number of bytes to write */
56528:   sqlite3_int64 iOffset      /* Start writing at this offset */
56529: ){
56530:   int rc;
56531:   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
56532:     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
56533:     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
56534:     if( rc ) return rc;
56535:     iOffset += iFirstAmt;
56536:     iAmt -= iFirstAmt;
56537:     pContent = (void*)(iFirstAmt + (char*)pContent);
56538:     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
56539:     rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
56540:     if( iAmt==0 || rc ) return rc;
56541:   }
56542:   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
56543:   return rc;
56544: }
56545: 
56546: /*
56547: ** Write out a single frame of the WAL
56548: */
56549: static int walWriteOneFrame(
56550:   WalWriter *p,               /* Where to write the frame */
56551:   PgHdr *pPage,               /* The page of the frame to be written */
56552:   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
56553:   sqlite3_int64 iOffset       /* Byte offset at which to write */
56554: ){
56555:   int rc;                         /* Result code from subfunctions */
56556:   void *pData;                    /* Data actually written */
56557:   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
56558: #if defined(SQLITE_HAS_CODEC)
56559:   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
56560: #else
56561:   pData = pPage->pData;
56562: #endif
56563:   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
56564:   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
56565:   if( rc ) return rc;
56566:   /* Write the page data */
56567:   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
56568:   return rc;
56569: }
56570: 
56571: /*
56572: ** This function is called as part of committing a transaction within which
56573: ** one or more frames have been overwritten. It updates the checksums for
56574: ** all frames written to the wal file by the current transaction starting
56575: ** with the earliest to have been overwritten.
56576: **
56577: ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
56578: */
56579: static int walRewriteChecksums(Wal *pWal, u32 iLast){
56580:   const int szPage = pWal->szPage;/* Database page size */
56581:   int rc = SQLITE_OK;             /* Return code */
56582:   u8 *aBuf;                       /* Buffer to load data from wal file into */
56583:   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-headers in */
56584:   u32 iRead;                      /* Next frame to read from wal file */
56585:   i64 iCksumOff;
56586: 
56587:   aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
56588:   if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
56589: 
56590:   /* Find the checksum values to use as input for the recalculating the
56591:   ** first checksum. If the first frame is frame 1 (implying that the current
56592:   ** transaction restarted the wal file), these values must be read from the
56593:   ** wal-file header. Otherwise, read them from the frame header of the
56594:   ** previous frame.  */
56595:   assert( pWal->iReCksum>0 );
56596:   if( pWal->iReCksum==1 ){
56597:     iCksumOff = 24;
56598:   }else{
56599:     iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
56600:   }
56601:   rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
56602:   pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
56603:   pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
56604: 
56605:   iRead = pWal->iReCksum;
56606:   pWal->iReCksum = 0;
56607:   for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
56608:     i64 iOff = walFrameOffset(iRead, szPage);
56609:     rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
56610:     if( rc==SQLITE_OK ){
56611:       u32 iPgno, nDbSize;
56612:       iPgno = sqlite3Get4byte(aBuf);
56613:       nDbSize = sqlite3Get4byte(&aBuf[4]);
56614: 
56615:       walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
56616:       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
56617:     }
56618:   }
56619: 
56620:   sqlite3_free(aBuf);
56621:   return rc;
56622: }
56623: 
56624: /* 
56625: ** Write a set of frames to the log. The caller must hold the write-lock
56626: ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
56627: */
56628: SQLITE_PRIVATE int sqlite3WalFrames(
56629:   Wal *pWal,                      /* Wal handle to write to */
56630:   int szPage,                     /* Database page-size in bytes */
56631:   PgHdr *pList,                   /* List of dirty pages to write */
56632:   Pgno nTruncate,                 /* Database size after this commit */
56633:   int isCommit,                   /* True if this is a commit */
56634:   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
56635: ){
56636:   int rc;                         /* Used to catch return codes */
56637:   u32 iFrame;                     /* Next frame address */
56638:   PgHdr *p;                       /* Iterator to run through pList with. */
56639:   PgHdr *pLast = 0;               /* Last frame in list */
56640:   int nExtra = 0;                 /* Number of extra copies of last page */
56641:   int szFrame;                    /* The size of a single frame */
56642:   i64 iOffset;                    /* Next byte to write in WAL file */
56643:   WalWriter w;                    /* The writer */
56644:   u32 iFirst = 0;                 /* First frame that may be overwritten */
56645:   WalIndexHdr *pLive;             /* Pointer to shared header */
56646: 
56647:   assert( pList );
56648:   assert( pWal->writeLock );
56649: 
56650:   /* If this frame set completes a transaction, then nTruncate>0.  If
56651:   ** nTruncate==0 then this frame set does not complete the transaction. */
56652:   assert( (isCommit!=0)==(nTruncate!=0) );
56653: 
56654: #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
56655:   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
56656:     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
56657:               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
56658:   }
56659: #endif
56660: 
56661:   pLive = (WalIndexHdr*)walIndexHdr(pWal);
56662:   if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
56663:     iFirst = pLive->mxFrame+1;
56664:   }
56665: 
56666:   /* See if it is possible to write these frames into the start of the
56667:   ** log file, instead of appending to it at pWal->hdr.mxFrame.
56668:   */
56669:   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
56670:     return rc;
56671:   }
56672: 
56673:   /* If this is the first frame written into the log, write the WAL
56674:   ** header to the start of the WAL file. See comments at the top of
56675:   ** this source file for a description of the WAL header format.
56676:   */
56677:   iFrame = pWal->hdr.mxFrame;
56678:   if( iFrame==0 ){
56679:     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
56680:     u32 aCksum[2];                /* Checksum for wal-header */
56681: 
56682:     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
56683:     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
56684:     sqlite3Put4byte(&aWalHdr[8], szPage);
56685:     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
56686:     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
56687:     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
56688:     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
56689:     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
56690:     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
56691:     
56692:     pWal->szPage = szPage;
56693:     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
56694:     pWal->hdr.aFrameCksum[0] = aCksum[0];
56695:     pWal->hdr.aFrameCksum[1] = aCksum[1];
56696:     pWal->truncateOnCommit = 1;
56697: 
56698:     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
56699:     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
56700:     if( rc!=SQLITE_OK ){
56701:       return rc;
56702:     }
56703: 
56704:     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
56705:     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
56706:     ** an out-of-order write following a WAL restart could result in
56707:     ** database corruption.  See the ticket:
56708:     **
56709:     **     http://localhost:591/sqlite/info/ff5be73dee
56710:     */
56711:     if( pWal->syncHeader && sync_flags ){
56712:       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
56713:       if( rc ) return rc;
56714:     }
56715:   }
56716:   assert( (int)pWal->szPage==szPage );
56717: 
56718:   /* Setup information needed to write frames into the WAL */
56719:   w.pWal = pWal;
56720:   w.pFd = pWal->pWalFd;
56721:   w.iSyncPoint = 0;
56722:   w.syncFlags = sync_flags;
56723:   w.szPage = szPage;
56724:   iOffset = walFrameOffset(iFrame+1, szPage);
56725:   szFrame = szPage + WAL_FRAME_HDRSIZE;
56726: 
56727:   /* Write all frames into the log file exactly once */
56728:   for(p=pList; p; p=p->pDirty){
56729:     int nDbSize;   /* 0 normally.  Positive == commit flag */
56730: 
56731:     /* Check if this page has already been written into the wal file by
56732:     ** the current transaction. If so, overwrite the existing frame and
56733:     ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that 
56734:     ** checksums must be recomputed when the transaction is committed.  */
56735:     if( iFirst && (p->pDirty || isCommit==0) ){
56736:       u32 iWrite = 0;
56737:       VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
56738:       assert( rc==SQLITE_OK || iWrite==0 );
56739:       if( iWrite>=iFirst ){
56740:         i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
56741:         void *pData;
56742:         if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
56743:           pWal->iReCksum = iWrite;
56744:         }
56745: #if defined(SQLITE_HAS_CODEC)
56746:         if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
56747: #else
56748:         pData = p->pData;
56749: #endif
56750:         rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
56751:         if( rc ) return rc;
56752:         p->flags &= ~PGHDR_WAL_APPEND;
56753:         continue;
56754:       }
56755:     }
56756: 
56757:     iFrame++;
56758:     assert( iOffset==walFrameOffset(iFrame, szPage) );
56759:     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
56760:     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
56761:     if( rc ) return rc;
56762:     pLast = p;
56763:     iOffset += szFrame;
56764:     p->flags |= PGHDR_WAL_APPEND;
56765:   }
56766: 
56767:   /* Recalculate checksums within the wal file if required. */
56768:   if( isCommit && pWal->iReCksum ){
56769:     rc = walRewriteChecksums(pWal, iFrame);
56770:     if( rc ) return rc;
56771:   }
56772: 
56773:   /* If this is the end of a transaction, then we might need to pad
56774:   ** the transaction and/or sync the WAL file.
56775:   **
56776:   ** Padding and syncing only occur if this set of frames complete a
56777:   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
56778:   ** or synchronous==OFF, then no padding or syncing are needed.
56779:   **
56780:   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
56781:   ** needed and only the sync is done.  If padding is needed, then the
56782:   ** final frame is repeated (with its commit mark) until the next sector
56783:   ** boundary is crossed.  Only the part of the WAL prior to the last
56784:   ** sector boundary is synced; the part of the last frame that extends
56785:   ** past the sector boundary is written after the sync.
56786:   */
56787:   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
56788:     int bSync = 1;
56789:     if( pWal->padToSectorBoundary ){
56790:       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
56791:       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
56792:       bSync = (w.iSyncPoint==iOffset);
56793:       testcase( bSync );
56794:       while( iOffset<w.iSyncPoint ){
56795:         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
56796:         if( rc ) return rc;
56797:         iOffset += szFrame;
56798:         nExtra++;
56799:       }
56800:     }
56801:     if( bSync ){
56802:       assert( rc==SQLITE_OK );
56803:       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
56804:     }
56805:   }
56806: 
56807:   /* If this frame set completes the first transaction in the WAL and
56808:   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
56809:   ** journal size limit, if possible.
56810:   */
56811:   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
56812:     i64 sz = pWal->mxWalSize;
56813:     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
56814:       sz = walFrameOffset(iFrame+nExtra+1, szPage);
56815:     }
56816:     walLimitSize(pWal, sz);
56817:     pWal->truncateOnCommit = 0;
56818:   }
56819: 
56820:   /* Append data to the wal-index. It is not necessary to lock the 
56821:   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
56822:   ** guarantees that there are no other writers, and no data that may
56823:   ** be in use by existing readers is being overwritten.
56824:   */
56825:   iFrame = pWal->hdr.mxFrame;
56826:   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
56827:     if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
56828:     iFrame++;
56829:     rc = walIndexAppend(pWal, iFrame, p->pgno);
56830:   }
56831:   while( rc==SQLITE_OK && nExtra>0 ){
56832:     iFrame++;
56833:     nExtra--;
56834:     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
56835:   }
56836: 
56837:   if( rc==SQLITE_OK ){
56838:     /* Update the private copy of the header. */
56839:     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56840:     testcase( szPage<=32768 );
56841:     testcase( szPage>=65536 );
56842:     pWal->hdr.mxFrame = iFrame;
56843:     if( isCommit ){
56844:       pWal->hdr.iChange++;
56845:       pWal->hdr.nPage = nTruncate;
56846:     }
56847:     /* If this is a commit, update the wal-index header too. */
56848:     if( isCommit ){
56849:       walIndexWriteHdr(pWal);
56850:       pWal->iCallback = iFrame;
56851:     }
56852:   }
56853: 
56854:   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
56855:   return rc;
56856: }
56857: 
56858: /* 
56859: ** This routine is called to implement sqlite3_wal_checkpoint() and
56860: ** related interfaces.
56861: **
56862: ** Obtain a CHECKPOINT lock and then backfill as much information as
56863: ** we can from WAL into the database.
56864: **
56865: ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
56866: ** callback. In this case this function runs a blocking checkpoint.
56867: */
56868: SQLITE_PRIVATE int sqlite3WalCheckpoint(
56869:   Wal *pWal,                      /* Wal connection */
56870:   int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
56871:   int (*xBusy)(void*),            /* Function to call when busy */
56872:   void *pBusyArg,                 /* Context argument for xBusyHandler */
56873:   int sync_flags,                 /* Flags to sync db file with (or 0) */
56874:   int nBuf,                       /* Size of temporary buffer */
56875:   u8 *zBuf,                       /* Temporary buffer to use */
56876:   int *pnLog,                     /* OUT: Number of frames in WAL */
56877:   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
56878: ){
56879:   int rc;                         /* Return code */
56880:   int isChanged = 0;              /* True if a new wal-index header is loaded */
56881:   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
56882:   int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
56883: 
56884:   assert( pWal->ckptLock==0 );
56885:   assert( pWal->writeLock==0 );
56886: 
56887:   /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56888:   ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56889:   assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56890: 
56891:   if( pWal->readOnly ) return SQLITE_READONLY;
56892:   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
56893: 
56894:   /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive 
56895:   ** "checkpoint" lock on the database file. */
56896:   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
56897:   if( rc ){
56898:     /* EVIDENCE-OF: R-10421-19736 If any other process is running a
56899:     ** checkpoint operation at the same time, the lock cannot be obtained and
56900:     ** SQLITE_BUSY is returned.
56901:     ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
56902:     ** it will not be invoked in this case.
56903:     */
56904:     testcase( rc==SQLITE_BUSY );
56905:     testcase( xBusy!=0 );
56906:     return rc;
56907:   }
56908:   pWal->ckptLock = 1;
56909: 
56910:   /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
56911:   ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
56912:   ** file.
56913:   **
56914:   ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
56915:   ** immediately, and a busy-handler is configured, it is invoked and the
56916:   ** writer lock retried until either the busy-handler returns 0 or the
56917:   ** lock is successfully obtained.
56918:   */
56919:   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
56920:     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
56921:     if( rc==SQLITE_OK ){
56922:       pWal->writeLock = 1;
56923:     }else if( rc==SQLITE_BUSY ){
56924:       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
56925:       xBusy2 = 0;
56926:       rc = SQLITE_OK;
56927:     }
56928:   }
56929: 
56930:   /* Read the wal-index header. */
56931:   if( rc==SQLITE_OK ){
56932:     rc = walIndexReadHdr(pWal, &isChanged);
56933:     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
56934:       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
56935:     }
56936:   }
56937: 
56938:   /* Copy data from the log to the database file. */
56939:   if( rc==SQLITE_OK ){
56940: 
56941:     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
56942:       rc = SQLITE_CORRUPT_BKPT;
56943:     }else{
56944:       rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
56945:     }
56946: 
56947:     /* If no error occurred, set the output variables. */
56948:     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
56949:       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
56950:       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
56951:     }
56952:   }
56953: 
56954:   if( isChanged ){
56955:     /* If a new wal-index header was loaded before the checkpoint was 
56956:     ** performed, then the pager-cache associated with pWal is now
56957:     ** out of date. So zero the cached wal-index header to ensure that
56958:     ** next time the pager opens a snapshot on this database it knows that
56959:     ** the cache needs to be reset.
56960:     */
56961:     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
56962:   }
56963: 
56964:   /* Release the locks. */
56965:   sqlite3WalEndWriteTransaction(pWal);
56966:   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
56967:   pWal->ckptLock = 0;
56968:   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
56969:   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
56970: }
56971: 
56972: /* Return the value to pass to a sqlite3_wal_hook callback, the
56973: ** number of frames in the WAL at the point of the last commit since
56974: ** sqlite3WalCallback() was called.  If no commits have occurred since
56975: ** the last call, then return 0.
56976: */
56977: SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
56978:   u32 ret = 0;
56979:   if( pWal ){
56980:     ret = pWal->iCallback;
56981:     pWal->iCallback = 0;
56982:   }
56983:   return (int)ret;
56984: }
56985: 
56986: /*
56987: ** This function is called to change the WAL subsystem into or out
56988: ** of locking_mode=EXCLUSIVE.
56989: **
56990: ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
56991: ** into locking_mode=NORMAL.  This means that we must acquire a lock
56992: ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
56993: ** or if the acquisition of the lock fails, then return 0.  If the
56994: ** transition out of exclusive-mode is successful, return 1.  This
56995: ** operation must occur while the pager is still holding the exclusive
56996: ** lock on the main database file.
56997: **
56998: ** If op is one, then change from locking_mode=NORMAL into 
56999: ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
57000: ** be released.  Return 1 if the transition is made and 0 if the
57001: ** WAL is already in exclusive-locking mode - meaning that this
57002: ** routine is a no-op.  The pager must already hold the exclusive lock
57003: ** on the main database file before invoking this operation.
57004: **
57005: ** If op is negative, then do a dry-run of the op==1 case but do
57006: ** not actually change anything. The pager uses this to see if it
57007: ** should acquire the database exclusive lock prior to invoking
57008: ** the op==1 case.
57009: */
57010: SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
57011:   int rc;
57012:   assert( pWal->writeLock==0 );
57013:   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
57014: 
57015:   /* pWal->readLock is usually set, but might be -1 if there was a 
57016:   ** prior error while attempting to acquire are read-lock. This cannot 
57017:   ** happen if the connection is actually in exclusive mode (as no xShmLock
57018:   ** locks are taken in this case). Nor should the pager attempt to
57019:   ** upgrade to exclusive-mode following such an error.
57020:   */
57021:   assert( pWal->readLock>=0 || pWal->lockError );
57022:   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
57023: 
57024:   if( op==0 ){
57025:     if( pWal->exclusiveMode ){
57026:       pWal->exclusiveMode = 0;
57027:       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
57028:         pWal->exclusiveMode = 1;
57029:       }
57030:       rc = pWal->exclusiveMode==0;
57031:     }else{
57032:       /* Already in locking_mode=NORMAL */
57033:       rc = 0;
57034:     }
57035:   }else if( op>0 ){
57036:     assert( pWal->exclusiveMode==0 );
57037:     assert( pWal->readLock>=0 );
57038:     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
57039:     pWal->exclusiveMode = 1;
57040:     rc = 1;
57041:   }else{
57042:     rc = pWal->exclusiveMode==0;
57043:   }
57044:   return rc;
57045: }
57046: 
57047: /* 
57048: ** Return true if the argument is non-NULL and the WAL module is using
57049: ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
57050: ** WAL module is using shared-memory, return false. 
57051: */
57052: SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
57053:   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
57054: }
57055: 
57056: #ifdef SQLITE_ENABLE_SNAPSHOT
57057: /* Create a snapshot object.  The content of a snapshot is opaque to
57058: ** every other subsystem, so the WAL module can put whatever it needs
57059: ** in the object.
57060: */
57061: SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
57062:   int rc = SQLITE_OK;
57063:   WalIndexHdr *pRet;
57064: 
57065:   assert( pWal->readLock>=0 && pWal->writeLock==0 );
57066: 
57067:   pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
57068:   if( pRet==0 ){
57069:     rc = SQLITE_NOMEM_BKPT;
57070:   }else{
57071:     memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
57072:     *ppSnapshot = (sqlite3_snapshot*)pRet;
57073:   }
57074: 
57075:   return rc;
57076: }
57077: 
57078: /* Try to open on pSnapshot when the next read-transaction starts
57079: */
57080: SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
57081:   pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
57082: }
57083: 
57084: /* 
57085: ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
57086: ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
57087: */
57088: SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
57089:   WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
57090:   WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
57091: 
57092:   /* aSalt[0] is a copy of the value stored in the wal file header. It
57093:   ** is incremented each time the wal file is restarted.  */
57094:   if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
57095:   if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
57096:   if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
57097:   if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
57098:   return 0;
57099: }
57100: #endif /* SQLITE_ENABLE_SNAPSHOT */
57101: 
57102: #ifdef SQLITE_ENABLE_ZIPVFS
57103: /*
57104: ** If the argument is not NULL, it points to a Wal object that holds a
57105: ** read-lock. This function returns the database page-size if it is known,
57106: ** or zero if it is not (or if pWal is NULL).
57107: */
57108: SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
57109:   assert( pWal==0 || pWal->readLock>=0 );
57110:   return (pWal ? pWal->szPage : 0);
57111: }
57112: #endif
57113: 
57114: /* Return the sqlite3_file object for the WAL file
57115: */
57116: SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
57117:   return pWal->pWalFd;
57118: }
57119: 
57120: #endif /* #ifndef SQLITE_OMIT_WAL */
57121: 
57122: /************** End of wal.c *************************************************/
57123: /************** Begin file btmutex.c *****************************************/
57124: /*
57125: ** 2007 August 27
57126: **
57127: ** The author disclaims copyright to this source code.  In place of
57128: ** a legal notice, here is a blessing:
57129: **
57130: **    May you do good and not evil.
57131: **    May you find forgiveness for yourself and forgive others.
57132: **    May you share freely, never taking more than you give.
57133: **
57134: *************************************************************************
57135: **
57136: ** This file contains code used to implement mutexes on Btree objects.
57137: ** This code really belongs in btree.c.  But btree.c is getting too
57138: ** big and we want to break it down some.  This packaged seemed like
57139: ** a good breakout.
57140: */
57141: /************** Include btreeInt.h in the middle of btmutex.c ****************/
57142: /************** Begin file btreeInt.h ****************************************/
57143: /*
57144: ** 2004 April 6
57145: **
57146: ** The author disclaims copyright to this source code.  In place of
57147: ** a legal notice, here is a blessing:
57148: **
57149: **    May you do good and not evil.
57150: **    May you find forgiveness for yourself and forgive others.
57151: **    May you share freely, never taking more than you give.
57152: **
57153: *************************************************************************
57154: ** This file implements an external (disk-based) database using BTrees.
57155: ** For a detailed discussion of BTrees, refer to
57156: **
57157: **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
57158: **     "Sorting And Searching", pages 473-480. Addison-Wesley
57159: **     Publishing Company, Reading, Massachusetts.
57160: **
57161: ** The basic idea is that each page of the file contains N database
57162: ** entries and N+1 pointers to subpages.
57163: **
57164: **   ----------------------------------------------------------------
57165: **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
57166: **   ----------------------------------------------------------------
57167: **
57168: ** All of the keys on the page that Ptr(0) points to have values less
57169: ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
57170: ** values greater than Key(0) and less than Key(1).  All of the keys
57171: ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
57172: ** so forth.
57173: **
57174: ** Finding a particular key requires reading O(log(M)) pages from the 
57175: ** disk where M is the number of entries in the tree.
57176: **
57177: ** In this implementation, a single file can hold one or more separate 
57178: ** BTrees.  Each BTree is identified by the index of its root page.  The
57179: ** key and data for any entry are combined to form the "payload".  A
57180: ** fixed amount of payload can be carried directly on the database
57181: ** page.  If the payload is larger than the preset amount then surplus
57182: ** bytes are stored on overflow pages.  The payload for an entry
57183: ** and the preceding pointer are combined to form a "Cell".  Each 
57184: ** page has a small header which contains the Ptr(N) pointer and other
57185: ** information such as the size of key and data.
57186: **
57187: ** FORMAT DETAILS
57188: **
57189: ** The file is divided into pages.  The first page is called page 1,
57190: ** the second is page 2, and so forth.  A page number of zero indicates
57191: ** "no such page".  The page size can be any power of 2 between 512 and 65536.
57192: ** Each page can be either a btree page, a freelist page, an overflow
57193: ** page, or a pointer-map page.
57194: **
57195: ** The first page is always a btree page.  The first 100 bytes of the first
57196: ** page contain a special header (the "file header") that describes the file.
57197: ** The format of the file header is as follows:
57198: **
57199: **   OFFSET   SIZE    DESCRIPTION
57200: **      0      16     Header string: "SQLite format 3\000"
57201: **     16       2     Page size in bytes.  (1 means 65536)
57202: **     18       1     File format write version
57203: **     19       1     File format read version
57204: **     20       1     Bytes of unused space at the end of each page
57205: **     21       1     Max embedded payload fraction (must be 64)
57206: **     22       1     Min embedded payload fraction (must be 32)
57207: **     23       1     Min leaf payload fraction (must be 32)
57208: **     24       4     File change counter
57209: **     28       4     Reserved for future use
57210: **     32       4     First freelist page
57211: **     36       4     Number of freelist pages in the file
57212: **     40      60     15 4-byte meta values passed to higher layers
57213: **
57214: **     40       4     Schema cookie
57215: **     44       4     File format of schema layer
57216: **     48       4     Size of page cache
57217: **     52       4     Largest root-page (auto/incr_vacuum)
57218: **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
57219: **     60       4     User version
57220: **     64       4     Incremental vacuum mode
57221: **     68       4     Application-ID
57222: **     72      20     unused
57223: **     92       4     The version-valid-for number
57224: **     96       4     SQLITE_VERSION_NUMBER
57225: **
57226: ** All of the integer values are big-endian (most significant byte first).
57227: **
57228: ** The file change counter is incremented when the database is changed
57229: ** This counter allows other processes to know when the file has changed
57230: ** and thus when they need to flush their cache.
57231: **
57232: ** The max embedded payload fraction is the amount of the total usable
57233: ** space in a page that can be consumed by a single cell for standard
57234: ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
57235: ** is to limit the maximum cell size so that at least 4 cells will fit
57236: ** on one page.  Thus the default max embedded payload fraction is 64.
57237: **
57238: ** If the payload for a cell is larger than the max payload, then extra
57239: ** payload is spilled to overflow pages.  Once an overflow page is allocated,
57240: ** as many bytes as possible are moved into the overflow pages without letting
57241: ** the cell size drop below the min embedded payload fraction.
57242: **
57243: ** The min leaf payload fraction is like the min embedded payload fraction
57244: ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
57245: ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
57246: ** not specified in the header.
57247: **
57248: ** Each btree pages is divided into three sections:  The header, the
57249: ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
57250: ** file header that occurs before the page header.
57251: **
57252: **      |----------------|
57253: **      | file header    |   100 bytes.  Page 1 only.
57254: **      |----------------|
57255: **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
57256: **      |----------------|
57257: **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
57258: **      | array          |   |  Grows downward
57259: **      |                |   v
57260: **      |----------------|
57261: **      | unallocated    |
57262: **      | space          |
57263: **      |----------------|   ^  Grows upwards
57264: **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
57265: **      | area           |   |  and free space fragments.
57266: **      |----------------|
57267: **
57268: ** The page headers looks like this:
57269: **
57270: **   OFFSET   SIZE     DESCRIPTION
57271: **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
57272: **      1       2      byte offset to the first freeblock
57273: **      3       2      number of cells on this page
57274: **      5       2      first byte of the cell content area
57275: **      7       1      number of fragmented free bytes
57276: **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
57277: **
57278: ** The flags define the format of this btree page.  The leaf flag means that
57279: ** this page has no children.  The zerodata flag means that this page carries
57280: ** only keys and no data.  The intkey flag means that the key is an integer
57281: ** which is stored in the key size entry of the cell header rather than in
57282: ** the payload area.
57283: **
57284: ** The cell pointer array begins on the first byte after the page header.
57285: ** The cell pointer array contains zero or more 2-byte numbers which are
57286: ** offsets from the beginning of the page to the cell content in the cell
57287: ** content area.  The cell pointers occur in sorted order.  The system strives
57288: ** to keep free space after the last cell pointer so that new cells can
57289: ** be easily added without having to defragment the page.
57290: **
57291: ** Cell content is stored at the very end of the page and grows toward the
57292: ** beginning of the page.
57293: **
57294: ** Unused space within the cell content area is collected into a linked list of
57295: ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
57296: ** to the first freeblock is given in the header.  Freeblocks occur in
57297: ** increasing order.  Because a freeblock must be at least 4 bytes in size,
57298: ** any group of 3 or fewer unused bytes in the cell content area cannot
57299: ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
57300: ** a fragment.  The total number of bytes in all fragments is recorded.
57301: ** in the page header at offset 7.
57302: **
57303: **    SIZE    DESCRIPTION
57304: **      2     Byte offset of the next freeblock
57305: **      2     Bytes in this freeblock
57306: **
57307: ** Cells are of variable length.  Cells are stored in the cell content area at
57308: ** the end of the page.  Pointers to the cells are in the cell pointer array
57309: ** that immediately follows the page header.  Cells is not necessarily
57310: ** contiguous or in order, but cell pointers are contiguous and in order.
57311: **
57312: ** Cell content makes use of variable length integers.  A variable
57313: ** length integer is 1 to 9 bytes where the lower 7 bits of each 
57314: ** byte are used.  The integer consists of all bytes that have bit 8 set and
57315: ** the first byte with bit 8 clear.  The most significant byte of the integer
57316: ** appears first.  A variable-length integer may not be more than 9 bytes long.
57317: ** As a special case, all 8 bytes of the 9th byte are used as data.  This
57318: ** allows a 64-bit integer to be encoded in 9 bytes.
57319: **
57320: **    0x00                      becomes  0x00000000
57321: **    0x7f                      becomes  0x0000007f
57322: **    0x81 0x00                 becomes  0x00000080
57323: **    0x82 0x00                 becomes  0x00000100
57324: **    0x80 0x7f                 becomes  0x0000007f
57325: **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
57326: **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
57327: **
57328: ** Variable length integers are used for rowids and to hold the number of
57329: ** bytes of key and data in a btree cell.
57330: **
57331: ** The content of a cell looks like this:
57332: **
57333: **    SIZE    DESCRIPTION
57334: **      4     Page number of the left child. Omitted if leaf flag is set.
57335: **     var    Number of bytes of data. Omitted if the zerodata flag is set.
57336: **     var    Number of bytes of key. Or the key itself if intkey flag is set.
57337: **      *     Payload
57338: **      4     First page of the overflow chain.  Omitted if no overflow
57339: **
57340: ** Overflow pages form a linked list.  Each page except the last is completely
57341: ** filled with data (pagesize - 4 bytes).  The last page can have as little
57342: ** as 1 byte of data.
57343: **
57344: **    SIZE    DESCRIPTION
57345: **      4     Page number of next overflow page
57346: **      *     Data
57347: **
57348: ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
57349: ** file header points to the first in a linked list of trunk page.  Each trunk
57350: ** page points to multiple leaf pages.  The content of a leaf page is
57351: ** unspecified.  A trunk page looks like this:
57352: **
57353: **    SIZE    DESCRIPTION
57354: **      4     Page number of next trunk page
57355: **      4     Number of leaf pointers on this page
57356: **      *     zero or more pages numbers of leaves
57357: */
57358: /* #include "sqliteInt.h" */
57359: 
57360: 
57361: /* The following value is the maximum cell size assuming a maximum page
57362: ** size give above.
57363: */
57364: #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
57365: 
57366: /* The maximum number of cells on a single page of the database.  This
57367: ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
57368: ** plus 2 bytes for the index to the cell in the page header).  Such
57369: ** small cells will be rare, but they are possible.
57370: */
57371: #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
57372: 
57373: /* Forward declarations */
57374: typedef struct MemPage MemPage;
57375: typedef struct BtLock BtLock;
57376: typedef struct CellInfo CellInfo;
57377: 
57378: /*
57379: ** This is a magic string that appears at the beginning of every
57380: ** SQLite database in order to identify the file as a real database.
57381: **
57382: ** You can change this value at compile-time by specifying a
57383: ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
57384: ** header must be exactly 16 bytes including the zero-terminator so
57385: ** the string itself should be 15 characters long.  If you change
57386: ** the header, then your custom library will not be able to read 
57387: ** databases generated by the standard tools and the standard tools
57388: ** will not be able to read databases created by your custom library.
57389: */
57390: #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
57391: #  define SQLITE_FILE_HEADER "SQLite format 3"
57392: #endif
57393: 
57394: /*
57395: ** Page type flags.  An ORed combination of these flags appear as the
57396: ** first byte of on-disk image of every BTree page.
57397: */
57398: #define PTF_INTKEY    0x01
57399: #define PTF_ZERODATA  0x02
57400: #define PTF_LEAFDATA  0x04
57401: #define PTF_LEAF      0x08
57402: 
57403: /*
57404: ** As each page of the file is loaded into memory, an instance of the following
57405: ** structure is appended and initialized to zero.  This structure stores
57406: ** information about the page that is decoded from the raw file page.
57407: **
57408: ** The pParent field points back to the parent page.  This allows us to
57409: ** walk up the BTree from any leaf to the root.  Care must be taken to
57410: ** unref() the parent page pointer when this page is no longer referenced.
57411: ** The pageDestructor() routine handles that chore.
57412: **
57413: ** Access to all fields of this structure is controlled by the mutex
57414: ** stored in MemPage.pBt->mutex.
57415: */
57416: struct MemPage {
57417:   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
57418:   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
57419:   u8 intKey;           /* True if table b-trees.  False for index b-trees */
57420:   u8 intKeyLeaf;       /* True if the leaf of an intKey table */
57421:   u8 leaf;             /* True if a leaf page */
57422:   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
57423:   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
57424:   u8 max1bytePayload;  /* min(maxLocal,127) */
57425:   u8 bBusy;            /* Prevent endless loops on corrupt database files */
57426:   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
57427:   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
57428:   u16 cellOffset;      /* Index in aData of first cell pointer */
57429:   u16 nFree;           /* Number of free bytes on the page */
57430:   u16 nCell;           /* Number of cells on this page, local and ovfl */
57431:   u16 maskPage;        /* Mask for page offset */
57432:   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
57433:                        ** non-overflow cell */
57434:   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
57435:   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
57436:   u8 *aData;           /* Pointer to disk image of the page data */
57437:   u8 *aDataEnd;        /* One byte past the end of usable data */
57438:   u8 *aCellIdx;        /* The cell index area */
57439:   u8 *aDataOfst;       /* Same as aData for leaves.  aData+4 for interior */
57440:   DbPage *pDbPage;     /* Pager page handle */
57441:   u16 (*xCellSize)(MemPage*,u8*);             /* cellSizePtr method */
57442:   void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
57443:   Pgno pgno;           /* Page number for this page */
57444: };
57445: 
57446: /*
57447: ** The in-memory image of a disk page has the auxiliary information appended
57448: ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
57449: ** that extra information.
57450: */
57451: #define EXTRA_SIZE sizeof(MemPage)
57452: 
57453: /*
57454: ** A linked list of the following structures is stored at BtShared.pLock.
57455: ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
57456: ** is opened on the table with root page BtShared.iTable. Locks are removed
57457: ** from this list when a transaction is committed or rolled back, or when
57458: ** a btree handle is closed.
57459: */
57460: struct BtLock {
57461:   Btree *pBtree;        /* Btree handle holding this lock */
57462:   Pgno iTable;          /* Root page of table */
57463:   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
57464:   BtLock *pNext;        /* Next in BtShared.pLock list */
57465: };
57466: 
57467: /* Candidate values for BtLock.eLock */
57468: #define READ_LOCK     1
57469: #define WRITE_LOCK    2
57470: 
57471: /* A Btree handle
57472: **
57473: ** A database connection contains a pointer to an instance of
57474: ** this object for every database file that it has open.  This structure
57475: ** is opaque to the database connection.  The database connection cannot
57476: ** see the internals of this structure and only deals with pointers to
57477: ** this structure.
57478: **
57479: ** For some database files, the same underlying database cache might be 
57480: ** shared between multiple connections.  In that case, each connection
57481: ** has it own instance of this object.  But each instance of this object
57482: ** points to the same BtShared object.  The database cache and the
57483: ** schema associated with the database file are all contained within
57484: ** the BtShared object.
57485: **
57486: ** All fields in this structure are accessed under sqlite3.mutex.
57487: ** The pBt pointer itself may not be changed while there exists cursors 
57488: ** in the referenced BtShared that point back to this Btree since those
57489: ** cursors have to go through this Btree to find their BtShared and
57490: ** they often do so without holding sqlite3.mutex.
57491: */
57492: struct Btree {
57493:   sqlite3 *db;       /* The database connection holding this btree */
57494:   BtShared *pBt;     /* Sharable content of this btree */
57495:   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
57496:   u8 sharable;       /* True if we can share pBt with another db */
57497:   u8 locked;         /* True if db currently has pBt locked */
57498:   u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
57499:   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
57500:   int nBackup;       /* Number of backup operations reading this btree */
57501:   u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
57502:   Btree *pNext;      /* List of other sharable Btrees from the same db */
57503:   Btree *pPrev;      /* Back pointer of the same list */
57504: #ifndef SQLITE_OMIT_SHARED_CACHE
57505:   BtLock lock;       /* Object used to lock page 1 */
57506: #endif
57507: };
57508: 
57509: /*
57510: ** Btree.inTrans may take one of the following values.
57511: **
57512: ** If the shared-data extension is enabled, there may be multiple users
57513: ** of the Btree structure. At most one of these may open a write transaction,
57514: ** but any number may have active read transactions.
57515: */
57516: #define TRANS_NONE  0
57517: #define TRANS_READ  1
57518: #define TRANS_WRITE 2
57519: 
57520: /*
57521: ** An instance of this object represents a single database file.
57522: ** 
57523: ** A single database file can be in use at the same time by two
57524: ** or more database connections.  When two or more connections are
57525: ** sharing the same database file, each connection has it own
57526: ** private Btree object for the file and each of those Btrees points
57527: ** to this one BtShared object.  BtShared.nRef is the number of
57528: ** connections currently sharing this database file.
57529: **
57530: ** Fields in this structure are accessed under the BtShared.mutex
57531: ** mutex, except for nRef and pNext which are accessed under the
57532: ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
57533: ** may not be modified once it is initially set as long as nRef>0.
57534: ** The pSchema field may be set once under BtShared.mutex and
57535: ** thereafter is unchanged as long as nRef>0.
57536: **
57537: ** isPending:
57538: **
57539: **   If a BtShared client fails to obtain a write-lock on a database
57540: **   table (because there exists one or more read-locks on the table),
57541: **   the shared-cache enters 'pending-lock' state and isPending is
57542: **   set to true.
57543: **
57544: **   The shared-cache leaves the 'pending lock' state when either of
57545: **   the following occur:
57546: **
57547: **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
57548: **     2) The number of locks held by other connections drops to zero.
57549: **
57550: **   while in the 'pending-lock' state, no connection may start a new
57551: **   transaction.
57552: **
57553: **   This feature is included to help prevent writer-starvation.
57554: */
57555: struct BtShared {
57556:   Pager *pPager;        /* The page cache */
57557:   sqlite3 *db;          /* Database connection currently using this Btree */
57558:   BtCursor *pCursor;    /* A list of all open cursors */
57559:   MemPage *pPage1;      /* First page of the database */
57560:   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
57561: #ifndef SQLITE_OMIT_AUTOVACUUM
57562:   u8 autoVacuum;        /* True if auto-vacuum is enabled */
57563:   u8 incrVacuum;        /* True if incr-vacuum is enabled */
57564:   u8 bDoTruncate;       /* True to truncate db on commit */
57565: #endif
57566:   u8 inTransaction;     /* Transaction state */
57567:   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
57568: #ifdef SQLITE_HAS_CODEC
57569:   u8 optimalReserve;    /* Desired amount of reserved space per page */
57570: #endif
57571:   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
57572:   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
57573:   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
57574:   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
57575:   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
57576:   u32 pageSize;         /* Total number of bytes on a page */
57577:   u32 usableSize;       /* Number of usable bytes on each page */
57578:   int nTransaction;     /* Number of open transactions (read + write) */
57579:   u32 nPage;            /* Number of pages in the database */
57580:   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
57581:   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
57582:   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
57583:   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
57584: #ifndef SQLITE_OMIT_SHARED_CACHE
57585:   int nRef;             /* Number of references to this structure */
57586:   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
57587:   BtLock *pLock;        /* List of locks held on this shared-btree struct */
57588:   Btree *pWriter;       /* Btree with currently open write transaction */
57589: #endif
57590:   u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
57591: };
57592: 
57593: /*
57594: ** Allowed values for BtShared.btsFlags
57595: */
57596: #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
57597: #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
57598: #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
57599: #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
57600: #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
57601: #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
57602: #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
57603: 
57604: /*
57605: ** An instance of the following structure is used to hold information
57606: ** about a cell.  The parseCellPtr() function fills in this structure
57607: ** based on information extract from the raw disk page.
57608: */
57609: struct CellInfo {
57610:   i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
57611:   u8 *pPayload;  /* Pointer to the start of payload */
57612:   u32 nPayload;  /* Bytes of payload */
57613:   u16 nLocal;    /* Amount of payload held locally, not on overflow */
57614:   u16 nSize;     /* Size of the cell content on the main b-tree page */
57615: };
57616: 
57617: /*
57618: ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
57619: ** this will be declared corrupt. This value is calculated based on a
57620: ** maximum database size of 2^31 pages a minimum fanout of 2 for a
57621: ** root-node and 3 for all other internal nodes.
57622: **
57623: ** If a tree that appears to be taller than this is encountered, it is
57624: ** assumed that the database is corrupt.
57625: */
57626: #define BTCURSOR_MAX_DEPTH 20
57627: 
57628: /*
57629: ** A cursor is a pointer to a particular entry within a particular
57630: ** b-tree within a database file.
57631: **
57632: ** The entry is identified by its MemPage and the index in
57633: ** MemPage.aCell[] of the entry.
57634: **
57635: ** A single database file can be shared by two more database connections,
57636: ** but cursors cannot be shared.  Each cursor is associated with a
57637: ** particular database connection identified BtCursor.pBtree.db.
57638: **
57639: ** Fields in this structure are accessed under the BtShared.mutex
57640: ** found at self->pBt->mutex. 
57641: **
57642: ** skipNext meaning:
57643: **    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
57644: **    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
57645: **    eState==FAULT:                   Cursor fault with skipNext as error code.
57646: */
57647: struct BtCursor {
57648:   Btree *pBtree;            /* The Btree to which this cursor belongs */
57649:   BtShared *pBt;            /* The BtShared this cursor points to */
57650:   BtCursor *pNext;          /* Forms a linked list of all cursors */
57651:   Pgno *aOverflow;          /* Cache of overflow page locations */
57652:   CellInfo info;            /* A parse of the cell we are pointing at */
57653:   i64 nKey;                 /* Size of pKey, or last integer key */
57654:   void *pKey;               /* Saved key that was cursor last known position */
57655:   Pgno pgnoRoot;            /* The root page of this tree */
57656:   int nOvflAlloc;           /* Allocated size of aOverflow[] array */
57657:   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
57658:                    ** Error code if eState==CURSOR_FAULT */
57659:   u8 curFlags;              /* zero or more BTCF_* flags defined below */
57660:   u8 curPagerFlags;         /* Flags to send to sqlite3PagerGet() */
57661:   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
57662:   u8 hints;                 /* As configured by CursorSetHints() */
57663:   /* All fields above are zeroed when the cursor is allocated.  See
57664:   ** sqlite3BtreeCursorZero().  Fields that follow must be manually
57665:   ** initialized. */
57666:   i8 iPage;                 /* Index of current page in apPage */
57667:   u8 curIntKey;             /* Value of apPage[0]->intKey */
57668:   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
57669:   void *padding1;           /* Make object size a multiple of 16 */
57670:   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
57671:   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
57672: };
57673: 
57674: /*
57675: ** Legal values for BtCursor.curFlags
57676: */
57677: #define BTCF_WriteFlag    0x01   /* True if a write cursor */
57678: #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
57679: #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
57680: #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
57681: #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
57682: #define BTCF_Multiple     0x20   /* Maybe another cursor on the same btree */
57683: 
57684: /*
57685: ** Potential values for BtCursor.eState.
57686: **
57687: ** CURSOR_INVALID:
57688: **   Cursor does not point to a valid entry. This can happen (for example) 
57689: **   because the table is empty or because BtreeCursorFirst() has not been
57690: **   called.
57691: **
57692: ** CURSOR_VALID:
57693: **   Cursor points to a valid entry. getPayload() etc. may be called.
57694: **
57695: ** CURSOR_SKIPNEXT:
57696: **   Cursor is valid except that the Cursor.skipNext field is non-zero
57697: **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
57698: **   operation should be a no-op.
57699: **
57700: ** CURSOR_REQUIRESEEK:
57701: **   The table that this cursor was opened on still exists, but has been 
57702: **   modified since the cursor was last used. The cursor position is saved
57703: **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
57704: **   this state, restoreCursorPosition() can be called to attempt to
57705: **   seek the cursor to the saved position.
57706: **
57707: ** CURSOR_FAULT:
57708: **   An unrecoverable error (an I/O error or a malloc failure) has occurred
57709: **   on a different connection that shares the BtShared cache with this
57710: **   cursor.  The error has left the cache in an inconsistent state.
57711: **   Do nothing else with this cursor.  Any attempt to use the cursor
57712: **   should return the error code stored in BtCursor.skipNext
57713: */
57714: #define CURSOR_INVALID           0
57715: #define CURSOR_VALID             1
57716: #define CURSOR_SKIPNEXT          2
57717: #define CURSOR_REQUIRESEEK       3
57718: #define CURSOR_FAULT             4
57719: 
57720: /* 
57721: ** The database page the PENDING_BYTE occupies. This page is never used.
57722: */
57723: # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
57724: 
57725: /*
57726: ** These macros define the location of the pointer-map entry for a 
57727: ** database page. The first argument to each is the number of usable
57728: ** bytes on each page of the database (often 1024). The second is the
57729: ** page number to look up in the pointer map.
57730: **
57731: ** PTRMAP_PAGENO returns the database page number of the pointer-map
57732: ** page that stores the required pointer. PTRMAP_PTROFFSET returns
57733: ** the offset of the requested map entry.
57734: **
57735: ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
57736: ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
57737: ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
57738: ** this test.
57739: */
57740: #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
57741: #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
57742: #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
57743: 
57744: /*
57745: ** The pointer map is a lookup table that identifies the parent page for
57746: ** each child page in the database file.  The parent page is the page that
57747: ** contains a pointer to the child.  Every page in the database contains
57748: ** 0 or 1 parent pages.  (In this context 'database page' refers
57749: ** to any page that is not part of the pointer map itself.)  Each pointer map
57750: ** entry consists of a single byte 'type' and a 4 byte parent page number.
57751: ** The PTRMAP_XXX identifiers below are the valid types.
57752: **
57753: ** The purpose of the pointer map is to facility moving pages from one
57754: ** position in the file to another as part of autovacuum.  When a page
57755: ** is moved, the pointer in its parent must be updated to point to the
57756: ** new location.  The pointer map is used to locate the parent page quickly.
57757: **
57758: ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
57759: **                  used in this case.
57760: **
57761: ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
57762: **                  is not used in this case.
57763: **
57764: ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
57765: **                   overflow pages. The page number identifies the page that
57766: **                   contains the cell with a pointer to this overflow page.
57767: **
57768: ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
57769: **                   overflow pages. The page-number identifies the previous
57770: **                   page in the overflow page list.
57771: **
57772: ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
57773: **               identifies the parent page in the btree.
57774: */
57775: #define PTRMAP_ROOTPAGE 1
57776: #define PTRMAP_FREEPAGE 2
57777: #define PTRMAP_OVERFLOW1 3
57778: #define PTRMAP_OVERFLOW2 4
57779: #define PTRMAP_BTREE 5
57780: 
57781: /* A bunch of assert() statements to check the transaction state variables
57782: ** of handle p (type Btree*) are internally consistent.
57783: */
57784: #define btreeIntegrity(p) \
57785:   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
57786:   assert( p->pBt->inTransaction>=p->inTrans ); 
57787: 
57788: 
57789: /*
57790: ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
57791: ** if the database supports auto-vacuum or not. Because it is used
57792: ** within an expression that is an argument to another macro 
57793: ** (sqliteMallocRaw), it is not possible to use conditional compilation.
57794: ** So, this macro is defined instead.
57795: */
57796: #ifndef SQLITE_OMIT_AUTOVACUUM
57797: #define ISAUTOVACUUM (pBt->autoVacuum)
57798: #else
57799: #define ISAUTOVACUUM 0
57800: #endif
57801: 
57802: 
57803: /*
57804: ** This structure is passed around through all the sanity checking routines
57805: ** in order to keep track of some global state information.
57806: **
57807: ** The aRef[] array is allocated so that there is 1 bit for each page in
57808: ** the database. As the integrity-check proceeds, for each page used in
57809: ** the database the corresponding bit is set. This allows integrity-check to 
57810: ** detect pages that are used twice and orphaned pages (both of which 
57811: ** indicate corruption).
57812: */
57813: typedef struct IntegrityCk IntegrityCk;
57814: struct IntegrityCk {
57815:   BtShared *pBt;    /* The tree being checked out */
57816:   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
57817:   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
57818:   Pgno nPage;       /* Number of pages in the database */
57819:   int mxErr;        /* Stop accumulating errors when this reaches zero */
57820:   int nErr;         /* Number of messages written to zErrMsg so far */
57821:   int mallocFailed; /* A memory allocation error has occurred */
57822:   const char *zPfx; /* Error message prefix */
57823:   int v1, v2;       /* Values for up to two %d fields in zPfx */
57824:   StrAccum errMsg;  /* Accumulate the error message text here */
57825:   u32 *heap;        /* Min-heap used for analyzing cell coverage */
57826: };
57827: 
57828: /*
57829: ** Routines to read or write a two- and four-byte big-endian integer values.
57830: */
57831: #define get2byte(x)   ((x)[0]<<8 | (x)[1])
57832: #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
57833: #define get4byte sqlite3Get4byte
57834: #define put4byte sqlite3Put4byte
57835: 
57836: /*
57837: ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
57838: ** two-byte aligned address.  get2bytea() is only used for accessing the
57839: ** cell addresses in a btree header.
57840: */
57841: #if SQLITE_BYTEORDER==4321
57842: # define get2byteAligned(x)  (*(u16*)(x))
57843: #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57844:     && GCC_VERSION>=4008000
57845: # define get2byteAligned(x)  __builtin_bswap16(*(u16*)(x))
57846: #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57847:     && defined(_MSC_VER) && _MSC_VER>=1300
57848: # define get2byteAligned(x)  _byteswap_ushort(*(u16*)(x))
57849: #else
57850: # define get2byteAligned(x)  ((x)[0]<<8 | (x)[1])
57851: #endif
57852: 
57853: /************** End of btreeInt.h ********************************************/
57854: /************** Continuing where we left off in btmutex.c ********************/
57855: #ifndef SQLITE_OMIT_SHARED_CACHE
57856: #if SQLITE_THREADSAFE
57857: 
57858: /*
57859: ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
57860: ** set BtShared.db to the database handle associated with p and the
57861: ** p->locked boolean to true.
57862: */
57863: static void lockBtreeMutex(Btree *p){
57864:   assert( p->locked==0 );
57865:   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
57866:   assert( sqlite3_mutex_held(p->db->mutex) );
57867: 
57868:   sqlite3_mutex_enter(p->pBt->mutex);
57869:   p->pBt->db = p->db;
57870:   p->locked = 1;
57871: }
57872: 
57873: /*
57874: ** Release the BtShared mutex associated with B-Tree handle p and
57875: ** clear the p->locked boolean.
57876: */
57877: static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
57878:   BtShared *pBt = p->pBt;
57879:   assert( p->locked==1 );
57880:   assert( sqlite3_mutex_held(pBt->mutex) );
57881:   assert( sqlite3_mutex_held(p->db->mutex) );
57882:   assert( p->db==pBt->db );
57883: 
57884:   sqlite3_mutex_leave(pBt->mutex);
57885:   p->locked = 0;
57886: }
57887: 
57888: /* Forward reference */
57889: static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
57890: 
57891: /*
57892: ** Enter a mutex on the given BTree object.
57893: **
57894: ** If the object is not sharable, then no mutex is ever required
57895: ** and this routine is a no-op.  The underlying mutex is non-recursive.
57896: ** But we keep a reference count in Btree.wantToLock so the behavior
57897: ** of this interface is recursive.
57898: **
57899: ** To avoid deadlocks, multiple Btrees are locked in the same order
57900: ** by all database connections.  The p->pNext is a list of other
57901: ** Btrees belonging to the same database connection as the p Btree
57902: ** which need to be locked after p.  If we cannot get a lock on
57903: ** p, then first unlock all of the others on p->pNext, then wait
57904: ** for the lock to become available on p, then relock all of the
57905: ** subsequent Btrees that desire a lock.
57906: */
57907: SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
57908:   /* Some basic sanity checking on the Btree.  The list of Btrees
57909:   ** connected by pNext and pPrev should be in sorted order by
57910:   ** Btree.pBt value. All elements of the list should belong to
57911:   ** the same connection. Only shared Btrees are on the list. */
57912:   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
57913:   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
57914:   assert( p->pNext==0 || p->pNext->db==p->db );
57915:   assert( p->pPrev==0 || p->pPrev->db==p->db );
57916:   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
57917: 
57918:   /* Check for locking consistency */
57919:   assert( !p->locked || p->wantToLock>0 );
57920:   assert( p->sharable || p->wantToLock==0 );
57921: 
57922:   /* We should already hold a lock on the database connection */
57923:   assert( sqlite3_mutex_held(p->db->mutex) );
57924: 
57925:   /* Unless the database is sharable and unlocked, then BtShared.db
57926:   ** should already be set correctly. */
57927:   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
57928: 
57929:   if( !p->sharable ) return;
57930:   p->wantToLock++;
57931:   if( p->locked ) return;
57932:   btreeLockCarefully(p);
57933: }
57934: 
57935: /* This is a helper function for sqlite3BtreeLock(). By moving
57936: ** complex, but seldom used logic, out of sqlite3BtreeLock() and
57937: ** into this routine, we avoid unnecessary stack pointer changes
57938: ** and thus help the sqlite3BtreeLock() routine to run much faster
57939: ** in the common case.
57940: */
57941: static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
57942:   Btree *pLater;
57943: 
57944:   /* In most cases, we should be able to acquire the lock we
57945:   ** want without having to go through the ascending lock
57946:   ** procedure that follows.  Just be sure not to block.
57947:   */
57948:   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
57949:     p->pBt->db = p->db;
57950:     p->locked = 1;
57951:     return;
57952:   }
57953: 
57954:   /* To avoid deadlock, first release all locks with a larger
57955:   ** BtShared address.  Then acquire our lock.  Then reacquire
57956:   ** the other BtShared locks that we used to hold in ascending
57957:   ** order.
57958:   */
57959:   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57960:     assert( pLater->sharable );
57961:     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
57962:     assert( !pLater->locked || pLater->wantToLock>0 );
57963:     if( pLater->locked ){
57964:       unlockBtreeMutex(pLater);
57965:     }
57966:   }
57967:   lockBtreeMutex(p);
57968:   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57969:     if( pLater->wantToLock ){
57970:       lockBtreeMutex(pLater);
57971:     }
57972:   }
57973: }
57974: 
57975: 
57976: /*
57977: ** Exit the recursive mutex on a Btree.
57978: */
57979: SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
57980:   assert( sqlite3_mutex_held(p->db->mutex) );
57981:   if( p->sharable ){
57982:     assert( p->wantToLock>0 );
57983:     p->wantToLock--;
57984:     if( p->wantToLock==0 ){
57985:       unlockBtreeMutex(p);
57986:     }
57987:   }
57988: }
57989: 
57990: #ifndef NDEBUG
57991: /*
57992: ** Return true if the BtShared mutex is held on the btree, or if the
57993: ** B-Tree is not marked as sharable.
57994: **
57995: ** This routine is used only from within assert() statements.
57996: */
57997: SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
57998:   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
57999:   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
58000:   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
58001:   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
58002: 
58003:   return (p->sharable==0 || p->locked);
58004: }
58005: #endif
58006: 
58007: 
58008: /*
58009: ** Enter the mutex on every Btree associated with a database
58010: ** connection.  This is needed (for example) prior to parsing
58011: ** a statement since we will be comparing table and column names
58012: ** against all schemas and we do not want those schemas being
58013: ** reset out from under us.
58014: **
58015: ** There is a corresponding leave-all procedures.
58016: **
58017: ** Enter the mutexes in accending order by BtShared pointer address
58018: ** to avoid the possibility of deadlock when two threads with
58019: ** two or more btrees in common both try to lock all their btrees
58020: ** at the same instant.
58021: */
58022: SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58023:   int i;
58024:   Btree *p;
58025:   assert( sqlite3_mutex_held(db->mutex) );
58026:   for(i=0; i<db->nDb; i++){
58027:     p = db->aDb[i].pBt;
58028:     if( p ) sqlite3BtreeEnter(p);
58029:   }
58030: }
58031: SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
58032:   int i;
58033:   Btree *p;
58034:   assert( sqlite3_mutex_held(db->mutex) );
58035:   for(i=0; i<db->nDb; i++){
58036:     p = db->aDb[i].pBt;
58037:     if( p ) sqlite3BtreeLeave(p);
58038:   }
58039: }
58040: 
58041: #ifndef NDEBUG
58042: /*
58043: ** Return true if the current thread holds the database connection
58044: ** mutex and all required BtShared mutexes.
58045: **
58046: ** This routine is used inside assert() statements only.
58047: */
58048: SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
58049:   int i;
58050:   if( !sqlite3_mutex_held(db->mutex) ){
58051:     return 0;
58052:   }
58053:   for(i=0; i<db->nDb; i++){
58054:     Btree *p;
58055:     p = db->aDb[i].pBt;
58056:     if( p && p->sharable &&
58057:          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
58058:       return 0;
58059:     }
58060:   }
58061:   return 1;
58062: }
58063: #endif /* NDEBUG */
58064: 
58065: #ifndef NDEBUG
58066: /*
58067: ** Return true if the correct mutexes are held for accessing the
58068: ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
58069: ** access are:
58070: **
58071: **   (1) The mutex on db
58072: **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
58073: **
58074: ** If pSchema is not NULL, then iDb is computed from pSchema and
58075: ** db using sqlite3SchemaToIndex().
58076: */
58077: SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
58078:   Btree *p;
58079:   assert( db!=0 );
58080:   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
58081:   assert( iDb>=0 && iDb<db->nDb );
58082:   if( !sqlite3_mutex_held(db->mutex) ) return 0;
58083:   if( iDb==1 ) return 1;
58084:   p = db->aDb[iDb].pBt;
58085:   assert( p!=0 );
58086:   return p->sharable==0 || p->locked==1;
58087: }
58088: #endif /* NDEBUG */
58089: 
58090: #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
58091: /*
58092: ** The following are special cases for mutex enter routines for use
58093: ** in single threaded applications that use shared cache.  Except for
58094: ** these two routines, all mutex operations are no-ops in that case and
58095: ** are null #defines in btree.h.
58096: **
58097: ** If shared cache is disabled, then all btree mutex routines, including
58098: ** the ones below, are no-ops and are null #defines in btree.h.
58099: */
58100: 
58101: SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
58102:   p->pBt->db = p->db;
58103: }
58104: SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
58105:   int i;
58106:   for(i=0; i<db->nDb; i++){
58107:     Btree *p = db->aDb[i].pBt;
58108:     if( p ){
58109:       p->pBt->db = p->db;
58110:     }
58111:   }
58112: }
58113: #endif /* if SQLITE_THREADSAFE */
58114: 
58115: #ifndef SQLITE_OMIT_INCRBLOB
58116: /*
58117: ** Enter a mutex on a Btree given a cursor owned by that Btree. 
58118: **
58119: ** These entry points are used by incremental I/O only. Enter() is required 
58120: ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not 
58121: ** the build is threadsafe. Leave() is only required by threadsafe builds.
58122: */
58123: SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
58124:   sqlite3BtreeEnter(pCur->pBtree);
58125: }
58126: # if SQLITE_THREADSAFE
58127: SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
58128:   sqlite3BtreeLeave(pCur->pBtree);
58129: }
58130: # endif
58131: #endif /* ifndef SQLITE_OMIT_INCRBLOB */
58132: 
58133: #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
58134: 
58135: /************** End of btmutex.c *********************************************/
58136: /************** Begin file btree.c *******************************************/
58137: /*
58138: ** 2004 April 6
58139: **
58140: ** The author disclaims copyright to this source code.  In place of
58141: ** a legal notice, here is a blessing:
58142: **
58143: **    May you do good and not evil.
58144: **    May you find forgiveness for yourself and forgive others.
58145: **    May you share freely, never taking more than you give.
58146: **
58147: *************************************************************************
58148: ** This file implements an external (disk-based) database using BTrees.
58149: ** See the header comment on "btreeInt.h" for additional information.
58150: ** Including a description of file format and an overview of operation.
58151: */
58152: /* #include "btreeInt.h" */
58153: 
58154: /*
58155: ** The header string that appears at the beginning of every
58156: ** SQLite database.
58157: */
58158: static const char zMagicHeader[] = SQLITE_FILE_HEADER;
58159: 
58160: /*
58161: ** Set this global variable to 1 to enable tracing using the TRACE
58162: ** macro.
58163: */
58164: #if 0
58165: int sqlite3BtreeTrace=1;  /* True to enable tracing */
58166: # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
58167: #else
58168: # define TRACE(X)
58169: #endif
58170: 
58171: /*
58172: ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
58173: ** But if the value is zero, make it 65536.
58174: **
58175: ** This routine is used to extract the "offset to cell content area" value
58176: ** from the header of a btree page.  If the page size is 65536 and the page
58177: ** is empty, the offset should be 65536, but the 2-byte value stores zero.
58178: ** This routine makes the necessary adjustment to 65536.
58179: */
58180: #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
58181: 
58182: /*
58183: ** Values passed as the 5th argument to allocateBtreePage()
58184: */
58185: #define BTALLOC_ANY   0           /* Allocate any page */
58186: #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
58187: #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
58188: 
58189: /*
58190: ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
58191: ** defined, or 0 if it is. For example:
58192: **
58193: **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58194: */
58195: #ifndef SQLITE_OMIT_AUTOVACUUM
58196: #define IfNotOmitAV(expr) (expr)
58197: #else
58198: #define IfNotOmitAV(expr) 0
58199: #endif
58200: 
58201: #ifndef SQLITE_OMIT_SHARED_CACHE
58202: /*
58203: ** A list of BtShared objects that are eligible for participation
58204: ** in shared cache.  This variable has file scope during normal builds,
58205: ** but the test harness needs to access it so we make it global for 
58206: ** test builds.
58207: **
58208: ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
58209: */
58210: #ifdef SQLITE_TEST
58211: SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58212: #else
58213: static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
58214: #endif
58215: #endif /* SQLITE_OMIT_SHARED_CACHE */
58216: 
58217: #ifndef SQLITE_OMIT_SHARED_CACHE
58218: /*
58219: ** Enable or disable the shared pager and schema features.
58220: **
58221: ** This routine has no effect on existing database connections.
58222: ** The shared cache setting effects only future calls to
58223: ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
58224: */
58225: SQLITE_API int sqlite3_enable_shared_cache(int enable){
58226:   sqlite3GlobalConfig.sharedCacheEnabled = enable;
58227:   return SQLITE_OK;
58228: }
58229: #endif
58230: 
58231: 
58232: 
58233: #ifdef SQLITE_OMIT_SHARED_CACHE
58234:   /*
58235:   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
58236:   ** and clearAllSharedCacheTableLocks()
58237:   ** manipulate entries in the BtShared.pLock linked list used to store
58238:   ** shared-cache table level locks. If the library is compiled with the
58239:   ** shared-cache feature disabled, then there is only ever one user
58240:   ** of each BtShared structure and so this locking is not necessary. 
58241:   ** So define the lock related functions as no-ops.
58242:   */
58243:   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
58244:   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
58245:   #define clearAllSharedCacheTableLocks(a)
58246:   #define downgradeAllSharedCacheTableLocks(a)
58247:   #define hasSharedCacheTableLock(a,b,c,d) 1
58248:   #define hasReadConflicts(a, b) 0
58249: #endif
58250: 
58251: #ifndef SQLITE_OMIT_SHARED_CACHE
58252: 
58253: #ifdef SQLITE_DEBUG
58254: /*
58255: **** This function is only used as part of an assert() statement. ***
58256: **
58257: ** Check to see if pBtree holds the required locks to read or write to the 
58258: ** table with root page iRoot.   Return 1 if it does and 0 if not.
58259: **
58260: ** For example, when writing to a table with root-page iRoot via 
58261: ** Btree connection pBtree:
58262: **
58263: **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
58264: **
58265: ** When writing to an index that resides in a sharable database, the 
58266: ** caller should have first obtained a lock specifying the root page of
58267: ** the corresponding table. This makes things a bit more complicated,
58268: ** as this module treats each table as a separate structure. To determine
58269: ** the table corresponding to the index being written, this
58270: ** function has to search through the database schema.
58271: **
58272: ** Instead of a lock on the table/index rooted at page iRoot, the caller may
58273: ** hold a write-lock on the schema table (root page 1). This is also
58274: ** acceptable.
58275: */
58276: static int hasSharedCacheTableLock(
58277:   Btree *pBtree,         /* Handle that must hold lock */
58278:   Pgno iRoot,            /* Root page of b-tree */
58279:   int isIndex,           /* True if iRoot is the root of an index b-tree */
58280:   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
58281: ){
58282:   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
58283:   Pgno iTab = 0;
58284:   BtLock *pLock;
58285: 
58286:   /* If this database is not shareable, or if the client is reading
58287:   ** and has the read-uncommitted flag set, then no lock is required. 
58288:   ** Return true immediately.
58289:   */
58290:   if( (pBtree->sharable==0)
58291:    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
58292:   ){
58293:     return 1;
58294:   }
58295: 
58296:   /* If the client is reading  or writing an index and the schema is
58297:   ** not loaded, then it is too difficult to actually check to see if
58298:   ** the correct locks are held.  So do not bother - just return true.
58299:   ** This case does not come up very often anyhow.
58300:   */
58301:   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
58302:     return 1;
58303:   }
58304: 
58305:   /* Figure out the root-page that the lock should be held on. For table
58306:   ** b-trees, this is just the root page of the b-tree being read or
58307:   ** written. For index b-trees, it is the root page of the associated
58308:   ** table.  */
58309:   if( isIndex ){
58310:     HashElem *p;
58311:     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
58312:       Index *pIdx = (Index *)sqliteHashData(p);
58313:       if( pIdx->tnum==(int)iRoot ){
58314:         if( iTab ){
58315:           /* Two or more indexes share the same root page.  There must
58316:           ** be imposter tables.  So just return true.  The assert is not
58317:           ** useful in that case. */
58318:           return 1;
58319:         }
58320:         iTab = pIdx->pTable->tnum;
58321:       }
58322:     }
58323:   }else{
58324:     iTab = iRoot;
58325:   }
58326: 
58327:   /* Search for the required lock. Either a write-lock on root-page iTab, a 
58328:   ** write-lock on the schema table, or (if the client is reading) a
58329:   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
58330:   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
58331:     if( pLock->pBtree==pBtree 
58332:      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
58333:      && pLock->eLock>=eLockType 
58334:     ){
58335:       return 1;
58336:     }
58337:   }
58338: 
58339:   /* Failed to find the required lock. */
58340:   return 0;
58341: }
58342: #endif /* SQLITE_DEBUG */
58343: 
58344: #ifdef SQLITE_DEBUG
58345: /*
58346: **** This function may be used as part of assert() statements only. ****
58347: **
58348: ** Return true if it would be illegal for pBtree to write into the
58349: ** table or index rooted at iRoot because other shared connections are
58350: ** simultaneously reading that same table or index.
58351: **
58352: ** It is illegal for pBtree to write if some other Btree object that
58353: ** shares the same BtShared object is currently reading or writing
58354: ** the iRoot table.  Except, if the other Btree object has the
58355: ** read-uncommitted flag set, then it is OK for the other object to
58356: ** have a read cursor.
58357: **
58358: ** For example, before writing to any part of the table or index
58359: ** rooted at page iRoot, one should call:
58360: **
58361: **    assert( !hasReadConflicts(pBtree, iRoot) );
58362: */
58363: static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
58364:   BtCursor *p;
58365:   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58366:     if( p->pgnoRoot==iRoot 
58367:      && p->pBtree!=pBtree
58368:      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
58369:     ){
58370:       return 1;
58371:     }
58372:   }
58373:   return 0;
58374: }
58375: #endif    /* #ifdef SQLITE_DEBUG */
58376: 
58377: /*
58378: ** Query to see if Btree handle p may obtain a lock of type eLock 
58379: ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
58380: ** SQLITE_OK if the lock may be obtained (by calling
58381: ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
58382: */
58383: static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
58384:   BtShared *pBt = p->pBt;
58385:   BtLock *pIter;
58386: 
58387:   assert( sqlite3BtreeHoldsMutex(p) );
58388:   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58389:   assert( p->db!=0 );
58390:   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
58391:   
58392:   /* If requesting a write-lock, then the Btree must have an open write
58393:   ** transaction on this file. And, obviously, for this to be so there 
58394:   ** must be an open write transaction on the file itself.
58395:   */
58396:   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
58397:   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
58398:   
58399:   /* This routine is a no-op if the shared-cache is not enabled */
58400:   if( !p->sharable ){
58401:     return SQLITE_OK;
58402:   }
58403: 
58404:   /* If some other connection is holding an exclusive lock, the
58405:   ** requested lock may not be obtained.
58406:   */
58407:   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
58408:     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
58409:     return SQLITE_LOCKED_SHAREDCACHE;
58410:   }
58411: 
58412:   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58413:     /* The condition (pIter->eLock!=eLock) in the following if(...) 
58414:     ** statement is a simplification of:
58415:     **
58416:     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
58417:     **
58418:     ** since we know that if eLock==WRITE_LOCK, then no other connection
58419:     ** may hold a WRITE_LOCK on any table in this file (since there can
58420:     ** only be a single writer).
58421:     */
58422:     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
58423:     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
58424:     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
58425:       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
58426:       if( eLock==WRITE_LOCK ){
58427:         assert( p==pBt->pWriter );
58428:         pBt->btsFlags |= BTS_PENDING;
58429:       }
58430:       return SQLITE_LOCKED_SHAREDCACHE;
58431:     }
58432:   }
58433:   return SQLITE_OK;
58434: }
58435: #endif /* !SQLITE_OMIT_SHARED_CACHE */
58436: 
58437: #ifndef SQLITE_OMIT_SHARED_CACHE
58438: /*
58439: ** Add a lock on the table with root-page iTable to the shared-btree used
58440: ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
58441: ** WRITE_LOCK.
58442: **
58443: ** This function assumes the following:
58444: **
58445: **   (a) The specified Btree object p is connected to a sharable
58446: **       database (one with the BtShared.sharable flag set), and
58447: **
58448: **   (b) No other Btree objects hold a lock that conflicts
58449: **       with the requested lock (i.e. querySharedCacheTableLock() has
58450: **       already been called and returned SQLITE_OK).
58451: **
58452: ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
58453: ** is returned if a malloc attempt fails.
58454: */
58455: static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
58456:   BtShared *pBt = p->pBt;
58457:   BtLock *pLock = 0;
58458:   BtLock *pIter;
58459: 
58460:   assert( sqlite3BtreeHoldsMutex(p) );
58461:   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
58462:   assert( p->db!=0 );
58463: 
58464:   /* A connection with the read-uncommitted flag set will never try to
58465:   ** obtain a read-lock using this function. The only read-lock obtained
58466:   ** by a connection in read-uncommitted mode is on the sqlite_master 
58467:   ** table, and that lock is obtained in BtreeBeginTrans().  */
58468:   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
58469: 
58470:   /* This function should only be called on a sharable b-tree after it 
58471:   ** has been determined that no other b-tree holds a conflicting lock.  */
58472:   assert( p->sharable );
58473:   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
58474: 
58475:   /* First search the list for an existing lock on this table. */
58476:   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58477:     if( pIter->iTable==iTable && pIter->pBtree==p ){
58478:       pLock = pIter;
58479:       break;
58480:     }
58481:   }
58482: 
58483:   /* If the above search did not find a BtLock struct associating Btree p
58484:   ** with table iTable, allocate one and link it into the list.
58485:   */
58486:   if( !pLock ){
58487:     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
58488:     if( !pLock ){
58489:       return SQLITE_NOMEM_BKPT;
58490:     }
58491:     pLock->iTable = iTable;
58492:     pLock->pBtree = p;
58493:     pLock->pNext = pBt->pLock;
58494:     pBt->pLock = pLock;
58495:   }
58496: 
58497:   /* Set the BtLock.eLock variable to the maximum of the current lock
58498:   ** and the requested lock. This means if a write-lock was already held
58499:   ** and a read-lock requested, we don't incorrectly downgrade the lock.
58500:   */
58501:   assert( WRITE_LOCK>READ_LOCK );
58502:   if( eLock>pLock->eLock ){
58503:     pLock->eLock = eLock;
58504:   }
58505: 
58506:   return SQLITE_OK;
58507: }
58508: #endif /* !SQLITE_OMIT_SHARED_CACHE */
58509: 
58510: #ifndef SQLITE_OMIT_SHARED_CACHE
58511: /*
58512: ** Release all the table locks (locks obtained via calls to
58513: ** the setSharedCacheTableLock() procedure) held by Btree object p.
58514: **
58515: ** This function assumes that Btree p has an open read or write 
58516: ** transaction. If it does not, then the BTS_PENDING flag
58517: ** may be incorrectly cleared.
58518: */
58519: static void clearAllSharedCacheTableLocks(Btree *p){
58520:   BtShared *pBt = p->pBt;
58521:   BtLock **ppIter = &pBt->pLock;
58522: 
58523:   assert( sqlite3BtreeHoldsMutex(p) );
58524:   assert( p->sharable || 0==*ppIter );
58525:   assert( p->inTrans>0 );
58526: 
58527:   while( *ppIter ){
58528:     BtLock *pLock = *ppIter;
58529:     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
58530:     assert( pLock->pBtree->inTrans>=pLock->eLock );
58531:     if( pLock->pBtree==p ){
58532:       *ppIter = pLock->pNext;
58533:       assert( pLock->iTable!=1 || pLock==&p->lock );
58534:       if( pLock->iTable!=1 ){
58535:         sqlite3_free(pLock);
58536:       }
58537:     }else{
58538:       ppIter = &pLock->pNext;
58539:     }
58540:   }
58541: 
58542:   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
58543:   if( pBt->pWriter==p ){
58544:     pBt->pWriter = 0;
58545:     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58546:   }else if( pBt->nTransaction==2 ){
58547:     /* This function is called when Btree p is concluding its 
58548:     ** transaction. If there currently exists a writer, and p is not
58549:     ** that writer, then the number of locks held by connections other
58550:     ** than the writer must be about to drop to zero. In this case
58551:     ** set the BTS_PENDING flag to 0.
58552:     **
58553:     ** If there is not currently a writer, then BTS_PENDING must
58554:     ** be zero already. So this next line is harmless in that case.
58555:     */
58556:     pBt->btsFlags &= ~BTS_PENDING;
58557:   }
58558: }
58559: 
58560: /*
58561: ** This function changes all write-locks held by Btree p into read-locks.
58562: */
58563: static void downgradeAllSharedCacheTableLocks(Btree *p){
58564:   BtShared *pBt = p->pBt;
58565:   if( pBt->pWriter==p ){
58566:     BtLock *pLock;
58567:     pBt->pWriter = 0;
58568:     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58569:     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
58570:       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
58571:       pLock->eLock = READ_LOCK;
58572:     }
58573:   }
58574: }
58575: 
58576: #endif /* SQLITE_OMIT_SHARED_CACHE */
58577: 
58578: static void releasePage(MemPage *pPage);  /* Forward reference */
58579: 
58580: /*
58581: ***** This routine is used inside of assert() only ****
58582: **
58583: ** Verify that the cursor holds the mutex on its BtShared
58584: */
58585: #ifdef SQLITE_DEBUG
58586: static int cursorHoldsMutex(BtCursor *p){
58587:   return sqlite3_mutex_held(p->pBt->mutex);
58588: }
58589: 
58590: /* Verify that the cursor and the BtShared agree about what is the current
58591: ** database connetion. This is important in shared-cache mode. If the database 
58592: ** connection pointers get out-of-sync, it is possible for routines like
58593: ** btreeInitPage() to reference an stale connection pointer that references a
58594: ** a connection that has already closed.  This routine is used inside assert()
58595: ** statements only and for the purpose of double-checking that the btree code
58596: ** does keep the database connection pointers up-to-date.
58597: */
58598: static int cursorOwnsBtShared(BtCursor *p){
58599:   assert( cursorHoldsMutex(p) );
58600:   return (p->pBtree->db==p->pBt->db);
58601: }
58602: #endif
58603: 
58604: /*
58605: ** Invalidate the overflow cache of the cursor passed as the first argument.
58606: ** on the shared btree structure pBt.
58607: */
58608: #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
58609: 
58610: /*
58611: ** Invalidate the overflow page-list cache for all cursors opened
58612: ** on the shared btree structure pBt.
58613: */
58614: static void invalidateAllOverflowCache(BtShared *pBt){
58615:   BtCursor *p;
58616:   assert( sqlite3_mutex_held(pBt->mutex) );
58617:   for(p=pBt->pCursor; p; p=p->pNext){
58618:     invalidateOverflowCache(p);
58619:   }
58620: }
58621: 
58622: #ifndef SQLITE_OMIT_INCRBLOB
58623: /*
58624: ** This function is called before modifying the contents of a table
58625: ** to invalidate any incrblob cursors that are open on the
58626: ** row or one of the rows being modified.
58627: **
58628: ** If argument isClearTable is true, then the entire contents of the
58629: ** table is about to be deleted. In this case invalidate all incrblob
58630: ** cursors open on any row within the table with root-page pgnoRoot.
58631: **
58632: ** Otherwise, if argument isClearTable is false, then the row with
58633: ** rowid iRow is being replaced or deleted. In this case invalidate
58634: ** only those incrblob cursors open on that specific row.
58635: */
58636: static void invalidateIncrblobCursors(
58637:   Btree *pBtree,          /* The database file to check */
58638:   i64 iRow,               /* The rowid that might be changing */
58639:   int isClearTable        /* True if all rows are being deleted */
58640: ){
58641:   BtCursor *p;
58642:   if( pBtree->hasIncrblobCur==0 ) return;
58643:   assert( sqlite3BtreeHoldsMutex(pBtree) );
58644:   pBtree->hasIncrblobCur = 0;
58645:   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58646:     if( (p->curFlags & BTCF_Incrblob)!=0 ){
58647:       pBtree->hasIncrblobCur = 1;
58648:       if( isClearTable || p->info.nKey==iRow ){
58649:         p->eState = CURSOR_INVALID;
58650:       }
58651:     }
58652:   }
58653: }
58654: 
58655: #else
58656:   /* Stub function when INCRBLOB is omitted */
58657:   #define invalidateIncrblobCursors(x,y,z)
58658: #endif /* SQLITE_OMIT_INCRBLOB */
58659: 
58660: /*
58661: ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
58662: ** when a page that previously contained data becomes a free-list leaf 
58663: ** page.
58664: **
58665: ** The BtShared.pHasContent bitvec exists to work around an obscure
58666: ** bug caused by the interaction of two useful IO optimizations surrounding
58667: ** free-list leaf pages:
58668: **
58669: **   1) When all data is deleted from a page and the page becomes
58670: **      a free-list leaf page, the page is not written to the database
58671: **      (as free-list leaf pages contain no meaningful data). Sometimes
58672: **      such a page is not even journalled (as it will not be modified,
58673: **      why bother journalling it?).
58674: **
58675: **   2) When a free-list leaf page is reused, its content is not read
58676: **      from the database or written to the journal file (why should it
58677: **      be, if it is not at all meaningful?).
58678: **
58679: ** By themselves, these optimizations work fine and provide a handy
58680: ** performance boost to bulk delete or insert operations. However, if
58681: ** a page is moved to the free-list and then reused within the same
58682: ** transaction, a problem comes up. If the page is not journalled when
58683: ** it is moved to the free-list and it is also not journalled when it
58684: ** is extracted from the free-list and reused, then the original data
58685: ** may be lost. In the event of a rollback, it may not be possible
58686: ** to restore the database to its original configuration.
58687: **
58688: ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
58689: ** moved to become a free-list leaf page, the corresponding bit is
58690: ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
58691: ** optimization 2 above is omitted if the corresponding bit is already
58692: ** set in BtShared.pHasContent. The contents of the bitvec are cleared
58693: ** at the end of every transaction.
58694: */
58695: static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
58696:   int rc = SQLITE_OK;
58697:   if( !pBt->pHasContent ){
58698:     assert( pgno<=pBt->nPage );
58699:     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
58700:     if( !pBt->pHasContent ){
58701:       rc = SQLITE_NOMEM_BKPT;
58702:     }
58703:   }
58704:   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
58705:     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
58706:   }
58707:   return rc;
58708: }
58709: 
58710: /*
58711: ** Query the BtShared.pHasContent vector.
58712: **
58713: ** This function is called when a free-list leaf page is removed from the
58714: ** free-list for reuse. It returns false if it is safe to retrieve the
58715: ** page from the pager layer with the 'no-content' flag set. True otherwise.
58716: */
58717: static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
58718:   Bitvec *p = pBt->pHasContent;
58719:   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
58720: }
58721: 
58722: /*
58723: ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
58724: ** invoked at the conclusion of each write-transaction.
58725: */
58726: static void btreeClearHasContent(BtShared *pBt){
58727:   sqlite3BitvecDestroy(pBt->pHasContent);
58728:   pBt->pHasContent = 0;
58729: }
58730: 
58731: /*
58732: ** Release all of the apPage[] pages for a cursor.
58733: */
58734: static void btreeReleaseAllCursorPages(BtCursor *pCur){
58735:   int i;
58736:   for(i=0; i<=pCur->iPage; i++){
58737:     releasePage(pCur->apPage[i]);
58738:     pCur->apPage[i] = 0;
58739:   }
58740:   pCur->iPage = -1;
58741: }
58742: 
58743: /*
58744: ** The cursor passed as the only argument must point to a valid entry
58745: ** when this function is called (i.e. have eState==CURSOR_VALID). This
58746: ** function saves the current cursor key in variables pCur->nKey and
58747: ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error 
58748: ** code otherwise.
58749: **
58750: ** If the cursor is open on an intkey table, then the integer key
58751: ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
58752: ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is 
58753: ** set to point to a malloced buffer pCur->nKey bytes in size containing 
58754: ** the key.
58755: */
58756: static int saveCursorKey(BtCursor *pCur){
58757:   int rc = SQLITE_OK;
58758:   assert( CURSOR_VALID==pCur->eState );
58759:   assert( 0==pCur->pKey );
58760:   assert( cursorHoldsMutex(pCur) );
58761: 
58762:   if( pCur->curIntKey ){
58763:     /* Only the rowid is required for a table btree */
58764:     pCur->nKey = sqlite3BtreeIntegerKey(pCur);
58765:   }else{
58766:     /* For an index btree, save the complete key content */
58767:     void *pKey;
58768:     pCur->nKey = sqlite3BtreePayloadSize(pCur);
58769:     pKey = sqlite3Malloc( pCur->nKey );
58770:     if( pKey ){
58771:       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
58772:       if( rc==SQLITE_OK ){
58773:         pCur->pKey = pKey;
58774:       }else{
58775:         sqlite3_free(pKey);
58776:       }
58777:     }else{
58778:       rc = SQLITE_NOMEM_BKPT;
58779:     }
58780:   }
58781:   assert( !pCur->curIntKey || !pCur->pKey );
58782:   return rc;
58783: }
58784: 
58785: /*
58786: ** Save the current cursor position in the variables BtCursor.nKey 
58787: ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
58788: **
58789: ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
58790: ** prior to calling this routine.  
58791: */
58792: static int saveCursorPosition(BtCursor *pCur){
58793:   int rc;
58794: 
58795:   assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
58796:   assert( 0==pCur->pKey );
58797:   assert( cursorHoldsMutex(pCur) );
58798: 
58799:   if( pCur->eState==CURSOR_SKIPNEXT ){
58800:     pCur->eState = CURSOR_VALID;
58801:   }else{
58802:     pCur->skipNext = 0;
58803:   }
58804: 
58805:   rc = saveCursorKey(pCur);
58806:   if( rc==SQLITE_OK ){
58807:     btreeReleaseAllCursorPages(pCur);
58808:     pCur->eState = CURSOR_REQUIRESEEK;
58809:   }
58810: 
58811:   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
58812:   return rc;
58813: }
58814: 
58815: /* Forward reference */
58816: static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
58817: 
58818: /*
58819: ** Save the positions of all cursors (except pExcept) that are open on
58820: ** the table with root-page iRoot.  "Saving the cursor position" means that
58821: ** the location in the btree is remembered in such a way that it can be
58822: ** moved back to the same spot after the btree has been modified.  This
58823: ** routine is called just before cursor pExcept is used to modify the
58824: ** table, for example in BtreeDelete() or BtreeInsert().
58825: **
58826: ** If there are two or more cursors on the same btree, then all such 
58827: ** cursors should have their BTCF_Multiple flag set.  The btreeCursor()
58828: ** routine enforces that rule.  This routine only needs to be called in
58829: ** the uncommon case when pExpect has the BTCF_Multiple flag set.
58830: **
58831: ** If pExpect!=NULL and if no other cursors are found on the same root-page,
58832: ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
58833: ** pointless call to this routine.
58834: **
58835: ** Implementation note:  This routine merely checks to see if any cursors
58836: ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
58837: ** event that cursors are in need to being saved.
58838: */
58839: static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
58840:   BtCursor *p;
58841:   assert( sqlite3_mutex_held(pBt->mutex) );
58842:   assert( pExcept==0 || pExcept->pBt==pBt );
58843:   for(p=pBt->pCursor; p; p=p->pNext){
58844:     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
58845:   }
58846:   if( p ) return saveCursorsOnList(p, iRoot, pExcept);
58847:   if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
58848:   return SQLITE_OK;
58849: }
58850: 
58851: /* This helper routine to saveAllCursors does the actual work of saving
58852: ** the cursors if and when a cursor is found that actually requires saving.
58853: ** The common case is that no cursors need to be saved, so this routine is
58854: ** broken out from its caller to avoid unnecessary stack pointer movement.
58855: */
58856: static int SQLITE_NOINLINE saveCursorsOnList(
58857:   BtCursor *p,         /* The first cursor that needs saving */
58858:   Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
58859:   BtCursor *pExcept    /* Do not save this cursor */
58860: ){
58861:   do{
58862:     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
58863:       if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58864:         int rc = saveCursorPosition(p);
58865:         if( SQLITE_OK!=rc ){
58866:           return rc;
58867:         }
58868:       }else{
58869:         testcase( p->iPage>0 );
58870:         btreeReleaseAllCursorPages(p);
58871:       }
58872:     }
58873:     p = p->pNext;
58874:   }while( p );
58875:   return SQLITE_OK;
58876: }
58877: 
58878: /*
58879: ** Clear the current cursor position.
58880: */
58881: SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
58882:   assert( cursorHoldsMutex(pCur) );
58883:   sqlite3_free(pCur->pKey);
58884:   pCur->pKey = 0;
58885:   pCur->eState = CURSOR_INVALID;
58886: }
58887: 
58888: /*
58889: ** In this version of BtreeMoveto, pKey is a packed index record
58890: ** such as is generated by the OP_MakeRecord opcode.  Unpack the
58891: ** record and then call BtreeMovetoUnpacked() to do the work.
58892: */
58893: static int btreeMoveto(
58894:   BtCursor *pCur,     /* Cursor open on the btree to be searched */
58895:   const void *pKey,   /* Packed key if the btree is an index */
58896:   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
58897:   int bias,           /* Bias search to the high end */
58898:   int *pRes           /* Write search results here */
58899: ){
58900:   int rc;                    /* Status code */
58901:   UnpackedRecord *pIdxKey;   /* Unpacked index key */
58902:   char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
58903:   char *pFree = 0;
58904: 
58905:   if( pKey ){
58906:     assert( nKey==(i64)(int)nKey );
58907:     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
58908:         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
58909:     );
58910:     if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
58911:     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
58912:     if( pIdxKey->nField==0 ){
58913:       sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58914:       return SQLITE_CORRUPT_BKPT;
58915:     }
58916:   }else{
58917:     pIdxKey = 0;
58918:   }
58919:   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
58920:   if( pFree ){
58921:     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58922:   }
58923:   return rc;
58924: }
58925: 
58926: /*
58927: ** Restore the cursor to the position it was in (or as close to as possible)
58928: ** when saveCursorPosition() was called. Note that this call deletes the 
58929: ** saved position info stored by saveCursorPosition(), so there can be
58930: ** at most one effective restoreCursorPosition() call after each 
58931: ** saveCursorPosition().
58932: */
58933: static int btreeRestoreCursorPosition(BtCursor *pCur){
58934:   int rc;
58935:   int skipNext;
58936:   assert( cursorOwnsBtShared(pCur) );
58937:   assert( pCur->eState>=CURSOR_REQUIRESEEK );
58938:   if( pCur->eState==CURSOR_FAULT ){
58939:     return pCur->skipNext;
58940:   }
58941:   pCur->eState = CURSOR_INVALID;
58942:   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
58943:   if( rc==SQLITE_OK ){
58944:     sqlite3_free(pCur->pKey);
58945:     pCur->pKey = 0;
58946:     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
58947:     pCur->skipNext |= skipNext;
58948:     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
58949:       pCur->eState = CURSOR_SKIPNEXT;
58950:     }
58951:   }
58952:   return rc;
58953: }
58954: 
58955: #define restoreCursorPosition(p) \
58956:   (p->eState>=CURSOR_REQUIRESEEK ? \
58957:          btreeRestoreCursorPosition(p) : \
58958:          SQLITE_OK)
58959: 
58960: /*
58961: ** Determine whether or not a cursor has moved from the position where
58962: ** it was last placed, or has been invalidated for any other reason.
58963: ** Cursors can move when the row they are pointing at is deleted out
58964: ** from under them, for example.  Cursor might also move if a btree
58965: ** is rebalanced.
58966: **
58967: ** Calling this routine with a NULL cursor pointer returns false.
58968: **
58969: ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
58970: ** back to where it ought to be if this routine returns true.
58971: */
58972: SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
58973:   return pCur->eState!=CURSOR_VALID;
58974: }
58975: 
58976: /*
58977: ** This routine restores a cursor back to its original position after it
58978: ** has been moved by some outside activity (such as a btree rebalance or
58979: ** a row having been deleted out from under the cursor).  
58980: **
58981: ** On success, the *pDifferentRow parameter is false if the cursor is left
58982: ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
58983: ** was pointing to has been deleted, forcing the cursor to point to some
58984: ** nearby row.
58985: **
58986: ** This routine should only be called for a cursor that just returned
58987: ** TRUE from sqlite3BtreeCursorHasMoved().
58988: */
58989: SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
58990:   int rc;
58991: 
58992:   assert( pCur!=0 );
58993:   assert( pCur->eState!=CURSOR_VALID );
58994:   rc = restoreCursorPosition(pCur);
58995:   if( rc ){
58996:     *pDifferentRow = 1;
58997:     return rc;
58998:   }
58999:   if( pCur->eState!=CURSOR_VALID ){
59000:     *pDifferentRow = 1;
59001:   }else{
59002:     assert( pCur->skipNext==0 );
59003:     *pDifferentRow = 0;
59004:   }
59005:   return SQLITE_OK;
59006: }
59007: 
59008: #ifdef SQLITE_ENABLE_CURSOR_HINTS
59009: /*
59010: ** Provide hints to the cursor.  The particular hint given (and the type
59011: ** and number of the varargs parameters) is determined by the eHintType
59012: ** parameter.  See the definitions of the BTREE_HINT_* macros for details.
59013: */
59014: SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
59015:   /* Used only by system that substitute their own storage engine */
59016: }
59017: #endif
59018: 
59019: /*
59020: ** Provide flag hints to the cursor.
59021: */
59022: SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
59023:   assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
59024:   pCur->hints = x;
59025: }
59026: 
59027: 
59028: #ifndef SQLITE_OMIT_AUTOVACUUM
59029: /*
59030: ** Given a page number of a regular database page, return the page
59031: ** number for the pointer-map page that contains the entry for the
59032: ** input page number.
59033: **
59034: ** Return 0 (not a valid page) for pgno==1 since there is
59035: ** no pointer map associated with page 1.  The integrity_check logic
59036: ** requires that ptrmapPageno(*,1)!=1.
59037: */
59038: static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
59039:   int nPagesPerMapPage;
59040:   Pgno iPtrMap, ret;
59041:   assert( sqlite3_mutex_held(pBt->mutex) );
59042:   if( pgno<2 ) return 0;
59043:   nPagesPerMapPage = (pBt->usableSize/5)+1;
59044:   iPtrMap = (pgno-2)/nPagesPerMapPage;
59045:   ret = (iPtrMap*nPagesPerMapPage) + 2; 
59046:   if( ret==PENDING_BYTE_PAGE(pBt) ){
59047:     ret++;
59048:   }
59049:   return ret;
59050: }
59051: 
59052: /*
59053: ** Write an entry into the pointer map.
59054: **
59055: ** This routine updates the pointer map entry for page number 'key'
59056: ** so that it maps to type 'eType' and parent page number 'pgno'.
59057: **
59058: ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
59059: ** a no-op.  If an error occurs, the appropriate error code is written
59060: ** into *pRC.
59061: */
59062: static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
59063:   DbPage *pDbPage;  /* The pointer map page */
59064:   u8 *pPtrmap;      /* The pointer map data */
59065:   Pgno iPtrmap;     /* The pointer map page number */
59066:   int offset;       /* Offset in pointer map page */
59067:   int rc;           /* Return code from subfunctions */
59068: 
59069:   if( *pRC ) return;
59070: 
59071:   assert( sqlite3_mutex_held(pBt->mutex) );
59072:   /* The master-journal page number must never be used as a pointer map page */
59073:   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
59074: 
59075:   assert( pBt->autoVacuum );
59076:   if( key==0 ){
59077:     *pRC = SQLITE_CORRUPT_BKPT;
59078:     return;
59079:   }
59080:   iPtrmap = PTRMAP_PAGENO(pBt, key);
59081:   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59082:   if( rc!=SQLITE_OK ){
59083:     *pRC = rc;
59084:     return;
59085:   }
59086:   offset = PTRMAP_PTROFFSET(iPtrmap, key);
59087:   if( offset<0 ){
59088:     *pRC = SQLITE_CORRUPT_BKPT;
59089:     goto ptrmap_exit;
59090:   }
59091:   assert( offset <= (int)pBt->usableSize-5 );
59092:   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59093: 
59094:   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
59095:     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
59096:     *pRC= rc = sqlite3PagerWrite(pDbPage);
59097:     if( rc==SQLITE_OK ){
59098:       pPtrmap[offset] = eType;
59099:       put4byte(&pPtrmap[offset+1], parent);
59100:     }
59101:   }
59102: 
59103: ptrmap_exit:
59104:   sqlite3PagerUnref(pDbPage);
59105: }
59106: 
59107: /*
59108: ** Read an entry from the pointer map.
59109: **
59110: ** This routine retrieves the pointer map entry for page 'key', writing
59111: ** the type and parent page number to *pEType and *pPgno respectively.
59112: ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
59113: */
59114: static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
59115:   DbPage *pDbPage;   /* The pointer map page */
59116:   int iPtrmap;       /* Pointer map page index */
59117:   u8 *pPtrmap;       /* Pointer map page data */
59118:   int offset;        /* Offset of entry in pointer map */
59119:   int rc;
59120: 
59121:   assert( sqlite3_mutex_held(pBt->mutex) );
59122: 
59123:   iPtrmap = PTRMAP_PAGENO(pBt, key);
59124:   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
59125:   if( rc!=0 ){
59126:     return rc;
59127:   }
59128:   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
59129: 
59130:   offset = PTRMAP_PTROFFSET(iPtrmap, key);
59131:   if( offset<0 ){
59132:     sqlite3PagerUnref(pDbPage);
59133:     return SQLITE_CORRUPT_BKPT;
59134:   }
59135:   assert( offset <= (int)pBt->usableSize-5 );
59136:   assert( pEType!=0 );
59137:   *pEType = pPtrmap[offset];
59138:   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
59139: 
59140:   sqlite3PagerUnref(pDbPage);
59141:   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
59142:   return SQLITE_OK;
59143: }
59144: 
59145: #else /* if defined SQLITE_OMIT_AUTOVACUUM */
59146:   #define ptrmapPut(w,x,y,z,rc)
59147:   #define ptrmapGet(w,x,y,z) SQLITE_OK
59148:   #define ptrmapPutOvflPtr(x, y, rc)
59149: #endif
59150: 
59151: /*
59152: ** Given a btree page and a cell index (0 means the first cell on
59153: ** the page, 1 means the second cell, and so forth) return a pointer
59154: ** to the cell content.
59155: **
59156: ** findCellPastPtr() does the same except it skips past the initial
59157: ** 4-byte child pointer found on interior pages, if there is one.
59158: **
59159: ** This routine works only for pages that do not contain overflow cells.
59160: */
59161: #define findCell(P,I) \
59162:   ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59163: #define findCellPastPtr(P,I) \
59164:   ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
59165: 
59166: 
59167: /*
59168: ** This is common tail processing for btreeParseCellPtr() and
59169: ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
59170: ** on a single B-tree page.  Make necessary adjustments to the CellInfo
59171: ** structure.
59172: */
59173: static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
59174:   MemPage *pPage,         /* Page containing the cell */
59175:   u8 *pCell,              /* Pointer to the cell text. */
59176:   CellInfo *pInfo         /* Fill in this structure */
59177: ){
59178:   /* If the payload will not fit completely on the local page, we have
59179:   ** to decide how much to store locally and how much to spill onto
59180:   ** overflow pages.  The strategy is to minimize the amount of unused
59181:   ** space on overflow pages while keeping the amount of local storage
59182:   ** in between minLocal and maxLocal.
59183:   **
59184:   ** Warning:  changing the way overflow payload is distributed in any
59185:   ** way will result in an incompatible file format.
59186:   */
59187:   int minLocal;  /* Minimum amount of payload held locally */
59188:   int maxLocal;  /* Maximum amount of payload held locally */
59189:   int surplus;   /* Overflow payload available for local storage */
59190: 
59191:   minLocal = pPage->minLocal;
59192:   maxLocal = pPage->maxLocal;
59193:   surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
59194:   testcase( surplus==maxLocal );
59195:   testcase( surplus==maxLocal+1 );
59196:   if( surplus <= maxLocal ){
59197:     pInfo->nLocal = (u16)surplus;
59198:   }else{
59199:     pInfo->nLocal = (u16)minLocal;
59200:   }
59201:   pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
59202: }
59203: 
59204: /*
59205: ** The following routines are implementations of the MemPage.xParseCell()
59206: ** method.
59207: **
59208: ** Parse a cell content block and fill in the CellInfo structure.
59209: **
59210: ** btreeParseCellPtr()        =>   table btree leaf nodes
59211: ** btreeParseCellNoPayload()  =>   table btree internal nodes
59212: ** btreeParseCellPtrIndex()   =>   index btree nodes
59213: **
59214: ** There is also a wrapper function btreeParseCell() that works for
59215: ** all MemPage types and that references the cell by index rather than
59216: ** by pointer.
59217: */
59218: static void btreeParseCellPtrNoPayload(
59219:   MemPage *pPage,         /* Page containing the cell */
59220:   u8 *pCell,              /* Pointer to the cell text. */
59221:   CellInfo *pInfo         /* Fill in this structure */
59222: ){
59223:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59224:   assert( pPage->leaf==0 );
59225:   assert( pPage->childPtrSize==4 );
59226: #ifndef SQLITE_DEBUG
59227:   UNUSED_PARAMETER(pPage);
59228: #endif
59229:   pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
59230:   pInfo->nPayload = 0;
59231:   pInfo->nLocal = 0;
59232:   pInfo->pPayload = 0;
59233:   return;
59234: }
59235: static void btreeParseCellPtr(
59236:   MemPage *pPage,         /* Page containing the cell */
59237:   u8 *pCell,              /* Pointer to the cell text. */
59238:   CellInfo *pInfo         /* Fill in this structure */
59239: ){
59240:   u8 *pIter;              /* For scanning through pCell */
59241:   u32 nPayload;           /* Number of bytes of cell payload */
59242:   u64 iKey;               /* Extracted Key value */
59243: 
59244:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59245:   assert( pPage->leaf==0 || pPage->leaf==1 );
59246:   assert( pPage->intKeyLeaf );
59247:   assert( pPage->childPtrSize==0 );
59248:   pIter = pCell;
59249: 
59250:   /* The next block of code is equivalent to:
59251:   **
59252:   **     pIter += getVarint32(pIter, nPayload);
59253:   **
59254:   ** The code is inlined to avoid a function call.
59255:   */
59256:   nPayload = *pIter;
59257:   if( nPayload>=0x80 ){
59258:     u8 *pEnd = &pIter[8];
59259:     nPayload &= 0x7f;
59260:     do{
59261:       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59262:     }while( (*pIter)>=0x80 && pIter<pEnd );
59263:   }
59264:   pIter++;
59265: 
59266:   /* The next block of code is equivalent to:
59267:   **
59268:   **     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
59269:   **
59270:   ** The code is inlined to avoid a function call.
59271:   */
59272:   iKey = *pIter;
59273:   if( iKey>=0x80 ){
59274:     u8 *pEnd = &pIter[7];
59275:     iKey &= 0x7f;
59276:     while(1){
59277:       iKey = (iKey<<7) | (*++pIter & 0x7f);
59278:       if( (*pIter)<0x80 ) break;
59279:       if( pIter>=pEnd ){
59280:         iKey = (iKey<<8) | *++pIter;
59281:         break;
59282:       }
59283:     }
59284:   }
59285:   pIter++;
59286: 
59287:   pInfo->nKey = *(i64*)&iKey;
59288:   pInfo->nPayload = nPayload;
59289:   pInfo->pPayload = pIter;
59290:   testcase( nPayload==pPage->maxLocal );
59291:   testcase( nPayload==pPage->maxLocal+1 );
59292:   if( nPayload<=pPage->maxLocal ){
59293:     /* This is the (easy) common case where the entire payload fits
59294:     ** on the local page.  No overflow is required.
59295:     */
59296:     pInfo->nSize = nPayload + (u16)(pIter - pCell);
59297:     if( pInfo->nSize<4 ) pInfo->nSize = 4;
59298:     pInfo->nLocal = (u16)nPayload;
59299:   }else{
59300:     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59301:   }
59302: }
59303: static void btreeParseCellPtrIndex(
59304:   MemPage *pPage,         /* Page containing the cell */
59305:   u8 *pCell,              /* Pointer to the cell text. */
59306:   CellInfo *pInfo         /* Fill in this structure */
59307: ){
59308:   u8 *pIter;              /* For scanning through pCell */
59309:   u32 nPayload;           /* Number of bytes of cell payload */
59310: 
59311:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59312:   assert( pPage->leaf==0 || pPage->leaf==1 );
59313:   assert( pPage->intKeyLeaf==0 );
59314:   pIter = pCell + pPage->childPtrSize;
59315:   nPayload = *pIter;
59316:   if( nPayload>=0x80 ){
59317:     u8 *pEnd = &pIter[8];
59318:     nPayload &= 0x7f;
59319:     do{
59320:       nPayload = (nPayload<<7) | (*++pIter & 0x7f);
59321:     }while( *(pIter)>=0x80 && pIter<pEnd );
59322:   }
59323:   pIter++;
59324:   pInfo->nKey = nPayload;
59325:   pInfo->nPayload = nPayload;
59326:   pInfo->pPayload = pIter;
59327:   testcase( nPayload==pPage->maxLocal );
59328:   testcase( nPayload==pPage->maxLocal+1 );
59329:   if( nPayload<=pPage->maxLocal ){
59330:     /* This is the (easy) common case where the entire payload fits
59331:     ** on the local page.  No overflow is required.
59332:     */
59333:     pInfo->nSize = nPayload + (u16)(pIter - pCell);
59334:     if( pInfo->nSize<4 ) pInfo->nSize = 4;
59335:     pInfo->nLocal = (u16)nPayload;
59336:   }else{
59337:     btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
59338:   }
59339: }
59340: static void btreeParseCell(
59341:   MemPage *pPage,         /* Page containing the cell */
59342:   int iCell,              /* The cell index.  First cell is 0 */
59343:   CellInfo *pInfo         /* Fill in this structure */
59344: ){
59345:   pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
59346: }
59347: 
59348: /*
59349: ** The following routines are implementations of the MemPage.xCellSize
59350: ** method.
59351: **
59352: ** Compute the total number of bytes that a Cell needs in the cell
59353: ** data area of the btree-page.  The return number includes the cell
59354: ** data header and the local payload, but not any overflow page or
59355: ** the space used by the cell pointer.
59356: **
59357: ** cellSizePtrNoPayload()    =>   table internal nodes
59358: ** cellSizePtr()             =>   all index nodes & table leaf nodes
59359: */
59360: static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
59361:   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
59362:   u8 *pEnd;                                /* End mark for a varint */
59363:   u32 nSize;                               /* Size value to return */
59364: 
59365: #ifdef SQLITE_DEBUG
59366:   /* The value returned by this function should always be the same as
59367:   ** the (CellInfo.nSize) value found by doing a full parse of the
59368:   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59369:   ** this function verifies that this invariant is not violated. */
59370:   CellInfo debuginfo;
59371:   pPage->xParseCell(pPage, pCell, &debuginfo);
59372: #endif
59373: 
59374:   nSize = *pIter;
59375:   if( nSize>=0x80 ){
59376:     pEnd = &pIter[8];
59377:     nSize &= 0x7f;
59378:     do{
59379:       nSize = (nSize<<7) | (*++pIter & 0x7f);
59380:     }while( *(pIter)>=0x80 && pIter<pEnd );
59381:   }
59382:   pIter++;
59383:   if( pPage->intKey ){
59384:     /* pIter now points at the 64-bit integer key value, a variable length 
59385:     ** integer. The following block moves pIter to point at the first byte
59386:     ** past the end of the key value. */
59387:     pEnd = &pIter[9];
59388:     while( (*pIter++)&0x80 && pIter<pEnd );
59389:   }
59390:   testcase( nSize==pPage->maxLocal );
59391:   testcase( nSize==pPage->maxLocal+1 );
59392:   if( nSize<=pPage->maxLocal ){
59393:     nSize += (u32)(pIter - pCell);
59394:     if( nSize<4 ) nSize = 4;
59395:   }else{
59396:     int minLocal = pPage->minLocal;
59397:     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
59398:     testcase( nSize==pPage->maxLocal );
59399:     testcase( nSize==pPage->maxLocal+1 );
59400:     if( nSize>pPage->maxLocal ){
59401:       nSize = minLocal;
59402:     }
59403:     nSize += 4 + (u16)(pIter - pCell);
59404:   }
59405:   assert( nSize==debuginfo.nSize || CORRUPT_DB );
59406:   return (u16)nSize;
59407: }
59408: static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
59409:   u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
59410:   u8 *pEnd;              /* End mark for a varint */
59411: 
59412: #ifdef SQLITE_DEBUG
59413:   /* The value returned by this function should always be the same as
59414:   ** the (CellInfo.nSize) value found by doing a full parse of the
59415:   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
59416:   ** this function verifies that this invariant is not violated. */
59417:   CellInfo debuginfo;
59418:   pPage->xParseCell(pPage, pCell, &debuginfo);
59419: #else
59420:   UNUSED_PARAMETER(pPage);
59421: #endif
59422: 
59423:   assert( pPage->childPtrSize==4 );
59424:   pEnd = pIter + 9;
59425:   while( (*pIter++)&0x80 && pIter<pEnd );
59426:   assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
59427:   return (u16)(pIter - pCell);
59428: }
59429: 
59430: 
59431: #ifdef SQLITE_DEBUG
59432: /* This variation on cellSizePtr() is used inside of assert() statements
59433: ** only. */
59434: static u16 cellSize(MemPage *pPage, int iCell){
59435:   return pPage->xCellSize(pPage, findCell(pPage, iCell));
59436: }
59437: #endif
59438: 
59439: #ifndef SQLITE_OMIT_AUTOVACUUM
59440: /*
59441: ** If the cell pCell, part of page pPage contains a pointer
59442: ** to an overflow page, insert an entry into the pointer-map
59443: ** for the overflow page.
59444: */
59445: static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
59446:   CellInfo info;
59447:   if( *pRC ) return;
59448:   assert( pCell!=0 );
59449:   pPage->xParseCell(pPage, pCell, &info);
59450:   if( info.nLocal<info.nPayload ){
59451:     Pgno ovfl = get4byte(&pCell[info.nSize-4]);
59452:     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
59453:   }
59454: }
59455: #endif
59456: 
59457: 
59458: /*
59459: ** Defragment the page given.  All Cells are moved to the
59460: ** end of the page and all free space is collected into one
59461: ** big FreeBlk that occurs in between the header and cell
59462: ** pointer array and the cell content area.
59463: **
59464: ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
59465: ** b-tree page so that there are no freeblocks or fragment bytes, all
59466: ** unused bytes are contained in the unallocated space region, and all
59467: ** cells are packed tightly at the end of the page.
59468: */
59469: static int defragmentPage(MemPage *pPage){
59470:   int i;                     /* Loop counter */
59471:   int pc;                    /* Address of the i-th cell */
59472:   int hdr;                   /* Offset to the page header */
59473:   int size;                  /* Size of a cell */
59474:   int usableSize;            /* Number of usable bytes on a page */
59475:   int cellOffset;            /* Offset to the cell pointer array */
59476:   int cbrk;                  /* Offset to the cell content area */
59477:   int nCell;                 /* Number of cells on the page */
59478:   unsigned char *data;       /* The page data */
59479:   unsigned char *temp;       /* Temp area for cell content */
59480:   unsigned char *src;        /* Source of content */
59481:   int iCellFirst;            /* First allowable cell index */
59482:   int iCellLast;             /* Last possible cell index */
59483: 
59484: 
59485:   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59486:   assert( pPage->pBt!=0 );
59487:   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
59488:   assert( pPage->nOverflow==0 );
59489:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59490:   temp = 0;
59491:   src = data = pPage->aData;
59492:   hdr = pPage->hdrOffset;
59493:   cellOffset = pPage->cellOffset;
59494:   nCell = pPage->nCell;
59495:   assert( nCell==get2byte(&data[hdr+3]) );
59496:   usableSize = pPage->pBt->usableSize;
59497:   cbrk = usableSize;
59498:   iCellFirst = cellOffset + 2*nCell;
59499:   iCellLast = usableSize - 4;
59500:   for(i=0; i<nCell; i++){
59501:     u8 *pAddr;     /* The i-th cell pointer */
59502:     pAddr = &data[cellOffset + i*2];
59503:     pc = get2byte(pAddr);
59504:     testcase( pc==iCellFirst );
59505:     testcase( pc==iCellLast );
59506:     /* These conditions have already been verified in btreeInitPage()
59507:     ** if PRAGMA cell_size_check=ON.
59508:     */
59509:     if( pc<iCellFirst || pc>iCellLast ){
59510:       return SQLITE_CORRUPT_BKPT;
59511:     }
59512:     assert( pc>=iCellFirst && pc<=iCellLast );
59513:     size = pPage->xCellSize(pPage, &src[pc]);
59514:     cbrk -= size;
59515:     if( cbrk<iCellFirst || pc+size>usableSize ){
59516:       return SQLITE_CORRUPT_BKPT;
59517:     }
59518:     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
59519:     testcase( cbrk+size==usableSize );
59520:     testcase( pc+size==usableSize );
59521:     put2byte(pAddr, cbrk);
59522:     if( temp==0 ){
59523:       int x;
59524:       if( cbrk==pc ) continue;
59525:       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
59526:       x = get2byte(&data[hdr+5]);
59527:       memcpy(&temp[x], &data[x], (cbrk+size) - x);
59528:       src = temp;
59529:     }
59530:     memcpy(&data[cbrk], &src[pc], size);
59531:   }
59532:   assert( cbrk>=iCellFirst );
59533:   put2byte(&data[hdr+5], cbrk);
59534:   data[hdr+1] = 0;
59535:   data[hdr+2] = 0;
59536:   data[hdr+7] = 0;
59537:   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
59538:   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59539:   if( cbrk-iCellFirst!=pPage->nFree ){
59540:     return SQLITE_CORRUPT_BKPT;
59541:   }
59542:   return SQLITE_OK;
59543: }
59544: 
59545: /*
59546: ** Search the free-list on page pPg for space to store a cell nByte bytes in
59547: ** size. If one can be found, return a pointer to the space and remove it
59548: ** from the free-list.
59549: **
59550: ** If no suitable space can be found on the free-list, return NULL.
59551: **
59552: ** This function may detect corruption within pPg.  If corruption is
59553: ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
59554: **
59555: ** Slots on the free list that are between 1 and 3 bytes larger than nByte
59556: ** will be ignored if adding the extra space to the fragmentation count
59557: ** causes the fragmentation count to exceed 60.
59558: */
59559: static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
59560:   const int hdr = pPg->hdrOffset;
59561:   u8 * const aData = pPg->aData;
59562:   int iAddr = hdr + 1;
59563:   int pc = get2byte(&aData[iAddr]);
59564:   int x;
59565:   int usableSize = pPg->pBt->usableSize;
59566: 
59567:   assert( pc>0 );
59568:   do{
59569:     int size;            /* Size of the free slot */
59570:     /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
59571:     ** increasing offset. */
59572:     if( pc>usableSize-4 || pc<iAddr+4 ){
59573:       *pRc = SQLITE_CORRUPT_BKPT;
59574:       return 0;
59575:     }
59576:     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
59577:     ** freeblock form a big-endian integer which is the size of the freeblock
59578:     ** in bytes, including the 4-byte header. */
59579:     size = get2byte(&aData[pc+2]);
59580:     if( (x = size - nByte)>=0 ){
59581:       testcase( x==4 );
59582:       testcase( x==3 );
59583:       if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
59584:         *pRc = SQLITE_CORRUPT_BKPT;
59585:         return 0;
59586:       }else if( x<4 ){
59587:         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
59588:         ** number of bytes in fragments may not exceed 60. */
59589:         if( aData[hdr+7]>57 ) return 0;
59590: 
59591:         /* Remove the slot from the free-list. Update the number of
59592:         ** fragmented bytes within the page. */
59593:         memcpy(&aData[iAddr], &aData[pc], 2);
59594:         aData[hdr+7] += (u8)x;
59595:       }else{
59596:         /* The slot remains on the free-list. Reduce its size to account
59597:          ** for the portion used by the new allocation. */
59598:         put2byte(&aData[pc+2], x);
59599:       }
59600:       return &aData[pc + x];
59601:     }
59602:     iAddr = pc;
59603:     pc = get2byte(&aData[pc]);
59604:   }while( pc );
59605: 
59606:   return 0;
59607: }
59608: 
59609: /*
59610: ** Allocate nByte bytes of space from within the B-Tree page passed
59611: ** as the first argument. Write into *pIdx the index into pPage->aData[]
59612: ** of the first byte of allocated space. Return either SQLITE_OK or
59613: ** an error code (usually SQLITE_CORRUPT).
59614: **
59615: ** The caller guarantees that there is sufficient space to make the
59616: ** allocation.  This routine might need to defragment in order to bring
59617: ** all the space together, however.  This routine will avoid using
59618: ** the first two bytes past the cell pointer area since presumably this
59619: ** allocation is being made in order to insert a new cell, so we will
59620: ** also end up needing a new cell pointer.
59621: */
59622: static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
59623:   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
59624:   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
59625:   int top;                             /* First byte of cell content area */
59626:   int rc = SQLITE_OK;                  /* Integer return code */
59627:   int gap;        /* First byte of gap between cell pointers and cell content */
59628:   
59629:   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59630:   assert( pPage->pBt );
59631:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59632:   assert( nByte>=0 );  /* Minimum cell size is 4 */
59633:   assert( pPage->nFree>=nByte );
59634:   assert( pPage->nOverflow==0 );
59635:   assert( nByte < (int)(pPage->pBt->usableSize-8) );
59636: 
59637:   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
59638:   gap = pPage->cellOffset + 2*pPage->nCell;
59639:   assert( gap<=65536 );
59640:   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
59641:   ** and the reserved space is zero (the usual value for reserved space)
59642:   ** then the cell content offset of an empty page wants to be 65536.
59643:   ** However, that integer is too large to be stored in a 2-byte unsigned
59644:   ** integer, so a value of 0 is used in its place. */
59645:   top = get2byte(&data[hdr+5]);
59646:   assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
59647:   if( gap>top ){
59648:     if( top==0 && pPage->pBt->usableSize==65536 ){
59649:       top = 65536;
59650:     }else{
59651:       return SQLITE_CORRUPT_BKPT;
59652:     }
59653:   }
59654: 
59655:   /* If there is enough space between gap and top for one more cell pointer
59656:   ** array entry offset, and if the freelist is not empty, then search the
59657:   ** freelist looking for a free slot big enough to satisfy the request.
59658:   */
59659:   testcase( gap+2==top );
59660:   testcase( gap+1==top );
59661:   testcase( gap==top );
59662:   if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
59663:     u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
59664:     if( pSpace ){
59665:       assert( pSpace>=data && (pSpace - data)<65536 );
59666:       *pIdx = (int)(pSpace - data);
59667:       return SQLITE_OK;
59668:     }else if( rc ){
59669:       return rc;
59670:     }
59671:   }
59672: 
59673:   /* The request could not be fulfilled using a freelist slot.  Check
59674:   ** to see if defragmentation is necessary.
59675:   */
59676:   testcase( gap+2+nByte==top );
59677:   if( gap+2+nByte>top ){
59678:     assert( pPage->nCell>0 || CORRUPT_DB );
59679:     rc = defragmentPage(pPage);
59680:     if( rc ) return rc;
59681:     top = get2byteNotZero(&data[hdr+5]);
59682:     assert( gap+nByte<=top );
59683:   }
59684: 
59685: 
59686:   /* Allocate memory from the gap in between the cell pointer array
59687:   ** and the cell content area.  The btreeInitPage() call has already
59688:   ** validated the freelist.  Given that the freelist is valid, there
59689:   ** is no way that the allocation can extend off the end of the page.
59690:   ** The assert() below verifies the previous sentence.
59691:   */
59692:   top -= nByte;
59693:   put2byte(&data[hdr+5], top);
59694:   assert( top+nByte <= (int)pPage->pBt->usableSize );
59695:   *pIdx = top;
59696:   return SQLITE_OK;
59697: }
59698: 
59699: /*
59700: ** Return a section of the pPage->aData to the freelist.
59701: ** The first byte of the new free block is pPage->aData[iStart]
59702: ** and the size of the block is iSize bytes.
59703: **
59704: ** Adjacent freeblocks are coalesced.
59705: **
59706: ** Note that even though the freeblock list was checked by btreeInitPage(),
59707: ** that routine will not detect overlap between cells or freeblocks.  Nor
59708: ** does it detect cells or freeblocks that encrouch into the reserved bytes
59709: ** at the end of the page.  So do additional corruption checks inside this
59710: ** routine and return SQLITE_CORRUPT if any problems are found.
59711: */
59712: static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
59713:   u16 iPtr;                             /* Address of ptr to next freeblock */
59714:   u16 iFreeBlk;                         /* Address of the next freeblock */
59715:   u8 hdr;                               /* Page header size.  0 or 100 */
59716:   u8 nFrag = 0;                         /* Reduction in fragmentation */
59717:   u16 iOrigSize = iSize;                /* Original value of iSize */
59718:   u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
59719:   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
59720:   unsigned char *data = pPage->aData;   /* Page content */
59721: 
59722:   assert( pPage->pBt!=0 );
59723:   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59724:   assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
59725:   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
59726:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59727:   assert( iSize>=4 );   /* Minimum cell size is 4 */
59728:   assert( iStart<=iLast );
59729: 
59730:   /* Overwrite deleted information with zeros when the secure_delete
59731:   ** option is enabled */
59732:   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
59733:     memset(&data[iStart], 0, iSize);
59734:   }
59735: 
59736:   /* The list of freeblocks must be in ascending order.  Find the 
59737:   ** spot on the list where iStart should be inserted.
59738:   */
59739:   hdr = pPage->hdrOffset;
59740:   iPtr = hdr + 1;
59741:   if( data[iPtr+1]==0 && data[iPtr]==0 ){
59742:     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
59743:   }else{
59744:     while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
59745:       if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
59746:       iPtr = iFreeBlk;
59747:     }
59748:     if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
59749:     assert( iFreeBlk>iPtr || iFreeBlk==0 );
59750:   
59751:     /* At this point:
59752:     **    iFreeBlk:   First freeblock after iStart, or zero if none
59753:     **    iPtr:       The address of a pointer to iFreeBlk
59754:     **
59755:     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
59756:     */
59757:     if( iFreeBlk && iEnd+3>=iFreeBlk ){
59758:       nFrag = iFreeBlk - iEnd;
59759:       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
59760:       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
59761:       if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
59762:       iSize = iEnd - iStart;
59763:       iFreeBlk = get2byte(&data[iFreeBlk]);
59764:     }
59765:   
59766:     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
59767:     ** pointer in the page header) then check to see if iStart should be
59768:     ** coalesced onto the end of iPtr.
59769:     */
59770:     if( iPtr>hdr+1 ){
59771:       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
59772:       if( iPtrEnd+3>=iStart ){
59773:         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
59774:         nFrag += iStart - iPtrEnd;
59775:         iSize = iEnd - iPtr;
59776:         iStart = iPtr;
59777:       }
59778:     }
59779:     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
59780:     data[hdr+7] -= nFrag;
59781:   }
59782:   if( iStart==get2byte(&data[hdr+5]) ){
59783:     /* The new freeblock is at the beginning of the cell content area,
59784:     ** so just extend the cell content area rather than create another
59785:     ** freelist entry */
59786:     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
59787:     put2byte(&data[hdr+1], iFreeBlk);
59788:     put2byte(&data[hdr+5], iEnd);
59789:   }else{
59790:     /* Insert the new freeblock into the freelist */
59791:     put2byte(&data[iPtr], iStart);
59792:     put2byte(&data[iStart], iFreeBlk);
59793:     put2byte(&data[iStart+2], iSize);
59794:   }
59795:   pPage->nFree += iOrigSize;
59796:   return SQLITE_OK;
59797: }
59798: 
59799: /*
59800: ** Decode the flags byte (the first byte of the header) for a page
59801: ** and initialize fields of the MemPage structure accordingly.
59802: **
59803: ** Only the following combinations are supported.  Anything different
59804: ** indicates a corrupt database files:
59805: **
59806: **         PTF_ZERODATA
59807: **         PTF_ZERODATA | PTF_LEAF
59808: **         PTF_LEAFDATA | PTF_INTKEY
59809: **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
59810: */
59811: static int decodeFlags(MemPage *pPage, int flagByte){
59812:   BtShared *pBt;     /* A copy of pPage->pBt */
59813: 
59814:   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
59815:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59816:   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
59817:   flagByte &= ~PTF_LEAF;
59818:   pPage->childPtrSize = 4-4*pPage->leaf;
59819:   pPage->xCellSize = cellSizePtr;
59820:   pBt = pPage->pBt;
59821:   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
59822:     /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59823:     ** interior table b-tree page. */
59824:     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
59825:     /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59826:     ** leaf table b-tree page. */
59827:     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
59828:     pPage->intKey = 1;
59829:     if( pPage->leaf ){
59830:       pPage->intKeyLeaf = 1;
59831:       pPage->xParseCell = btreeParseCellPtr;
59832:     }else{
59833:       pPage->intKeyLeaf = 0;
59834:       pPage->xCellSize = cellSizePtrNoPayload;
59835:       pPage->xParseCell = btreeParseCellPtrNoPayload;
59836:     }
59837:     pPage->maxLocal = pBt->maxLeaf;
59838:     pPage->minLocal = pBt->minLeaf;
59839:   }else if( flagByte==PTF_ZERODATA ){
59840:     /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59841:     ** interior index b-tree page. */
59842:     assert( (PTF_ZERODATA)==2 );
59843:     /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59844:     ** leaf index b-tree page. */
59845:     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
59846:     pPage->intKey = 0;
59847:     pPage->intKeyLeaf = 0;
59848:     pPage->xParseCell = btreeParseCellPtrIndex;
59849:     pPage->maxLocal = pBt->maxLocal;
59850:     pPage->minLocal = pBt->minLocal;
59851:   }else{
59852:     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
59853:     ** an error. */
59854:     return SQLITE_CORRUPT_BKPT;
59855:   }
59856:   pPage->max1bytePayload = pBt->max1bytePayload;
59857:   return SQLITE_OK;
59858: }
59859: 
59860: /*
59861: ** Initialize the auxiliary information for a disk block.
59862: **
59863: ** Return SQLITE_OK on success.  If we see that the page does
59864: ** not contain a well-formed database page, then return 
59865: ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
59866: ** guarantee that the page is well-formed.  It only shows that
59867: ** we failed to detect any corruption.
59868: */
59869: static int btreeInitPage(MemPage *pPage){
59870: 
59871:   assert( pPage->pBt!=0 );
59872:   assert( pPage->pBt->db!=0 );
59873:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59874:   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
59875:   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
59876:   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
59877: 
59878:   if( !pPage->isInit ){
59879:     u16 pc;            /* Address of a freeblock within pPage->aData[] */
59880:     u8 hdr;            /* Offset to beginning of page header */
59881:     u8 *data;          /* Equal to pPage->aData */
59882:     BtShared *pBt;        /* The main btree structure */
59883:     int usableSize;    /* Amount of usable space on each page */
59884:     u16 cellOffset;    /* Offset from start of page to first cell pointer */
59885:     int nFree;         /* Number of unused bytes on the page */
59886:     int top;           /* First byte of the cell content area */
59887:     int iCellFirst;    /* First allowable cell or freeblock offset */
59888:     int iCellLast;     /* Last possible cell or freeblock offset */
59889: 
59890:     pBt = pPage->pBt;
59891: 
59892:     hdr = pPage->hdrOffset;
59893:     data = pPage->aData;
59894:     /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
59895:     ** the b-tree page type. */
59896:     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
59897:     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
59898:     pPage->maskPage = (u16)(pBt->pageSize - 1);
59899:     pPage->nOverflow = 0;
59900:     usableSize = pBt->usableSize;
59901:     pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
59902:     pPage->aDataEnd = &data[usableSize];
59903:     pPage->aCellIdx = &data[cellOffset];
59904:     pPage->aDataOfst = &data[pPage->childPtrSize];
59905:     /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
59906:     ** the start of the cell content area. A zero value for this integer is
59907:     ** interpreted as 65536. */
59908:     top = get2byteNotZero(&data[hdr+5]);
59909:     /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
59910:     ** number of cells on the page. */
59911:     pPage->nCell = get2byte(&data[hdr+3]);
59912:     if( pPage->nCell>MX_CELL(pBt) ){
59913:       /* To many cells for a single page.  The page must be corrupt */
59914:       return SQLITE_CORRUPT_BKPT;
59915:     }
59916:     testcase( pPage->nCell==MX_CELL(pBt) );
59917:     /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
59918:     ** possible for a root page of a table that contains no rows) then the
59919:     ** offset to the cell content area will equal the page size minus the
59920:     ** bytes of reserved space. */
59921:     assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
59922: 
59923:     /* A malformed database page might cause us to read past the end
59924:     ** of page when parsing a cell.  
59925:     **
59926:     ** The following block of code checks early to see if a cell extends
59927:     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
59928:     ** returned if it does.
59929:     */
59930:     iCellFirst = cellOffset + 2*pPage->nCell;
59931:     iCellLast = usableSize - 4;
59932:     if( pBt->db->flags & SQLITE_CellSizeCk ){
59933:       int i;            /* Index into the cell pointer array */
59934:       int sz;           /* Size of a cell */
59935: 
59936:       if( !pPage->leaf ) iCellLast--;
59937:       for(i=0; i<pPage->nCell; i++){
59938:         pc = get2byteAligned(&data[cellOffset+i*2]);
59939:         testcase( pc==iCellFirst );
59940:         testcase( pc==iCellLast );
59941:         if( pc<iCellFirst || pc>iCellLast ){
59942:           return SQLITE_CORRUPT_BKPT;
59943:         }
59944:         sz = pPage->xCellSize(pPage, &data[pc]);
59945:         testcase( pc+sz==usableSize );
59946:         if( pc+sz>usableSize ){
59947:           return SQLITE_CORRUPT_BKPT;
59948:         }
59949:       }
59950:       if( !pPage->leaf ) iCellLast++;
59951:     }  
59952: 
59953:     /* Compute the total free space on the page
59954:     ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
59955:     ** start of the first freeblock on the page, or is zero if there are no
59956:     ** freeblocks. */
59957:     pc = get2byte(&data[hdr+1]);
59958:     nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
59959:     while( pc>0 ){
59960:       u16 next, size;
59961:       if( pc<iCellFirst || pc>iCellLast ){
59962:         /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
59963:         ** always be at least one cell before the first freeblock.
59964:         **
59965:         ** Or, the freeblock is off the end of the page
59966:         */
59967:         return SQLITE_CORRUPT_BKPT; 
59968:       }
59969:       next = get2byte(&data[pc]);
59970:       size = get2byte(&data[pc+2]);
59971:       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
59972:         /* Free blocks must be in ascending order. And the last byte of
59973:         ** the free-block must lie on the database page.  */
59974:         return SQLITE_CORRUPT_BKPT; 
59975:       }
59976:       nFree = nFree + size;
59977:       pc = next;
59978:     }
59979: 
59980:     /* At this point, nFree contains the sum of the offset to the start
59981:     ** of the cell-content area plus the number of free bytes within
59982:     ** the cell-content area. If this is greater than the usable-size
59983:     ** of the page, then the page must be corrupted. This check also
59984:     ** serves to verify that the offset to the start of the cell-content
59985:     ** area, according to the page header, lies within the page.
59986:     */
59987:     if( nFree>usableSize ){
59988:       return SQLITE_CORRUPT_BKPT; 
59989:     }
59990:     pPage->nFree = (u16)(nFree - iCellFirst);
59991:     pPage->isInit = 1;
59992:   }
59993:   return SQLITE_OK;
59994: }
59995: 
59996: /*
59997: ** Set up a raw page so that it looks like a database page holding
59998: ** no entries.
59999: */
60000: static void zeroPage(MemPage *pPage, int flags){
60001:   unsigned char *data = pPage->aData;
60002:   BtShared *pBt = pPage->pBt;
60003:   u8 hdr = pPage->hdrOffset;
60004:   u16 first;
60005: 
60006:   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
60007:   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60008:   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
60009:   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60010:   assert( sqlite3_mutex_held(pBt->mutex) );
60011:   if( pBt->btsFlags & BTS_SECURE_DELETE ){
60012:     memset(&data[hdr], 0, pBt->usableSize - hdr);
60013:   }
60014:   data[hdr] = (char)flags;
60015:   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
60016:   memset(&data[hdr+1], 0, 4);
60017:   data[hdr+7] = 0;
60018:   put2byte(&data[hdr+5], pBt->usableSize);
60019:   pPage->nFree = (u16)(pBt->usableSize - first);
60020:   decodeFlags(pPage, flags);
60021:   pPage->cellOffset = first;
60022:   pPage->aDataEnd = &data[pBt->usableSize];
60023:   pPage->aCellIdx = &data[first];
60024:   pPage->aDataOfst = &data[pPage->childPtrSize];
60025:   pPage->nOverflow = 0;
60026:   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
60027:   pPage->maskPage = (u16)(pBt->pageSize - 1);
60028:   pPage->nCell = 0;
60029:   pPage->isInit = 1;
60030: }
60031: 
60032: 
60033: /*
60034: ** Convert a DbPage obtained from the pager into a MemPage used by
60035: ** the btree layer.
60036: */
60037: static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
60038:   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60039:   if( pgno!=pPage->pgno ){
60040:     pPage->aData = sqlite3PagerGetData(pDbPage);
60041:     pPage->pDbPage = pDbPage;
60042:     pPage->pBt = pBt;
60043:     pPage->pgno = pgno;
60044:     pPage->hdrOffset = pgno==1 ? 100 : 0;
60045:   }
60046:   assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
60047:   return pPage; 
60048: }
60049: 
60050: /*
60051: ** Get a page from the pager.  Initialize the MemPage.pBt and
60052: ** MemPage.aData elements if needed.  See also: btreeGetUnusedPage().
60053: **
60054: ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
60055: ** about the content of the page at this time.  So do not go to the disk
60056: ** to fetch the content.  Just fill in the content with zeros for now.
60057: ** If in the future we call sqlite3PagerWrite() on this page, that
60058: ** means we have started to be concerned about content and the disk
60059: ** read should occur at that point.
60060: */
60061: static int btreeGetPage(
60062:   BtShared *pBt,       /* The btree */
60063:   Pgno pgno,           /* Number of the page to fetch */
60064:   MemPage **ppPage,    /* Return the page in this parameter */
60065:   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60066: ){
60067:   int rc;
60068:   DbPage *pDbPage;
60069: 
60070:   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
60071:   assert( sqlite3_mutex_held(pBt->mutex) );
60072:   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
60073:   if( rc ) return rc;
60074:   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
60075:   return SQLITE_OK;
60076: }
60077: 
60078: /*
60079: ** Retrieve a page from the pager cache. If the requested page is not
60080: ** already in the pager cache return NULL. Initialize the MemPage.pBt and
60081: ** MemPage.aData elements if needed.
60082: */
60083: static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
60084:   DbPage *pDbPage;
60085:   assert( sqlite3_mutex_held(pBt->mutex) );
60086:   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
60087:   if( pDbPage ){
60088:     return btreePageFromDbPage(pDbPage, pgno, pBt);
60089:   }
60090:   return 0;
60091: }
60092: 
60093: /*
60094: ** Return the size of the database file in pages. If there is any kind of
60095: ** error, return ((unsigned int)-1).
60096: */
60097: static Pgno btreePagecount(BtShared *pBt){
60098:   return pBt->nPage;
60099: }
60100: SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
60101:   assert( sqlite3BtreeHoldsMutex(p) );
60102:   assert( ((p->pBt->nPage)&0x8000000)==0 );
60103:   return btreePagecount(p->pBt);
60104: }
60105: 
60106: /*
60107: ** Get a page from the pager and initialize it.
60108: **
60109: ** If pCur!=0 then the page is being fetched as part of a moveToChild()
60110: ** call.  Do additional sanity checking on the page in this case.
60111: ** And if the fetch fails, this routine must decrement pCur->iPage.
60112: **
60113: ** The page is fetched as read-write unless pCur is not NULL and is
60114: ** a read-only cursor.
60115: **
60116: ** If an error occurs, then *ppPage is undefined. It
60117: ** may remain unchanged, or it may be set to an invalid value.
60118: */
60119: static int getAndInitPage(
60120:   BtShared *pBt,                  /* The database file */
60121:   Pgno pgno,                      /* Number of the page to get */
60122:   MemPage **ppPage,               /* Write the page pointer here */
60123:   BtCursor *pCur,                 /* Cursor to receive the page, or NULL */
60124:   int bReadOnly                   /* True for a read-only page */
60125: ){
60126:   int rc;
60127:   DbPage *pDbPage;
60128:   assert( sqlite3_mutex_held(pBt->mutex) );
60129:   assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
60130:   assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
60131:   assert( pCur==0 || pCur->iPage>0 );
60132: 
60133:   if( pgno>btreePagecount(pBt) ){
60134:     rc = SQLITE_CORRUPT_BKPT;
60135:     goto getAndInitPage_error;
60136:   }
60137:   rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
60138:   if( rc ){
60139:     goto getAndInitPage_error;
60140:   }
60141:   *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
60142:   if( (*ppPage)->isInit==0 ){
60143:     btreePageFromDbPage(pDbPage, pgno, pBt);
60144:     rc = btreeInitPage(*ppPage);
60145:     if( rc!=SQLITE_OK ){
60146:       releasePage(*ppPage);
60147:       goto getAndInitPage_error;
60148:     }
60149:   }
60150:   assert( (*ppPage)->pgno==pgno );
60151:   assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
60152: 
60153:   /* If obtaining a child page for a cursor, we must verify that the page is
60154:   ** compatible with the root page. */
60155:   if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
60156:     rc = SQLITE_CORRUPT_BKPT;
60157:     releasePage(*ppPage);
60158:     goto getAndInitPage_error;
60159:   }
60160:   return SQLITE_OK;
60161: 
60162: getAndInitPage_error:
60163:   if( pCur ) pCur->iPage--;
60164:   testcase( pgno==0 );
60165:   assert( pgno!=0 || rc==SQLITE_CORRUPT );
60166:   return rc;
60167: }
60168: 
60169: /*
60170: ** Release a MemPage.  This should be called once for each prior
60171: ** call to btreeGetPage.
60172: */
60173: static void releasePageNotNull(MemPage *pPage){
60174:   assert( pPage->aData );
60175:   assert( pPage->pBt );
60176:   assert( pPage->pDbPage!=0 );
60177:   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
60178:   assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
60179:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60180:   sqlite3PagerUnrefNotNull(pPage->pDbPage);
60181: }
60182: static void releasePage(MemPage *pPage){
60183:   if( pPage ) releasePageNotNull(pPage);
60184: }
60185: 
60186: /*
60187: ** Get an unused page.
60188: **
60189: ** This works just like btreeGetPage() with the addition:
60190: **
60191: **   *  If the page is already in use for some other purpose, immediately
60192: **      release it and return an SQLITE_CURRUPT error.
60193: **   *  Make sure the isInit flag is clear
60194: */
60195: static int btreeGetUnusedPage(
60196:   BtShared *pBt,       /* The btree */
60197:   Pgno pgno,           /* Number of the page to fetch */
60198:   MemPage **ppPage,    /* Return the page in this parameter */
60199:   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
60200: ){
60201:   int rc = btreeGetPage(pBt, pgno, ppPage, flags);
60202:   if( rc==SQLITE_OK ){
60203:     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
60204:       releasePage(*ppPage);
60205:       *ppPage = 0;
60206:       return SQLITE_CORRUPT_BKPT;
60207:     }
60208:     (*ppPage)->isInit = 0;
60209:   }else{
60210:     *ppPage = 0;
60211:   }
60212:   return rc;
60213: }
60214: 
60215: 
60216: /*
60217: ** During a rollback, when the pager reloads information into the cache
60218: ** so that the cache is restored to its original state at the start of
60219: ** the transaction, for each page restored this routine is called.
60220: **
60221: ** This routine needs to reset the extra data section at the end of the
60222: ** page to agree with the restored data.
60223: */
60224: static void pageReinit(DbPage *pData){
60225:   MemPage *pPage;
60226:   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
60227:   assert( sqlite3PagerPageRefcount(pData)>0 );
60228:   if( pPage->isInit ){
60229:     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60230:     pPage->isInit = 0;
60231:     if( sqlite3PagerPageRefcount(pData)>1 ){
60232:       /* pPage might not be a btree page;  it might be an overflow page
60233:       ** or ptrmap page or a free page.  In those cases, the following
60234:       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
60235:       ** But no harm is done by this.  And it is very important that
60236:       ** btreeInitPage() be called on every btree page so we make
60237:       ** the call for every page that comes in for re-initing. */
60238:       btreeInitPage(pPage);
60239:     }
60240:   }
60241: }
60242: 
60243: /*
60244: ** Invoke the busy handler for a btree.
60245: */
60246: static int btreeInvokeBusyHandler(void *pArg){
60247:   BtShared *pBt = (BtShared*)pArg;
60248:   assert( pBt->db );
60249:   assert( sqlite3_mutex_held(pBt->db->mutex) );
60250:   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
60251: }
60252: 
60253: /*
60254: ** Open a database file.
60255: ** 
60256: ** zFilename is the name of the database file.  If zFilename is NULL
60257: ** then an ephemeral database is created.  The ephemeral database might
60258: ** be exclusively in memory, or it might use a disk-based memory cache.
60259: ** Either way, the ephemeral database will be automatically deleted 
60260: ** when sqlite3BtreeClose() is called.
60261: **
60262: ** If zFilename is ":memory:" then an in-memory database is created
60263: ** that is automatically destroyed when it is closed.
60264: **
60265: ** The "flags" parameter is a bitmask that might contain bits like
60266: ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
60267: **
60268: ** If the database is already opened in the same database connection
60269: ** and we are in shared cache mode, then the open will fail with an
60270: ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
60271: ** objects in the same database connection since doing so will lead
60272: ** to problems with locking.
60273: */
60274: SQLITE_PRIVATE int sqlite3BtreeOpen(
60275:   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
60276:   const char *zFilename,  /* Name of the file containing the BTree database */
60277:   sqlite3 *db,            /* Associated database handle */
60278:   Btree **ppBtree,        /* Pointer to new Btree object written here */
60279:   int flags,              /* Options */
60280:   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
60281: ){
60282:   BtShared *pBt = 0;             /* Shared part of btree structure */
60283:   Btree *p;                      /* Handle to return */
60284:   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
60285:   int rc = SQLITE_OK;            /* Result code from this function */
60286:   u8 nReserve;                   /* Byte of unused space on each page */
60287:   unsigned char zDbHeader[100];  /* Database header content */
60288: 
60289:   /* True if opening an ephemeral, temporary database */
60290:   const int isTempDb = zFilename==0 || zFilename[0]==0;
60291: 
60292:   /* Set the variable isMemdb to true for an in-memory database, or 
60293:   ** false for a file-based database.
60294:   */
60295: #ifdef SQLITE_OMIT_MEMORYDB
60296:   const int isMemdb = 0;
60297: #else
60298:   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
60299:                        || (isTempDb && sqlite3TempInMemory(db))
60300:                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
60301: #endif
60302: 
60303:   assert( db!=0 );
60304:   assert( pVfs!=0 );
60305:   assert( sqlite3_mutex_held(db->mutex) );
60306:   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
60307: 
60308:   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
60309:   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
60310: 
60311:   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
60312:   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
60313: 
60314:   if( isMemdb ){
60315:     flags |= BTREE_MEMORY;
60316:   }
60317:   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
60318:     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
60319:   }
60320:   p = sqlite3MallocZero(sizeof(Btree));
60321:   if( !p ){
60322:     return SQLITE_NOMEM_BKPT;
60323:   }
60324:   p->inTrans = TRANS_NONE;
60325:   p->db = db;
60326: #ifndef SQLITE_OMIT_SHARED_CACHE
60327:   p->lock.pBtree = p;
60328:   p->lock.iTable = 1;
60329: #endif
60330: 
60331: #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60332:   /*
60333:   ** If this Btree is a candidate for shared cache, try to find an
60334:   ** existing BtShared object that we can share with
60335:   */
60336:   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
60337:     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
60338:       int nFilename = sqlite3Strlen30(zFilename)+1;
60339:       int nFullPathname = pVfs->mxPathname+1;
60340:       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
60341:       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60342: 
60343:       p->sharable = 1;
60344:       if( !zFullPathname ){
60345:         sqlite3_free(p);
60346:         return SQLITE_NOMEM_BKPT;
60347:       }
60348:       if( isMemdb ){
60349:         memcpy(zFullPathname, zFilename, nFilename);
60350:       }else{
60351:         rc = sqlite3OsFullPathname(pVfs, zFilename,
60352:                                    nFullPathname, zFullPathname);
60353:         if( rc ){
60354:           sqlite3_free(zFullPathname);
60355:           sqlite3_free(p);
60356:           return rc;
60357:         }
60358:       }
60359: #if SQLITE_THREADSAFE
60360:       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
60361:       sqlite3_mutex_enter(mutexOpen);
60362:       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
60363:       sqlite3_mutex_enter(mutexShared);
60364: #endif
60365:       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
60366:         assert( pBt->nRef>0 );
60367:         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
60368:                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
60369:           int iDb;
60370:           for(iDb=db->nDb-1; iDb>=0; iDb--){
60371:             Btree *pExisting = db->aDb[iDb].pBt;
60372:             if( pExisting && pExisting->pBt==pBt ){
60373:               sqlite3_mutex_leave(mutexShared);
60374:               sqlite3_mutex_leave(mutexOpen);
60375:               sqlite3_free(zFullPathname);
60376:               sqlite3_free(p);
60377:               return SQLITE_CONSTRAINT;
60378:             }
60379:           }
60380:           p->pBt = pBt;
60381:           pBt->nRef++;
60382:           break;
60383:         }
60384:       }
60385:       sqlite3_mutex_leave(mutexShared);
60386:       sqlite3_free(zFullPathname);
60387:     }
60388: #ifdef SQLITE_DEBUG
60389:     else{
60390:       /* In debug mode, we mark all persistent databases as sharable
60391:       ** even when they are not.  This exercises the locking code and
60392:       ** gives more opportunity for asserts(sqlite3_mutex_held())
60393:       ** statements to find locking problems.
60394:       */
60395:       p->sharable = 1;
60396:     }
60397: #endif
60398:   }
60399: #endif
60400:   if( pBt==0 ){
60401:     /*
60402:     ** The following asserts make sure that structures used by the btree are
60403:     ** the right size.  This is to guard against size changes that result
60404:     ** when compiling on a different architecture.
60405:     */
60406:     assert( sizeof(i64)==8 );
60407:     assert( sizeof(u64)==8 );
60408:     assert( sizeof(u32)==4 );
60409:     assert( sizeof(u16)==2 );
60410:     assert( sizeof(Pgno)==4 );
60411:   
60412:     pBt = sqlite3MallocZero( sizeof(*pBt) );
60413:     if( pBt==0 ){
60414:       rc = SQLITE_NOMEM_BKPT;
60415:       goto btree_open_out;
60416:     }
60417:     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
60418:                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
60419:     if( rc==SQLITE_OK ){
60420:       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
60421:       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
60422:     }
60423:     if( rc!=SQLITE_OK ){
60424:       goto btree_open_out;
60425:     }
60426:     pBt->openFlags = (u8)flags;
60427:     pBt->db = db;
60428:     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
60429:     p->pBt = pBt;
60430:   
60431:     pBt->pCursor = 0;
60432:     pBt->pPage1 = 0;
60433:     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
60434: #ifdef SQLITE_SECURE_DELETE
60435:     pBt->btsFlags |= BTS_SECURE_DELETE;
60436: #endif
60437:     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
60438:     ** determined by the 2-byte integer located at an offset of 16 bytes from
60439:     ** the beginning of the database file. */
60440:     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
60441:     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
60442:          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
60443:       pBt->pageSize = 0;
60444: #ifndef SQLITE_OMIT_AUTOVACUUM
60445:       /* If the magic name ":memory:" will create an in-memory database, then
60446:       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
60447:       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
60448:       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
60449:       ** regular file-name. In this case the auto-vacuum applies as per normal.
60450:       */
60451:       if( zFilename && !isMemdb ){
60452:         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
60453:         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
60454:       }
60455: #endif
60456:       nReserve = 0;
60457:     }else{
60458:       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
60459:       ** determined by the one-byte unsigned integer found at an offset of 20
60460:       ** into the database file header. */
60461:       nReserve = zDbHeader[20];
60462:       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60463: #ifndef SQLITE_OMIT_AUTOVACUUM
60464:       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
60465:       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
60466: #endif
60467:     }
60468:     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60469:     if( rc ) goto btree_open_out;
60470:     pBt->usableSize = pBt->pageSize - nReserve;
60471:     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
60472:    
60473: #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60474:     /* Add the new BtShared object to the linked list sharable BtShareds.
60475:     */
60476:     pBt->nRef = 1;
60477:     if( p->sharable ){
60478:       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60479:       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
60480:       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
60481:         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
60482:         if( pBt->mutex==0 ){
60483:           rc = SQLITE_NOMEM_BKPT;
60484:           goto btree_open_out;
60485:         }
60486:       }
60487:       sqlite3_mutex_enter(mutexShared);
60488:       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
60489:       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
60490:       sqlite3_mutex_leave(mutexShared);
60491:     }
60492: #endif
60493:   }
60494: 
60495: #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60496:   /* If the new Btree uses a sharable pBtShared, then link the new
60497:   ** Btree into the list of all sharable Btrees for the same connection.
60498:   ** The list is kept in ascending order by pBt address.
60499:   */
60500:   if( p->sharable ){
60501:     int i;
60502:     Btree *pSib;
60503:     for(i=0; i<db->nDb; i++){
60504:       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
60505:         while( pSib->pPrev ){ pSib = pSib->pPrev; }
60506:         if( (uptr)p->pBt<(uptr)pSib->pBt ){
60507:           p->pNext = pSib;
60508:           p->pPrev = 0;
60509:           pSib->pPrev = p;
60510:         }else{
60511:           while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
60512:             pSib = pSib->pNext;
60513:           }
60514:           p->pNext = pSib->pNext;
60515:           p->pPrev = pSib;
60516:           if( p->pNext ){
60517:             p->pNext->pPrev = p;
60518:           }
60519:           pSib->pNext = p;
60520:         }
60521:         break;
60522:       }
60523:     }
60524:   }
60525: #endif
60526:   *ppBtree = p;
60527: 
60528: btree_open_out:
60529:   if( rc!=SQLITE_OK ){
60530:     if( pBt && pBt->pPager ){
60531:       sqlite3PagerClose(pBt->pPager);
60532:     }
60533:     sqlite3_free(pBt);
60534:     sqlite3_free(p);
60535:     *ppBtree = 0;
60536:   }else{
60537:     /* If the B-Tree was successfully opened, set the pager-cache size to the
60538:     ** default value. Except, when opening on an existing shared pager-cache,
60539:     ** do not change the pager-cache size.
60540:     */
60541:     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
60542:       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
60543:     }
60544:   }
60545:   if( mutexOpen ){
60546:     assert( sqlite3_mutex_held(mutexOpen) );
60547:     sqlite3_mutex_leave(mutexOpen);
60548:   }
60549:   assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
60550:   return rc;
60551: }
60552: 
60553: /*
60554: ** Decrement the BtShared.nRef counter.  When it reaches zero,
60555: ** remove the BtShared structure from the sharing list.  Return
60556: ** true if the BtShared.nRef counter reaches zero and return
60557: ** false if it is still positive.
60558: */
60559: static int removeFromSharingList(BtShared *pBt){
60560: #ifndef SQLITE_OMIT_SHARED_CACHE
60561:   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
60562:   BtShared *pList;
60563:   int removed = 0;
60564: 
60565:   assert( sqlite3_mutex_notheld(pBt->mutex) );
60566:   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
60567:   sqlite3_mutex_enter(pMaster);
60568:   pBt->nRef--;
60569:   if( pBt->nRef<=0 ){
60570:     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
60571:       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
60572:     }else{
60573:       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
60574:       while( ALWAYS(pList) && pList->pNext!=pBt ){
60575:         pList=pList->pNext;
60576:       }
60577:       if( ALWAYS(pList) ){
60578:         pList->pNext = pBt->pNext;
60579:       }
60580:     }
60581:     if( SQLITE_THREADSAFE ){
60582:       sqlite3_mutex_free(pBt->mutex);
60583:     }
60584:     removed = 1;
60585:   }
60586:   sqlite3_mutex_leave(pMaster);
60587:   return removed;
60588: #else
60589:   return 1;
60590: #endif
60591: }
60592: 
60593: /*
60594: ** Make sure pBt->pTmpSpace points to an allocation of 
60595: ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
60596: ** pointer.
60597: */
60598: static void allocateTempSpace(BtShared *pBt){
60599:   if( !pBt->pTmpSpace ){
60600:     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
60601: 
60602:     /* One of the uses of pBt->pTmpSpace is to format cells before
60603:     ** inserting them into a leaf page (function fillInCell()). If
60604:     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
60605:     ** by the various routines that manipulate binary cells. Which
60606:     ** can mean that fillInCell() only initializes the first 2 or 3
60607:     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
60608:     ** it into a database page. This is not actually a problem, but it
60609:     ** does cause a valgrind error when the 1 or 2 bytes of unitialized 
60610:     ** data is passed to system call write(). So to avoid this error,
60611:     ** zero the first 4 bytes of temp space here.
60612:     **
60613:     ** Also:  Provide four bytes of initialized space before the
60614:     ** beginning of pTmpSpace as an area available to prepend the
60615:     ** left-child pointer to the beginning of a cell.
60616:     */
60617:     if( pBt->pTmpSpace ){
60618:       memset(pBt->pTmpSpace, 0, 8);
60619:       pBt->pTmpSpace += 4;
60620:     }
60621:   }
60622: }
60623: 
60624: /*
60625: ** Free the pBt->pTmpSpace allocation
60626: */
60627: static void freeTempSpace(BtShared *pBt){
60628:   if( pBt->pTmpSpace ){
60629:     pBt->pTmpSpace -= 4;
60630:     sqlite3PageFree(pBt->pTmpSpace);
60631:     pBt->pTmpSpace = 0;
60632:   }
60633: }
60634: 
60635: /*
60636: ** Close an open database and invalidate all cursors.
60637: */
60638: SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
60639:   BtShared *pBt = p->pBt;
60640:   BtCursor *pCur;
60641: 
60642:   /* Close all cursors opened via this handle.  */
60643:   assert( sqlite3_mutex_held(p->db->mutex) );
60644:   sqlite3BtreeEnter(p);
60645:   pCur = pBt->pCursor;
60646:   while( pCur ){
60647:     BtCursor *pTmp = pCur;
60648:     pCur = pCur->pNext;
60649:     if( pTmp->pBtree==p ){
60650:       sqlite3BtreeCloseCursor(pTmp);
60651:     }
60652:   }
60653: 
60654:   /* Rollback any active transaction and free the handle structure.
60655:   ** The call to sqlite3BtreeRollback() drops any table-locks held by
60656:   ** this handle.
60657:   */
60658:   sqlite3BtreeRollback(p, SQLITE_OK, 0);
60659:   sqlite3BtreeLeave(p);
60660: 
60661:   /* If there are still other outstanding references to the shared-btree
60662:   ** structure, return now. The remainder of this procedure cleans 
60663:   ** up the shared-btree.
60664:   */
60665:   assert( p->wantToLock==0 && p->locked==0 );
60666:   if( !p->sharable || removeFromSharingList(pBt) ){
60667:     /* The pBt is no longer on the sharing list, so we can access
60668:     ** it without having to hold the mutex.
60669:     **
60670:     ** Clean out and delete the BtShared object.
60671:     */
60672:     assert( !pBt->pCursor );
60673:     sqlite3PagerClose(pBt->pPager);
60674:     if( pBt->xFreeSchema && pBt->pSchema ){
60675:       pBt->xFreeSchema(pBt->pSchema);
60676:     }
60677:     sqlite3DbFree(0, pBt->pSchema);
60678:     freeTempSpace(pBt);
60679:     sqlite3_free(pBt);
60680:   }
60681: 
60682: #ifndef SQLITE_OMIT_SHARED_CACHE
60683:   assert( p->wantToLock==0 );
60684:   assert( p->locked==0 );
60685:   if( p->pPrev ) p->pPrev->pNext = p->pNext;
60686:   if( p->pNext ) p->pNext->pPrev = p->pPrev;
60687: #endif
60688: 
60689:   sqlite3_free(p);
60690:   return SQLITE_OK;
60691: }
60692: 
60693: /*
60694: ** Change the "soft" limit on the number of pages in the cache.
60695: ** Unused and unmodified pages will be recycled when the number of
60696: ** pages in the cache exceeds this soft limit.  But the size of the
60697: ** cache is allowed to grow larger than this limit if it contains
60698: ** dirty pages or pages still in active use.
60699: */
60700: SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
60701:   BtShared *pBt = p->pBt;
60702:   assert( sqlite3_mutex_held(p->db->mutex) );
60703:   sqlite3BtreeEnter(p);
60704:   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
60705:   sqlite3BtreeLeave(p);
60706:   return SQLITE_OK;
60707: }
60708: 
60709: /*
60710: ** Change the "spill" limit on the number of pages in the cache.
60711: ** If the number of pages exceeds this limit during a write transaction,
60712: ** the pager might attempt to "spill" pages to the journal early in
60713: ** order to free up memory.
60714: **
60715: ** The value returned is the current spill size.  If zero is passed
60716: ** as an argument, no changes are made to the spill size setting, so
60717: ** using mxPage of 0 is a way to query the current spill size.
60718: */
60719: SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
60720:   BtShared *pBt = p->pBt;
60721:   int res;
60722:   assert( sqlite3_mutex_held(p->db->mutex) );
60723:   sqlite3BtreeEnter(p);
60724:   res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
60725:   sqlite3BtreeLeave(p);
60726:   return res;
60727: }
60728: 
60729: #if SQLITE_MAX_MMAP_SIZE>0
60730: /*
60731: ** Change the limit on the amount of the database file that may be
60732: ** memory mapped.
60733: */
60734: SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
60735:   BtShared *pBt = p->pBt;
60736:   assert( sqlite3_mutex_held(p->db->mutex) );
60737:   sqlite3BtreeEnter(p);
60738:   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
60739:   sqlite3BtreeLeave(p);
60740:   return SQLITE_OK;
60741: }
60742: #endif /* SQLITE_MAX_MMAP_SIZE>0 */
60743: 
60744: /*
60745: ** Change the way data is synced to disk in order to increase or decrease
60746: ** how well the database resists damage due to OS crashes and power
60747: ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
60748: ** there is a high probability of damage)  Level 2 is the default.  There
60749: ** is a very low but non-zero probability of damage.  Level 3 reduces the
60750: ** probability of damage to near zero but with a write performance reduction.
60751: */
60752: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
60753: SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
60754:   Btree *p,              /* The btree to set the safety level on */
60755:   unsigned pgFlags       /* Various PAGER_* flags */
60756: ){
60757:   BtShared *pBt = p->pBt;
60758:   assert( sqlite3_mutex_held(p->db->mutex) );
60759:   sqlite3BtreeEnter(p);
60760:   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
60761:   sqlite3BtreeLeave(p);
60762:   return SQLITE_OK;
60763: }
60764: #endif
60765: 
60766: /*
60767: ** Change the default pages size and the number of reserved bytes per page.
60768: ** Or, if the page size has already been fixed, return SQLITE_READONLY 
60769: ** without changing anything.
60770: **
60771: ** The page size must be a power of 2 between 512 and 65536.  If the page
60772: ** size supplied does not meet this constraint then the page size is not
60773: ** changed.
60774: **
60775: ** Page sizes are constrained to be a power of two so that the region
60776: ** of the database file used for locking (beginning at PENDING_BYTE,
60777: ** the first byte past the 1GB boundary, 0x40000000) needs to occur
60778: ** at the beginning of a page.
60779: **
60780: ** If parameter nReserve is less than zero, then the number of reserved
60781: ** bytes per page is left unchanged.
60782: **
60783: ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
60784: ** and autovacuum mode can no longer be changed.
60785: */
60786: SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
60787:   int rc = SQLITE_OK;
60788:   BtShared *pBt = p->pBt;
60789:   assert( nReserve>=-1 && nReserve<=255 );
60790:   sqlite3BtreeEnter(p);
60791: #if SQLITE_HAS_CODEC
60792:   if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
60793: #endif
60794:   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
60795:     sqlite3BtreeLeave(p);
60796:     return SQLITE_READONLY;
60797:   }
60798:   if( nReserve<0 ){
60799:     nReserve = pBt->pageSize - pBt->usableSize;
60800:   }
60801:   assert( nReserve>=0 && nReserve<=255 );
60802:   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
60803:         ((pageSize-1)&pageSize)==0 ){
60804:     assert( (pageSize & 7)==0 );
60805:     assert( !pBt->pCursor );
60806:     pBt->pageSize = (u32)pageSize;
60807:     freeTempSpace(pBt);
60808:   }
60809:   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60810:   pBt->usableSize = pBt->pageSize - (u16)nReserve;
60811:   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60812:   sqlite3BtreeLeave(p);
60813:   return rc;
60814: }
60815: 
60816: /*
60817: ** Return the currently defined page size
60818: */
60819: SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
60820:   return p->pBt->pageSize;
60821: }
60822: 
60823: /*
60824: ** This function is similar to sqlite3BtreeGetReserve(), except that it
60825: ** may only be called if it is guaranteed that the b-tree mutex is already
60826: ** held.
60827: **
60828: ** This is useful in one special case in the backup API code where it is
60829: ** known that the shared b-tree mutex is held, but the mutex on the 
60830: ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
60831: ** were to be called, it might collide with some other operation on the
60832: ** database handle that owns *p, causing undefined behavior.
60833: */
60834: SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
60835:   int n;
60836:   assert( sqlite3_mutex_held(p->pBt->mutex) );
60837:   n = p->pBt->pageSize - p->pBt->usableSize;
60838:   return n;
60839: }
60840: 
60841: /*
60842: ** Return the number of bytes of space at the end of every page that
60843: ** are intentually left unused.  This is the "reserved" space that is
60844: ** sometimes used by extensions.
60845: **
60846: ** If SQLITE_HAS_MUTEX is defined then the number returned is the
60847: ** greater of the current reserved space and the maximum requested
60848: ** reserve space.
60849: */
60850: SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
60851:   int n;
60852:   sqlite3BtreeEnter(p);
60853:   n = sqlite3BtreeGetReserveNoMutex(p);
60854: #ifdef SQLITE_HAS_CODEC
60855:   if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
60856: #endif
60857:   sqlite3BtreeLeave(p);
60858:   return n;
60859: }
60860: 
60861: 
60862: /*
60863: ** Set the maximum page count for a database if mxPage is positive.
60864: ** No changes are made if mxPage is 0 or negative.
60865: ** Regardless of the value of mxPage, return the maximum page count.
60866: */
60867: SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
60868:   int n;
60869:   sqlite3BtreeEnter(p);
60870:   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
60871:   sqlite3BtreeLeave(p);
60872:   return n;
60873: }
60874: 
60875: /*
60876: ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
60877: ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
60878: ** setting after the change.
60879: */
60880: SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
60881:   int b;
60882:   if( p==0 ) return 0;
60883:   sqlite3BtreeEnter(p);
60884:   if( newFlag>=0 ){
60885:     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
60886:     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
60887:   } 
60888:   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
60889:   sqlite3BtreeLeave(p);
60890:   return b;
60891: }
60892: 
60893: /*
60894: ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
60895: ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
60896: ** is disabled. The default value for the auto-vacuum property is 
60897: ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
60898: */
60899: SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
60900: #ifdef SQLITE_OMIT_AUTOVACUUM
60901:   return SQLITE_READONLY;
60902: #else
60903:   BtShared *pBt = p->pBt;
60904:   int rc = SQLITE_OK;
60905:   u8 av = (u8)autoVacuum;
60906: 
60907:   sqlite3BtreeEnter(p);
60908:   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
60909:     rc = SQLITE_READONLY;
60910:   }else{
60911:     pBt->autoVacuum = av ?1:0;
60912:     pBt->incrVacuum = av==2 ?1:0;
60913:   }
60914:   sqlite3BtreeLeave(p);
60915:   return rc;
60916: #endif
60917: }
60918: 
60919: /*
60920: ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
60921: ** enabled 1 is returned. Otherwise 0.
60922: */
60923: SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
60924: #ifdef SQLITE_OMIT_AUTOVACUUM
60925:   return BTREE_AUTOVACUUM_NONE;
60926: #else
60927:   int rc;
60928:   sqlite3BtreeEnter(p);
60929:   rc = (
60930:     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
60931:     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
60932:     BTREE_AUTOVACUUM_INCR
60933:   );
60934:   sqlite3BtreeLeave(p);
60935:   return rc;
60936: #endif
60937: }
60938: 
60939: 
60940: /*
60941: ** Get a reference to pPage1 of the database file.  This will
60942: ** also acquire a readlock on that file.
60943: **
60944: ** SQLITE_OK is returned on success.  If the file is not a
60945: ** well-formed database file, then SQLITE_CORRUPT is returned.
60946: ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
60947: ** is returned if we run out of memory. 
60948: */
60949: static int lockBtree(BtShared *pBt){
60950:   int rc;              /* Result code from subfunctions */
60951:   MemPage *pPage1;     /* Page 1 of the database file */
60952:   int nPage;           /* Number of pages in the database */
60953:   int nPageFile = 0;   /* Number of pages in the database file */
60954:   int nPageHeader;     /* Number of pages in the database according to hdr */
60955: 
60956:   assert( sqlite3_mutex_held(pBt->mutex) );
60957:   assert( pBt->pPage1==0 );
60958:   rc = sqlite3PagerSharedLock(pBt->pPager);
60959:   if( rc!=SQLITE_OK ) return rc;
60960:   rc = btreeGetPage(pBt, 1, &pPage1, 0);
60961:   if( rc!=SQLITE_OK ) return rc;
60962: 
60963:   /* Do some checking to help insure the file we opened really is
60964:   ** a valid database file. 
60965:   */
60966:   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
60967:   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
60968:   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
60969:     nPage = nPageFile;
60970:   }
60971:   if( nPage>0 ){
60972:     u32 pageSize;
60973:     u32 usableSize;
60974:     u8 *page1 = pPage1->aData;
60975:     rc = SQLITE_NOTADB;
60976:     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
60977:     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
60978:     ** 61 74 20 33 00. */
60979:     if( memcmp(page1, zMagicHeader, 16)!=0 ){
60980:       goto page1_init_failed;
60981:     }
60982: 
60983: #ifdef SQLITE_OMIT_WAL
60984:     if( page1[18]>1 ){
60985:       pBt->btsFlags |= BTS_READ_ONLY;
60986:     }
60987:     if( page1[19]>1 ){
60988:       goto page1_init_failed;
60989:     }
60990: #else
60991:     if( page1[18]>2 ){
60992:       pBt->btsFlags |= BTS_READ_ONLY;
60993:     }
60994:     if( page1[19]>2 ){
60995:       goto page1_init_failed;
60996:     }
60997: 
60998:     /* If the write version is set to 2, this database should be accessed
60999:     ** in WAL mode. If the log is not already open, open it now. Then 
61000:     ** return SQLITE_OK and return without populating BtShared.pPage1.
61001:     ** The caller detects this and calls this function again. This is
61002:     ** required as the version of page 1 currently in the page1 buffer
61003:     ** may not be the latest version - there may be a newer one in the log
61004:     ** file.
61005:     */
61006:     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
61007:       int isOpen = 0;
61008:       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
61009:       if( rc!=SQLITE_OK ){
61010:         goto page1_init_failed;
61011:       }else{
61012: #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
61013:         sqlite3 *db;
61014:         Db *pDb;
61015:         if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
61016:           while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
61017:           if( pDb->bSyncSet==0
61018:            && pDb->safety_level==SQLITE_DEFAULT_SYNCHRONOUS+1
61019:           ){
61020:             pDb->safety_level = SQLITE_DEFAULT_WAL_SYNCHRONOUS+1;
61021:             sqlite3PagerSetFlags(pBt->pPager,
61022:                pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
61023:           }
61024:         }
61025: #endif
61026:         if( isOpen==0 ){
61027:           releasePage(pPage1);
61028:           return SQLITE_OK;
61029:         }
61030:       }
61031:       rc = SQLITE_NOTADB;
61032:     }
61033: #endif
61034: 
61035:     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
61036:     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
61037:     **
61038:     ** The original design allowed these amounts to vary, but as of
61039:     ** version 3.6.0, we require them to be fixed.
61040:     */
61041:     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
61042:       goto page1_init_failed;
61043:     }
61044:     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
61045:     ** determined by the 2-byte integer located at an offset of 16 bytes from
61046:     ** the beginning of the database file. */
61047:     pageSize = (page1[16]<<8) | (page1[17]<<16);
61048:     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
61049:     ** between 512 and 65536 inclusive. */
61050:     if( ((pageSize-1)&pageSize)!=0
61051:      || pageSize>SQLITE_MAX_PAGE_SIZE 
61052:      || pageSize<=256 
61053:     ){
61054:       goto page1_init_failed;
61055:     }
61056:     assert( (pageSize & 7)==0 );
61057:     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
61058:     ** integer at offset 20 is the number of bytes of space at the end of
61059:     ** each page to reserve for extensions. 
61060:     **
61061:     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
61062:     ** determined by the one-byte unsigned integer found at an offset of 20
61063:     ** into the database file header. */
61064:     usableSize = pageSize - page1[20];
61065:     if( (u32)pageSize!=pBt->pageSize ){
61066:       /* After reading the first page of the database assuming a page size
61067:       ** of BtShared.pageSize, we have discovered that the page-size is
61068:       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
61069:       ** zero and return SQLITE_OK. The caller will call this function
61070:       ** again with the correct page-size.
61071:       */
61072:       releasePage(pPage1);
61073:       pBt->usableSize = usableSize;
61074:       pBt->pageSize = pageSize;
61075:       freeTempSpace(pBt);
61076:       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
61077:                                    pageSize-usableSize);
61078:       return rc;
61079:     }
61080:     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
61081:       rc = SQLITE_CORRUPT_BKPT;
61082:       goto page1_init_failed;
61083:     }
61084:     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
61085:     ** be less than 480. In other words, if the page size is 512, then the
61086:     ** reserved space size cannot exceed 32. */
61087:     if( usableSize<480 ){
61088:       goto page1_init_failed;
61089:     }
61090:     pBt->pageSize = pageSize;
61091:     pBt->usableSize = usableSize;
61092: #ifndef SQLITE_OMIT_AUTOVACUUM
61093:     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
61094:     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
61095: #endif
61096:   }
61097: 
61098:   /* maxLocal is the maximum amount of payload to store locally for
61099:   ** a cell.  Make sure it is small enough so that at least minFanout
61100:   ** cells can will fit on one page.  We assume a 10-byte page header.
61101:   ** Besides the payload, the cell must store:
61102:   **     2-byte pointer to the cell
61103:   **     4-byte child pointer
61104:   **     9-byte nKey value
61105:   **     4-byte nData value
61106:   **     4-byte overflow page pointer
61107:   ** So a cell consists of a 2-byte pointer, a header which is as much as
61108:   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
61109:   ** page pointer.
61110:   */
61111:   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
61112:   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
61113:   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
61114:   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
61115:   if( pBt->maxLocal>127 ){
61116:     pBt->max1bytePayload = 127;
61117:   }else{
61118:     pBt->max1bytePayload = (u8)pBt->maxLocal;
61119:   }
61120:   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
61121:   pBt->pPage1 = pPage1;
61122:   pBt->nPage = nPage;
61123:   return SQLITE_OK;
61124: 
61125: page1_init_failed:
61126:   releasePage(pPage1);
61127:   pBt->pPage1 = 0;
61128:   return rc;
61129: }
61130: 
61131: #ifndef NDEBUG
61132: /*
61133: ** Return the number of cursors open on pBt. This is for use
61134: ** in assert() expressions, so it is only compiled if NDEBUG is not
61135: ** defined.
61136: **
61137: ** Only write cursors are counted if wrOnly is true.  If wrOnly is
61138: ** false then all cursors are counted.
61139: **
61140: ** For the purposes of this routine, a cursor is any cursor that
61141: ** is capable of reading or writing to the database.  Cursors that
61142: ** have been tripped into the CURSOR_FAULT state are not counted.
61143: */
61144: static int countValidCursors(BtShared *pBt, int wrOnly){
61145:   BtCursor *pCur;
61146:   int r = 0;
61147:   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
61148:     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
61149:      && pCur->eState!=CURSOR_FAULT ) r++; 
61150:   }
61151:   return r;
61152: }
61153: #endif
61154: 
61155: /*
61156: ** If there are no outstanding cursors and we are not in the middle
61157: ** of a transaction but there is a read lock on the database, then
61158: ** this routine unrefs the first page of the database file which 
61159: ** has the effect of releasing the read lock.
61160: **
61161: ** If there is a transaction in progress, this routine is a no-op.
61162: */
61163: static void unlockBtreeIfUnused(BtShared *pBt){
61164:   assert( sqlite3_mutex_held(pBt->mutex) );
61165:   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
61166:   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
61167:     MemPage *pPage1 = pBt->pPage1;
61168:     assert( pPage1->aData );
61169:     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
61170:     pBt->pPage1 = 0;
61171:     releasePageNotNull(pPage1);
61172:   }
61173: }
61174: 
61175: /*
61176: ** If pBt points to an empty file then convert that empty file
61177: ** into a new empty database by initializing the first page of
61178: ** the database.
61179: */
61180: static int newDatabase(BtShared *pBt){
61181:   MemPage *pP1;
61182:   unsigned char *data;
61183:   int rc;
61184: 
61185:   assert( sqlite3_mutex_held(pBt->mutex) );
61186:   if( pBt->nPage>0 ){
61187:     return SQLITE_OK;
61188:   }
61189:   pP1 = pBt->pPage1;
61190:   assert( pP1!=0 );
61191:   data = pP1->aData;
61192:   rc = sqlite3PagerWrite(pP1->pDbPage);
61193:   if( rc ) return rc;
61194:   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
61195:   assert( sizeof(zMagicHeader)==16 );
61196:   data[16] = (u8)((pBt->pageSize>>8)&0xff);
61197:   data[17] = (u8)((pBt->pageSize>>16)&0xff);
61198:   data[18] = 1;
61199:   data[19] = 1;
61200:   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
61201:   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
61202:   data[21] = 64;
61203:   data[22] = 32;
61204:   data[23] = 32;
61205:   memset(&data[24], 0, 100-24);
61206:   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
61207:   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
61208: #ifndef SQLITE_OMIT_AUTOVACUUM
61209:   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
61210:   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
61211:   put4byte(&data[36 + 4*4], pBt->autoVacuum);
61212:   put4byte(&data[36 + 7*4], pBt->incrVacuum);
61213: #endif
61214:   pBt->nPage = 1;
61215:   data[31] = 1;
61216:   return SQLITE_OK;
61217: }
61218: 
61219: /*
61220: ** Initialize the first page of the database file (creating a database
61221: ** consisting of a single page and no schema objects). Return SQLITE_OK
61222: ** if successful, or an SQLite error code otherwise.
61223: */
61224: SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
61225:   int rc;
61226:   sqlite3BtreeEnter(p);
61227:   p->pBt->nPage = 0;
61228:   rc = newDatabase(p->pBt);
61229:   sqlite3BtreeLeave(p);
61230:   return rc;
61231: }
61232: 
61233: /*
61234: ** Attempt to start a new transaction. A write-transaction
61235: ** is started if the second argument is nonzero, otherwise a read-
61236: ** transaction.  If the second argument is 2 or more and exclusive
61237: ** transaction is started, meaning that no other process is allowed
61238: ** to access the database.  A preexisting transaction may not be
61239: ** upgraded to exclusive by calling this routine a second time - the
61240: ** exclusivity flag only works for a new transaction.
61241: **
61242: ** A write-transaction must be started before attempting any 
61243: ** changes to the database.  None of the following routines 
61244: ** will work unless a transaction is started first:
61245: **
61246: **      sqlite3BtreeCreateTable()
61247: **      sqlite3BtreeCreateIndex()
61248: **      sqlite3BtreeClearTable()
61249: **      sqlite3BtreeDropTable()
61250: **      sqlite3BtreeInsert()
61251: **      sqlite3BtreeDelete()
61252: **      sqlite3BtreeUpdateMeta()
61253: **
61254: ** If an initial attempt to acquire the lock fails because of lock contention
61255: ** and the database was previously unlocked, then invoke the busy handler
61256: ** if there is one.  But if there was previously a read-lock, do not
61257: ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
61258: ** returned when there is already a read-lock in order to avoid a deadlock.
61259: **
61260: ** Suppose there are two processes A and B.  A has a read lock and B has
61261: ** a reserved lock.  B tries to promote to exclusive but is blocked because
61262: ** of A's read lock.  A tries to promote to reserved but is blocked by B.
61263: ** One or the other of the two processes must give way or there can be
61264: ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
61265: ** when A already has a read lock, we encourage A to give up and let B
61266: ** proceed.
61267: */
61268: SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
61269:   BtShared *pBt = p->pBt;
61270:   int rc = SQLITE_OK;
61271: 
61272:   sqlite3BtreeEnter(p);
61273:   btreeIntegrity(p);
61274: 
61275:   /* If the btree is already in a write-transaction, or it
61276:   ** is already in a read-transaction and a read-transaction
61277:   ** is requested, this is a no-op.
61278:   */
61279:   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
61280:     goto trans_begun;
61281:   }
61282:   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
61283: 
61284:   /* Write transactions are not possible on a read-only database */
61285:   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
61286:     rc = SQLITE_READONLY;
61287:     goto trans_begun;
61288:   }
61289: 
61290: #ifndef SQLITE_OMIT_SHARED_CACHE
61291:   {
61292:     sqlite3 *pBlock = 0;
61293:     /* If another database handle has already opened a write transaction 
61294:     ** on this shared-btree structure and a second write transaction is
61295:     ** requested, return SQLITE_LOCKED.
61296:     */
61297:     if( (wrflag && pBt->inTransaction==TRANS_WRITE)
61298:      || (pBt->btsFlags & BTS_PENDING)!=0
61299:     ){
61300:       pBlock = pBt->pWriter->db;
61301:     }else if( wrflag>1 ){
61302:       BtLock *pIter;
61303:       for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
61304:         if( pIter->pBtree!=p ){
61305:           pBlock = pIter->pBtree->db;
61306:           break;
61307:         }
61308:       }
61309:     }
61310:     if( pBlock ){
61311:       sqlite3ConnectionBlocked(p->db, pBlock);
61312:       rc = SQLITE_LOCKED_SHAREDCACHE;
61313:       goto trans_begun;
61314:     }
61315:   }
61316: #endif
61317: 
61318:   /* Any read-only or read-write transaction implies a read-lock on 
61319:   ** page 1. So if some other shared-cache client already has a write-lock 
61320:   ** on page 1, the transaction cannot be opened. */
61321:   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
61322:   if( SQLITE_OK!=rc ) goto trans_begun;
61323: 
61324:   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
61325:   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
61326:   do {
61327:     /* Call lockBtree() until either pBt->pPage1 is populated or
61328:     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
61329:     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
61330:     ** reading page 1 it discovers that the page-size of the database 
61331:     ** file is not pBt->pageSize. In this case lockBtree() will update
61332:     ** pBt->pageSize to the page-size of the file on disk.
61333:     */
61334:     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
61335: 
61336:     if( rc==SQLITE_OK && wrflag ){
61337:       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
61338:         rc = SQLITE_READONLY;
61339:       }else{
61340:         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
61341:         if( rc==SQLITE_OK ){
61342:           rc = newDatabase(pBt);
61343:         }
61344:       }
61345:     }
61346:   
61347:     if( rc!=SQLITE_OK ){
61348:       unlockBtreeIfUnused(pBt);
61349:     }
61350:   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
61351:           btreeInvokeBusyHandler(pBt) );
61352: 
61353:   if( rc==SQLITE_OK ){
61354:     if( p->inTrans==TRANS_NONE ){
61355:       pBt->nTransaction++;
61356: #ifndef SQLITE_OMIT_SHARED_CACHE
61357:       if( p->sharable ){
61358:         assert( p->lock.pBtree==p && p->lock.iTable==1 );
61359:         p->lock.eLock = READ_LOCK;
61360:         p->lock.pNext = pBt->pLock;
61361:         pBt->pLock = &p->lock;
61362:       }
61363: #endif
61364:     }
61365:     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
61366:     if( p->inTrans>pBt->inTransaction ){
61367:       pBt->inTransaction = p->inTrans;
61368:     }
61369:     if( wrflag ){
61370:       MemPage *pPage1 = pBt->pPage1;
61371: #ifndef SQLITE_OMIT_SHARED_CACHE
61372:       assert( !pBt->pWriter );
61373:       pBt->pWriter = p;
61374:       pBt->btsFlags &= ~BTS_EXCLUSIVE;
61375:       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
61376: #endif
61377: 
61378:       /* If the db-size header field is incorrect (as it may be if an old
61379:       ** client has been writing the database file), update it now. Doing
61380:       ** this sooner rather than later means the database size can safely 
61381:       ** re-read the database size from page 1 if a savepoint or transaction
61382:       ** rollback occurs within the transaction.
61383:       */
61384:       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
61385:         rc = sqlite3PagerWrite(pPage1->pDbPage);
61386:         if( rc==SQLITE_OK ){
61387:           put4byte(&pPage1->aData[28], pBt->nPage);
61388:         }
61389:       }
61390:     }
61391:   }
61392: 
61393: 
61394: trans_begun:
61395:   if( rc==SQLITE_OK && wrflag ){
61396:     /* This call makes sure that the pager has the correct number of
61397:     ** open savepoints. If the second parameter is greater than 0 and
61398:     ** the sub-journal is not already open, then it will be opened here.
61399:     */
61400:     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
61401:   }
61402: 
61403:   btreeIntegrity(p);
61404:   sqlite3BtreeLeave(p);
61405:   return rc;
61406: }
61407: 
61408: #ifndef SQLITE_OMIT_AUTOVACUUM
61409: 
61410: /*
61411: ** Set the pointer-map entries for all children of page pPage. Also, if
61412: ** pPage contains cells that point to overflow pages, set the pointer
61413: ** map entries for the overflow pages as well.
61414: */
61415: static int setChildPtrmaps(MemPage *pPage){
61416:   int i;                             /* Counter variable */
61417:   int nCell;                         /* Number of cells in page pPage */
61418:   int rc;                            /* Return code */
61419:   BtShared *pBt = pPage->pBt;
61420:   u8 isInitOrig = pPage->isInit;
61421:   Pgno pgno = pPage->pgno;
61422: 
61423:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61424:   rc = btreeInitPage(pPage);
61425:   if( rc!=SQLITE_OK ){
61426:     goto set_child_ptrmaps_out;
61427:   }
61428:   nCell = pPage->nCell;
61429: 
61430:   for(i=0; i<nCell; i++){
61431:     u8 *pCell = findCell(pPage, i);
61432: 
61433:     ptrmapPutOvflPtr(pPage, pCell, &rc);
61434: 
61435:     if( !pPage->leaf ){
61436:       Pgno childPgno = get4byte(pCell);
61437:       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61438:     }
61439:   }
61440: 
61441:   if( !pPage->leaf ){
61442:     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61443:     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
61444:   }
61445: 
61446: set_child_ptrmaps_out:
61447:   pPage->isInit = isInitOrig;
61448:   return rc;
61449: }
61450: 
61451: /*
61452: ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
61453: ** that it points to iTo. Parameter eType describes the type of pointer to
61454: ** be modified, as  follows:
61455: **
61456: ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
61457: **                   page of pPage.
61458: **
61459: ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
61460: **                   page pointed to by one of the cells on pPage.
61461: **
61462: ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
61463: **                   overflow page in the list.
61464: */
61465: static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
61466:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
61467:   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
61468:   if( eType==PTRMAP_OVERFLOW2 ){
61469:     /* The pointer is always the first 4 bytes of the page in this case.  */
61470:     if( get4byte(pPage->aData)!=iFrom ){
61471:       return SQLITE_CORRUPT_BKPT;
61472:     }
61473:     put4byte(pPage->aData, iTo);
61474:   }else{
61475:     u8 isInitOrig = pPage->isInit;
61476:     int i;
61477:     int nCell;
61478:     int rc;
61479: 
61480:     rc = btreeInitPage(pPage);
61481:     if( rc ) return rc;
61482:     nCell = pPage->nCell;
61483: 
61484:     for(i=0; i<nCell; i++){
61485:       u8 *pCell = findCell(pPage, i);
61486:       if( eType==PTRMAP_OVERFLOW1 ){
61487:         CellInfo info;
61488:         pPage->xParseCell(pPage, pCell, &info);
61489:         if( info.nLocal<info.nPayload
61490:          && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
61491:          && iFrom==get4byte(pCell+info.nSize-4)
61492:         ){
61493:           put4byte(pCell+info.nSize-4, iTo);
61494:           break;
61495:         }
61496:       }else{
61497:         if( get4byte(pCell)==iFrom ){
61498:           put4byte(pCell, iTo);
61499:           break;
61500:         }
61501:       }
61502:     }
61503:   
61504:     if( i==nCell ){
61505:       if( eType!=PTRMAP_BTREE || 
61506:           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
61507:         return SQLITE_CORRUPT_BKPT;
61508:       }
61509:       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
61510:     }
61511: 
61512:     pPage->isInit = isInitOrig;
61513:   }
61514:   return SQLITE_OK;
61515: }
61516: 
61517: 
61518: /*
61519: ** Move the open database page pDbPage to location iFreePage in the 
61520: ** database. The pDbPage reference remains valid.
61521: **
61522: ** The isCommit flag indicates that there is no need to remember that
61523: ** the journal needs to be sync()ed before database page pDbPage->pgno 
61524: ** can be written to. The caller has already promised not to write to that
61525: ** page.
61526: */
61527: static int relocatePage(
61528:   BtShared *pBt,           /* Btree */
61529:   MemPage *pDbPage,        /* Open page to move */
61530:   u8 eType,                /* Pointer map 'type' entry for pDbPage */
61531:   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
61532:   Pgno iFreePage,          /* The location to move pDbPage to */
61533:   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
61534: ){
61535:   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
61536:   Pgno iDbPage = pDbPage->pgno;
61537:   Pager *pPager = pBt->pPager;
61538:   int rc;
61539: 
61540:   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
61541:       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
61542:   assert( sqlite3_mutex_held(pBt->mutex) );
61543:   assert( pDbPage->pBt==pBt );
61544: 
61545:   /* Move page iDbPage from its current location to page number iFreePage */
61546:   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
61547:       iDbPage, iFreePage, iPtrPage, eType));
61548:   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
61549:   if( rc!=SQLITE_OK ){
61550:     return rc;
61551:   }
61552:   pDbPage->pgno = iFreePage;
61553: 
61554:   /* If pDbPage was a btree-page, then it may have child pages and/or cells
61555:   ** that point to overflow pages. The pointer map entries for all these
61556:   ** pages need to be changed.
61557:   **
61558:   ** If pDbPage is an overflow page, then the first 4 bytes may store a
61559:   ** pointer to a subsequent overflow page. If this is the case, then
61560:   ** the pointer map needs to be updated for the subsequent overflow page.
61561:   */
61562:   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
61563:     rc = setChildPtrmaps(pDbPage);
61564:     if( rc!=SQLITE_OK ){
61565:       return rc;
61566:     }
61567:   }else{
61568:     Pgno nextOvfl = get4byte(pDbPage->aData);
61569:     if( nextOvfl!=0 ){
61570:       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
61571:       if( rc!=SQLITE_OK ){
61572:         return rc;
61573:       }
61574:     }
61575:   }
61576: 
61577:   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
61578:   ** that it points at iFreePage. Also fix the pointer map entry for
61579:   ** iPtrPage.
61580:   */
61581:   if( eType!=PTRMAP_ROOTPAGE ){
61582:     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
61583:     if( rc!=SQLITE_OK ){
61584:       return rc;
61585:     }
61586:     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
61587:     if( rc!=SQLITE_OK ){
61588:       releasePage(pPtrPage);
61589:       return rc;
61590:     }
61591:     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
61592:     releasePage(pPtrPage);
61593:     if( rc==SQLITE_OK ){
61594:       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
61595:     }
61596:   }
61597:   return rc;
61598: }
61599: 
61600: /* Forward declaration required by incrVacuumStep(). */
61601: static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
61602: 
61603: /*
61604: ** Perform a single step of an incremental-vacuum. If successful, return
61605: ** SQLITE_OK. If there is no work to do (and therefore no point in 
61606: ** calling this function again), return SQLITE_DONE. Or, if an error 
61607: ** occurs, return some other error code.
61608: **
61609: ** More specifically, this function attempts to re-organize the database so 
61610: ** that the last page of the file currently in use is no longer in use.
61611: **
61612: ** Parameter nFin is the number of pages that this database would contain
61613: ** were this function called until it returns SQLITE_DONE.
61614: **
61615: ** If the bCommit parameter is non-zero, this function assumes that the 
61616: ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
61617: ** or an error. bCommit is passed true for an auto-vacuum-on-commit 
61618: ** operation, or false for an incremental vacuum.
61619: */
61620: static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
61621:   Pgno nFreeList;           /* Number of pages still on the free-list */
61622:   int rc;
61623: 
61624:   assert( sqlite3_mutex_held(pBt->mutex) );
61625:   assert( iLastPg>nFin );
61626: 
61627:   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
61628:     u8 eType;
61629:     Pgno iPtrPage;
61630: 
61631:     nFreeList = get4byte(&pBt->pPage1->aData[36]);
61632:     if( nFreeList==0 ){
61633:       return SQLITE_DONE;
61634:     }
61635: 
61636:     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
61637:     if( rc!=SQLITE_OK ){
61638:       return rc;
61639:     }
61640:     if( eType==PTRMAP_ROOTPAGE ){
61641:       return SQLITE_CORRUPT_BKPT;
61642:     }
61643: 
61644:     if( eType==PTRMAP_FREEPAGE ){
61645:       if( bCommit==0 ){
61646:         /* Remove the page from the files free-list. This is not required
61647:         ** if bCommit is non-zero. In that case, the free-list will be
61648:         ** truncated to zero after this function returns, so it doesn't 
61649:         ** matter if it still contains some garbage entries.
61650:         */
61651:         Pgno iFreePg;
61652:         MemPage *pFreePg;
61653:         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
61654:         if( rc!=SQLITE_OK ){
61655:           return rc;
61656:         }
61657:         assert( iFreePg==iLastPg );
61658:         releasePage(pFreePg);
61659:       }
61660:     } else {
61661:       Pgno iFreePg;             /* Index of free page to move pLastPg to */
61662:       MemPage *pLastPg;
61663:       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
61664:       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
61665: 
61666:       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
61667:       if( rc!=SQLITE_OK ){
61668:         return rc;
61669:       }
61670: 
61671:       /* If bCommit is zero, this loop runs exactly once and page pLastPg
61672:       ** is swapped with the first free page pulled off the free list.
61673:       **
61674:       ** On the other hand, if bCommit is greater than zero, then keep
61675:       ** looping until a free-page located within the first nFin pages
61676:       ** of the file is found.
61677:       */
61678:       if( bCommit==0 ){
61679:         eMode = BTALLOC_LE;
61680:         iNear = nFin;
61681:       }
61682:       do {
61683:         MemPage *pFreePg;
61684:         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
61685:         if( rc!=SQLITE_OK ){
61686:           releasePage(pLastPg);
61687:           return rc;
61688:         }
61689:         releasePage(pFreePg);
61690:       }while( bCommit && iFreePg>nFin );
61691:       assert( iFreePg<iLastPg );
61692:       
61693:       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
61694:       releasePage(pLastPg);
61695:       if( rc!=SQLITE_OK ){
61696:         return rc;
61697:       }
61698:     }
61699:   }
61700: 
61701:   if( bCommit==0 ){
61702:     do {
61703:       iLastPg--;
61704:     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
61705:     pBt->bDoTruncate = 1;
61706:     pBt->nPage = iLastPg;
61707:   }
61708:   return SQLITE_OK;
61709: }
61710: 
61711: /*
61712: ** The database opened by the first argument is an auto-vacuum database
61713: ** nOrig pages in size containing nFree free pages. Return the expected 
61714: ** size of the database in pages following an auto-vacuum operation.
61715: */
61716: static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
61717:   int nEntry;                     /* Number of entries on one ptrmap page */
61718:   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
61719:   Pgno nFin;                      /* Return value */
61720: 
61721:   nEntry = pBt->usableSize/5;
61722:   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
61723:   nFin = nOrig - nFree - nPtrmap;
61724:   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
61725:     nFin--;
61726:   }
61727:   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
61728:     nFin--;
61729:   }
61730: 
61731:   return nFin;
61732: }
61733: 
61734: /*
61735: ** A write-transaction must be opened before calling this function.
61736: ** It performs a single unit of work towards an incremental vacuum.
61737: **
61738: ** If the incremental vacuum is finished after this function has run,
61739: ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
61740: ** SQLITE_OK is returned. Otherwise an SQLite error code. 
61741: */
61742: SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
61743:   int rc;
61744:   BtShared *pBt = p->pBt;
61745: 
61746:   sqlite3BtreeEnter(p);
61747:   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
61748:   if( !pBt->autoVacuum ){
61749:     rc = SQLITE_DONE;
61750:   }else{
61751:     Pgno nOrig = btreePagecount(pBt);
61752:     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
61753:     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
61754: 
61755:     if( nOrig<nFin ){
61756:       rc = SQLITE_CORRUPT_BKPT;
61757:     }else if( nFree>0 ){
61758:       rc = saveAllCursors(pBt, 0, 0);
61759:       if( rc==SQLITE_OK ){
61760:         invalidateAllOverflowCache(pBt);
61761:         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
61762:       }
61763:       if( rc==SQLITE_OK ){
61764:         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61765:         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
61766:       }
61767:     }else{
61768:       rc = SQLITE_DONE;
61769:     }
61770:   }
61771:   sqlite3BtreeLeave(p);
61772:   return rc;
61773: }
61774: 
61775: /*
61776: ** This routine is called prior to sqlite3PagerCommit when a transaction
61777: ** is committed for an auto-vacuum database.
61778: **
61779: ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
61780: ** the database file should be truncated to during the commit process. 
61781: ** i.e. the database has been reorganized so that only the first *pnTrunc
61782: ** pages are in use.
61783: */
61784: static int autoVacuumCommit(BtShared *pBt){
61785:   int rc = SQLITE_OK;
61786:   Pager *pPager = pBt->pPager;
61787:   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
61788: 
61789:   assert( sqlite3_mutex_held(pBt->mutex) );
61790:   invalidateAllOverflowCache(pBt);
61791:   assert(pBt->autoVacuum);
61792:   if( !pBt->incrVacuum ){
61793:     Pgno nFin;         /* Number of pages in database after autovacuuming */
61794:     Pgno nFree;        /* Number of pages on the freelist initially */
61795:     Pgno iFree;        /* The next page to be freed */
61796:     Pgno nOrig;        /* Database size before freeing */
61797: 
61798:     nOrig = btreePagecount(pBt);
61799:     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
61800:       /* It is not possible to create a database for which the final page
61801:       ** is either a pointer-map page or the pending-byte page. If one
61802:       ** is encountered, this indicates corruption.
61803:       */
61804:       return SQLITE_CORRUPT_BKPT;
61805:     }
61806: 
61807:     nFree = get4byte(&pBt->pPage1->aData[36]);
61808:     nFin = finalDbSize(pBt, nOrig, nFree);
61809:     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
61810:     if( nFin<nOrig ){
61811:       rc = saveAllCursors(pBt, 0, 0);
61812:     }
61813:     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
61814:       rc = incrVacuumStep(pBt, nFin, iFree, 1);
61815:     }
61816:     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
61817:       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61818:       put4byte(&pBt->pPage1->aData[32], 0);
61819:       put4byte(&pBt->pPage1->aData[36], 0);
61820:       put4byte(&pBt->pPage1->aData[28], nFin);
61821:       pBt->bDoTruncate = 1;
61822:       pBt->nPage = nFin;
61823:     }
61824:     if( rc!=SQLITE_OK ){
61825:       sqlite3PagerRollback(pPager);
61826:     }
61827:   }
61828: 
61829:   assert( nRef>=sqlite3PagerRefcount(pPager) );
61830:   return rc;
61831: }
61832: 
61833: #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
61834: # define setChildPtrmaps(x) SQLITE_OK
61835: #endif
61836: 
61837: /*
61838: ** This routine does the first phase of a two-phase commit.  This routine
61839: ** causes a rollback journal to be created (if it does not already exist)
61840: ** and populated with enough information so that if a power loss occurs
61841: ** the database can be restored to its original state by playing back
61842: ** the journal.  Then the contents of the journal are flushed out to
61843: ** the disk.  After the journal is safely on oxide, the changes to the
61844: ** database are written into the database file and flushed to oxide.
61845: ** At the end of this call, the rollback journal still exists on the
61846: ** disk and we are still holding all locks, so the transaction has not
61847: ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
61848: ** commit process.
61849: **
61850: ** This call is a no-op if no write-transaction is currently active on pBt.
61851: **
61852: ** Otherwise, sync the database file for the btree pBt. zMaster points to
61853: ** the name of a master journal file that should be written into the
61854: ** individual journal file, or is NULL, indicating no master journal file 
61855: ** (single database transaction).
61856: **
61857: ** When this is called, the master journal should already have been
61858: ** created, populated with this journal pointer and synced to disk.
61859: **
61860: ** Once this is routine has returned, the only thing required to commit
61861: ** the write-transaction for this database file is to delete the journal.
61862: */
61863: SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
61864:   int rc = SQLITE_OK;
61865:   if( p->inTrans==TRANS_WRITE ){
61866:     BtShared *pBt = p->pBt;
61867:     sqlite3BtreeEnter(p);
61868: #ifndef SQLITE_OMIT_AUTOVACUUM
61869:     if( pBt->autoVacuum ){
61870:       rc = autoVacuumCommit(pBt);
61871:       if( rc!=SQLITE_OK ){
61872:         sqlite3BtreeLeave(p);
61873:         return rc;
61874:       }
61875:     }
61876:     if( pBt->bDoTruncate ){
61877:       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
61878:     }
61879: #endif
61880:     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
61881:     sqlite3BtreeLeave(p);
61882:   }
61883:   return rc;
61884: }
61885: 
61886: /*
61887: ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
61888: ** at the conclusion of a transaction.
61889: */
61890: static void btreeEndTransaction(Btree *p){
61891:   BtShared *pBt = p->pBt;
61892:   sqlite3 *db = p->db;
61893:   assert( sqlite3BtreeHoldsMutex(p) );
61894: 
61895: #ifndef SQLITE_OMIT_AUTOVACUUM
61896:   pBt->bDoTruncate = 0;
61897: #endif
61898:   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
61899:     /* If there are other active statements that belong to this database
61900:     ** handle, downgrade to a read-only transaction. The other statements
61901:     ** may still be reading from the database.  */
61902:     downgradeAllSharedCacheTableLocks(p);
61903:     p->inTrans = TRANS_READ;
61904:   }else{
61905:     /* If the handle had any kind of transaction open, decrement the 
61906:     ** transaction count of the shared btree. If the transaction count 
61907:     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
61908:     ** call below will unlock the pager.  */
61909:     if( p->inTrans!=TRANS_NONE ){
61910:       clearAllSharedCacheTableLocks(p);
61911:       pBt->nTransaction--;
61912:       if( 0==pBt->nTransaction ){
61913:         pBt->inTransaction = TRANS_NONE;
61914:       }
61915:     }
61916: 
61917:     /* Set the current transaction state to TRANS_NONE and unlock the 
61918:     ** pager if this call closed the only read or write transaction.  */
61919:     p->inTrans = TRANS_NONE;
61920:     unlockBtreeIfUnused(pBt);
61921:   }
61922: 
61923:   btreeIntegrity(p);
61924: }
61925: 
61926: /*
61927: ** Commit the transaction currently in progress.
61928: **
61929: ** This routine implements the second phase of a 2-phase commit.  The
61930: ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
61931: ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
61932: ** routine did all the work of writing information out to disk and flushing the
61933: ** contents so that they are written onto the disk platter.  All this
61934: ** routine has to do is delete or truncate or zero the header in the
61935: ** the rollback journal (which causes the transaction to commit) and
61936: ** drop locks.
61937: **
61938: ** Normally, if an error occurs while the pager layer is attempting to 
61939: ** finalize the underlying journal file, this function returns an error and
61940: ** the upper layer will attempt a rollback. However, if the second argument
61941: ** is non-zero then this b-tree transaction is part of a multi-file 
61942: ** transaction. In this case, the transaction has already been committed 
61943: ** (by deleting a master journal file) and the caller will ignore this 
61944: ** functions return code. So, even if an error occurs in the pager layer,
61945: ** reset the b-tree objects internal state to indicate that the write
61946: ** transaction has been closed. This is quite safe, as the pager will have
61947: ** transitioned to the error state.
61948: **
61949: ** This will release the write lock on the database file.  If there
61950: ** are no active cursors, it also releases the read lock.
61951: */
61952: SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
61953: 
61954:   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
61955:   sqlite3BtreeEnter(p);
61956:   btreeIntegrity(p);
61957: 
61958:   /* If the handle has a write-transaction open, commit the shared-btrees 
61959:   ** transaction and set the shared state to TRANS_READ.
61960:   */
61961:   if( p->inTrans==TRANS_WRITE ){
61962:     int rc;
61963:     BtShared *pBt = p->pBt;
61964:     assert( pBt->inTransaction==TRANS_WRITE );
61965:     assert( pBt->nTransaction>0 );
61966:     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
61967:     if( rc!=SQLITE_OK && bCleanup==0 ){
61968:       sqlite3BtreeLeave(p);
61969:       return rc;
61970:     }
61971:     p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
61972:     pBt->inTransaction = TRANS_READ;
61973:     btreeClearHasContent(pBt);
61974:   }
61975: 
61976:   btreeEndTransaction(p);
61977:   sqlite3BtreeLeave(p);
61978:   return SQLITE_OK;
61979: }
61980: 
61981: /*
61982: ** Do both phases of a commit.
61983: */
61984: SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
61985:   int rc;
61986:   sqlite3BtreeEnter(p);
61987:   rc = sqlite3BtreeCommitPhaseOne(p, 0);
61988:   if( rc==SQLITE_OK ){
61989:     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
61990:   }
61991:   sqlite3BtreeLeave(p);
61992:   return rc;
61993: }
61994: 
61995: /*
61996: ** This routine sets the state to CURSOR_FAULT and the error
61997: ** code to errCode for every cursor on any BtShared that pBtree
61998: ** references.  Or if the writeOnly flag is set to 1, then only
61999: ** trip write cursors and leave read cursors unchanged.
62000: **
62001: ** Every cursor is a candidate to be tripped, including cursors
62002: ** that belong to other database connections that happen to be
62003: ** sharing the cache with pBtree.
62004: **
62005: ** This routine gets called when a rollback occurs. If the writeOnly
62006: ** flag is true, then only write-cursors need be tripped - read-only
62007: ** cursors save their current positions so that they may continue 
62008: ** following the rollback. Or, if writeOnly is false, all cursors are 
62009: ** tripped. In general, writeOnly is false if the transaction being
62010: ** rolled back modified the database schema. In this case b-tree root
62011: ** pages may be moved or deleted from the database altogether, making
62012: ** it unsafe for read cursors to continue.
62013: **
62014: ** If the writeOnly flag is true and an error is encountered while 
62015: ** saving the current position of a read-only cursor, all cursors, 
62016: ** including all read-cursors are tripped.
62017: **
62018: ** SQLITE_OK is returned if successful, or if an error occurs while
62019: ** saving a cursor position, an SQLite error code.
62020: */
62021: SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
62022:   BtCursor *p;
62023:   int rc = SQLITE_OK;
62024: 
62025:   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
62026:   if( pBtree ){
62027:     sqlite3BtreeEnter(pBtree);
62028:     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
62029:       int i;
62030:       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
62031:         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
62032:           rc = saveCursorPosition(p);
62033:           if( rc!=SQLITE_OK ){
62034:             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
62035:             break;
62036:           }
62037:         }
62038:       }else{
62039:         sqlite3BtreeClearCursor(p);
62040:         p->eState = CURSOR_FAULT;
62041:         p->skipNext = errCode;
62042:       }
62043:       for(i=0; i<=p->iPage; i++){
62044:         releasePage(p->apPage[i]);
62045:         p->apPage[i] = 0;
62046:       }
62047:     }
62048:     sqlite3BtreeLeave(pBtree);
62049:   }
62050:   return rc;
62051: }
62052: 
62053: /*
62054: ** Rollback the transaction in progress.
62055: **
62056: ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
62057: ** Only write cursors are tripped if writeOnly is true but all cursors are
62058: ** tripped if writeOnly is false.  Any attempt to use
62059: ** a tripped cursor will result in an error.
62060: **
62061: ** This will release the write lock on the database file.  If there
62062: ** are no active cursors, it also releases the read lock.
62063: */
62064: SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
62065:   int rc;
62066:   BtShared *pBt = p->pBt;
62067:   MemPage *pPage1;
62068: 
62069:   assert( writeOnly==1 || writeOnly==0 );
62070:   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
62071:   sqlite3BtreeEnter(p);
62072:   if( tripCode==SQLITE_OK ){
62073:     rc = tripCode = saveAllCursors(pBt, 0, 0);
62074:     if( rc ) writeOnly = 0;
62075:   }else{
62076:     rc = SQLITE_OK;
62077:   }
62078:   if( tripCode ){
62079:     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
62080:     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
62081:     if( rc2!=SQLITE_OK ) rc = rc2;
62082:   }
62083:   btreeIntegrity(p);
62084: 
62085:   if( p->inTrans==TRANS_WRITE ){
62086:     int rc2;
62087: 
62088:     assert( TRANS_WRITE==pBt->inTransaction );
62089:     rc2 = sqlite3PagerRollback(pBt->pPager);
62090:     if( rc2!=SQLITE_OK ){
62091:       rc = rc2;
62092:     }
62093: 
62094:     /* The rollback may have destroyed the pPage1->aData value.  So
62095:     ** call btreeGetPage() on page 1 again to make
62096:     ** sure pPage1->aData is set correctly. */
62097:     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
62098:       int nPage = get4byte(28+(u8*)pPage1->aData);
62099:       testcase( nPage==0 );
62100:       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
62101:       testcase( pBt->nPage!=nPage );
62102:       pBt->nPage = nPage;
62103:       releasePage(pPage1);
62104:     }
62105:     assert( countValidCursors(pBt, 1)==0 );
62106:     pBt->inTransaction = TRANS_READ;
62107:     btreeClearHasContent(pBt);
62108:   }
62109: 
62110:   btreeEndTransaction(p);
62111:   sqlite3BtreeLeave(p);
62112:   return rc;
62113: }
62114: 
62115: /*
62116: ** Start a statement subtransaction. The subtransaction can be rolled
62117: ** back independently of the main transaction. You must start a transaction 
62118: ** before starting a subtransaction. The subtransaction is ended automatically 
62119: ** if the main transaction commits or rolls back.
62120: **
62121: ** Statement subtransactions are used around individual SQL statements
62122: ** that are contained within a BEGIN...COMMIT block.  If a constraint
62123: ** error occurs within the statement, the effect of that one statement
62124: ** can be rolled back without having to rollback the entire transaction.
62125: **
62126: ** A statement sub-transaction is implemented as an anonymous savepoint. The
62127: ** value passed as the second parameter is the total number of savepoints,
62128: ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
62129: ** are no active savepoints and no other statement-transactions open,
62130: ** iStatement is 1. This anonymous savepoint can be released or rolled back
62131: ** using the sqlite3BtreeSavepoint() function.
62132: */
62133: SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
62134:   int rc;
62135:   BtShared *pBt = p->pBt;
62136:   sqlite3BtreeEnter(p);
62137:   assert( p->inTrans==TRANS_WRITE );
62138:   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
62139:   assert( iStatement>0 );
62140:   assert( iStatement>p->db->nSavepoint );
62141:   assert( pBt->inTransaction==TRANS_WRITE );
62142:   /* At the pager level, a statement transaction is a savepoint with
62143:   ** an index greater than all savepoints created explicitly using
62144:   ** SQL statements. It is illegal to open, release or rollback any
62145:   ** such savepoints while the statement transaction savepoint is active.
62146:   */
62147:   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
62148:   sqlite3BtreeLeave(p);
62149:   return rc;
62150: }
62151: 
62152: /*
62153: ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
62154: ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
62155: ** savepoint identified by parameter iSavepoint, depending on the value 
62156: ** of op.
62157: **
62158: ** Normally, iSavepoint is greater than or equal to zero. However, if op is
62159: ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
62160: ** contents of the entire transaction are rolled back. This is different
62161: ** from a normal transaction rollback, as no locks are released and the
62162: ** transaction remains open.
62163: */
62164: SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
62165:   int rc = SQLITE_OK;
62166:   if( p && p->inTrans==TRANS_WRITE ){
62167:     BtShared *pBt = p->pBt;
62168:     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
62169:     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
62170:     sqlite3BtreeEnter(p);
62171:     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
62172:     if( rc==SQLITE_OK ){
62173:       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
62174:         pBt->nPage = 0;
62175:       }
62176:       rc = newDatabase(pBt);
62177:       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
62178: 
62179:       /* The database size was written into the offset 28 of the header
62180:       ** when the transaction started, so we know that the value at offset
62181:       ** 28 is nonzero. */
62182:       assert( pBt->nPage>0 );
62183:     }
62184:     sqlite3BtreeLeave(p);
62185:   }
62186:   return rc;
62187: }
62188: 
62189: /*
62190: ** Create a new cursor for the BTree whose root is on the page
62191: ** iTable. If a read-only cursor is requested, it is assumed that
62192: ** the caller already has at least a read-only transaction open
62193: ** on the database already. If a write-cursor is requested, then
62194: ** the caller is assumed to have an open write transaction.
62195: **
62196: ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
62197: ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
62198: ** can be used for reading or for writing if other conditions for writing
62199: ** are also met.  These are the conditions that must be met in order
62200: ** for writing to be allowed:
62201: **
62202: ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
62203: **
62204: ** 2:  Other database connections that share the same pager cache
62205: **     but which are not in the READ_UNCOMMITTED state may not have
62206: **     cursors open with wrFlag==0 on the same table.  Otherwise
62207: **     the changes made by this write cursor would be visible to
62208: **     the read cursors in the other database connection.
62209: **
62210: ** 3:  The database must be writable (not on read-only media)
62211: **
62212: ** 4:  There must be an active transaction.
62213: **
62214: ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
62215: ** is set.  If FORDELETE is set, that is a hint to the implementation that
62216: ** this cursor will only be used to seek to and delete entries of an index
62217: ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
62218: ** this implementation.  But in a hypothetical alternative storage engine 
62219: ** in which index entries are automatically deleted when corresponding table
62220: ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
62221: ** operations on this cursor can be no-ops and all READ operations can 
62222: ** return a null row (2-bytes: 0x01 0x00).
62223: **
62224: ** No checking is done to make sure that page iTable really is the
62225: ** root page of a b-tree.  If it is not, then the cursor acquired
62226: ** will not work correctly.
62227: **
62228: ** It is assumed that the sqlite3BtreeCursorZero() has been called
62229: ** on pCur to initialize the memory space prior to invoking this routine.
62230: */
62231: static int btreeCursor(
62232:   Btree *p,                              /* The btree */
62233:   int iTable,                            /* Root page of table to open */
62234:   int wrFlag,                            /* 1 to write. 0 read-only */
62235:   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
62236:   BtCursor *pCur                         /* Space for new cursor */
62237: ){
62238:   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
62239:   BtCursor *pX;                          /* Looping over other all cursors */
62240: 
62241:   assert( sqlite3BtreeHoldsMutex(p) );
62242:   assert( wrFlag==0 
62243:        || wrFlag==BTREE_WRCSR 
62244:        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE) 
62245:   );
62246: 
62247:   /* The following assert statements verify that if this is a sharable 
62248:   ** b-tree database, the connection is holding the required table locks, 
62249:   ** and that no other connection has any open cursor that conflicts with 
62250:   ** this lock.  */
62251:   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
62252:   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
62253: 
62254:   /* Assert that the caller has opened the required transaction. */
62255:   assert( p->inTrans>TRANS_NONE );
62256:   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
62257:   assert( pBt->pPage1 && pBt->pPage1->aData );
62258:   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
62259: 
62260:   if( wrFlag ){
62261:     allocateTempSpace(pBt);
62262:     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
62263:   }
62264:   if( iTable==1 && btreePagecount(pBt)==0 ){
62265:     assert( wrFlag==0 );
62266:     iTable = 0;
62267:   }
62268: 
62269:   /* Now that no other errors can occur, finish filling in the BtCursor
62270:   ** variables and link the cursor into the BtShared list.  */
62271:   pCur->pgnoRoot = (Pgno)iTable;
62272:   pCur->iPage = -1;
62273:   pCur->pKeyInfo = pKeyInfo;
62274:   pCur->pBtree = p;
62275:   pCur->pBt = pBt;
62276:   pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
62277:   pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
62278:   /* If there are two or more cursors on the same btree, then all such
62279:   ** cursors *must* have the BTCF_Multiple flag set. */
62280:   for(pX=pBt->pCursor; pX; pX=pX->pNext){
62281:     if( pX->pgnoRoot==(Pgno)iTable ){
62282:       pX->curFlags |= BTCF_Multiple;
62283:       pCur->curFlags |= BTCF_Multiple;
62284:     }
62285:   }
62286:   pCur->pNext = pBt->pCursor;
62287:   pBt->pCursor = pCur;
62288:   pCur->eState = CURSOR_INVALID;
62289:   return SQLITE_OK;
62290: }
62291: SQLITE_PRIVATE int sqlite3BtreeCursor(
62292:   Btree *p,                                   /* The btree */
62293:   int iTable,                                 /* Root page of table to open */
62294:   int wrFlag,                                 /* 1 to write. 0 read-only */
62295:   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
62296:   BtCursor *pCur                              /* Write new cursor here */
62297: ){
62298:   int rc;
62299:   if( iTable<1 ){
62300:     rc = SQLITE_CORRUPT_BKPT;
62301:   }else{
62302:     sqlite3BtreeEnter(p);
62303:     rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
62304:     sqlite3BtreeLeave(p);
62305:   }
62306:   return rc;
62307: }
62308: 
62309: /*
62310: ** Return the size of a BtCursor object in bytes.
62311: **
62312: ** This interfaces is needed so that users of cursors can preallocate
62313: ** sufficient storage to hold a cursor.  The BtCursor object is opaque
62314: ** to users so they cannot do the sizeof() themselves - they must call
62315: ** this routine.
62316: */
62317: SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
62318:   return ROUND8(sizeof(BtCursor));
62319: }
62320: 
62321: /*
62322: ** Initialize memory that will be converted into a BtCursor object.
62323: **
62324: ** The simple approach here would be to memset() the entire object
62325: ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
62326: ** do not need to be zeroed and they are large, so we can save a lot
62327: ** of run-time by skipping the initialization of those elements.
62328: */
62329: SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
62330:   memset(p, 0, offsetof(BtCursor, iPage));
62331: }
62332: 
62333: /*
62334: ** Close a cursor.  The read lock on the database file is released
62335: ** when the last cursor is closed.
62336: */
62337: SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
62338:   Btree *pBtree = pCur->pBtree;
62339:   if( pBtree ){
62340:     int i;
62341:     BtShared *pBt = pCur->pBt;
62342:     sqlite3BtreeEnter(pBtree);
62343:     sqlite3BtreeClearCursor(pCur);
62344:     assert( pBt->pCursor!=0 );
62345:     if( pBt->pCursor==pCur ){
62346:       pBt->pCursor = pCur->pNext;
62347:     }else{
62348:       BtCursor *pPrev = pBt->pCursor;
62349:       do{
62350:         if( pPrev->pNext==pCur ){
62351:           pPrev->pNext = pCur->pNext;
62352:           break;
62353:         }
62354:         pPrev = pPrev->pNext;
62355:       }while( ALWAYS(pPrev) );
62356:     }
62357:     for(i=0; i<=pCur->iPage; i++){
62358:       releasePage(pCur->apPage[i]);
62359:     }
62360:     unlockBtreeIfUnused(pBt);
62361:     sqlite3_free(pCur->aOverflow);
62362:     /* sqlite3_free(pCur); */
62363:     sqlite3BtreeLeave(pBtree);
62364:   }
62365:   return SQLITE_OK;
62366: }
62367: 
62368: /*
62369: ** Make sure the BtCursor* given in the argument has a valid
62370: ** BtCursor.info structure.  If it is not already valid, call
62371: ** btreeParseCell() to fill it in.
62372: **
62373: ** BtCursor.info is a cache of the information in the current cell.
62374: ** Using this cache reduces the number of calls to btreeParseCell().
62375: */
62376: #ifndef NDEBUG
62377:   static void assertCellInfo(BtCursor *pCur){
62378:     CellInfo info;
62379:     int iPage = pCur->iPage;
62380:     memset(&info, 0, sizeof(info));
62381:     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
62382:     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
62383:   }
62384: #else
62385:   #define assertCellInfo(x)
62386: #endif
62387: static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
62388:   if( pCur->info.nSize==0 ){
62389:     int iPage = pCur->iPage;
62390:     pCur->curFlags |= BTCF_ValidNKey;
62391:     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
62392:   }else{
62393:     assertCellInfo(pCur);
62394:   }
62395: }
62396: 
62397: #ifndef NDEBUG  /* The next routine used only within assert() statements */
62398: /*
62399: ** Return true if the given BtCursor is valid.  A valid cursor is one
62400: ** that is currently pointing to a row in a (non-empty) table.
62401: ** This is a verification routine is used only within assert() statements.
62402: */
62403: SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
62404:   return pCur && pCur->eState==CURSOR_VALID;
62405: }
62406: #endif /* NDEBUG */
62407: 
62408: /*
62409: ** Return the value of the integer key or "rowid" for a table btree.
62410: ** This routine is only valid for a cursor that is pointing into a
62411: ** ordinary table btree.  If the cursor points to an index btree or
62412: ** is invalid, the result of this routine is undefined.
62413: */
62414: SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
62415:   assert( cursorHoldsMutex(pCur) );
62416:   assert( pCur->eState==CURSOR_VALID );
62417:   assert( pCur->curIntKey );
62418:   getCellInfo(pCur);
62419:   return pCur->info.nKey;
62420: }
62421: 
62422: /*
62423: ** Return the number of bytes of payload for the entry that pCur is
62424: ** currently pointing to.  For table btrees, this will be the amount
62425: ** of data.  For index btrees, this will be the size of the key.
62426: **
62427: ** The caller must guarantee that the cursor is pointing to a non-NULL
62428: ** valid entry.  In other words, the calling procedure must guarantee
62429: ** that the cursor has Cursor.eState==CURSOR_VALID.
62430: */
62431: SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
62432:   assert( cursorHoldsMutex(pCur) );
62433:   assert( pCur->eState==CURSOR_VALID );
62434:   getCellInfo(pCur);
62435:   return pCur->info.nPayload;
62436: }
62437: 
62438: /*
62439: ** Given the page number of an overflow page in the database (parameter
62440: ** ovfl), this function finds the page number of the next page in the 
62441: ** linked list of overflow pages. If possible, it uses the auto-vacuum
62442: ** pointer-map data instead of reading the content of page ovfl to do so. 
62443: **
62444: ** If an error occurs an SQLite error code is returned. Otherwise:
62445: **
62446: ** The page number of the next overflow page in the linked list is 
62447: ** written to *pPgnoNext. If page ovfl is the last page in its linked 
62448: ** list, *pPgnoNext is set to zero. 
62449: **
62450: ** If ppPage is not NULL, and a reference to the MemPage object corresponding
62451: ** to page number pOvfl was obtained, then *ppPage is set to point to that
62452: ** reference. It is the responsibility of the caller to call releasePage()
62453: ** on *ppPage to free the reference. In no reference was obtained (because
62454: ** the pointer-map was used to obtain the value for *pPgnoNext), then
62455: ** *ppPage is set to zero.
62456: */
62457: static int getOverflowPage(
62458:   BtShared *pBt,               /* The database file */
62459:   Pgno ovfl,                   /* Current overflow page number */
62460:   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
62461:   Pgno *pPgnoNext              /* OUT: Next overflow page number */
62462: ){
62463:   Pgno next = 0;
62464:   MemPage *pPage = 0;
62465:   int rc = SQLITE_OK;
62466: 
62467:   assert( sqlite3_mutex_held(pBt->mutex) );
62468:   assert(pPgnoNext);
62469: 
62470: #ifndef SQLITE_OMIT_AUTOVACUUM
62471:   /* Try to find the next page in the overflow list using the
62472:   ** autovacuum pointer-map pages. Guess that the next page in 
62473:   ** the overflow list is page number (ovfl+1). If that guess turns 
62474:   ** out to be wrong, fall back to loading the data of page 
62475:   ** number ovfl to determine the next page number.
62476:   */
62477:   if( pBt->autoVacuum ){
62478:     Pgno pgno;
62479:     Pgno iGuess = ovfl+1;
62480:     u8 eType;
62481: 
62482:     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
62483:       iGuess++;
62484:     }
62485: 
62486:     if( iGuess<=btreePagecount(pBt) ){
62487:       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
62488:       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
62489:         next = iGuess;
62490:         rc = SQLITE_DONE;
62491:       }
62492:     }
62493:   }
62494: #endif
62495: 
62496:   assert( next==0 || rc==SQLITE_DONE );
62497:   if( rc==SQLITE_OK ){
62498:     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
62499:     assert( rc==SQLITE_OK || pPage==0 );
62500:     if( rc==SQLITE_OK ){
62501:       next = get4byte(pPage->aData);
62502:     }
62503:   }
62504: 
62505:   *pPgnoNext = next;
62506:   if( ppPage ){
62507:     *ppPage = pPage;
62508:   }else{
62509:     releasePage(pPage);
62510:   }
62511:   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
62512: }
62513: 
62514: /*
62515: ** Copy data from a buffer to a page, or from a page to a buffer.
62516: **
62517: ** pPayload is a pointer to data stored on database page pDbPage.
62518: ** If argument eOp is false, then nByte bytes of data are copied
62519: ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
62520: ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
62521: ** of data are copied from the buffer pBuf to pPayload.
62522: **
62523: ** SQLITE_OK is returned on success, otherwise an error code.
62524: */
62525: static int copyPayload(
62526:   void *pPayload,           /* Pointer to page data */
62527:   void *pBuf,               /* Pointer to buffer */
62528:   int nByte,                /* Number of bytes to copy */
62529:   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
62530:   DbPage *pDbPage           /* Page containing pPayload */
62531: ){
62532:   if( eOp ){
62533:     /* Copy data from buffer to page (a write operation) */
62534:     int rc = sqlite3PagerWrite(pDbPage);
62535:     if( rc!=SQLITE_OK ){
62536:       return rc;
62537:     }
62538:     memcpy(pPayload, pBuf, nByte);
62539:   }else{
62540:     /* Copy data from page to buffer (a read operation) */
62541:     memcpy(pBuf, pPayload, nByte);
62542:   }
62543:   return SQLITE_OK;
62544: }
62545: 
62546: /*
62547: ** This function is used to read or overwrite payload information
62548: ** for the entry that the pCur cursor is pointing to. The eOp
62549: ** argument is interpreted as follows:
62550: **
62551: **   0: The operation is a read. Populate the overflow cache.
62552: **   1: The operation is a write. Populate the overflow cache.
62553: **   2: The operation is a read. Do not populate the overflow cache.
62554: **
62555: ** A total of "amt" bytes are read or written beginning at "offset".
62556: ** Data is read to or from the buffer pBuf.
62557: **
62558: ** The content being read or written might appear on the main page
62559: ** or be scattered out on multiple overflow pages.
62560: **
62561: ** If the current cursor entry uses one or more overflow pages and the
62562: ** eOp argument is not 2, this function may allocate space for and lazily 
62563: ** populates the overflow page-list cache array (BtCursor.aOverflow). 
62564: ** Subsequent calls use this cache to make seeking to the supplied offset 
62565: ** more efficient.
62566: **
62567: ** Once an overflow page-list cache has been allocated, it may be
62568: ** invalidated if some other cursor writes to the same table, or if
62569: ** the cursor is moved to a different row. Additionally, in auto-vacuum
62570: ** mode, the following events may invalidate an overflow page-list cache.
62571: **
62572: **   * An incremental vacuum,
62573: **   * A commit in auto_vacuum="full" mode,
62574: **   * Creating a table (may require moving an overflow page).
62575: */
62576: static int accessPayload(
62577:   BtCursor *pCur,      /* Cursor pointing to entry to read from */
62578:   u32 offset,          /* Begin reading this far into payload */
62579:   u32 amt,             /* Read this many bytes */
62580:   unsigned char *pBuf, /* Write the bytes into this buffer */ 
62581:   int eOp              /* zero to read. non-zero to write. */
62582: ){
62583:   unsigned char *aPayload;
62584:   int rc = SQLITE_OK;
62585:   int iIdx = 0;
62586:   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
62587:   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
62588: #ifdef SQLITE_DIRECT_OVERFLOW_READ
62589:   unsigned char * const pBufStart = pBuf;
62590:   int bEnd;                                 /* True if reading to end of data */
62591: #endif
62592: 
62593:   assert( pPage );
62594:   assert( pCur->eState==CURSOR_VALID );
62595:   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
62596:   assert( cursorHoldsMutex(pCur) );
62597:   assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
62598: 
62599:   getCellInfo(pCur);
62600:   aPayload = pCur->info.pPayload;
62601: #ifdef SQLITE_DIRECT_OVERFLOW_READ
62602:   bEnd = offset+amt==pCur->info.nPayload;
62603: #endif
62604:   assert( offset+amt <= pCur->info.nPayload );
62605: 
62606:   assert( aPayload > pPage->aData );
62607:   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
62608:     /* Trying to read or write past the end of the data is an error.  The
62609:     ** conditional above is really:
62610:     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
62611:     ** but is recast into its current form to avoid integer overflow problems
62612:     */
62613:     return SQLITE_CORRUPT_BKPT;
62614:   }
62615: 
62616:   /* Check if data must be read/written to/from the btree page itself. */
62617:   if( offset<pCur->info.nLocal ){
62618:     int a = amt;
62619:     if( a+offset>pCur->info.nLocal ){
62620:       a = pCur->info.nLocal - offset;
62621:     }
62622:     rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
62623:     offset = 0;
62624:     pBuf += a;
62625:     amt -= a;
62626:   }else{
62627:     offset -= pCur->info.nLocal;
62628:   }
62629: 
62630: 
62631:   if( rc==SQLITE_OK && amt>0 ){
62632:     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
62633:     Pgno nextPage;
62634: 
62635:     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
62636: 
62637:     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
62638:     ** Except, do not allocate aOverflow[] for eOp==2.
62639:     **
62640:     ** The aOverflow[] array is sized at one entry for each overflow page
62641:     ** in the overflow chain. The page number of the first overflow page is
62642:     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
62643:     ** means "not yet known" (the cache is lazily populated).
62644:     */
62645:     if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
62646:       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
62647:       if( nOvfl>pCur->nOvflAlloc ){
62648:         Pgno *aNew = (Pgno*)sqlite3Realloc(
62649:             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
62650:         );
62651:         if( aNew==0 ){
62652:           rc = SQLITE_NOMEM_BKPT;
62653:         }else{
62654:           pCur->nOvflAlloc = nOvfl*2;
62655:           pCur->aOverflow = aNew;
62656:         }
62657:       }
62658:       if( rc==SQLITE_OK ){
62659:         memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
62660:         pCur->curFlags |= BTCF_ValidOvfl;
62661:       }
62662:     }
62663: 
62664:     /* If the overflow page-list cache has been allocated and the
62665:     ** entry for the first required overflow page is valid, skip
62666:     ** directly to it.
62667:     */
62668:     if( (pCur->curFlags & BTCF_ValidOvfl)!=0
62669:      && pCur->aOverflow[offset/ovflSize]
62670:     ){
62671:       iIdx = (offset/ovflSize);
62672:       nextPage = pCur->aOverflow[iIdx];
62673:       offset = (offset%ovflSize);
62674:     }
62675: 
62676:     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
62677: 
62678:       /* If required, populate the overflow page-list cache. */
62679:       if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
62680:         assert( pCur->aOverflow[iIdx]==0
62681:                 || pCur->aOverflow[iIdx]==nextPage
62682:                 || CORRUPT_DB );
62683:         pCur->aOverflow[iIdx] = nextPage;
62684:       }
62685: 
62686:       if( offset>=ovflSize ){
62687:         /* The only reason to read this page is to obtain the page
62688:         ** number for the next page in the overflow chain. The page
62689:         ** data is not required. So first try to lookup the overflow
62690:         ** page-list cache, if any, then fall back to the getOverflowPage()
62691:         ** function.
62692:         **
62693:         ** Note that the aOverflow[] array must be allocated because eOp!=2
62694:         ** here.  If eOp==2, then offset==0 and this branch is never taken.
62695:         */
62696:         assert( eOp!=2 );
62697:         assert( pCur->curFlags & BTCF_ValidOvfl );
62698:         assert( pCur->pBtree->db==pBt->db );
62699:         if( pCur->aOverflow[iIdx+1] ){
62700:           nextPage = pCur->aOverflow[iIdx+1];
62701:         }else{
62702:           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
62703:         }
62704:         offset -= ovflSize;
62705:       }else{
62706:         /* Need to read this page properly. It contains some of the
62707:         ** range of data that is being read (eOp==0) or written (eOp!=0).
62708:         */
62709: #ifdef SQLITE_DIRECT_OVERFLOW_READ
62710:         sqlite3_file *fd;
62711: #endif
62712:         int a = amt;
62713:         if( a + offset > ovflSize ){
62714:           a = ovflSize - offset;
62715:         }
62716: 
62717: #ifdef SQLITE_DIRECT_OVERFLOW_READ
62718:         /* If all the following are true:
62719:         **
62720:         **   1) this is a read operation, and 
62721:         **   2) data is required from the start of this overflow page, and
62722:         **   3) the database is file-backed, and
62723:         **   4) there is no open write-transaction, and
62724:         **   5) the database is not a WAL database,
62725:         **   6) all data from the page is being read.
62726:         **   7) at least 4 bytes have already been read into the output buffer 
62727:         **
62728:         ** then data can be read directly from the database file into the
62729:         ** output buffer, bypassing the page-cache altogether. This speeds
62730:         ** up loading large records that span many overflow pages.
62731:         */
62732:         if( (eOp&0x01)==0                                      /* (1) */
62733:          && offset==0                                          /* (2) */
62734:          && (bEnd || a==ovflSize)                              /* (6) */
62735:          && pBt->inTransaction==TRANS_READ                     /* (4) */
62736:          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
62737:          && pBt->pPage1->aData[19]==0x01                       /* (5) */
62738:          && &pBuf[-4]>=pBufStart                               /* (7) */
62739:         ){
62740:           u8 aSave[4];
62741:           u8 *aWrite = &pBuf[-4];
62742:           assert( aWrite>=pBufStart );                         /* hence (7) */
62743:           memcpy(aSave, aWrite, 4);
62744:           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
62745:           nextPage = get4byte(aWrite);
62746:           memcpy(aWrite, aSave, 4);
62747:         }else
62748: #endif
62749: 
62750:         {
62751:           DbPage *pDbPage;
62752:           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
62753:               ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
62754:           );
62755:           if( rc==SQLITE_OK ){
62756:             aPayload = sqlite3PagerGetData(pDbPage);
62757:             nextPage = get4byte(aPayload);
62758:             rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
62759:             sqlite3PagerUnref(pDbPage);
62760:             offset = 0;
62761:           }
62762:         }
62763:         amt -= a;
62764:         pBuf += a;
62765:       }
62766:     }
62767:   }
62768: 
62769:   if( rc==SQLITE_OK && amt>0 ){
62770:     return SQLITE_CORRUPT_BKPT;
62771:   }
62772:   return rc;
62773: }
62774: 
62775: /*
62776: ** Read part of the key associated with cursor pCur.  Exactly
62777: ** "amt" bytes will be transferred into pBuf[].  The transfer
62778: ** begins at "offset".
62779: **
62780: ** The caller must ensure that pCur is pointing to a valid row
62781: ** in the table.
62782: **
62783: ** Return SQLITE_OK on success or an error code if anything goes
62784: ** wrong.  An error is returned if "offset+amt" is larger than
62785: ** the available payload.
62786: */
62787: SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62788:   assert( cursorHoldsMutex(pCur) );
62789:   assert( pCur->eState==CURSOR_VALID );
62790:   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62791:   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62792:   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
62793: }
62794: 
62795: /*
62796: ** Read part of the data associated with cursor pCur.  Exactly
62797: ** "amt" bytes will be transfered into pBuf[].  The transfer
62798: ** begins at "offset".
62799: **
62800: ** Return SQLITE_OK on success or an error code if anything goes
62801: ** wrong.  An error is returned if "offset+amt" is larger than
62802: ** the available payload.
62803: */
62804: SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62805:   int rc;
62806: 
62807: #ifndef SQLITE_OMIT_INCRBLOB
62808:   if ( pCur->eState==CURSOR_INVALID ){
62809:     return SQLITE_ABORT;
62810:   }
62811: #endif
62812: 
62813:   assert( cursorOwnsBtShared(pCur) );
62814:   rc = restoreCursorPosition(pCur);
62815:   if( rc==SQLITE_OK ){
62816:     assert( pCur->eState==CURSOR_VALID );
62817:     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62818:     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62819:     rc = accessPayload(pCur, offset, amt, pBuf, 0);
62820:   }
62821:   return rc;
62822: }
62823: 
62824: /*
62825: ** Return a pointer to payload information from the entry that the 
62826: ** pCur cursor is pointing to.  The pointer is to the beginning of
62827: ** the key if index btrees (pPage->intKey==0) and is the data for
62828: ** table btrees (pPage->intKey==1). The number of bytes of available
62829: ** key/data is written into *pAmt.  If *pAmt==0, then the value
62830: ** returned will not be a valid pointer.
62831: **
62832: ** This routine is an optimization.  It is common for the entire key
62833: ** and data to fit on the local page and for there to be no overflow
62834: ** pages.  When that is so, this routine can be used to access the
62835: ** key and data without making a copy.  If the key and/or data spills
62836: ** onto overflow pages, then accessPayload() must be used to reassemble
62837: ** the key/data and copy it into a preallocated buffer.
62838: **
62839: ** The pointer returned by this routine looks directly into the cached
62840: ** page of the database.  The data might change or move the next time
62841: ** any btree routine is called.
62842: */
62843: static const void *fetchPayload(
62844:   BtCursor *pCur,      /* Cursor pointing to entry to read from */
62845:   u32 *pAmt            /* Write the number of available bytes here */
62846: ){
62847:   u32 amt;
62848:   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
62849:   assert( pCur->eState==CURSOR_VALID );
62850:   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62851:   assert( cursorOwnsBtShared(pCur) );
62852:   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62853:   assert( pCur->info.nSize>0 );
62854:   assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
62855:   assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
62856:   amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
62857:   if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
62858:   *pAmt = amt;
62859:   return (void*)pCur->info.pPayload;
62860: }
62861: 
62862: 
62863: /*
62864: ** For the entry that cursor pCur is point to, return as
62865: ** many bytes of the key or data as are available on the local
62866: ** b-tree page.  Write the number of available bytes into *pAmt.
62867: **
62868: ** The pointer returned is ephemeral.  The key/data may move
62869: ** or be destroyed on the next call to any Btree routine,
62870: ** including calls from other threads against the same cache.
62871: ** Hence, a mutex on the BtShared should be held prior to calling
62872: ** this routine.
62873: **
62874: ** These routines is used to get quick access to key and data
62875: ** in the common case where no overflow pages are used.
62876: */
62877: SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
62878:   return fetchPayload(pCur, pAmt);
62879: }
62880: 
62881: 
62882: /*
62883: ** Move the cursor down to a new child page.  The newPgno argument is the
62884: ** page number of the child page to move to.
62885: **
62886: ** This function returns SQLITE_CORRUPT if the page-header flags field of
62887: ** the new child page does not match the flags field of the parent (i.e.
62888: ** if an intkey page appears to be the parent of a non-intkey page, or
62889: ** vice-versa).
62890: */
62891: static int moveToChild(BtCursor *pCur, u32 newPgno){
62892:   BtShared *pBt = pCur->pBt;
62893: 
62894:   assert( cursorOwnsBtShared(pCur) );
62895:   assert( pCur->eState==CURSOR_VALID );
62896:   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
62897:   assert( pCur->iPage>=0 );
62898:   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
62899:     return SQLITE_CORRUPT_BKPT;
62900:   }
62901:   pCur->info.nSize = 0;
62902:   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
62903:   pCur->iPage++;
62904:   pCur->aiIdx[pCur->iPage] = 0;
62905:   return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
62906:                         pCur, pCur->curPagerFlags);
62907: }
62908: 
62909: #if SQLITE_DEBUG
62910: /*
62911: ** Page pParent is an internal (non-leaf) tree page. This function 
62912: ** asserts that page number iChild is the left-child if the iIdx'th
62913: ** cell in page pParent. Or, if iIdx is equal to the total number of
62914: ** cells in pParent, that page number iChild is the right-child of
62915: ** the page.
62916: */
62917: static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
62918:   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
62919:                             ** in a corrupt database */
62920:   assert( iIdx<=pParent->nCell );
62921:   if( iIdx==pParent->nCell ){
62922:     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
62923:   }else{
62924:     assert( get4byte(findCell(pParent, iIdx))==iChild );
62925:   }
62926: }
62927: #else
62928: #  define assertParentIndex(x,y,z) 
62929: #endif
62930: 
62931: /*
62932: ** Move the cursor up to the parent page.
62933: **
62934: ** pCur->idx is set to the cell index that contains the pointer
62935: ** to the page we are coming from.  If we are coming from the
62936: ** right-most child page then pCur->idx is set to one more than
62937: ** the largest cell index.
62938: */
62939: static void moveToParent(BtCursor *pCur){
62940:   assert( cursorOwnsBtShared(pCur) );
62941:   assert( pCur->eState==CURSOR_VALID );
62942:   assert( pCur->iPage>0 );
62943:   assert( pCur->apPage[pCur->iPage] );
62944:   assertParentIndex(
62945:     pCur->apPage[pCur->iPage-1], 
62946:     pCur->aiIdx[pCur->iPage-1], 
62947:     pCur->apPage[pCur->iPage]->pgno
62948:   );
62949:   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
62950:   pCur->info.nSize = 0;
62951:   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
62952:   releasePageNotNull(pCur->apPage[pCur->iPage--]);
62953: }
62954: 
62955: /*
62956: ** Move the cursor to point to the root page of its b-tree structure.
62957: **
62958: ** If the table has a virtual root page, then the cursor is moved to point
62959: ** to the virtual root page instead of the actual root page. A table has a
62960: ** virtual root page when the actual root page contains no cells and a 
62961: ** single child page. This can only happen with the table rooted at page 1.
62962: **
62963: ** If the b-tree structure is empty, the cursor state is set to 
62964: ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
62965: ** cell located on the root (or virtual root) page and the cursor state
62966: ** is set to CURSOR_VALID.
62967: **
62968: ** If this function returns successfully, it may be assumed that the
62969: ** page-header flags indicate that the [virtual] root-page is the expected 
62970: ** kind of b-tree page (i.e. if when opening the cursor the caller did not
62971: ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
62972: ** indicating a table b-tree, or if the caller did specify a KeyInfo 
62973: ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
62974: ** b-tree).
62975: */
62976: static int moveToRoot(BtCursor *pCur){
62977:   MemPage *pRoot;
62978:   int rc = SQLITE_OK;
62979: 
62980:   assert( cursorOwnsBtShared(pCur) );
62981:   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
62982:   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
62983:   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
62984:   if( pCur->eState>=CURSOR_REQUIRESEEK ){
62985:     if( pCur->eState==CURSOR_FAULT ){
62986:       assert( pCur->skipNext!=SQLITE_OK );
62987:       return pCur->skipNext;
62988:     }
62989:     sqlite3BtreeClearCursor(pCur);
62990:   }
62991: 
62992:   if( pCur->iPage>=0 ){
62993:     while( pCur->iPage ){
62994:       assert( pCur->apPage[pCur->iPage]!=0 );
62995:       releasePageNotNull(pCur->apPage[pCur->iPage--]);
62996:     }
62997:   }else if( pCur->pgnoRoot==0 ){
62998:     pCur->eState = CURSOR_INVALID;
62999:     return SQLITE_OK;
63000:   }else{
63001:     assert( pCur->iPage==(-1) );
63002:     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
63003:                         0, pCur->curPagerFlags);
63004:     if( rc!=SQLITE_OK ){
63005:       pCur->eState = CURSOR_INVALID;
63006:       return rc;
63007:     }
63008:     pCur->iPage = 0;
63009:     pCur->curIntKey = pCur->apPage[0]->intKey;
63010:   }
63011:   pRoot = pCur->apPage[0];
63012:   assert( pRoot->pgno==pCur->pgnoRoot );
63013: 
63014:   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
63015:   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
63016:   ** NULL, the caller expects a table b-tree. If this is not the case,
63017:   ** return an SQLITE_CORRUPT error. 
63018:   **
63019:   ** Earlier versions of SQLite assumed that this test could not fail
63020:   ** if the root page was already loaded when this function was called (i.e.
63021:   ** if pCur->iPage>=0). But this is not so if the database is corrupted 
63022:   ** in such a way that page pRoot is linked into a second b-tree table 
63023:   ** (or the freelist).  */
63024:   assert( pRoot->intKey==1 || pRoot->intKey==0 );
63025:   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
63026:     return SQLITE_CORRUPT_BKPT;
63027:   }
63028: 
63029:   pCur->aiIdx[0] = 0;
63030:   pCur->info.nSize = 0;
63031:   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
63032: 
63033:   if( pRoot->nCell>0 ){
63034:     pCur->eState = CURSOR_VALID;
63035:   }else if( !pRoot->leaf ){
63036:     Pgno subpage;
63037:     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
63038:     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
63039:     pCur->eState = CURSOR_VALID;
63040:     rc = moveToChild(pCur, subpage);
63041:   }else{
63042:     pCur->eState = CURSOR_INVALID;
63043:   }
63044:   return rc;
63045: }
63046: 
63047: /*
63048: ** Move the cursor down to the left-most leaf entry beneath the
63049: ** entry to which it is currently pointing.
63050: **
63051: ** The left-most leaf is the one with the smallest key - the first
63052: ** in ascending order.
63053: */
63054: static int moveToLeftmost(BtCursor *pCur){
63055:   Pgno pgno;
63056:   int rc = SQLITE_OK;
63057:   MemPage *pPage;
63058: 
63059:   assert( cursorOwnsBtShared(pCur) );
63060:   assert( pCur->eState==CURSOR_VALID );
63061:   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63062:     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
63063:     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
63064:     rc = moveToChild(pCur, pgno);
63065:   }
63066:   return rc;
63067: }
63068: 
63069: /*
63070: ** Move the cursor down to the right-most leaf entry beneath the
63071: ** page to which it is currently pointing.  Notice the difference
63072: ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
63073: ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
63074: ** finds the right-most entry beneath the *page*.
63075: **
63076: ** The right-most entry is the one with the largest key - the last
63077: ** key in ascending order.
63078: */
63079: static int moveToRightmost(BtCursor *pCur){
63080:   Pgno pgno;
63081:   int rc = SQLITE_OK;
63082:   MemPage *pPage = 0;
63083: 
63084:   assert( cursorOwnsBtShared(pCur) );
63085:   assert( pCur->eState==CURSOR_VALID );
63086:   while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
63087:     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63088:     pCur->aiIdx[pCur->iPage] = pPage->nCell;
63089:     rc = moveToChild(pCur, pgno);
63090:     if( rc ) return rc;
63091:   }
63092:   pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
63093:   assert( pCur->info.nSize==0 );
63094:   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
63095:   return SQLITE_OK;
63096: }
63097: 
63098: /* Move the cursor to the first entry in the table.  Return SQLITE_OK
63099: ** on success.  Set *pRes to 0 if the cursor actually points to something
63100: ** or set *pRes to 1 if the table is empty.
63101: */
63102: SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
63103:   int rc;
63104: 
63105:   assert( cursorOwnsBtShared(pCur) );
63106:   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63107:   rc = moveToRoot(pCur);
63108:   if( rc==SQLITE_OK ){
63109:     if( pCur->eState==CURSOR_INVALID ){
63110:       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63111:       *pRes = 1;
63112:     }else{
63113:       assert( pCur->apPage[pCur->iPage]->nCell>0 );
63114:       *pRes = 0;
63115:       rc = moveToLeftmost(pCur);
63116:     }
63117:   }
63118:   return rc;
63119: }
63120: 
63121: /* Move the cursor to the last entry in the table.  Return SQLITE_OK
63122: ** on success.  Set *pRes to 0 if the cursor actually points to something
63123: ** or set *pRes to 1 if the table is empty.
63124: */
63125: SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
63126:   int rc;
63127:  
63128:   assert( cursorOwnsBtShared(pCur) );
63129:   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63130: 
63131:   /* If the cursor already points to the last entry, this is a no-op. */
63132:   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
63133: #ifdef SQLITE_DEBUG
63134:     /* This block serves to assert() that the cursor really does point 
63135:     ** to the last entry in the b-tree. */
63136:     int ii;
63137:     for(ii=0; ii<pCur->iPage; ii++){
63138:       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
63139:     }
63140:     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
63141:     assert( pCur->apPage[pCur->iPage]->leaf );
63142: #endif
63143:     return SQLITE_OK;
63144:   }
63145: 
63146:   rc = moveToRoot(pCur);
63147:   if( rc==SQLITE_OK ){
63148:     if( CURSOR_INVALID==pCur->eState ){
63149:       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63150:       *pRes = 1;
63151:     }else{
63152:       assert( pCur->eState==CURSOR_VALID );
63153:       *pRes = 0;
63154:       rc = moveToRightmost(pCur);
63155:       if( rc==SQLITE_OK ){
63156:         pCur->curFlags |= BTCF_AtLast;
63157:       }else{
63158:         pCur->curFlags &= ~BTCF_AtLast;
63159:       }
63160:    
63161:     }
63162:   }
63163:   return rc;
63164: }
63165: 
63166: /* Move the cursor so that it points to an entry near the key 
63167: ** specified by pIdxKey or intKey.   Return a success code.
63168: **
63169: ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
63170: ** must be NULL.  For index tables, pIdxKey is used and intKey
63171: ** is ignored.
63172: **
63173: ** If an exact match is not found, then the cursor is always
63174: ** left pointing at a leaf page which would hold the entry if it
63175: ** were present.  The cursor might point to an entry that comes
63176: ** before or after the key.
63177: **
63178: ** An integer is written into *pRes which is the result of
63179: ** comparing the key with the entry to which the cursor is 
63180: ** pointing.  The meaning of the integer written into
63181: ** *pRes is as follows:
63182: **
63183: **     *pRes<0      The cursor is left pointing at an entry that
63184: **                  is smaller than intKey/pIdxKey or if the table is empty
63185: **                  and the cursor is therefore left point to nothing.
63186: **
63187: **     *pRes==0     The cursor is left pointing at an entry that
63188: **                  exactly matches intKey/pIdxKey.
63189: **
63190: **     *pRes>0      The cursor is left pointing at an entry that
63191: **                  is larger than intKey/pIdxKey.
63192: **
63193: ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
63194: ** exists an entry in the table that exactly matches pIdxKey.  
63195: */
63196: SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
63197:   BtCursor *pCur,          /* The cursor to be moved */
63198:   UnpackedRecord *pIdxKey, /* Unpacked index key */
63199:   i64 intKey,              /* The table key */
63200:   int biasRight,           /* If true, bias the search to the high end */
63201:   int *pRes                /* Write search results here */
63202: ){
63203:   int rc;
63204:   RecordCompare xRecordCompare;
63205: 
63206:   assert( cursorOwnsBtShared(pCur) );
63207:   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
63208:   assert( pRes );
63209:   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
63210:   assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
63211: 
63212:   /* If the cursor is already positioned at the point we are trying
63213:   ** to move to, then just return without doing any work */
63214:   if( pIdxKey==0
63215:    && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
63216:   ){
63217:     if( pCur->info.nKey==intKey ){
63218:       *pRes = 0;
63219:       return SQLITE_OK;
63220:     }
63221:     if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
63222:       *pRes = -1;
63223:       return SQLITE_OK;
63224:     }
63225:   }
63226: 
63227:   if( pIdxKey ){
63228:     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
63229:     pIdxKey->errCode = 0;
63230:     assert( pIdxKey->default_rc==1 
63231:          || pIdxKey->default_rc==0 
63232:          || pIdxKey->default_rc==-1
63233:     );
63234:   }else{
63235:     xRecordCompare = 0; /* All keys are integers */
63236:   }
63237: 
63238:   rc = moveToRoot(pCur);
63239:   if( rc ){
63240:     return rc;
63241:   }
63242:   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
63243:   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
63244:   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
63245:   if( pCur->eState==CURSOR_INVALID ){
63246:     *pRes = -1;
63247:     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
63248:     return SQLITE_OK;
63249:   }
63250:   assert( pCur->apPage[0]->intKey==pCur->curIntKey );
63251:   assert( pCur->curIntKey || pIdxKey );
63252:   for(;;){
63253:     int lwr, upr, idx, c;
63254:     Pgno chldPg;
63255:     MemPage *pPage = pCur->apPage[pCur->iPage];
63256:     u8 *pCell;                          /* Pointer to current cell in pPage */
63257: 
63258:     /* pPage->nCell must be greater than zero. If this is the root-page
63259:     ** the cursor would have been INVALID above and this for(;;) loop
63260:     ** not run. If this is not the root-page, then the moveToChild() routine
63261:     ** would have already detected db corruption. Similarly, pPage must
63262:     ** be the right kind (index or table) of b-tree page. Otherwise
63263:     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
63264:     assert( pPage->nCell>0 );
63265:     assert( pPage->intKey==(pIdxKey==0) );
63266:     lwr = 0;
63267:     upr = pPage->nCell-1;
63268:     assert( biasRight==0 || biasRight==1 );
63269:     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
63270:     pCur->aiIdx[pCur->iPage] = (u16)idx;
63271:     if( xRecordCompare==0 ){
63272:       for(;;){
63273:         i64 nCellKey;
63274:         pCell = findCellPastPtr(pPage, idx);
63275:         if( pPage->intKeyLeaf ){
63276:           while( 0x80 <= *(pCell++) ){
63277:             if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
63278:           }
63279:         }
63280:         getVarint(pCell, (u64*)&nCellKey);
63281:         if( nCellKey<intKey ){
63282:           lwr = idx+1;
63283:           if( lwr>upr ){ c = -1; break; }
63284:         }else if( nCellKey>intKey ){
63285:           upr = idx-1;
63286:           if( lwr>upr ){ c = +1; break; }
63287:         }else{
63288:           assert( nCellKey==intKey );
63289:           pCur->curFlags |= BTCF_ValidNKey;
63290:           pCur->info.nKey = nCellKey;
63291:           pCur->aiIdx[pCur->iPage] = (u16)idx;
63292:           if( !pPage->leaf ){
63293:             lwr = idx;
63294:             goto moveto_next_layer;
63295:           }else{
63296:             *pRes = 0;
63297:             rc = SQLITE_OK;
63298:             goto moveto_finish;
63299:           }
63300:         }
63301:         assert( lwr+upr>=0 );
63302:         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
63303:       }
63304:     }else{
63305:       for(;;){
63306:         int nCell;  /* Size of the pCell cell in bytes */
63307:         pCell = findCellPastPtr(pPage, idx);
63308: 
63309:         /* The maximum supported page-size is 65536 bytes. This means that
63310:         ** the maximum number of record bytes stored on an index B-Tree
63311:         ** page is less than 16384 bytes and may be stored as a 2-byte
63312:         ** varint. This information is used to attempt to avoid parsing 
63313:         ** the entire cell by checking for the cases where the record is 
63314:         ** stored entirely within the b-tree page by inspecting the first 
63315:         ** 2 bytes of the cell.
63316:         */
63317:         nCell = pCell[0];
63318:         if( nCell<=pPage->max1bytePayload ){
63319:           /* This branch runs if the record-size field of the cell is a
63320:           ** single byte varint and the record fits entirely on the main
63321:           ** b-tree page.  */
63322:           testcase( pCell+nCell+1==pPage->aDataEnd );
63323:           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
63324:         }else if( !(pCell[1] & 0x80) 
63325:           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
63326:         ){
63327:           /* The record-size field is a 2 byte varint and the record 
63328:           ** fits entirely on the main b-tree page.  */
63329:           testcase( pCell+nCell+2==pPage->aDataEnd );
63330:           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
63331:         }else{
63332:           /* The record flows over onto one or more overflow pages. In
63333:           ** this case the whole cell needs to be parsed, a buffer allocated
63334:           ** and accessPayload() used to retrieve the record into the
63335:           ** buffer before VdbeRecordCompare() can be called. 
63336:           **
63337:           ** If the record is corrupt, the xRecordCompare routine may read
63338:           ** up to two varints past the end of the buffer. An extra 18 
63339:           ** bytes of padding is allocated at the end of the buffer in
63340:           ** case this happens.  */
63341:           void *pCellKey;
63342:           u8 * const pCellBody = pCell - pPage->childPtrSize;
63343:           pPage->xParseCell(pPage, pCellBody, &pCur->info);
63344:           nCell = (int)pCur->info.nKey;
63345:           testcase( nCell<0 );   /* True if key size is 2^32 or more */
63346:           testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
63347:           testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
63348:           testcase( nCell==2 );  /* Minimum legal index key size */
63349:           if( nCell<2 ){
63350:             rc = SQLITE_CORRUPT_BKPT;
63351:             goto moveto_finish;
63352:           }
63353:           pCellKey = sqlite3Malloc( nCell+18 );
63354:           if( pCellKey==0 ){
63355:             rc = SQLITE_NOMEM_BKPT;
63356:             goto moveto_finish;
63357:           }
63358:           pCur->aiIdx[pCur->iPage] = (u16)idx;
63359:           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
63360:           if( rc ){
63361:             sqlite3_free(pCellKey);
63362:             goto moveto_finish;
63363:           }
63364:           c = xRecordCompare(nCell, pCellKey, pIdxKey);
63365:           sqlite3_free(pCellKey);
63366:         }
63367:         assert( 
63368:             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
63369:          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
63370:         );
63371:         if( c<0 ){
63372:           lwr = idx+1;
63373:         }else if( c>0 ){
63374:           upr = idx-1;
63375:         }else{
63376:           assert( c==0 );
63377:           *pRes = 0;
63378:           rc = SQLITE_OK;
63379:           pCur->aiIdx[pCur->iPage] = (u16)idx;
63380:           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
63381:           goto moveto_finish;
63382:         }
63383:         if( lwr>upr ) break;
63384:         assert( lwr+upr>=0 );
63385:         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
63386:       }
63387:     }
63388:     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
63389:     assert( pPage->isInit );
63390:     if( pPage->leaf ){
63391:       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
63392:       pCur->aiIdx[pCur->iPage] = (u16)idx;
63393:       *pRes = c;
63394:       rc = SQLITE_OK;
63395:       goto moveto_finish;
63396:     }
63397: moveto_next_layer:
63398:     if( lwr>=pPage->nCell ){
63399:       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
63400:     }else{
63401:       chldPg = get4byte(findCell(pPage, lwr));
63402:     }
63403:     pCur->aiIdx[pCur->iPage] = (u16)lwr;
63404:     rc = moveToChild(pCur, chldPg);
63405:     if( rc ) break;
63406:   }
63407: moveto_finish:
63408:   pCur->info.nSize = 0;
63409:   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63410:   return rc;
63411: }
63412: 
63413: 
63414: /*
63415: ** Return TRUE if the cursor is not pointing at an entry of the table.
63416: **
63417: ** TRUE will be returned after a call to sqlite3BtreeNext() moves
63418: ** past the last entry in the table or sqlite3BtreePrev() moves past
63419: ** the first entry.  TRUE is also returned if the table is empty.
63420: */
63421: SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
63422:   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
63423:   ** have been deleted? This API will need to change to return an error code
63424:   ** as well as the boolean result value.
63425:   */
63426:   return (CURSOR_VALID!=pCur->eState);
63427: }
63428: 
63429: /*
63430: ** Advance the cursor to the next entry in the database.  If
63431: ** successful then set *pRes=0.  If the cursor
63432: ** was already pointing to the last entry in the database before
63433: ** this routine was called, then set *pRes=1.
63434: **
63435: ** The main entry point is sqlite3BtreeNext().  That routine is optimized
63436: ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
63437: ** to the next cell on the current page.  The (slower) btreeNext() helper
63438: ** routine is called when it is necessary to move to a different page or
63439: ** to restore the cursor.
63440: **
63441: ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
63442: ** will be 1 if the cursor being stepped corresponds to an SQL index and
63443: ** if this routine could have been skipped if that SQL index had been
63444: ** a unique index.  Otherwise the caller will have set *pRes to zero.
63445: ** Zero is the common case. The btree implementation is free to use the
63446: ** initial *pRes value as a hint to improve performance, but the current
63447: ** SQLite btree implementation does not. (Note that the comdb2 btree
63448: ** implementation does use this hint, however.)
63449: */
63450: static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
63451:   int rc;
63452:   int idx;
63453:   MemPage *pPage;
63454: 
63455:   assert( cursorOwnsBtShared(pCur) );
63456:   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63457:   assert( *pRes==0 );
63458:   if( pCur->eState!=CURSOR_VALID ){
63459:     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
63460:     rc = restoreCursorPosition(pCur);
63461:     if( rc!=SQLITE_OK ){
63462:       return rc;
63463:     }
63464:     if( CURSOR_INVALID==pCur->eState ){
63465:       *pRes = 1;
63466:       return SQLITE_OK;
63467:     }
63468:     if( pCur->skipNext ){
63469:       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63470:       pCur->eState = CURSOR_VALID;
63471:       if( pCur->skipNext>0 ){
63472:         pCur->skipNext = 0;
63473:         return SQLITE_OK;
63474:       }
63475:       pCur->skipNext = 0;
63476:     }
63477:   }
63478: 
63479:   pPage = pCur->apPage[pCur->iPage];
63480:   idx = ++pCur->aiIdx[pCur->iPage];
63481:   assert( pPage->isInit );
63482: 
63483:   /* If the database file is corrupt, it is possible for the value of idx 
63484:   ** to be invalid here. This can only occur if a second cursor modifies
63485:   ** the page while cursor pCur is holding a reference to it. Which can
63486:   ** only happen if the database is corrupt in such a way as to link the
63487:   ** page into more than one b-tree structure. */
63488:   testcase( idx>pPage->nCell );
63489: 
63490:   if( idx>=pPage->nCell ){
63491:     if( !pPage->leaf ){
63492:       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63493:       if( rc ) return rc;
63494:       return moveToLeftmost(pCur);
63495:     }
63496:     do{
63497:       if( pCur->iPage==0 ){
63498:         *pRes = 1;
63499:         pCur->eState = CURSOR_INVALID;
63500:         return SQLITE_OK;
63501:       }
63502:       moveToParent(pCur);
63503:       pPage = pCur->apPage[pCur->iPage];
63504:     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
63505:     if( pPage->intKey ){
63506:       return sqlite3BtreeNext(pCur, pRes);
63507:     }else{
63508:       return SQLITE_OK;
63509:     }
63510:   }
63511:   if( pPage->leaf ){
63512:     return SQLITE_OK;
63513:   }else{
63514:     return moveToLeftmost(pCur);
63515:   }
63516: }
63517: SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
63518:   MemPage *pPage;
63519:   assert( cursorOwnsBtShared(pCur) );
63520:   assert( pRes!=0 );
63521:   assert( *pRes==0 || *pRes==1 );
63522:   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63523:   pCur->info.nSize = 0;
63524:   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
63525:   *pRes = 0;
63526:   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
63527:   pPage = pCur->apPage[pCur->iPage];
63528:   if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
63529:     pCur->aiIdx[pCur->iPage]--;
63530:     return btreeNext(pCur, pRes);
63531:   }
63532:   if( pPage->leaf ){
63533:     return SQLITE_OK;
63534:   }else{
63535:     return moveToLeftmost(pCur);
63536:   }
63537: }
63538: 
63539: /*
63540: ** Step the cursor to the back to the previous entry in the database.  If
63541: ** successful then set *pRes=0.  If the cursor
63542: ** was already pointing to the first entry in the database before
63543: ** this routine was called, then set *pRes=1.
63544: **
63545: ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
63546: ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
63547: ** to the previous cell on the current page.  The (slower) btreePrevious()
63548: ** helper routine is called when it is necessary to move to a different page
63549: ** or to restore the cursor.
63550: **
63551: ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
63552: ** will be 1 if the cursor being stepped corresponds to an SQL index and
63553: ** if this routine could have been skipped if that SQL index had been
63554: ** a unique index.  Otherwise the caller will have set *pRes to zero.
63555: ** Zero is the common case. The btree implementation is free to use the
63556: ** initial *pRes value as a hint to improve performance, but the current
63557: ** SQLite btree implementation does not. (Note that the comdb2 btree
63558: ** implementation does use this hint, however.)
63559: */
63560: static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
63561:   int rc;
63562:   MemPage *pPage;
63563: 
63564:   assert( cursorOwnsBtShared(pCur) );
63565:   assert( pRes!=0 );
63566:   assert( *pRes==0 );
63567:   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63568:   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
63569:   assert( pCur->info.nSize==0 );
63570:   if( pCur->eState!=CURSOR_VALID ){
63571:     rc = restoreCursorPosition(pCur);
63572:     if( rc!=SQLITE_OK ){
63573:       return rc;
63574:     }
63575:     if( CURSOR_INVALID==pCur->eState ){
63576:       *pRes = 1;
63577:       return SQLITE_OK;
63578:     }
63579:     if( pCur->skipNext ){
63580:       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63581:       pCur->eState = CURSOR_VALID;
63582:       if( pCur->skipNext<0 ){
63583:         pCur->skipNext = 0;
63584:         return SQLITE_OK;
63585:       }
63586:       pCur->skipNext = 0;
63587:     }
63588:   }
63589: 
63590:   pPage = pCur->apPage[pCur->iPage];
63591:   assert( pPage->isInit );
63592:   if( !pPage->leaf ){
63593:     int idx = pCur->aiIdx[pCur->iPage];
63594:     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
63595:     if( rc ) return rc;
63596:     rc = moveToRightmost(pCur);
63597:   }else{
63598:     while( pCur->aiIdx[pCur->iPage]==0 ){
63599:       if( pCur->iPage==0 ){
63600:         pCur->eState = CURSOR_INVALID;
63601:         *pRes = 1;
63602:         return SQLITE_OK;
63603:       }
63604:       moveToParent(pCur);
63605:     }
63606:     assert( pCur->info.nSize==0 );
63607:     assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
63608: 
63609:     pCur->aiIdx[pCur->iPage]--;
63610:     pPage = pCur->apPage[pCur->iPage];
63611:     if( pPage->intKey && !pPage->leaf ){
63612:       rc = sqlite3BtreePrevious(pCur, pRes);
63613:     }else{
63614:       rc = SQLITE_OK;
63615:     }
63616:   }
63617:   return rc;
63618: }
63619: SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
63620:   assert( cursorOwnsBtShared(pCur) );
63621:   assert( pRes!=0 );
63622:   assert( *pRes==0 || *pRes==1 );
63623:   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63624:   *pRes = 0;
63625:   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
63626:   pCur->info.nSize = 0;
63627:   if( pCur->eState!=CURSOR_VALID
63628:    || pCur->aiIdx[pCur->iPage]==0
63629:    || pCur->apPage[pCur->iPage]->leaf==0
63630:   ){
63631:     return btreePrevious(pCur, pRes);
63632:   }
63633:   pCur->aiIdx[pCur->iPage]--;
63634:   return SQLITE_OK;
63635: }
63636: 
63637: /*
63638: ** Allocate a new page from the database file.
63639: **
63640: ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
63641: ** has already been called on the new page.)  The new page has also
63642: ** been referenced and the calling routine is responsible for calling
63643: ** sqlite3PagerUnref() on the new page when it is done.
63644: **
63645: ** SQLITE_OK is returned on success.  Any other return value indicates
63646: ** an error.  *ppPage is set to NULL in the event of an error.
63647: **
63648: ** If the "nearby" parameter is not 0, then an effort is made to 
63649: ** locate a page close to the page number "nearby".  This can be used in an
63650: ** attempt to keep related pages close to each other in the database file,
63651: ** which in turn can make database access faster.
63652: **
63653: ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
63654: ** anywhere on the free-list, then it is guaranteed to be returned.  If
63655: ** eMode is BTALLOC_LT then the page returned will be less than or equal
63656: ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
63657: ** are no restrictions on which page is returned.
63658: */
63659: static int allocateBtreePage(
63660:   BtShared *pBt,         /* The btree */
63661:   MemPage **ppPage,      /* Store pointer to the allocated page here */
63662:   Pgno *pPgno,           /* Store the page number here */
63663:   Pgno nearby,           /* Search for a page near this one */
63664:   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
63665: ){
63666:   MemPage *pPage1;
63667:   int rc;
63668:   u32 n;     /* Number of pages on the freelist */
63669:   u32 k;     /* Number of leaves on the trunk of the freelist */
63670:   MemPage *pTrunk = 0;
63671:   MemPage *pPrevTrunk = 0;
63672:   Pgno mxPage;     /* Total size of the database file */
63673: 
63674:   assert( sqlite3_mutex_held(pBt->mutex) );
63675:   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
63676:   pPage1 = pBt->pPage1;
63677:   mxPage = btreePagecount(pBt);
63678:   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
63679:   ** stores stores the total number of pages on the freelist. */
63680:   n = get4byte(&pPage1->aData[36]);
63681:   testcase( n==mxPage-1 );
63682:   if( n>=mxPage ){
63683:     return SQLITE_CORRUPT_BKPT;
63684:   }
63685:   if( n>0 ){
63686:     /* There are pages on the freelist.  Reuse one of those pages. */
63687:     Pgno iTrunk;
63688:     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
63689:     u32 nSearch = 0;   /* Count of the number of search attempts */
63690:     
63691:     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
63692:     ** shows that the page 'nearby' is somewhere on the free-list, then
63693:     ** the entire-list will be searched for that page.
63694:     */
63695: #ifndef SQLITE_OMIT_AUTOVACUUM
63696:     if( eMode==BTALLOC_EXACT ){
63697:       if( nearby<=mxPage ){
63698:         u8 eType;
63699:         assert( nearby>0 );
63700:         assert( pBt->autoVacuum );
63701:         rc = ptrmapGet(pBt, nearby, &eType, 0);
63702:         if( rc ) return rc;
63703:         if( eType==PTRMAP_FREEPAGE ){
63704:           searchList = 1;
63705:         }
63706:       }
63707:     }else if( eMode==BTALLOC_LE ){
63708:       searchList = 1;
63709:     }
63710: #endif
63711: 
63712:     /* Decrement the free-list count by 1. Set iTrunk to the index of the
63713:     ** first free-list trunk page. iPrevTrunk is initially 1.
63714:     */
63715:     rc = sqlite3PagerWrite(pPage1->pDbPage);
63716:     if( rc ) return rc;
63717:     put4byte(&pPage1->aData[36], n-1);
63718: 
63719:     /* The code within this loop is run only once if the 'searchList' variable
63720:     ** is not true. Otherwise, it runs once for each trunk-page on the
63721:     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
63722:     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
63723:     */
63724:     do {
63725:       pPrevTrunk = pTrunk;
63726:       if( pPrevTrunk ){
63727:         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
63728:         ** is the page number of the next freelist trunk page in the list or
63729:         ** zero if this is the last freelist trunk page. */
63730:         iTrunk = get4byte(&pPrevTrunk->aData[0]);
63731:       }else{
63732:         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
63733:         ** stores the page number of the first page of the freelist, or zero if
63734:         ** the freelist is empty. */
63735:         iTrunk = get4byte(&pPage1->aData[32]);
63736:       }
63737:       testcase( iTrunk==mxPage );
63738:       if( iTrunk>mxPage || nSearch++ > n ){
63739:         rc = SQLITE_CORRUPT_BKPT;
63740:       }else{
63741:         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
63742:       }
63743:       if( rc ){
63744:         pTrunk = 0;
63745:         goto end_allocate_page;
63746:       }
63747:       assert( pTrunk!=0 );
63748:       assert( pTrunk->aData!=0 );
63749:       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
63750:       ** is the number of leaf page pointers to follow. */
63751:       k = get4byte(&pTrunk->aData[4]);
63752:       if( k==0 && !searchList ){
63753:         /* The trunk has no leaves and the list is not being searched. 
63754:         ** So extract the trunk page itself and use it as the newly 
63755:         ** allocated page */
63756:         assert( pPrevTrunk==0 );
63757:         rc = sqlite3PagerWrite(pTrunk->pDbPage);
63758:         if( rc ){
63759:           goto end_allocate_page;
63760:         }
63761:         *pPgno = iTrunk;
63762:         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63763:         *ppPage = pTrunk;
63764:         pTrunk = 0;
63765:         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63766:       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
63767:         /* Value of k is out of range.  Database corruption */
63768:         rc = SQLITE_CORRUPT_BKPT;
63769:         goto end_allocate_page;
63770: #ifndef SQLITE_OMIT_AUTOVACUUM
63771:       }else if( searchList 
63772:             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
63773:       ){
63774:         /* The list is being searched and this trunk page is the page
63775:         ** to allocate, regardless of whether it has leaves.
63776:         */
63777:         *pPgno = iTrunk;
63778:         *ppPage = pTrunk;
63779:         searchList = 0;
63780:         rc = sqlite3PagerWrite(pTrunk->pDbPage);
63781:         if( rc ){
63782:           goto end_allocate_page;
63783:         }
63784:         if( k==0 ){
63785:           if( !pPrevTrunk ){
63786:             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63787:           }else{
63788:             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63789:             if( rc!=SQLITE_OK ){
63790:               goto end_allocate_page;
63791:             }
63792:             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
63793:           }
63794:         }else{
63795:           /* The trunk page is required by the caller but it contains 
63796:           ** pointers to free-list leaves. The first leaf becomes a trunk
63797:           ** page in this case.
63798:           */
63799:           MemPage *pNewTrunk;
63800:           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
63801:           if( iNewTrunk>mxPage ){ 
63802:             rc = SQLITE_CORRUPT_BKPT;
63803:             goto end_allocate_page;
63804:           }
63805:           testcase( iNewTrunk==mxPage );
63806:           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
63807:           if( rc!=SQLITE_OK ){
63808:             goto end_allocate_page;
63809:           }
63810:           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
63811:           if( rc!=SQLITE_OK ){
63812:             releasePage(pNewTrunk);
63813:             goto end_allocate_page;
63814:           }
63815:           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
63816:           put4byte(&pNewTrunk->aData[4], k-1);
63817:           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
63818:           releasePage(pNewTrunk);
63819:           if( !pPrevTrunk ){
63820:             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
63821:             put4byte(&pPage1->aData[32], iNewTrunk);
63822:           }else{
63823:             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63824:             if( rc ){
63825:               goto end_allocate_page;
63826:             }
63827:             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
63828:           }
63829:         }
63830:         pTrunk = 0;
63831:         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63832: #endif
63833:       }else if( k>0 ){
63834:         /* Extract a leaf from the trunk */
63835:         u32 closest;
63836:         Pgno iPage;
63837:         unsigned char *aData = pTrunk->aData;
63838:         if( nearby>0 ){
63839:           u32 i;
63840:           closest = 0;
63841:           if( eMode==BTALLOC_LE ){
63842:             for(i=0; i<k; i++){
63843:               iPage = get4byte(&aData[8+i*4]);
63844:               if( iPage<=nearby ){
63845:                 closest = i;
63846:                 break;
63847:               }
63848:             }
63849:           }else{
63850:             int dist;
63851:             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
63852:             for(i=1; i<k; i++){
63853:               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
63854:               if( d2<dist ){
63855:                 closest = i;
63856:                 dist = d2;
63857:               }
63858:             }
63859:           }
63860:         }else{
63861:           closest = 0;
63862:         }
63863: 
63864:         iPage = get4byte(&aData[8+closest*4]);
63865:         testcase( iPage==mxPage );
63866:         if( iPage>mxPage ){
63867:           rc = SQLITE_CORRUPT_BKPT;
63868:           goto end_allocate_page;
63869:         }
63870:         testcase( iPage==mxPage );
63871:         if( !searchList 
63872:          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
63873:         ){
63874:           int noContent;
63875:           *pPgno = iPage;
63876:           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
63877:                  ": %d more free pages\n",
63878:                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
63879:           rc = sqlite3PagerWrite(pTrunk->pDbPage);
63880:           if( rc ) goto end_allocate_page;
63881:           if( closest<k-1 ){
63882:             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
63883:           }
63884:           put4byte(&aData[4], k-1);
63885:           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
63886:           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
63887:           if( rc==SQLITE_OK ){
63888:             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63889:             if( rc!=SQLITE_OK ){
63890:               releasePage(*ppPage);
63891:               *ppPage = 0;
63892:             }
63893:           }
63894:           searchList = 0;
63895:         }
63896:       }
63897:       releasePage(pPrevTrunk);
63898:       pPrevTrunk = 0;
63899:     }while( searchList );
63900:   }else{
63901:     /* There are no pages on the freelist, so append a new page to the
63902:     ** database image.
63903:     **
63904:     ** Normally, new pages allocated by this block can be requested from the
63905:     ** pager layer with the 'no-content' flag set. This prevents the pager
63906:     ** from trying to read the pages content from disk. However, if the
63907:     ** current transaction has already run one or more incremental-vacuum
63908:     ** steps, then the page we are about to allocate may contain content
63909:     ** that is required in the event of a rollback. In this case, do
63910:     ** not set the no-content flag. This causes the pager to load and journal
63911:     ** the current page content before overwriting it.
63912:     **
63913:     ** Note that the pager will not actually attempt to load or journal 
63914:     ** content for any page that really does lie past the end of the database
63915:     ** file on disk. So the effects of disabling the no-content optimization
63916:     ** here are confined to those pages that lie between the end of the
63917:     ** database image and the end of the database file.
63918:     */
63919:     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
63920: 
63921:     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63922:     if( rc ) return rc;
63923:     pBt->nPage++;
63924:     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
63925: 
63926: #ifndef SQLITE_OMIT_AUTOVACUUM
63927:     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
63928:       /* If *pPgno refers to a pointer-map page, allocate two new pages
63929:       ** at the end of the file instead of one. The first allocated page
63930:       ** becomes a new pointer-map page, the second is used by the caller.
63931:       */
63932:       MemPage *pPg = 0;
63933:       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
63934:       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
63935:       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
63936:       if( rc==SQLITE_OK ){
63937:         rc = sqlite3PagerWrite(pPg->pDbPage);
63938:         releasePage(pPg);
63939:       }
63940:       if( rc ) return rc;
63941:       pBt->nPage++;
63942:       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
63943:     }
63944: #endif
63945:     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
63946:     *pPgno = pBt->nPage;
63947: 
63948:     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63949:     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
63950:     if( rc ) return rc;
63951:     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63952:     if( rc!=SQLITE_OK ){
63953:       releasePage(*ppPage);
63954:       *ppPage = 0;
63955:     }
63956:     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
63957:   }
63958: 
63959:   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63960: 
63961: end_allocate_page:
63962:   releasePage(pTrunk);
63963:   releasePage(pPrevTrunk);
63964:   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
63965:   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
63966:   return rc;
63967: }
63968: 
63969: /*
63970: ** This function is used to add page iPage to the database file free-list. 
63971: ** It is assumed that the page is not already a part of the free-list.
63972: **
63973: ** The value passed as the second argument to this function is optional.
63974: ** If the caller happens to have a pointer to the MemPage object 
63975: ** corresponding to page iPage handy, it may pass it as the second value. 
63976: ** Otherwise, it may pass NULL.
63977: **
63978: ** If a pointer to a MemPage object is passed as the second argument,
63979: ** its reference count is not altered by this function.
63980: */
63981: static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
63982:   MemPage *pTrunk = 0;                /* Free-list trunk page */
63983:   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
63984:   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
63985:   MemPage *pPage;                     /* Page being freed. May be NULL. */
63986:   int rc;                             /* Return Code */
63987:   int nFree;                          /* Initial number of pages on free-list */
63988: 
63989:   assert( sqlite3_mutex_held(pBt->mutex) );
63990:   assert( CORRUPT_DB || iPage>1 );
63991:   assert( !pMemPage || pMemPage->pgno==iPage );
63992: 
63993:   if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
63994:   if( pMemPage ){
63995:     pPage = pMemPage;
63996:     sqlite3PagerRef(pPage->pDbPage);
63997:   }else{
63998:     pPage = btreePageLookup(pBt, iPage);
63999:   }
64000: 
64001:   /* Increment the free page count on pPage1 */
64002:   rc = sqlite3PagerWrite(pPage1->pDbPage);
64003:   if( rc ) goto freepage_out;
64004:   nFree = get4byte(&pPage1->aData[36]);
64005:   put4byte(&pPage1->aData[36], nFree+1);
64006: 
64007:   if( pBt->btsFlags & BTS_SECURE_DELETE ){
64008:     /* If the secure_delete option is enabled, then
64009:     ** always fully overwrite deleted information with zeros.
64010:     */
64011:     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
64012:      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
64013:     ){
64014:       goto freepage_out;
64015:     }
64016:     memset(pPage->aData, 0, pPage->pBt->pageSize);
64017:   }
64018: 
64019:   /* If the database supports auto-vacuum, write an entry in the pointer-map
64020:   ** to indicate that the page is free.
64021:   */
64022:   if( ISAUTOVACUUM ){
64023:     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
64024:     if( rc ) goto freepage_out;
64025:   }
64026: 
64027:   /* Now manipulate the actual database free-list structure. There are two
64028:   ** possibilities. If the free-list is currently empty, or if the first
64029:   ** trunk page in the free-list is full, then this page will become a
64030:   ** new free-list trunk page. Otherwise, it will become a leaf of the
64031:   ** first trunk page in the current free-list. This block tests if it
64032:   ** is possible to add the page as a new free-list leaf.
64033:   */
64034:   if( nFree!=0 ){
64035:     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
64036: 
64037:     iTrunk = get4byte(&pPage1->aData[32]);
64038:     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
64039:     if( rc!=SQLITE_OK ){
64040:       goto freepage_out;
64041:     }
64042: 
64043:     nLeaf = get4byte(&pTrunk->aData[4]);
64044:     assert( pBt->usableSize>32 );
64045:     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
64046:       rc = SQLITE_CORRUPT_BKPT;
64047:       goto freepage_out;
64048:     }
64049:     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
64050:       /* In this case there is room on the trunk page to insert the page
64051:       ** being freed as a new leaf.
64052:       **
64053:       ** Note that the trunk page is not really full until it contains
64054:       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
64055:       ** coded.  But due to a coding error in versions of SQLite prior to
64056:       ** 3.6.0, databases with freelist trunk pages holding more than
64057:       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
64058:       ** to maintain backwards compatibility with older versions of SQLite,
64059:       ** we will continue to restrict the number of entries to usableSize/4 - 8
64060:       ** for now.  At some point in the future (once everyone has upgraded
64061:       ** to 3.6.0 or later) we should consider fixing the conditional above
64062:       ** to read "usableSize/4-2" instead of "usableSize/4-8".
64063:       **
64064:       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
64065:       ** avoid using the last six entries in the freelist trunk page array in
64066:       ** order that database files created by newer versions of SQLite can be
64067:       ** read by older versions of SQLite.
64068:       */
64069:       rc = sqlite3PagerWrite(pTrunk->pDbPage);
64070:       if( rc==SQLITE_OK ){
64071:         put4byte(&pTrunk->aData[4], nLeaf+1);
64072:         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
64073:         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
64074:           sqlite3PagerDontWrite(pPage->pDbPage);
64075:         }
64076:         rc = btreeSetHasContent(pBt, iPage);
64077:       }
64078:       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
64079:       goto freepage_out;
64080:     }
64081:   }
64082: 
64083:   /* If control flows to this point, then it was not possible to add the
64084:   ** the page being freed as a leaf page of the first trunk in the free-list.
64085:   ** Possibly because the free-list is empty, or possibly because the 
64086:   ** first trunk in the free-list is full. Either way, the page being freed
64087:   ** will become the new first trunk page in the free-list.
64088:   */
64089:   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
64090:     goto freepage_out;
64091:   }
64092:   rc = sqlite3PagerWrite(pPage->pDbPage);
64093:   if( rc!=SQLITE_OK ){
64094:     goto freepage_out;
64095:   }
64096:   put4byte(pPage->aData, iTrunk);
64097:   put4byte(&pPage->aData[4], 0);
64098:   put4byte(&pPage1->aData[32], iPage);
64099:   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
64100: 
64101: freepage_out:
64102:   if( pPage ){
64103:     pPage->isInit = 0;
64104:   }
64105:   releasePage(pPage);
64106:   releasePage(pTrunk);
64107:   return rc;
64108: }
64109: static void freePage(MemPage *pPage, int *pRC){
64110:   if( (*pRC)==SQLITE_OK ){
64111:     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
64112:   }
64113: }
64114: 
64115: /*
64116: ** Free any overflow pages associated with the given Cell.  Write the
64117: ** local Cell size (the number of bytes on the original page, omitting
64118: ** overflow) into *pnSize.
64119: */
64120: static int clearCell(
64121:   MemPage *pPage,          /* The page that contains the Cell */
64122:   unsigned char *pCell,    /* First byte of the Cell */
64123:   u16 *pnSize              /* Write the size of the Cell here */
64124: ){
64125:   BtShared *pBt = pPage->pBt;
64126:   CellInfo info;
64127:   Pgno ovflPgno;
64128:   int rc;
64129:   int nOvfl;
64130:   u32 ovflPageSize;
64131: 
64132:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64133:   pPage->xParseCell(pPage, pCell, &info);
64134:   *pnSize = info.nSize;
64135:   if( info.nLocal==info.nPayload ){
64136:     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
64137:   }
64138:   if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
64139:     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
64140:   }
64141:   ovflPgno = get4byte(pCell + info.nSize - 4);
64142:   assert( pBt->usableSize > 4 );
64143:   ovflPageSize = pBt->usableSize - 4;
64144:   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
64145:   assert( nOvfl>0 || 
64146:     (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
64147:   );
64148:   while( nOvfl-- ){
64149:     Pgno iNext = 0;
64150:     MemPage *pOvfl = 0;
64151:     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
64152:       /* 0 is not a legal page number and page 1 cannot be an 
64153:       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
64154:       ** file the database must be corrupt. */
64155:       return SQLITE_CORRUPT_BKPT;
64156:     }
64157:     if( nOvfl ){
64158:       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
64159:       if( rc ) return rc;
64160:     }
64161: 
64162:     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
64163:      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
64164:     ){
64165:       /* There is no reason any cursor should have an outstanding reference 
64166:       ** to an overflow page belonging to a cell that is being deleted/updated.
64167:       ** So if there exists more than one reference to this page, then it 
64168:       ** must not really be an overflow page and the database must be corrupt. 
64169:       ** It is helpful to detect this before calling freePage2(), as 
64170:       ** freePage2() may zero the page contents if secure-delete mode is
64171:       ** enabled. If this 'overflow' page happens to be a page that the
64172:       ** caller is iterating through or using in some other way, this
64173:       ** can be problematic.
64174:       */
64175:       rc = SQLITE_CORRUPT_BKPT;
64176:     }else{
64177:       rc = freePage2(pBt, pOvfl, ovflPgno);
64178:     }
64179: 
64180:     if( pOvfl ){
64181:       sqlite3PagerUnref(pOvfl->pDbPage);
64182:     }
64183:     if( rc ) return rc;
64184:     ovflPgno = iNext;
64185:   }
64186:   return SQLITE_OK;
64187: }
64188: 
64189: /*
64190: ** Create the byte sequence used to represent a cell on page pPage
64191: ** and write that byte sequence into pCell[].  Overflow pages are
64192: ** allocated and filled in as necessary.  The calling procedure
64193: ** is responsible for making sure sufficient space has been allocated
64194: ** for pCell[].
64195: **
64196: ** Note that pCell does not necessary need to point to the pPage->aData
64197: ** area.  pCell might point to some temporary storage.  The cell will
64198: ** be constructed in this temporary area then copied into pPage->aData
64199: ** later.
64200: */
64201: static int fillInCell(
64202:   MemPage *pPage,                /* The page that contains the cell */
64203:   unsigned char *pCell,          /* Complete text of the cell */
64204:   const BtreePayload *pX,        /* Payload with which to construct the cell */
64205:   int *pnSize                    /* Write cell size here */
64206: ){
64207:   int nPayload;
64208:   const u8 *pSrc;
64209:   int nSrc, n, rc;
64210:   int spaceLeft;
64211:   MemPage *pOvfl = 0;
64212:   MemPage *pToRelease = 0;
64213:   unsigned char *pPrior;
64214:   unsigned char *pPayload;
64215:   BtShared *pBt = pPage->pBt;
64216:   Pgno pgnoOvfl = 0;
64217:   int nHeader;
64218: 
64219:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64220: 
64221:   /* pPage is not necessarily writeable since pCell might be auxiliary
64222:   ** buffer space that is separate from the pPage buffer area */
64223:   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
64224:             || sqlite3PagerIswriteable(pPage->pDbPage) );
64225: 
64226:   /* Fill in the header. */
64227:   nHeader = pPage->childPtrSize;
64228:   if( pPage->intKey ){
64229:     nPayload = pX->nData + pX->nZero;
64230:     pSrc = pX->pData;
64231:     nSrc = pX->nData;
64232:     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
64233:     nHeader += putVarint32(&pCell[nHeader], nPayload);
64234:     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
64235:   }else{
64236:     assert( pX->nData==0 );
64237:     assert( pX->nZero==0 );
64238:     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
64239:     nSrc = nPayload = (int)pX->nKey;
64240:     pSrc = pX->pKey;
64241:     nHeader += putVarint32(&pCell[nHeader], nPayload);
64242:   }
64243:   
64244:   /* Fill in the payload */
64245:   if( nPayload<=pPage->maxLocal ){
64246:     n = nHeader + nPayload;
64247:     testcase( n==3 );
64248:     testcase( n==4 );
64249:     if( n<4 ) n = 4;
64250:     *pnSize = n;
64251:     spaceLeft = nPayload;
64252:     pPrior = pCell;
64253:   }else{
64254:     int mn = pPage->minLocal;
64255:     n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
64256:     testcase( n==pPage->maxLocal );
64257:     testcase( n==pPage->maxLocal+1 );
64258:     if( n > pPage->maxLocal ) n = mn;
64259:     spaceLeft = n;
64260:     *pnSize = n + nHeader + 4;
64261:     pPrior = &pCell[nHeader+n];
64262:   }
64263:   pPayload = &pCell[nHeader];
64264: 
64265:   /* At this point variables should be set as follows:
64266:   **
64267:   **   nPayload           Total payload size in bytes
64268:   **   pPayload           Begin writing payload here
64269:   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
64270:   **                      that means content must spill into overflow pages.
64271:   **   *pnSize            Size of the local cell (not counting overflow pages)
64272:   **   pPrior             Where to write the pgno of the first overflow page
64273:   **
64274:   ** Use a call to btreeParseCellPtr() to verify that the values above
64275:   ** were computed correctly.
64276:   */
64277: #if SQLITE_DEBUG
64278:   {
64279:     CellInfo info;
64280:     pPage->xParseCell(pPage, pCell, &info);
64281:     assert( nHeader==(int)(info.pPayload - pCell) );
64282:     assert( info.nKey==pX->nKey );
64283:     assert( *pnSize == info.nSize );
64284:     assert( spaceLeft == info.nLocal );
64285:   }
64286: #endif
64287: 
64288:   /* Write the payload into the local Cell and any extra into overflow pages */
64289:   while( nPayload>0 ){
64290:     if( spaceLeft==0 ){
64291: #ifndef SQLITE_OMIT_AUTOVACUUM
64292:       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
64293:       if( pBt->autoVacuum ){
64294:         do{
64295:           pgnoOvfl++;
64296:         } while( 
64297:           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
64298:         );
64299:       }
64300: #endif
64301:       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
64302: #ifndef SQLITE_OMIT_AUTOVACUUM
64303:       /* If the database supports auto-vacuum, and the second or subsequent
64304:       ** overflow page is being allocated, add an entry to the pointer-map
64305:       ** for that page now. 
64306:       **
64307:       ** If this is the first overflow page, then write a partial entry 
64308:       ** to the pointer-map. If we write nothing to this pointer-map slot,
64309:       ** then the optimistic overflow chain processing in clearCell()
64310:       ** may misinterpret the uninitialized values and delete the
64311:       ** wrong pages from the database.
64312:       */
64313:       if( pBt->autoVacuum && rc==SQLITE_OK ){
64314:         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
64315:         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
64316:         if( rc ){
64317:           releasePage(pOvfl);
64318:         }
64319:       }
64320: #endif
64321:       if( rc ){
64322:         releasePage(pToRelease);
64323:         return rc;
64324:       }
64325: 
64326:       /* If pToRelease is not zero than pPrior points into the data area
64327:       ** of pToRelease.  Make sure pToRelease is still writeable. */
64328:       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64329: 
64330:       /* If pPrior is part of the data area of pPage, then make sure pPage
64331:       ** is still writeable */
64332:       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
64333:             || sqlite3PagerIswriteable(pPage->pDbPage) );
64334: 
64335:       put4byte(pPrior, pgnoOvfl);
64336:       releasePage(pToRelease);
64337:       pToRelease = pOvfl;
64338:       pPrior = pOvfl->aData;
64339:       put4byte(pPrior, 0);
64340:       pPayload = &pOvfl->aData[4];
64341:       spaceLeft = pBt->usableSize - 4;
64342:     }
64343:     n = nPayload;
64344:     if( n>spaceLeft ) n = spaceLeft;
64345: 
64346:     /* If pToRelease is not zero than pPayload points into the data area
64347:     ** of pToRelease.  Make sure pToRelease is still writeable. */
64348:     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
64349: 
64350:     /* If pPayload is part of the data area of pPage, then make sure pPage
64351:     ** is still writeable */
64352:     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
64353:             || sqlite3PagerIswriteable(pPage->pDbPage) );
64354: 
64355:     if( nSrc>0 ){
64356:       if( n>nSrc ) n = nSrc;
64357:       assert( pSrc );
64358:       memcpy(pPayload, pSrc, n);
64359:     }else{
64360:       memset(pPayload, 0, n);
64361:     }
64362:     nPayload -= n;
64363:     pPayload += n;
64364:     pSrc += n;
64365:     nSrc -= n;
64366:     spaceLeft -= n;
64367:   }
64368:   releasePage(pToRelease);
64369:   return SQLITE_OK;
64370: }
64371: 
64372: /*
64373: ** Remove the i-th cell from pPage.  This routine effects pPage only.
64374: ** The cell content is not freed or deallocated.  It is assumed that
64375: ** the cell content has been copied someplace else.  This routine just
64376: ** removes the reference to the cell from pPage.
64377: **
64378: ** "sz" must be the number of bytes in the cell.
64379: */
64380: static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
64381:   u32 pc;         /* Offset to cell content of cell being deleted */
64382:   u8 *data;       /* pPage->aData */
64383:   u8 *ptr;        /* Used to move bytes around within data[] */
64384:   int rc;         /* The return code */
64385:   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
64386: 
64387:   if( *pRC ) return;
64388: 
64389:   assert( idx>=0 && idx<pPage->nCell );
64390:   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
64391:   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64392:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64393:   data = pPage->aData;
64394:   ptr = &pPage->aCellIdx[2*idx];
64395:   pc = get2byte(ptr);
64396:   hdr = pPage->hdrOffset;
64397:   testcase( pc==get2byte(&data[hdr+5]) );
64398:   testcase( pc+sz==pPage->pBt->usableSize );
64399:   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
64400:     *pRC = SQLITE_CORRUPT_BKPT;
64401:     return;
64402:   }
64403:   rc = freeSpace(pPage, pc, sz);
64404:   if( rc ){
64405:     *pRC = rc;
64406:     return;
64407:   }
64408:   pPage->nCell--;
64409:   if( pPage->nCell==0 ){
64410:     memset(&data[hdr+1], 0, 4);
64411:     data[hdr+7] = 0;
64412:     put2byte(&data[hdr+5], pPage->pBt->usableSize);
64413:     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
64414:                        - pPage->childPtrSize - 8;
64415:   }else{
64416:     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
64417:     put2byte(&data[hdr+3], pPage->nCell);
64418:     pPage->nFree += 2;
64419:   }
64420: }
64421: 
64422: /*
64423: ** Insert a new cell on pPage at cell index "i".  pCell points to the
64424: ** content of the cell.
64425: **
64426: ** If the cell content will fit on the page, then put it there.  If it
64427: ** will not fit, then make a copy of the cell content into pTemp if
64428: ** pTemp is not null.  Regardless of pTemp, allocate a new entry
64429: ** in pPage->apOvfl[] and make it point to the cell content (either
64430: ** in pTemp or the original pCell) and also record its index. 
64431: ** Allocating a new entry in pPage->aCell[] implies that 
64432: ** pPage->nOverflow is incremented.
64433: **
64434: ** *pRC must be SQLITE_OK when this routine is called.
64435: */
64436: static void insertCell(
64437:   MemPage *pPage,   /* Page into which we are copying */
64438:   int i,            /* New cell becomes the i-th cell of the page */
64439:   u8 *pCell,        /* Content of the new cell */
64440:   int sz,           /* Bytes of content in pCell */
64441:   u8 *pTemp,        /* Temp storage space for pCell, if needed */
64442:   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
64443:   int *pRC          /* Read and write return code from here */
64444: ){
64445:   int idx = 0;      /* Where to write new cell content in data[] */
64446:   int j;            /* Loop counter */
64447:   u8 *data;         /* The content of the whole page */
64448:   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
64449: 
64450:   assert( *pRC==SQLITE_OK );
64451:   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
64452:   assert( MX_CELL(pPage->pBt)<=10921 );
64453:   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
64454:   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
64455:   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
64456:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64457:   /* The cell should normally be sized correctly.  However, when moving a
64458:   ** malformed cell from a leaf page to an interior page, if the cell size
64459:   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
64460:   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
64461:   ** the term after the || in the following assert(). */
64462:   assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
64463:   if( pPage->nOverflow || sz+2>pPage->nFree ){
64464:     if( pTemp ){
64465:       memcpy(pTemp, pCell, sz);
64466:       pCell = pTemp;
64467:     }
64468:     if( iChild ){
64469:       put4byte(pCell, iChild);
64470:     }
64471:     j = pPage->nOverflow++;
64472:     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
64473:     pPage->apOvfl[j] = pCell;
64474:     pPage->aiOvfl[j] = (u16)i;
64475: 
64476:     /* When multiple overflows occur, they are always sequential and in
64477:     ** sorted order.  This invariants arise because multiple overflows can
64478:     ** only occur when inserting divider cells into the parent page during
64479:     ** balancing, and the dividers are adjacent and sorted.
64480:     */
64481:     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
64482:     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
64483:   }else{
64484:     int rc = sqlite3PagerWrite(pPage->pDbPage);
64485:     if( rc!=SQLITE_OK ){
64486:       *pRC = rc;
64487:       return;
64488:     }
64489:     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64490:     data = pPage->aData;
64491:     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
64492:     rc = allocateSpace(pPage, sz, &idx);
64493:     if( rc ){ *pRC = rc; return; }
64494:     /* The allocateSpace() routine guarantees the following properties
64495:     ** if it returns successfully */
64496:     assert( idx >= 0 );
64497:     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
64498:     assert( idx+sz <= (int)pPage->pBt->usableSize );
64499:     pPage->nFree -= (u16)(2 + sz);
64500:     memcpy(&data[idx], pCell, sz);
64501:     if( iChild ){
64502:       put4byte(&data[idx], iChild);
64503:     }
64504:     pIns = pPage->aCellIdx + i*2;
64505:     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
64506:     put2byte(pIns, idx);
64507:     pPage->nCell++;
64508:     /* increment the cell count */
64509:     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
64510:     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
64511: #ifndef SQLITE_OMIT_AUTOVACUUM
64512:     if( pPage->pBt->autoVacuum ){
64513:       /* The cell may contain a pointer to an overflow page. If so, write
64514:       ** the entry for the overflow page into the pointer map.
64515:       */
64516:       ptrmapPutOvflPtr(pPage, pCell, pRC);
64517:     }
64518: #endif
64519:   }
64520: }
64521: 
64522: /*
64523: ** A CellArray object contains a cache of pointers and sizes for a
64524: ** consecutive sequence of cells that might be held on multiple pages.
64525: */
64526: typedef struct CellArray CellArray;
64527: struct CellArray {
64528:   int nCell;              /* Number of cells in apCell[] */
64529:   MemPage *pRef;          /* Reference page */
64530:   u8 **apCell;            /* All cells begin balanced */
64531:   u16 *szCell;            /* Local size of all cells in apCell[] */
64532: };
64533: 
64534: /*
64535: ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
64536: ** computed.
64537: */
64538: static void populateCellCache(CellArray *p, int idx, int N){
64539:   assert( idx>=0 && idx+N<=p->nCell );
64540:   while( N>0 ){
64541:     assert( p->apCell[idx]!=0 );
64542:     if( p->szCell[idx]==0 ){
64543:       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
64544:     }else{
64545:       assert( CORRUPT_DB ||
64546:               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
64547:     }
64548:     idx++;
64549:     N--;
64550:   }
64551: }
64552: 
64553: /*
64554: ** Return the size of the Nth element of the cell array
64555: */
64556: static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
64557:   assert( N>=0 && N<p->nCell );
64558:   assert( p->szCell[N]==0 );
64559:   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
64560:   return p->szCell[N];
64561: }
64562: static u16 cachedCellSize(CellArray *p, int N){
64563:   assert( N>=0 && N<p->nCell );
64564:   if( p->szCell[N] ) return p->szCell[N];
64565:   return computeCellSize(p, N);
64566: }
64567: 
64568: /*
64569: ** Array apCell[] contains pointers to nCell b-tree page cells. The 
64570: ** szCell[] array contains the size in bytes of each cell. This function
64571: ** replaces the current contents of page pPg with the contents of the cell
64572: ** array.
64573: **
64574: ** Some of the cells in apCell[] may currently be stored in pPg. This
64575: ** function works around problems caused by this by making a copy of any 
64576: ** such cells before overwriting the page data.
64577: **
64578: ** The MemPage.nFree field is invalidated by this function. It is the 
64579: ** responsibility of the caller to set it correctly.
64580: */
64581: static int rebuildPage(
64582:   MemPage *pPg,                   /* Edit this page */
64583:   int nCell,                      /* Final number of cells on page */
64584:   u8 **apCell,                    /* Array of cells */
64585:   u16 *szCell                     /* Array of cell sizes */
64586: ){
64587:   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
64588:   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
64589:   const int usableSize = pPg->pBt->usableSize;
64590:   u8 * const pEnd = &aData[usableSize];
64591:   int i;
64592:   u8 *pCellptr = pPg->aCellIdx;
64593:   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64594:   u8 *pData;
64595: 
64596:   i = get2byte(&aData[hdr+5]);
64597:   memcpy(&pTmp[i], &aData[i], usableSize - i);
64598: 
64599:   pData = pEnd;
64600:   for(i=0; i<nCell; i++){
64601:     u8 *pCell = apCell[i];
64602:     if( SQLITE_WITHIN(pCell,aData,pEnd) ){
64603:       pCell = &pTmp[pCell - aData];
64604:     }
64605:     pData -= szCell[i];
64606:     put2byte(pCellptr, (pData - aData));
64607:     pCellptr += 2;
64608:     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
64609:     memcpy(pData, pCell, szCell[i]);
64610:     assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
64611:     testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
64612:   }
64613: 
64614:   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
64615:   pPg->nCell = nCell;
64616:   pPg->nOverflow = 0;
64617: 
64618:   put2byte(&aData[hdr+1], 0);
64619:   put2byte(&aData[hdr+3], pPg->nCell);
64620:   put2byte(&aData[hdr+5], pData - aData);
64621:   aData[hdr+7] = 0x00;
64622:   return SQLITE_OK;
64623: }
64624: 
64625: /*
64626: ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64627: ** contains the size in bytes of each such cell. This function attempts to 
64628: ** add the cells stored in the array to page pPg. If it cannot (because 
64629: ** the page needs to be defragmented before the cells will fit), non-zero
64630: ** is returned. Otherwise, if the cells are added successfully, zero is
64631: ** returned.
64632: **
64633: ** Argument pCellptr points to the first entry in the cell-pointer array
64634: ** (part of page pPg) to populate. After cell apCell[0] is written to the
64635: ** page body, a 16-bit offset is written to pCellptr. And so on, for each
64636: ** cell in the array. It is the responsibility of the caller to ensure
64637: ** that it is safe to overwrite this part of the cell-pointer array.
64638: **
64639: ** When this function is called, *ppData points to the start of the 
64640: ** content area on page pPg. If the size of the content area is extended,
64641: ** *ppData is updated to point to the new start of the content area
64642: ** before returning.
64643: **
64644: ** Finally, argument pBegin points to the byte immediately following the
64645: ** end of the space required by this page for the cell-pointer area (for
64646: ** all cells - not just those inserted by the current call). If the content
64647: ** area must be extended to before this point in order to accomodate all
64648: ** cells in apCell[], then the cells do not fit and non-zero is returned.
64649: */
64650: static int pageInsertArray(
64651:   MemPage *pPg,                   /* Page to add cells to */
64652:   u8 *pBegin,                     /* End of cell-pointer array */
64653:   u8 **ppData,                    /* IN/OUT: Page content -area pointer */
64654:   u8 *pCellptr,                   /* Pointer to cell-pointer area */
64655:   int iFirst,                     /* Index of first cell to add */
64656:   int nCell,                      /* Number of cells to add to pPg */
64657:   CellArray *pCArray              /* Array of cells */
64658: ){
64659:   int i;
64660:   u8 *aData = pPg->aData;
64661:   u8 *pData = *ppData;
64662:   int iEnd = iFirst + nCell;
64663:   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
64664:   for(i=iFirst; i<iEnd; i++){
64665:     int sz, rc;
64666:     u8 *pSlot;
64667:     sz = cachedCellSize(pCArray, i);
64668:     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64669:       if( (pData - pBegin)<sz ) return 1;
64670:       pData -= sz;
64671:       pSlot = pData;
64672:     }
64673:     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
64674:     ** database.  But they might for a corrupt database.  Hence use memmove()
64675:     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
64676:     assert( (pSlot+sz)<=pCArray->apCell[i]
64677:          || pSlot>=(pCArray->apCell[i]+sz)
64678:          || CORRUPT_DB );
64679:     memmove(pSlot, pCArray->apCell[i], sz);
64680:     put2byte(pCellptr, (pSlot - aData));
64681:     pCellptr += 2;
64682:   }
64683:   *ppData = pData;
64684:   return 0;
64685: }
64686: 
64687: /*
64688: ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell 
64689: ** contains the size in bytes of each such cell. This function adds the
64690: ** space associated with each cell in the array that is currently stored 
64691: ** within the body of pPg to the pPg free-list. The cell-pointers and other
64692: ** fields of the page are not updated.
64693: **
64694: ** This function returns the total number of cells added to the free-list.
64695: */
64696: static int pageFreeArray(
64697:   MemPage *pPg,                   /* Page to edit */
64698:   int iFirst,                     /* First cell to delete */
64699:   int nCell,                      /* Cells to delete */
64700:   CellArray *pCArray              /* Array of cells */
64701: ){
64702:   u8 * const aData = pPg->aData;
64703:   u8 * const pEnd = &aData[pPg->pBt->usableSize];
64704:   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
64705:   int nRet = 0;
64706:   int i;
64707:   int iEnd = iFirst + nCell;
64708:   u8 *pFree = 0;
64709:   int szFree = 0;
64710: 
64711:   for(i=iFirst; i<iEnd; i++){
64712:     u8 *pCell = pCArray->apCell[i];
64713:     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
64714:       int sz;
64715:       /* No need to use cachedCellSize() here.  The sizes of all cells that
64716:       ** are to be freed have already been computing while deciding which
64717:       ** cells need freeing */
64718:       sz = pCArray->szCell[i];  assert( sz>0 );
64719:       if( pFree!=(pCell + sz) ){
64720:         if( pFree ){
64721:           assert( pFree>aData && (pFree - aData)<65536 );
64722:           freeSpace(pPg, (u16)(pFree - aData), szFree);
64723:         }
64724:         pFree = pCell;
64725:         szFree = sz;
64726:         if( pFree+sz>pEnd ) return 0;
64727:       }else{
64728:         pFree = pCell;
64729:         szFree += sz;
64730:       }
64731:       nRet++;
64732:     }
64733:   }
64734:   if( pFree ){
64735:     assert( pFree>aData && (pFree - aData)<65536 );
64736:     freeSpace(pPg, (u16)(pFree - aData), szFree);
64737:   }
64738:   return nRet;
64739: }
64740: 
64741: /*
64742: ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
64743: ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
64744: ** with apCell[iOld].  After balancing, this page should hold nNew cells
64745: ** starting at apCell[iNew].
64746: **
64747: ** This routine makes the necessary adjustments to pPg so that it contains
64748: ** the correct cells after being balanced.
64749: **
64750: ** The pPg->nFree field is invalid when this function returns. It is the
64751: ** responsibility of the caller to set it correctly.
64752: */
64753: static int editPage(
64754:   MemPage *pPg,                   /* Edit this page */
64755:   int iOld,                       /* Index of first cell currently on page */
64756:   int iNew,                       /* Index of new first cell on page */
64757:   int nNew,                       /* Final number of cells on page */
64758:   CellArray *pCArray              /* Array of cells and sizes */
64759: ){
64760:   u8 * const aData = pPg->aData;
64761:   const int hdr = pPg->hdrOffset;
64762:   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
64763:   int nCell = pPg->nCell;       /* Cells stored on pPg */
64764:   u8 *pData;
64765:   u8 *pCellptr;
64766:   int i;
64767:   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
64768:   int iNewEnd = iNew + nNew;
64769: 
64770: #ifdef SQLITE_DEBUG
64771:   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64772:   memcpy(pTmp, aData, pPg->pBt->usableSize);
64773: #endif
64774: 
64775:   /* Remove cells from the start and end of the page */
64776:   if( iOld<iNew ){
64777:     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
64778:     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
64779:     nCell -= nShift;
64780:   }
64781:   if( iNewEnd < iOldEnd ){
64782:     nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
64783:   }
64784: 
64785:   pData = &aData[get2byteNotZero(&aData[hdr+5])];
64786:   if( pData<pBegin ) goto editpage_fail;
64787: 
64788:   /* Add cells to the start of the page */
64789:   if( iNew<iOld ){
64790:     int nAdd = MIN(nNew,iOld-iNew);
64791:     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
64792:     pCellptr = pPg->aCellIdx;
64793:     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
64794:     if( pageInsertArray(
64795:           pPg, pBegin, &pData, pCellptr,
64796:           iNew, nAdd, pCArray
64797:     ) ) goto editpage_fail;
64798:     nCell += nAdd;
64799:   }
64800: 
64801:   /* Add any overflow cells */
64802:   for(i=0; i<pPg->nOverflow; i++){
64803:     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
64804:     if( iCell>=0 && iCell<nNew ){
64805:       pCellptr = &pPg->aCellIdx[iCell * 2];
64806:       memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
64807:       nCell++;
64808:       if( pageInsertArray(
64809:             pPg, pBegin, &pData, pCellptr,
64810:             iCell+iNew, 1, pCArray
64811:       ) ) goto editpage_fail;
64812:     }
64813:   }
64814: 
64815:   /* Append cells to the end of the page */
64816:   pCellptr = &pPg->aCellIdx[nCell*2];
64817:   if( pageInsertArray(
64818:         pPg, pBegin, &pData, pCellptr,
64819:         iNew+nCell, nNew-nCell, pCArray
64820:   ) ) goto editpage_fail;
64821: 
64822:   pPg->nCell = nNew;
64823:   pPg->nOverflow = 0;
64824: 
64825:   put2byte(&aData[hdr+3], pPg->nCell);
64826:   put2byte(&aData[hdr+5], pData - aData);
64827: 
64828: #ifdef SQLITE_DEBUG
64829:   for(i=0; i<nNew && !CORRUPT_DB; i++){
64830:     u8 *pCell = pCArray->apCell[i+iNew];
64831:     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
64832:     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
64833:       pCell = &pTmp[pCell - aData];
64834:     }
64835:     assert( 0==memcmp(pCell, &aData[iOff],
64836:             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
64837:   }
64838: #endif
64839: 
64840:   return SQLITE_OK;
64841:  editpage_fail:
64842:   /* Unable to edit this page. Rebuild it from scratch instead. */
64843:   populateCellCache(pCArray, iNew, nNew);
64844:   return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
64845: }
64846: 
64847: /*
64848: ** The following parameters determine how many adjacent pages get involved
64849: ** in a balancing operation.  NN is the number of neighbors on either side
64850: ** of the page that participate in the balancing operation.  NB is the
64851: ** total number of pages that participate, including the target page and
64852: ** NN neighbors on either side.
64853: **
64854: ** The minimum value of NN is 1 (of course).  Increasing NN above 1
64855: ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
64856: ** in exchange for a larger degradation in INSERT and UPDATE performance.
64857: ** The value of NN appears to give the best results overall.
64858: */
64859: #define NN 1             /* Number of neighbors on either side of pPage */
64860: #define NB (NN*2+1)      /* Total pages involved in the balance */
64861: 
64862: 
64863: #ifndef SQLITE_OMIT_QUICKBALANCE
64864: /*
64865: ** This version of balance() handles the common special case where
64866: ** a new entry is being inserted on the extreme right-end of the
64867: ** tree, in other words, when the new entry will become the largest
64868: ** entry in the tree.
64869: **
64870: ** Instead of trying to balance the 3 right-most leaf pages, just add
64871: ** a new page to the right-hand side and put the one new entry in
64872: ** that page.  This leaves the right side of the tree somewhat
64873: ** unbalanced.  But odds are that we will be inserting new entries
64874: ** at the end soon afterwards so the nearly empty page will quickly
64875: ** fill up.  On average.
64876: **
64877: ** pPage is the leaf page which is the right-most page in the tree.
64878: ** pParent is its parent.  pPage must have a single overflow entry
64879: ** which is also the right-most entry on the page.
64880: **
64881: ** The pSpace buffer is used to store a temporary copy of the divider
64882: ** cell that will be inserted into pParent. Such a cell consists of a 4
64883: ** byte page number followed by a variable length integer. In other
64884: ** words, at most 13 bytes. Hence the pSpace buffer must be at
64885: ** least 13 bytes in size.
64886: */
64887: static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
64888:   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
64889:   MemPage *pNew;                       /* Newly allocated page */
64890:   int rc;                              /* Return Code */
64891:   Pgno pgnoNew;                        /* Page number of pNew */
64892: 
64893:   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64894:   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
64895:   assert( pPage->nOverflow==1 );
64896: 
64897:   /* This error condition is now caught prior to reaching this function */
64898:   if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
64899: 
64900:   /* Allocate a new page. This page will become the right-sibling of 
64901:   ** pPage. Make the parent page writable, so that the new divider cell
64902:   ** may be inserted. If both these operations are successful, proceed.
64903:   */
64904:   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
64905: 
64906:   if( rc==SQLITE_OK ){
64907: 
64908:     u8 *pOut = &pSpace[4];
64909:     u8 *pCell = pPage->apOvfl[0];
64910:     u16 szCell = pPage->xCellSize(pPage, pCell);
64911:     u8 *pStop;
64912: 
64913:     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
64914:     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
64915:     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
64916:     rc = rebuildPage(pNew, 1, &pCell, &szCell);
64917:     if( NEVER(rc) ) return rc;
64918:     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
64919: 
64920:     /* If this is an auto-vacuum database, update the pointer map
64921:     ** with entries for the new page, and any pointer from the 
64922:     ** cell on the page to an overflow page. If either of these
64923:     ** operations fails, the return code is set, but the contents
64924:     ** of the parent page are still manipulated by thh code below.
64925:     ** That is Ok, at this point the parent page is guaranteed to
64926:     ** be marked as dirty. Returning an error code will cause a
64927:     ** rollback, undoing any changes made to the parent page.
64928:     */
64929:     if( ISAUTOVACUUM ){
64930:       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
64931:       if( szCell>pNew->minLocal ){
64932:         ptrmapPutOvflPtr(pNew, pCell, &rc);
64933:       }
64934:     }
64935:   
64936:     /* Create a divider cell to insert into pParent. The divider cell
64937:     ** consists of a 4-byte page number (the page number of pPage) and
64938:     ** a variable length key value (which must be the same value as the
64939:     ** largest key on pPage).
64940:     **
64941:     ** To find the largest key value on pPage, first find the right-most 
64942:     ** cell on pPage. The first two fields of this cell are the 
64943:     ** record-length (a variable length integer at most 32-bits in size)
64944:     ** and the key value (a variable length integer, may have any value).
64945:     ** The first of the while(...) loops below skips over the record-length
64946:     ** field. The second while(...) loop copies the key value from the
64947:     ** cell on pPage into the pSpace buffer.
64948:     */
64949:     pCell = findCell(pPage, pPage->nCell-1);
64950:     pStop = &pCell[9];
64951:     while( (*(pCell++)&0x80) && pCell<pStop );
64952:     pStop = &pCell[9];
64953:     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
64954: 
64955:     /* Insert the new divider cell into pParent. */
64956:     if( rc==SQLITE_OK ){
64957:       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
64958:                    0, pPage->pgno, &rc);
64959:     }
64960: 
64961:     /* Set the right-child pointer of pParent to point to the new page. */
64962:     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
64963:   
64964:     /* Release the reference to the new page. */
64965:     releasePage(pNew);
64966:   }
64967: 
64968:   return rc;
64969: }
64970: #endif /* SQLITE_OMIT_QUICKBALANCE */
64971: 
64972: #if 0
64973: /*
64974: ** This function does not contribute anything to the operation of SQLite.
64975: ** it is sometimes activated temporarily while debugging code responsible 
64976: ** for setting pointer-map entries.
64977: */
64978: static int ptrmapCheckPages(MemPage **apPage, int nPage){
64979:   int i, j;
64980:   for(i=0; i<nPage; i++){
64981:     Pgno n;
64982:     u8 e;
64983:     MemPage *pPage = apPage[i];
64984:     BtShared *pBt = pPage->pBt;
64985:     assert( pPage->isInit );
64986: 
64987:     for(j=0; j<pPage->nCell; j++){
64988:       CellInfo info;
64989:       u8 *z;
64990:      
64991:       z = findCell(pPage, j);
64992:       pPage->xParseCell(pPage, z, &info);
64993:       if( info.nLocal<info.nPayload ){
64994:         Pgno ovfl = get4byte(&z[info.nSize-4]);
64995:         ptrmapGet(pBt, ovfl, &e, &n);
64996:         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
64997:       }
64998:       if( !pPage->leaf ){
64999:         Pgno child = get4byte(z);
65000:         ptrmapGet(pBt, child, &e, &n);
65001:         assert( n==pPage->pgno && e==PTRMAP_BTREE );
65002:       }
65003:     }
65004:     if( !pPage->leaf ){
65005:       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
65006:       ptrmapGet(pBt, child, &e, &n);
65007:       assert( n==pPage->pgno && e==PTRMAP_BTREE );
65008:     }
65009:   }
65010:   return 1;
65011: }
65012: #endif
65013: 
65014: /*
65015: ** This function is used to copy the contents of the b-tree node stored 
65016: ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
65017: ** the pointer-map entries for each child page are updated so that the
65018: ** parent page stored in the pointer map is page pTo. If pFrom contained
65019: ** any cells with overflow page pointers, then the corresponding pointer
65020: ** map entries are also updated so that the parent page is page pTo.
65021: **
65022: ** If pFrom is currently carrying any overflow cells (entries in the
65023: ** MemPage.apOvfl[] array), they are not copied to pTo. 
65024: **
65025: ** Before returning, page pTo is reinitialized using btreeInitPage().
65026: **
65027: ** The performance of this function is not critical. It is only used by 
65028: ** the balance_shallower() and balance_deeper() procedures, neither of
65029: ** which are called often under normal circumstances.
65030: */
65031: static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
65032:   if( (*pRC)==SQLITE_OK ){
65033:     BtShared * const pBt = pFrom->pBt;
65034:     u8 * const aFrom = pFrom->aData;
65035:     u8 * const aTo = pTo->aData;
65036:     int const iFromHdr = pFrom->hdrOffset;
65037:     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
65038:     int rc;
65039:     int iData;
65040:   
65041:   
65042:     assert( pFrom->isInit );
65043:     assert( pFrom->nFree>=iToHdr );
65044:     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
65045:   
65046:     /* Copy the b-tree node content from page pFrom to page pTo. */
65047:     iData = get2byte(&aFrom[iFromHdr+5]);
65048:     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
65049:     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
65050:   
65051:     /* Reinitialize page pTo so that the contents of the MemPage structure
65052:     ** match the new data. The initialization of pTo can actually fail under
65053:     ** fairly obscure circumstances, even though it is a copy of initialized 
65054:     ** page pFrom.
65055:     */
65056:     pTo->isInit = 0;
65057:     rc = btreeInitPage(pTo);
65058:     if( rc!=SQLITE_OK ){
65059:       *pRC = rc;
65060:       return;
65061:     }
65062:   
65063:     /* If this is an auto-vacuum database, update the pointer-map entries
65064:     ** for any b-tree or overflow pages that pTo now contains the pointers to.
65065:     */
65066:     if( ISAUTOVACUUM ){
65067:       *pRC = setChildPtrmaps(pTo);
65068:     }
65069:   }
65070: }
65071: 
65072: /*
65073: ** This routine redistributes cells on the iParentIdx'th child of pParent
65074: ** (hereafter "the page") and up to 2 siblings so that all pages have about the
65075: ** same amount of free space. Usually a single sibling on either side of the
65076: ** page are used in the balancing, though both siblings might come from one
65077: ** side if the page is the first or last child of its parent. If the page 
65078: ** has fewer than 2 siblings (something which can only happen if the page
65079: ** is a root page or a child of a root page) then all available siblings
65080: ** participate in the balancing.
65081: **
65082: ** The number of siblings of the page might be increased or decreased by 
65083: ** one or two in an effort to keep pages nearly full but not over full. 
65084: **
65085: ** Note that when this routine is called, some of the cells on the page
65086: ** might not actually be stored in MemPage.aData[]. This can happen
65087: ** if the page is overfull. This routine ensures that all cells allocated
65088: ** to the page and its siblings fit into MemPage.aData[] before returning.
65089: **
65090: ** In the course of balancing the page and its siblings, cells may be
65091: ** inserted into or removed from the parent page (pParent). Doing so
65092: ** may cause the parent page to become overfull or underfull. If this
65093: ** happens, it is the responsibility of the caller to invoke the correct
65094: ** balancing routine to fix this problem (see the balance() routine). 
65095: **
65096: ** If this routine fails for any reason, it might leave the database
65097: ** in a corrupted state. So if this routine fails, the database should
65098: ** be rolled back.
65099: **
65100: ** The third argument to this function, aOvflSpace, is a pointer to a
65101: ** buffer big enough to hold one page. If while inserting cells into the parent
65102: ** page (pParent) the parent page becomes overfull, this buffer is
65103: ** used to store the parent's overflow cells. Because this function inserts
65104: ** a maximum of four divider cells into the parent page, and the maximum
65105: ** size of a cell stored within an internal node is always less than 1/4
65106: ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
65107: ** enough for all overflow cells.
65108: **
65109: ** If aOvflSpace is set to a null pointer, this function returns 
65110: ** SQLITE_NOMEM.
65111: */
65112: static int balance_nonroot(
65113:   MemPage *pParent,               /* Parent page of siblings being balanced */
65114:   int iParentIdx,                 /* Index of "the page" in pParent */
65115:   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
65116:   int isRoot,                     /* True if pParent is a root-page */
65117:   int bBulk                       /* True if this call is part of a bulk load */
65118: ){
65119:   BtShared *pBt;               /* The whole database */
65120:   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
65121:   int nNew = 0;                /* Number of pages in apNew[] */
65122:   int nOld;                    /* Number of pages in apOld[] */
65123:   int i, j, k;                 /* Loop counters */
65124:   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
65125:   int rc = SQLITE_OK;          /* The return code */
65126:   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
65127:   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
65128:   int usableSpace;             /* Bytes in pPage beyond the header */
65129:   int pageFlags;               /* Value of pPage->aData[0] */
65130:   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
65131:   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
65132:   int szScratch;               /* Size of scratch memory requested */
65133:   MemPage *apOld[NB];          /* pPage and up to two siblings */
65134:   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
65135:   u8 *pRight;                  /* Location in parent of right-sibling pointer */
65136:   u8 *apDiv[NB-1];             /* Divider cells in pParent */
65137:   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
65138:   int cntOld[NB+2];            /* Old index in b.apCell[] */
65139:   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
65140:   u8 *aSpace1;                 /* Space for copies of dividers cells */
65141:   Pgno pgno;                   /* Temp var to store a page number in */
65142:   u8 abDone[NB+2];             /* True after i'th new page is populated */
65143:   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
65144:   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
65145:   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
65146:   CellArray b;                  /* Parsed information on cells being balanced */
65147: 
65148:   memset(abDone, 0, sizeof(abDone));
65149:   b.nCell = 0;
65150:   b.apCell = 0;
65151:   pBt = pParent->pBt;
65152:   assert( sqlite3_mutex_held(pBt->mutex) );
65153:   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65154: 
65155: #if 0
65156:   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
65157: #endif
65158: 
65159:   /* At this point pParent may have at most one overflow cell. And if
65160:   ** this overflow cell is present, it must be the cell with 
65161:   ** index iParentIdx. This scenario comes about when this function
65162:   ** is called (indirectly) from sqlite3BtreeDelete().
65163:   */
65164:   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
65165:   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
65166: 
65167:   if( !aOvflSpace ){
65168:     return SQLITE_NOMEM_BKPT;
65169:   }
65170: 
65171:   /* Find the sibling pages to balance. Also locate the cells in pParent 
65172:   ** that divide the siblings. An attempt is made to find NN siblings on 
65173:   ** either side of pPage. More siblings are taken from one side, however, 
65174:   ** if there are fewer than NN siblings on the other side. If pParent
65175:   ** has NB or fewer children then all children of pParent are taken.  
65176:   **
65177:   ** This loop also drops the divider cells from the parent page. This
65178:   ** way, the remainder of the function does not have to deal with any
65179:   ** overflow cells in the parent page, since if any existed they will
65180:   ** have already been removed.
65181:   */
65182:   i = pParent->nOverflow + pParent->nCell;
65183:   if( i<2 ){
65184:     nxDiv = 0;
65185:   }else{
65186:     assert( bBulk==0 || bBulk==1 );
65187:     if( iParentIdx==0 ){                 
65188:       nxDiv = 0;
65189:     }else if( iParentIdx==i ){
65190:       nxDiv = i-2+bBulk;
65191:     }else{
65192:       nxDiv = iParentIdx-1;
65193:     }
65194:     i = 2-bBulk;
65195:   }
65196:   nOld = i+1;
65197:   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
65198:     pRight = &pParent->aData[pParent->hdrOffset+8];
65199:   }else{
65200:     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
65201:   }
65202:   pgno = get4byte(pRight);
65203:   while( 1 ){
65204:     rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
65205:     if( rc ){
65206:       memset(apOld, 0, (i+1)*sizeof(MemPage*));
65207:       goto balance_cleanup;
65208:     }
65209:     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
65210:     if( (i--)==0 ) break;
65211: 
65212:     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
65213:       apDiv[i] = pParent->apOvfl[0];
65214:       pgno = get4byte(apDiv[i]);
65215:       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65216:       pParent->nOverflow = 0;
65217:     }else{
65218:       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
65219:       pgno = get4byte(apDiv[i]);
65220:       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
65221: 
65222:       /* Drop the cell from the parent page. apDiv[i] still points to
65223:       ** the cell within the parent, even though it has been dropped.
65224:       ** This is safe because dropping a cell only overwrites the first
65225:       ** four bytes of it, and this function does not need the first
65226:       ** four bytes of the divider cell. So the pointer is safe to use
65227:       ** later on.  
65228:       **
65229:       ** But not if we are in secure-delete mode. In secure-delete mode,
65230:       ** the dropCell() routine will overwrite the entire cell with zeroes.
65231:       ** In this case, temporarily copy the cell into the aOvflSpace[]
65232:       ** buffer. It will be copied out again as soon as the aSpace[] buffer
65233:       ** is allocated.  */
65234:       if( pBt->btsFlags & BTS_SECURE_DELETE ){
65235:         int iOff;
65236: 
65237:         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
65238:         if( (iOff+szNew[i])>(int)pBt->usableSize ){
65239:           rc = SQLITE_CORRUPT_BKPT;
65240:           memset(apOld, 0, (i+1)*sizeof(MemPage*));
65241:           goto balance_cleanup;
65242:         }else{
65243:           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
65244:           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
65245:         }
65246:       }
65247:       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
65248:     }
65249:   }
65250: 
65251:   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
65252:   ** alignment */
65253:   nMaxCells = (nMaxCells + 3)&~3;
65254: 
65255:   /*
65256:   ** Allocate space for memory structures
65257:   */
65258:   szScratch =
65259:        nMaxCells*sizeof(u8*)                       /* b.apCell */
65260:      + nMaxCells*sizeof(u16)                       /* b.szCell */
65261:      + pBt->pageSize;                              /* aSpace1 */
65262: 
65263:   /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
65264:   ** that is more than 6 times the database page size. */
65265:   assert( szScratch<=6*(int)pBt->pageSize );
65266:   b.apCell = sqlite3ScratchMalloc( szScratch ); 
65267:   if( b.apCell==0 ){
65268:     rc = SQLITE_NOMEM_BKPT;
65269:     goto balance_cleanup;
65270:   }
65271:   b.szCell = (u16*)&b.apCell[nMaxCells];
65272:   aSpace1 = (u8*)&b.szCell[nMaxCells];
65273:   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
65274: 
65275:   /*
65276:   ** Load pointers to all cells on sibling pages and the divider cells
65277:   ** into the local b.apCell[] array.  Make copies of the divider cells
65278:   ** into space obtained from aSpace1[]. The divider cells have already
65279:   ** been removed from pParent.
65280:   **
65281:   ** If the siblings are on leaf pages, then the child pointers of the
65282:   ** divider cells are stripped from the cells before they are copied
65283:   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
65284:   ** child pointers.  If siblings are not leaves, then all cell in
65285:   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
65286:   ** are alike.
65287:   **
65288:   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
65289:   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
65290:   */
65291:   b.pRef = apOld[0];
65292:   leafCorrection = b.pRef->leaf*4;
65293:   leafData = b.pRef->intKeyLeaf;
65294:   for(i=0; i<nOld; i++){
65295:     MemPage *pOld = apOld[i];
65296:     int limit = pOld->nCell;
65297:     u8 *aData = pOld->aData;
65298:     u16 maskPage = pOld->maskPage;
65299:     u8 *piCell = aData + pOld->cellOffset;
65300:     u8 *piEnd;
65301: 
65302:     /* Verify that all sibling pages are of the same "type" (table-leaf,
65303:     ** table-interior, index-leaf, or index-interior).
65304:     */
65305:     if( pOld->aData[0]!=apOld[0]->aData[0] ){
65306:       rc = SQLITE_CORRUPT_BKPT;
65307:       goto balance_cleanup;
65308:     }
65309: 
65310:     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
65311:     ** constains overflow cells, include them in the b.apCell[] array
65312:     ** in the correct spot.
65313:     **
65314:     ** Note that when there are multiple overflow cells, it is always the
65315:     ** case that they are sequential and adjacent.  This invariant arises
65316:     ** because multiple overflows can only occurs when inserting divider
65317:     ** cells into a parent on a prior balance, and divider cells are always
65318:     ** adjacent and are inserted in order.  There is an assert() tagged
65319:     ** with "NOTE 1" in the overflow cell insertion loop to prove this
65320:     ** invariant.
65321:     **
65322:     ** This must be done in advance.  Once the balance starts, the cell
65323:     ** offset section of the btree page will be overwritten and we will no
65324:     ** long be able to find the cells if a pointer to each cell is not saved
65325:     ** first.
65326:     */
65327:     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
65328:     if( pOld->nOverflow>0 ){
65329:       limit = pOld->aiOvfl[0];
65330:       for(j=0; j<limit; j++){
65331:         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65332:         piCell += 2;
65333:         b.nCell++;
65334:       }
65335:       for(k=0; k<pOld->nOverflow; k++){
65336:         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
65337:         b.apCell[b.nCell] = pOld->apOvfl[k];
65338:         b.nCell++;
65339:       }
65340:     }
65341:     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
65342:     while( piCell<piEnd ){
65343:       assert( b.nCell<nMaxCells );
65344:       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
65345:       piCell += 2;
65346:       b.nCell++;
65347:     }
65348: 
65349:     cntOld[i] = b.nCell;
65350:     if( i<nOld-1 && !leafData){
65351:       u16 sz = (u16)szNew[i];
65352:       u8 *pTemp;
65353:       assert( b.nCell<nMaxCells );
65354:       b.szCell[b.nCell] = sz;
65355:       pTemp = &aSpace1[iSpace1];
65356:       iSpace1 += sz;
65357:       assert( sz<=pBt->maxLocal+23 );
65358:       assert( iSpace1 <= (int)pBt->pageSize );
65359:       memcpy(pTemp, apDiv[i], sz);
65360:       b.apCell[b.nCell] = pTemp+leafCorrection;
65361:       assert( leafCorrection==0 || leafCorrection==4 );
65362:       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
65363:       if( !pOld->leaf ){
65364:         assert( leafCorrection==0 );
65365:         assert( pOld->hdrOffset==0 );
65366:         /* The right pointer of the child page pOld becomes the left
65367:         ** pointer of the divider cell */
65368:         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
65369:       }else{
65370:         assert( leafCorrection==4 );
65371:         while( b.szCell[b.nCell]<4 ){
65372:           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
65373:           ** does exist, pad it with 0x00 bytes. */
65374:           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
65375:           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
65376:           aSpace1[iSpace1++] = 0x00;
65377:           b.szCell[b.nCell]++;
65378:         }
65379:       }
65380:       b.nCell++;
65381:     }
65382:   }
65383: 
65384:   /*
65385:   ** Figure out the number of pages needed to hold all b.nCell cells.
65386:   ** Store this number in "k".  Also compute szNew[] which is the total
65387:   ** size of all cells on the i-th page and cntNew[] which is the index
65388:   ** in b.apCell[] of the cell that divides page i from page i+1.  
65389:   ** cntNew[k] should equal b.nCell.
65390:   **
65391:   ** Values computed by this block:
65392:   **
65393:   **           k: The total number of sibling pages
65394:   **    szNew[i]: Spaced used on the i-th sibling page.
65395:   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
65396:   **              the right of the i-th sibling page.
65397:   ** usableSpace: Number of bytes of space available on each sibling.
65398:   ** 
65399:   */
65400:   usableSpace = pBt->usableSize - 12 + leafCorrection;
65401:   for(i=0; i<nOld; i++){
65402:     MemPage *p = apOld[i];
65403:     szNew[i] = usableSpace - p->nFree;
65404:     if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65405:     for(j=0; j<p->nOverflow; j++){
65406:       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
65407:     }
65408:     cntNew[i] = cntOld[i];
65409:   }
65410:   k = nOld;
65411:   for(i=0; i<k; i++){
65412:     int sz;
65413:     while( szNew[i]>usableSpace ){
65414:       if( i+1>=k ){
65415:         k = i+2;
65416:         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
65417:         szNew[k-1] = 0;
65418:         cntNew[k-1] = b.nCell;
65419:       }
65420:       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
65421:       szNew[i] -= sz;
65422:       if( !leafData ){
65423:         if( cntNew[i]<b.nCell ){
65424:           sz = 2 + cachedCellSize(&b, cntNew[i]);
65425:         }else{
65426:           sz = 0;
65427:         }
65428:       }
65429:       szNew[i+1] += sz;
65430:       cntNew[i]--;
65431:     }
65432:     while( cntNew[i]<b.nCell ){
65433:       sz = 2 + cachedCellSize(&b, cntNew[i]);
65434:       if( szNew[i]+sz>usableSpace ) break;
65435:       szNew[i] += sz;
65436:       cntNew[i]++;
65437:       if( !leafData ){
65438:         if( cntNew[i]<b.nCell ){
65439:           sz = 2 + cachedCellSize(&b, cntNew[i]);
65440:         }else{
65441:           sz = 0;
65442:         }
65443:       }
65444:       szNew[i+1] -= sz;
65445:     }
65446:     if( cntNew[i]>=b.nCell ){
65447:       k = i+1;
65448:     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
65449:       rc = SQLITE_CORRUPT_BKPT;
65450:       goto balance_cleanup;
65451:     }
65452:   }
65453: 
65454:   /*
65455:   ** The packing computed by the previous block is biased toward the siblings
65456:   ** on the left side (siblings with smaller keys). The left siblings are
65457:   ** always nearly full, while the right-most sibling might be nearly empty.
65458:   ** The next block of code attempts to adjust the packing of siblings to
65459:   ** get a better balance.
65460:   **
65461:   ** This adjustment is more than an optimization.  The packing above might
65462:   ** be so out of balance as to be illegal.  For example, the right-most
65463:   ** sibling might be completely empty.  This adjustment is not optional.
65464:   */
65465:   for(i=k-1; i>0; i--){
65466:     int szRight = szNew[i];  /* Size of sibling on the right */
65467:     int szLeft = szNew[i-1]; /* Size of sibling on the left */
65468:     int r;              /* Index of right-most cell in left sibling */
65469:     int d;              /* Index of first cell to the left of right sibling */
65470: 
65471:     r = cntNew[i-1] - 1;
65472:     d = r + 1 - leafData;
65473:     (void)cachedCellSize(&b, d);
65474:     do{
65475:       assert( d<nMaxCells );
65476:       assert( r<nMaxCells );
65477:       (void)cachedCellSize(&b, r);
65478:       if( szRight!=0
65479:        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
65480:         break;
65481:       }
65482:       szRight += b.szCell[d] + 2;
65483:       szLeft -= b.szCell[r] + 2;
65484:       cntNew[i-1] = r;
65485:       r--;
65486:       d--;
65487:     }while( r>=0 );
65488:     szNew[i] = szRight;
65489:     szNew[i-1] = szLeft;
65490:     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
65491:       rc = SQLITE_CORRUPT_BKPT;
65492:       goto balance_cleanup;
65493:     }
65494:   }
65495: 
65496:   /* Sanity check:  For a non-corrupt database file one of the follwing
65497:   ** must be true:
65498:   **    (1) We found one or more cells (cntNew[0])>0), or
65499:   **    (2) pPage is a virtual root page.  A virtual root page is when
65500:   **        the real root page is page 1 and we are the only child of
65501:   **        that page.
65502:   */
65503:   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
65504:   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
65505:     apOld[0]->pgno, apOld[0]->nCell,
65506:     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
65507:     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
65508:   ));
65509: 
65510:   /*
65511:   ** Allocate k new pages.  Reuse old pages where possible.
65512:   */
65513:   pageFlags = apOld[0]->aData[0];
65514:   for(i=0; i<k; i++){
65515:     MemPage *pNew;
65516:     if( i<nOld ){
65517:       pNew = apNew[i] = apOld[i];
65518:       apOld[i] = 0;
65519:       rc = sqlite3PagerWrite(pNew->pDbPage);
65520:       nNew++;
65521:       if( rc ) goto balance_cleanup;
65522:     }else{
65523:       assert( i>0 );
65524:       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
65525:       if( rc ) goto balance_cleanup;
65526:       zeroPage(pNew, pageFlags);
65527:       apNew[i] = pNew;
65528:       nNew++;
65529:       cntOld[i] = b.nCell;
65530: 
65531:       /* Set the pointer-map entry for the new sibling page. */
65532:       if( ISAUTOVACUUM ){
65533:         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
65534:         if( rc!=SQLITE_OK ){
65535:           goto balance_cleanup;
65536:         }
65537:       }
65538:     }
65539:   }
65540: 
65541:   /*
65542:   ** Reassign page numbers so that the new pages are in ascending order. 
65543:   ** This helps to keep entries in the disk file in order so that a scan
65544:   ** of the table is closer to a linear scan through the file. That in turn 
65545:   ** helps the operating system to deliver pages from the disk more rapidly.
65546:   **
65547:   ** An O(n^2) insertion sort algorithm is used, but since n is never more 
65548:   ** than (NB+2) (a small constant), that should not be a problem.
65549:   **
65550:   ** When NB==3, this one optimization makes the database about 25% faster 
65551:   ** for large insertions and deletions.
65552:   */
65553:   for(i=0; i<nNew; i++){
65554:     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
65555:     aPgFlags[i] = apNew[i]->pDbPage->flags;
65556:     for(j=0; j<i; j++){
65557:       if( aPgno[j]==aPgno[i] ){
65558:         /* This branch is taken if the set of sibling pages somehow contains
65559:         ** duplicate entries. This can happen if the database is corrupt. 
65560:         ** It would be simpler to detect this as part of the loop below, but
65561:         ** we do the detection here in order to avoid populating the pager
65562:         ** cache with two separate objects associated with the same
65563:         ** page number.  */
65564:         assert( CORRUPT_DB );
65565:         rc = SQLITE_CORRUPT_BKPT;
65566:         goto balance_cleanup;
65567:       }
65568:     }
65569:   }
65570:   for(i=0; i<nNew; i++){
65571:     int iBest = 0;                /* aPgno[] index of page number to use */
65572:     for(j=1; j<nNew; j++){
65573:       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
65574:     }
65575:     pgno = aPgOrder[iBest];
65576:     aPgOrder[iBest] = 0xffffffff;
65577:     if( iBest!=i ){
65578:       if( iBest>i ){
65579:         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
65580:       }
65581:       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
65582:       apNew[i]->pgno = pgno;
65583:     }
65584:   }
65585: 
65586:   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
65587:          "%d(%d nc=%d) %d(%d nc=%d)\n",
65588:     apNew[0]->pgno, szNew[0], cntNew[0],
65589:     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
65590:     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
65591:     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
65592:     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
65593:     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
65594:     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
65595:     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
65596:     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
65597:   ));
65598: 
65599:   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65600:   put4byte(pRight, apNew[nNew-1]->pgno);
65601: 
65602:   /* If the sibling pages are not leaves, ensure that the right-child pointer
65603:   ** of the right-most new sibling page is set to the value that was 
65604:   ** originally in the same field of the right-most old sibling page. */
65605:   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
65606:     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
65607:     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
65608:   }
65609: 
65610:   /* Make any required updates to pointer map entries associated with 
65611:   ** cells stored on sibling pages following the balance operation. Pointer
65612:   ** map entries associated with divider cells are set by the insertCell()
65613:   ** routine. The associated pointer map entries are:
65614:   **
65615:   **   a) if the cell contains a reference to an overflow chain, the
65616:   **      entry associated with the first page in the overflow chain, and
65617:   **
65618:   **   b) if the sibling pages are not leaves, the child page associated
65619:   **      with the cell.
65620:   **
65621:   ** If the sibling pages are not leaves, then the pointer map entry 
65622:   ** associated with the right-child of each sibling may also need to be 
65623:   ** updated. This happens below, after the sibling pages have been 
65624:   ** populated, not here.
65625:   */
65626:   if( ISAUTOVACUUM ){
65627:     MemPage *pNew = apNew[0];
65628:     u8 *aOld = pNew->aData;
65629:     int cntOldNext = pNew->nCell + pNew->nOverflow;
65630:     int usableSize = pBt->usableSize;
65631:     int iNew = 0;
65632:     int iOld = 0;
65633: 
65634:     for(i=0; i<b.nCell; i++){
65635:       u8 *pCell = b.apCell[i];
65636:       if( i==cntOldNext ){
65637:         MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
65638:         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
65639:         aOld = pOld->aData;
65640:       }
65641:       if( i==cntNew[iNew] ){
65642:         pNew = apNew[++iNew];
65643:         if( !leafData ) continue;
65644:       }
65645: 
65646:       /* Cell pCell is destined for new sibling page pNew. Originally, it
65647:       ** was either part of sibling page iOld (possibly an overflow cell), 
65648:       ** or else the divider cell to the left of sibling page iOld. So,
65649:       ** if sibling page iOld had the same page number as pNew, and if
65650:       ** pCell really was a part of sibling page iOld (not a divider or
65651:       ** overflow cell), we can skip updating the pointer map entries.  */
65652:       if( iOld>=nNew
65653:        || pNew->pgno!=aPgno[iOld]
65654:        || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
65655:       ){
65656:         if( !leafCorrection ){
65657:           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
65658:         }
65659:         if( cachedCellSize(&b,i)>pNew->minLocal ){
65660:           ptrmapPutOvflPtr(pNew, pCell, &rc);
65661:         }
65662:         if( rc ) goto balance_cleanup;
65663:       }
65664:     }
65665:   }
65666: 
65667:   /* Insert new divider cells into pParent. */
65668:   for(i=0; i<nNew-1; i++){
65669:     u8 *pCell;
65670:     u8 *pTemp;
65671:     int sz;
65672:     MemPage *pNew = apNew[i];
65673:     j = cntNew[i];
65674: 
65675:     assert( j<nMaxCells );
65676:     assert( b.apCell[j]!=0 );
65677:     pCell = b.apCell[j];
65678:     sz = b.szCell[j] + leafCorrection;
65679:     pTemp = &aOvflSpace[iOvflSpace];
65680:     if( !pNew->leaf ){
65681:       memcpy(&pNew->aData[8], pCell, 4);
65682:     }else if( leafData ){
65683:       /* If the tree is a leaf-data tree, and the siblings are leaves, 
65684:       ** then there is no divider cell in b.apCell[]. Instead, the divider 
65685:       ** cell consists of the integer key for the right-most cell of 
65686:       ** the sibling-page assembled above only.
65687:       */
65688:       CellInfo info;
65689:       j--;
65690:       pNew->xParseCell(pNew, b.apCell[j], &info);
65691:       pCell = pTemp;
65692:       sz = 4 + putVarint(&pCell[4], info.nKey);
65693:       pTemp = 0;
65694:     }else{
65695:       pCell -= 4;
65696:       /* Obscure case for non-leaf-data trees: If the cell at pCell was
65697:       ** previously stored on a leaf node, and its reported size was 4
65698:       ** bytes, then it may actually be smaller than this 
65699:       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
65700:       ** any cell). But it is important to pass the correct size to 
65701:       ** insertCell(), so reparse the cell now.
65702:       **
65703:       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
65704:       ** and WITHOUT ROWID tables with exactly one column which is the
65705:       ** primary key.
65706:       */
65707:       if( b.szCell[j]==4 ){
65708:         assert(leafCorrection==4);
65709:         sz = pParent->xCellSize(pParent, pCell);
65710:       }
65711:     }
65712:     iOvflSpace += sz;
65713:     assert( sz<=pBt->maxLocal+23 );
65714:     assert( iOvflSpace <= (int)pBt->pageSize );
65715:     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
65716:     if( rc!=SQLITE_OK ) goto balance_cleanup;
65717:     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65718:   }
65719: 
65720:   /* Now update the actual sibling pages. The order in which they are updated
65721:   ** is important, as this code needs to avoid disrupting any page from which
65722:   ** cells may still to be read. In practice, this means:
65723:   **
65724:   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
65725:   **      then it is not safe to update page apNew[iPg] until after
65726:   **      the left-hand sibling apNew[iPg-1] has been updated.
65727:   **
65728:   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
65729:   **      then it is not safe to update page apNew[iPg] until after
65730:   **      the right-hand sibling apNew[iPg+1] has been updated.
65731:   **
65732:   ** If neither of the above apply, the page is safe to update.
65733:   **
65734:   ** The iPg value in the following loop starts at nNew-1 goes down
65735:   ** to 0, then back up to nNew-1 again, thus making two passes over
65736:   ** the pages.  On the initial downward pass, only condition (1) above
65737:   ** needs to be tested because (2) will always be true from the previous
65738:   ** step.  On the upward pass, both conditions are always true, so the
65739:   ** upwards pass simply processes pages that were missed on the downward
65740:   ** pass.
65741:   */
65742:   for(i=1-nNew; i<nNew; i++){
65743:     int iPg = i<0 ? -i : i;
65744:     assert( iPg>=0 && iPg<nNew );
65745:     if( abDone[iPg] ) continue;         /* Skip pages already processed */
65746:     if( i>=0                            /* On the upwards pass, or... */
65747:      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
65748:     ){
65749:       int iNew;
65750:       int iOld;
65751:       int nNewCell;
65752: 
65753:       /* Verify condition (1):  If cells are moving left, update iPg
65754:       ** only after iPg-1 has already been updated. */
65755:       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
65756: 
65757:       /* Verify condition (2):  If cells are moving right, update iPg
65758:       ** only after iPg+1 has already been updated. */
65759:       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
65760: 
65761:       if( iPg==0 ){
65762:         iNew = iOld = 0;
65763:         nNewCell = cntNew[0];
65764:       }else{
65765:         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
65766:         iNew = cntNew[iPg-1] + !leafData;
65767:         nNewCell = cntNew[iPg] - iNew;
65768:       }
65769: 
65770:       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
65771:       if( rc ) goto balance_cleanup;
65772:       abDone[iPg]++;
65773:       apNew[iPg]->nFree = usableSpace-szNew[iPg];
65774:       assert( apNew[iPg]->nOverflow==0 );
65775:       assert( apNew[iPg]->nCell==nNewCell );
65776:     }
65777:   }
65778: 
65779:   /* All pages have been processed exactly once */
65780:   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
65781: 
65782:   assert( nOld>0 );
65783:   assert( nNew>0 );
65784: 
65785:   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
65786:     /* The root page of the b-tree now contains no cells. The only sibling
65787:     ** page is the right-child of the parent. Copy the contents of the
65788:     ** child page into the parent, decreasing the overall height of the
65789:     ** b-tree structure by one. This is described as the "balance-shallower"
65790:     ** sub-algorithm in some documentation.
65791:     **
65792:     ** If this is an auto-vacuum database, the call to copyNodeContent() 
65793:     ** sets all pointer-map entries corresponding to database image pages 
65794:     ** for which the pointer is stored within the content being copied.
65795:     **
65796:     ** It is critical that the child page be defragmented before being
65797:     ** copied into the parent, because if the parent is page 1 then it will
65798:     ** by smaller than the child due to the database header, and so all the
65799:     ** free space needs to be up front.
65800:     */
65801:     assert( nNew==1 || CORRUPT_DB );
65802:     rc = defragmentPage(apNew[0]);
65803:     testcase( rc!=SQLITE_OK );
65804:     assert( apNew[0]->nFree == 
65805:         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
65806:       || rc!=SQLITE_OK
65807:     );
65808:     copyNodeContent(apNew[0], pParent, &rc);
65809:     freePage(apNew[0], &rc);
65810:   }else if( ISAUTOVACUUM && !leafCorrection ){
65811:     /* Fix the pointer map entries associated with the right-child of each
65812:     ** sibling page. All other pointer map entries have already been taken
65813:     ** care of.  */
65814:     for(i=0; i<nNew; i++){
65815:       u32 key = get4byte(&apNew[i]->aData[8]);
65816:       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
65817:     }
65818:   }
65819: 
65820:   assert( pParent->isInit );
65821:   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
65822:           nOld, nNew, b.nCell));
65823: 
65824:   /* Free any old pages that were not reused as new pages.
65825:   */
65826:   for(i=nNew; i<nOld; i++){
65827:     freePage(apOld[i], &rc);
65828:   }
65829: 
65830: #if 0
65831:   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
65832:     /* The ptrmapCheckPages() contains assert() statements that verify that
65833:     ** all pointer map pages are set correctly. This is helpful while 
65834:     ** debugging. This is usually disabled because a corrupt database may
65835:     ** cause an assert() statement to fail.  */
65836:     ptrmapCheckPages(apNew, nNew);
65837:     ptrmapCheckPages(&pParent, 1);
65838:   }
65839: #endif
65840: 
65841:   /*
65842:   ** Cleanup before returning.
65843:   */
65844: balance_cleanup:
65845:   sqlite3ScratchFree(b.apCell);
65846:   for(i=0; i<nOld; i++){
65847:     releasePage(apOld[i]);
65848:   }
65849:   for(i=0; i<nNew; i++){
65850:     releasePage(apNew[i]);
65851:   }
65852: 
65853:   return rc;
65854: }
65855: 
65856: 
65857: /*
65858: ** This function is called when the root page of a b-tree structure is
65859: ** overfull (has one or more overflow pages).
65860: **
65861: ** A new child page is allocated and the contents of the current root
65862: ** page, including overflow cells, are copied into the child. The root
65863: ** page is then overwritten to make it an empty page with the right-child 
65864: ** pointer pointing to the new page.
65865: **
65866: ** Before returning, all pointer-map entries corresponding to pages 
65867: ** that the new child-page now contains pointers to are updated. The
65868: ** entry corresponding to the new right-child pointer of the root
65869: ** page is also updated.
65870: **
65871: ** If successful, *ppChild is set to contain a reference to the child 
65872: ** page and SQLITE_OK is returned. In this case the caller is required
65873: ** to call releasePage() on *ppChild exactly once. If an error occurs,
65874: ** an error code is returned and *ppChild is set to 0.
65875: */
65876: static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
65877:   int rc;                        /* Return value from subprocedures */
65878:   MemPage *pChild = 0;           /* Pointer to a new child page */
65879:   Pgno pgnoChild = 0;            /* Page number of the new child page */
65880:   BtShared *pBt = pRoot->pBt;    /* The BTree */
65881: 
65882:   assert( pRoot->nOverflow>0 );
65883:   assert( sqlite3_mutex_held(pBt->mutex) );
65884: 
65885:   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
65886:   ** page that will become the new right-child of pPage. Copy the contents
65887:   ** of the node stored on pRoot into the new child page.
65888:   */
65889:   rc = sqlite3PagerWrite(pRoot->pDbPage);
65890:   if( rc==SQLITE_OK ){
65891:     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
65892:     copyNodeContent(pRoot, pChild, &rc);
65893:     if( ISAUTOVACUUM ){
65894:       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
65895:     }
65896:   }
65897:   if( rc ){
65898:     *ppChild = 0;
65899:     releasePage(pChild);
65900:     return rc;
65901:   }
65902:   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
65903:   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
65904:   assert( pChild->nCell==pRoot->nCell );
65905: 
65906:   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
65907: 
65908:   /* Copy the overflow cells from pRoot to pChild */
65909:   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
65910:          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
65911:   memcpy(pChild->apOvfl, pRoot->apOvfl,
65912:          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
65913:   pChild->nOverflow = pRoot->nOverflow;
65914: 
65915:   /* Zero the contents of pRoot. Then install pChild as the right-child. */
65916:   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
65917:   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
65918: 
65919:   *ppChild = pChild;
65920:   return SQLITE_OK;
65921: }
65922: 
65923: /*
65924: ** The page that pCur currently points to has just been modified in
65925: ** some way. This function figures out if this modification means the
65926: ** tree needs to be balanced, and if so calls the appropriate balancing 
65927: ** routine. Balancing routines are:
65928: **
65929: **   balance_quick()
65930: **   balance_deeper()
65931: **   balance_nonroot()
65932: */
65933: static int balance(BtCursor *pCur){
65934:   int rc = SQLITE_OK;
65935:   const int nMin = pCur->pBt->usableSize * 2 / 3;
65936:   u8 aBalanceQuickSpace[13];
65937:   u8 *pFree = 0;
65938: 
65939:   VVA_ONLY( int balance_quick_called = 0 );
65940:   VVA_ONLY( int balance_deeper_called = 0 );
65941: 
65942:   do {
65943:     int iPage = pCur->iPage;
65944:     MemPage *pPage = pCur->apPage[iPage];
65945: 
65946:     if( iPage==0 ){
65947:       if( pPage->nOverflow ){
65948:         /* The root page of the b-tree is overfull. In this case call the
65949:         ** balance_deeper() function to create a new child for the root-page
65950:         ** and copy the current contents of the root-page to it. The
65951:         ** next iteration of the do-loop will balance the child page.
65952:         */ 
65953:         assert( balance_deeper_called==0 );
65954:         VVA_ONLY( balance_deeper_called++ );
65955:         rc = balance_deeper(pPage, &pCur->apPage[1]);
65956:         if( rc==SQLITE_OK ){
65957:           pCur->iPage = 1;
65958:           pCur->aiIdx[0] = 0;
65959:           pCur->aiIdx[1] = 0;
65960:           assert( pCur->apPage[1]->nOverflow );
65961:         }
65962:       }else{
65963:         break;
65964:       }
65965:     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
65966:       break;
65967:     }else{
65968:       MemPage * const pParent = pCur->apPage[iPage-1];
65969:       int const iIdx = pCur->aiIdx[iPage-1];
65970: 
65971:       rc = sqlite3PagerWrite(pParent->pDbPage);
65972:       if( rc==SQLITE_OK ){
65973: #ifndef SQLITE_OMIT_QUICKBALANCE
65974:         if( pPage->intKeyLeaf
65975:          && pPage->nOverflow==1
65976:          && pPage->aiOvfl[0]==pPage->nCell
65977:          && pParent->pgno!=1
65978:          && pParent->nCell==iIdx
65979:         ){
65980:           /* Call balance_quick() to create a new sibling of pPage on which
65981:           ** to store the overflow cell. balance_quick() inserts a new cell
65982:           ** into pParent, which may cause pParent overflow. If this
65983:           ** happens, the next iteration of the do-loop will balance pParent 
65984:           ** use either balance_nonroot() or balance_deeper(). Until this
65985:           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
65986:           ** buffer. 
65987:           **
65988:           ** The purpose of the following assert() is to check that only a
65989:           ** single call to balance_quick() is made for each call to this
65990:           ** function. If this were not verified, a subtle bug involving reuse
65991:           ** of the aBalanceQuickSpace[] might sneak in.
65992:           */
65993:           assert( balance_quick_called==0 ); 
65994:           VVA_ONLY( balance_quick_called++ );
65995:           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
65996:         }else
65997: #endif
65998:         {
65999:           /* In this case, call balance_nonroot() to redistribute cells
66000:           ** between pPage and up to 2 of its sibling pages. This involves
66001:           ** modifying the contents of pParent, which may cause pParent to
66002:           ** become overfull or underfull. The next iteration of the do-loop
66003:           ** will balance the parent page to correct this.
66004:           ** 
66005:           ** If the parent page becomes overfull, the overflow cell or cells
66006:           ** are stored in the pSpace buffer allocated immediately below. 
66007:           ** A subsequent iteration of the do-loop will deal with this by
66008:           ** calling balance_nonroot() (balance_deeper() may be called first,
66009:           ** but it doesn't deal with overflow cells - just moves them to a
66010:           ** different page). Once this subsequent call to balance_nonroot() 
66011:           ** has completed, it is safe to release the pSpace buffer used by
66012:           ** the previous call, as the overflow cell data will have been 
66013:           ** copied either into the body of a database page or into the new
66014:           ** pSpace buffer passed to the latter call to balance_nonroot().
66015:           */
66016:           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
66017:           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
66018:                                pCur->hints&BTREE_BULKLOAD);
66019:           if( pFree ){
66020:             /* If pFree is not NULL, it points to the pSpace buffer used 
66021:             ** by a previous call to balance_nonroot(). Its contents are
66022:             ** now stored either on real database pages or within the 
66023:             ** new pSpace buffer, so it may be safely freed here. */
66024:             sqlite3PageFree(pFree);
66025:           }
66026: 
66027:           /* The pSpace buffer will be freed after the next call to
66028:           ** balance_nonroot(), or just before this function returns, whichever
66029:           ** comes first. */
66030:           pFree = pSpace;
66031:         }
66032:       }
66033: 
66034:       pPage->nOverflow = 0;
66035: 
66036:       /* The next iteration of the do-loop balances the parent page. */
66037:       releasePage(pPage);
66038:       pCur->iPage--;
66039:       assert( pCur->iPage>=0 );
66040:     }
66041:   }while( rc==SQLITE_OK );
66042: 
66043:   if( pFree ){
66044:     sqlite3PageFree(pFree);
66045:   }
66046:   return rc;
66047: }
66048: 
66049: 
66050: /*
66051: ** Insert a new record into the BTree.  The content of the new record
66052: ** is described by the pX object.  The pCur cursor is used only to
66053: ** define what table the record should be inserted into, and is left
66054: ** pointing at a random location.
66055: **
66056: ** For a table btree (used for rowid tables), only the pX.nKey value of
66057: ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
66058: ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
66059: ** hold the content of the row.
66060: **
66061: ** For an index btree (used for indexes and WITHOUT ROWID tables), the
66062: ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The 
66063: ** pX.pData,nData,nZero fields must be zero.
66064: **
66065: ** If the seekResult parameter is non-zero, then a successful call to
66066: ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
66067: ** been performed. seekResult is the search result returned (a negative
66068: ** number if pCur points at an entry that is smaller than (pKey, nKey), or
66069: ** a positive value if pCur points at an entry that is larger than 
66070: ** (pKey, nKey)). 
66071: **
66072: ** If the seekResult parameter is non-zero, then the caller guarantees that
66073: ** cursor pCur is pointing at the existing copy of a row that is to be
66074: ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
66075: ** point to any entry or to no entry at all and so this function has to seek
66076: ** the cursor before the new key can be inserted.
66077: */
66078: SQLITE_PRIVATE int sqlite3BtreeInsert(
66079:   BtCursor *pCur,                /* Insert data into the table of this cursor */
66080:   const BtreePayload *pX,        /* Content of the row to be inserted */
66081:   int appendBias,                /* True if this is likely an append */
66082:   int seekResult                 /* Result of prior MovetoUnpacked() call */
66083: ){
66084:   int rc;
66085:   int loc = seekResult;          /* -1: before desired location  +1: after */
66086:   int szNew = 0;
66087:   int idx;
66088:   MemPage *pPage;
66089:   Btree *p = pCur->pBtree;
66090:   BtShared *pBt = p->pBt;
66091:   unsigned char *oldCell;
66092:   unsigned char *newCell = 0;
66093: 
66094:   if( pCur->eState==CURSOR_FAULT ){
66095:     assert( pCur->skipNext!=SQLITE_OK );
66096:     return pCur->skipNext;
66097:   }
66098: 
66099:   assert( cursorOwnsBtShared(pCur) );
66100:   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
66101:               && pBt->inTransaction==TRANS_WRITE
66102:               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
66103:   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66104: 
66105:   /* Assert that the caller has been consistent. If this cursor was opened
66106:   ** expecting an index b-tree, then the caller should be inserting blob
66107:   ** keys with no associated data. If the cursor was opened expecting an
66108:   ** intkey table, the caller should be inserting integer keys with a
66109:   ** blob of associated data.  */
66110:   assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
66111: 
66112:   /* Save the positions of any other cursors open on this table.
66113:   **
66114:   ** In some cases, the call to btreeMoveto() below is a no-op. For
66115:   ** example, when inserting data into a table with auto-generated integer
66116:   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
66117:   ** integer key to use. It then calls this function to actually insert the 
66118:   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
66119:   ** that the cursor is already where it needs to be and returns without
66120:   ** doing any work. To avoid thwarting these optimizations, it is important
66121:   ** not to clear the cursor here.
66122:   */
66123:   if( pCur->curFlags & BTCF_Multiple ){
66124:     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66125:     if( rc ) return rc;
66126:   }
66127: 
66128:   if( pCur->pKeyInfo==0 ){
66129:     assert( pX->pKey==0 );
66130:     /* If this is an insert into a table b-tree, invalidate any incrblob 
66131:     ** cursors open on the row being replaced */
66132:     invalidateIncrblobCursors(p, pX->nKey, 0);
66133: 
66134:     /* If the cursor is currently on the last row and we are appending a
66135:     ** new row onto the end, set the "loc" to avoid an unnecessary
66136:     ** btreeMoveto() call */
66137:     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey>0
66138:       && pCur->info.nKey==pX->nKey-1 ){
66139:        loc = -1;
66140:     }else if( loc==0 ){
66141:       rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, appendBias, &loc);
66142:       if( rc ) return rc;
66143:     }
66144:   }else if( loc==0 ){
66145:     rc = btreeMoveto(pCur, pX->pKey, pX->nKey, appendBias, &loc);
66146:     if( rc ) return rc;
66147:   }
66148:   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
66149: 
66150:   pPage = pCur->apPage[pCur->iPage];
66151:   assert( pPage->intKey || pX->nKey>=0 );
66152:   assert( pPage->leaf || !pPage->intKey );
66153: 
66154:   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
66155:           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
66156:           loc==0 ? "overwrite" : "new entry"));
66157:   assert( pPage->isInit );
66158:   newCell = pBt->pTmpSpace;
66159:   assert( newCell!=0 );
66160:   rc = fillInCell(pPage, newCell, pX, &szNew);
66161:   if( rc ) goto end_insert;
66162:   assert( szNew==pPage->xCellSize(pPage, newCell) );
66163:   assert( szNew <= MX_CELL_SIZE(pBt) );
66164:   idx = pCur->aiIdx[pCur->iPage];
66165:   if( loc==0 ){
66166:     u16 szOld;
66167:     assert( idx<pPage->nCell );
66168:     rc = sqlite3PagerWrite(pPage->pDbPage);
66169:     if( rc ){
66170:       goto end_insert;
66171:     }
66172:     oldCell = findCell(pPage, idx);
66173:     if( !pPage->leaf ){
66174:       memcpy(newCell, oldCell, 4);
66175:     }
66176:     rc = clearCell(pPage, oldCell, &szOld);
66177:     dropCell(pPage, idx, szOld, &rc);
66178:     if( rc ) goto end_insert;
66179:   }else if( loc<0 && pPage->nCell>0 ){
66180:     assert( pPage->leaf );
66181:     idx = ++pCur->aiIdx[pCur->iPage];
66182:   }else{
66183:     assert( pPage->leaf );
66184:   }
66185:   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
66186:   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
66187:   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
66188: 
66189:   /* If no error has occurred and pPage has an overflow cell, call balance() 
66190:   ** to redistribute the cells within the tree. Since balance() may move
66191:   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
66192:   ** variables.
66193:   **
66194:   ** Previous versions of SQLite called moveToRoot() to move the cursor
66195:   ** back to the root page as balance() used to invalidate the contents
66196:   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
66197:   ** set the cursor state to "invalid". This makes common insert operations
66198:   ** slightly faster.
66199:   **
66200:   ** There is a subtle but important optimization here too. When inserting
66201:   ** multiple records into an intkey b-tree using a single cursor (as can
66202:   ** happen while processing an "INSERT INTO ... SELECT" statement), it
66203:   ** is advantageous to leave the cursor pointing to the last entry in
66204:   ** the b-tree if possible. If the cursor is left pointing to the last
66205:   ** entry in the table, and the next row inserted has an integer key
66206:   ** larger than the largest existing key, it is possible to insert the
66207:   ** row without seeking the cursor. This can be a big performance boost.
66208:   */
66209:   pCur->info.nSize = 0;
66210:   if( pPage->nOverflow ){
66211:     assert( rc==SQLITE_OK );
66212:     pCur->curFlags &= ~(BTCF_ValidNKey);
66213:     rc = balance(pCur);
66214: 
66215:     /* Must make sure nOverflow is reset to zero even if the balance()
66216:     ** fails. Internal data structure corruption will result otherwise. 
66217:     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
66218:     ** from trying to save the current position of the cursor.  */
66219:     pCur->apPage[pCur->iPage]->nOverflow = 0;
66220:     pCur->eState = CURSOR_INVALID;
66221:   }
66222:   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
66223: 
66224: end_insert:
66225:   return rc;
66226: }
66227: 
66228: /*
66229: ** Delete the entry that the cursor is pointing to. 
66230: **
66231: ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
66232: ** the cursor is left pointing at an arbitrary location after the delete.
66233: ** But if that bit is set, then the cursor is left in a state such that
66234: ** the next call to BtreeNext() or BtreePrev() moves it to the same row
66235: ** as it would have been on if the call to BtreeDelete() had been omitted.
66236: **
66237: ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
66238: ** associated with a single table entry and its indexes.  Only one of those
66239: ** deletes is considered the "primary" delete.  The primary delete occurs
66240: ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
66241: ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
66242: ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
66243: ** but which might be used by alternative storage engines.
66244: */
66245: SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
66246:   Btree *p = pCur->pBtree;
66247:   BtShared *pBt = p->pBt;              
66248:   int rc;                              /* Return code */
66249:   MemPage *pPage;                      /* Page to delete cell from */
66250:   unsigned char *pCell;                /* Pointer to cell to delete */
66251:   int iCellIdx;                        /* Index of cell to delete */
66252:   int iCellDepth;                      /* Depth of node containing pCell */ 
66253:   u16 szCell;                          /* Size of the cell being deleted */
66254:   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
66255:   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
66256: 
66257:   assert( cursorOwnsBtShared(pCur) );
66258:   assert( pBt->inTransaction==TRANS_WRITE );
66259:   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66260:   assert( pCur->curFlags & BTCF_WriteFlag );
66261:   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
66262:   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
66263:   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
66264:   assert( pCur->eState==CURSOR_VALID );
66265:   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
66266: 
66267:   iCellDepth = pCur->iPage;
66268:   iCellIdx = pCur->aiIdx[iCellDepth];
66269:   pPage = pCur->apPage[iCellDepth];
66270:   pCell = findCell(pPage, iCellIdx);
66271: 
66272:   /* If the bPreserve flag is set to true, then the cursor position must
66273:   ** be preserved following this delete operation. If the current delete
66274:   ** will cause a b-tree rebalance, then this is done by saving the cursor
66275:   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before 
66276:   ** returning. 
66277:   **
66278:   ** Or, if the current delete will not cause a rebalance, then the cursor
66279:   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
66280:   ** before or after the deleted entry. In this case set bSkipnext to true.  */
66281:   if( bPreserve ){
66282:     if( !pPage->leaf 
66283:      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
66284:     ){
66285:       /* A b-tree rebalance will be required after deleting this entry.
66286:       ** Save the cursor key.  */
66287:       rc = saveCursorKey(pCur);
66288:       if( rc ) return rc;
66289:     }else{
66290:       bSkipnext = 1;
66291:     }
66292:   }
66293: 
66294:   /* If the page containing the entry to delete is not a leaf page, move
66295:   ** the cursor to the largest entry in the tree that is smaller than
66296:   ** the entry being deleted. This cell will replace the cell being deleted
66297:   ** from the internal node. The 'previous' entry is used for this instead
66298:   ** of the 'next' entry, as the previous entry is always a part of the
66299:   ** sub-tree headed by the child page of the cell being deleted. This makes
66300:   ** balancing the tree following the delete operation easier.  */
66301:   if( !pPage->leaf ){
66302:     int notUsed = 0;
66303:     rc = sqlite3BtreePrevious(pCur, &notUsed);
66304:     if( rc ) return rc;
66305:   }
66306: 
66307:   /* Save the positions of any other cursors open on this table before
66308:   ** making any modifications.  */
66309:   if( pCur->curFlags & BTCF_Multiple ){
66310:     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
66311:     if( rc ) return rc;
66312:   }
66313: 
66314:   /* If this is a delete operation to remove a row from a table b-tree,
66315:   ** invalidate any incrblob cursors open on the row being deleted.  */
66316:   if( pCur->pKeyInfo==0 ){
66317:     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
66318:   }
66319: 
66320:   /* Make the page containing the entry to be deleted writable. Then free any
66321:   ** overflow pages associated with the entry and finally remove the cell
66322:   ** itself from within the page.  */
66323:   rc = sqlite3PagerWrite(pPage->pDbPage);
66324:   if( rc ) return rc;
66325:   rc = clearCell(pPage, pCell, &szCell);
66326:   dropCell(pPage, iCellIdx, szCell, &rc);
66327:   if( rc ) return rc;
66328: 
66329:   /* If the cell deleted was not located on a leaf page, then the cursor
66330:   ** is currently pointing to the largest entry in the sub-tree headed
66331:   ** by the child-page of the cell that was just deleted from an internal
66332:   ** node. The cell from the leaf node needs to be moved to the internal
66333:   ** node to replace the deleted cell.  */
66334:   if( !pPage->leaf ){
66335:     MemPage *pLeaf = pCur->apPage[pCur->iPage];
66336:     int nCell;
66337:     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
66338:     unsigned char *pTmp;
66339: 
66340:     pCell = findCell(pLeaf, pLeaf->nCell-1);
66341:     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
66342:     nCell = pLeaf->xCellSize(pLeaf, pCell);
66343:     assert( MX_CELL_SIZE(pBt) >= nCell );
66344:     pTmp = pBt->pTmpSpace;
66345:     assert( pTmp!=0 );
66346:     rc = sqlite3PagerWrite(pLeaf->pDbPage);
66347:     if( rc==SQLITE_OK ){
66348:       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
66349:     }
66350:     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
66351:     if( rc ) return rc;
66352:   }
66353: 
66354:   /* Balance the tree. If the entry deleted was located on a leaf page,
66355:   ** then the cursor still points to that page. In this case the first
66356:   ** call to balance() repairs the tree, and the if(...) condition is
66357:   ** never true.
66358:   **
66359:   ** Otherwise, if the entry deleted was on an internal node page, then
66360:   ** pCur is pointing to the leaf page from which a cell was removed to
66361:   ** replace the cell deleted from the internal node. This is slightly
66362:   ** tricky as the leaf node may be underfull, and the internal node may
66363:   ** be either under or overfull. In this case run the balancing algorithm
66364:   ** on the leaf node first. If the balance proceeds far enough up the
66365:   ** tree that we can be sure that any problem in the internal node has
66366:   ** been corrected, so be it. Otherwise, after balancing the leaf node,
66367:   ** walk the cursor up the tree to the internal node and balance it as 
66368:   ** well.  */
66369:   rc = balance(pCur);
66370:   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
66371:     while( pCur->iPage>iCellDepth ){
66372:       releasePage(pCur->apPage[pCur->iPage--]);
66373:     }
66374:     rc = balance(pCur);
66375:   }
66376: 
66377:   if( rc==SQLITE_OK ){
66378:     if( bSkipnext ){
66379:       assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
66380:       assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
66381:       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
66382:       pCur->eState = CURSOR_SKIPNEXT;
66383:       if( iCellIdx>=pPage->nCell ){
66384:         pCur->skipNext = -1;
66385:         pCur->aiIdx[iCellDepth] = pPage->nCell-1;
66386:       }else{
66387:         pCur->skipNext = 1;
66388:       }
66389:     }else{
66390:       rc = moveToRoot(pCur);
66391:       if( bPreserve ){
66392:         pCur->eState = CURSOR_REQUIRESEEK;
66393:       }
66394:     }
66395:   }
66396:   return rc;
66397: }
66398: 
66399: /*
66400: ** Create a new BTree table.  Write into *piTable the page
66401: ** number for the root page of the new table.
66402: **
66403: ** The type of type is determined by the flags parameter.  Only the
66404: ** following values of flags are currently in use.  Other values for
66405: ** flags might not work:
66406: **
66407: **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
66408: **     BTREE_ZERODATA                  Used for SQL indices
66409: */
66410: static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
66411:   BtShared *pBt = p->pBt;
66412:   MemPage *pRoot;
66413:   Pgno pgnoRoot;
66414:   int rc;
66415:   int ptfFlags;          /* Page-type flage for the root page of new table */
66416: 
66417:   assert( sqlite3BtreeHoldsMutex(p) );
66418:   assert( pBt->inTransaction==TRANS_WRITE );
66419:   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
66420: 
66421: #ifdef SQLITE_OMIT_AUTOVACUUM
66422:   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66423:   if( rc ){
66424:     return rc;
66425:   }
66426: #else
66427:   if( pBt->autoVacuum ){
66428:     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
66429:     MemPage *pPageMove; /* The page to move to. */
66430: 
66431:     /* Creating a new table may probably require moving an existing database
66432:     ** to make room for the new tables root page. In case this page turns
66433:     ** out to be an overflow page, delete all overflow page-map caches
66434:     ** held by open cursors.
66435:     */
66436:     invalidateAllOverflowCache(pBt);
66437: 
66438:     /* Read the value of meta[3] from the database to determine where the
66439:     ** root page of the new table should go. meta[3] is the largest root-page
66440:     ** created so far, so the new root-page is (meta[3]+1).
66441:     */
66442:     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
66443:     pgnoRoot++;
66444: 
66445:     /* The new root-page may not be allocated on a pointer-map page, or the
66446:     ** PENDING_BYTE page.
66447:     */
66448:     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
66449:         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
66450:       pgnoRoot++;
66451:     }
66452:     assert( pgnoRoot>=3 || CORRUPT_DB );
66453:     testcase( pgnoRoot<3 );
66454: 
66455:     /* Allocate a page. The page that currently resides at pgnoRoot will
66456:     ** be moved to the allocated page (unless the allocated page happens
66457:     ** to reside at pgnoRoot).
66458:     */
66459:     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
66460:     if( rc!=SQLITE_OK ){
66461:       return rc;
66462:     }
66463: 
66464:     if( pgnoMove!=pgnoRoot ){
66465:       /* pgnoRoot is the page that will be used for the root-page of
66466:       ** the new table (assuming an error did not occur). But we were
66467:       ** allocated pgnoMove. If required (i.e. if it was not allocated
66468:       ** by extending the file), the current page at position pgnoMove
66469:       ** is already journaled.
66470:       */
66471:       u8 eType = 0;
66472:       Pgno iPtrPage = 0;
66473: 
66474:       /* Save the positions of any open cursors. This is required in
66475:       ** case they are holding a reference to an xFetch reference
66476:       ** corresponding to page pgnoRoot.  */
66477:       rc = saveAllCursors(pBt, 0, 0);
66478:       releasePage(pPageMove);
66479:       if( rc!=SQLITE_OK ){
66480:         return rc;
66481:       }
66482: 
66483:       /* Move the page currently at pgnoRoot to pgnoMove. */
66484:       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66485:       if( rc!=SQLITE_OK ){
66486:         return rc;
66487:       }
66488:       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
66489:       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
66490:         rc = SQLITE_CORRUPT_BKPT;
66491:       }
66492:       if( rc!=SQLITE_OK ){
66493:         releasePage(pRoot);
66494:         return rc;
66495:       }
66496:       assert( eType!=PTRMAP_ROOTPAGE );
66497:       assert( eType!=PTRMAP_FREEPAGE );
66498:       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
66499:       releasePage(pRoot);
66500: 
66501:       /* Obtain the page at pgnoRoot */
66502:       if( rc!=SQLITE_OK ){
66503:         return rc;
66504:       }
66505:       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66506:       if( rc!=SQLITE_OK ){
66507:         return rc;
66508:       }
66509:       rc = sqlite3PagerWrite(pRoot->pDbPage);
66510:       if( rc!=SQLITE_OK ){
66511:         releasePage(pRoot);
66512:         return rc;
66513:       }
66514:     }else{
66515:       pRoot = pPageMove;
66516:     } 
66517: 
66518:     /* Update the pointer-map and meta-data with the new root-page number. */
66519:     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
66520:     if( rc ){
66521:       releasePage(pRoot);
66522:       return rc;
66523:     }
66524: 
66525:     /* When the new root page was allocated, page 1 was made writable in
66526:     ** order either to increase the database filesize, or to decrement the
66527:     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
66528:     */
66529:     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
66530:     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
66531:     if( NEVER(rc) ){
66532:       releasePage(pRoot);
66533:       return rc;
66534:     }
66535: 
66536:   }else{
66537:     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66538:     if( rc ) return rc;
66539:   }
66540: #endif
66541:   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66542:   if( createTabFlags & BTREE_INTKEY ){
66543:     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
66544:   }else{
66545:     ptfFlags = PTF_ZERODATA | PTF_LEAF;
66546:   }
66547:   zeroPage(pRoot, ptfFlags);
66548:   sqlite3PagerUnref(pRoot->pDbPage);
66549:   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
66550:   *piTable = (int)pgnoRoot;
66551:   return SQLITE_OK;
66552: }
66553: SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
66554:   int rc;
66555:   sqlite3BtreeEnter(p);
66556:   rc = btreeCreateTable(p, piTable, flags);
66557:   sqlite3BtreeLeave(p);
66558:   return rc;
66559: }
66560: 
66561: /*
66562: ** Erase the given database page and all its children.  Return
66563: ** the page to the freelist.
66564: */
66565: static int clearDatabasePage(
66566:   BtShared *pBt,           /* The BTree that contains the table */
66567:   Pgno pgno,               /* Page number to clear */
66568:   int freePageFlag,        /* Deallocate page if true */
66569:   int *pnChange            /* Add number of Cells freed to this counter */
66570: ){
66571:   MemPage *pPage;
66572:   int rc;
66573:   unsigned char *pCell;
66574:   int i;
66575:   int hdr;
66576:   u16 szCell;
66577: 
66578:   assert( sqlite3_mutex_held(pBt->mutex) );
66579:   if( pgno>btreePagecount(pBt) ){
66580:     return SQLITE_CORRUPT_BKPT;
66581:   }
66582:   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
66583:   if( rc ) return rc;
66584:   if( pPage->bBusy ){
66585:     rc = SQLITE_CORRUPT_BKPT;
66586:     goto cleardatabasepage_out;
66587:   }
66588:   pPage->bBusy = 1;
66589:   hdr = pPage->hdrOffset;
66590:   for(i=0; i<pPage->nCell; i++){
66591:     pCell = findCell(pPage, i);
66592:     if( !pPage->leaf ){
66593:       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
66594:       if( rc ) goto cleardatabasepage_out;
66595:     }
66596:     rc = clearCell(pPage, pCell, &szCell);
66597:     if( rc ) goto cleardatabasepage_out;
66598:   }
66599:   if( !pPage->leaf ){
66600:     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
66601:     if( rc ) goto cleardatabasepage_out;
66602:   }else if( pnChange ){
66603:     assert( pPage->intKey || CORRUPT_DB );
66604:     testcase( !pPage->intKey );
66605:     *pnChange += pPage->nCell;
66606:   }
66607:   if( freePageFlag ){
66608:     freePage(pPage, &rc);
66609:   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
66610:     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
66611:   }
66612: 
66613: cleardatabasepage_out:
66614:   pPage->bBusy = 0;
66615:   releasePage(pPage);
66616:   return rc;
66617: }
66618: 
66619: /*
66620: ** Delete all information from a single table in the database.  iTable is
66621: ** the page number of the root of the table.  After this routine returns,
66622: ** the root page is empty, but still exists.
66623: **
66624: ** This routine will fail with SQLITE_LOCKED if there are any open
66625: ** read cursors on the table.  Open write cursors are moved to the
66626: ** root of the table.
66627: **
66628: ** If pnChange is not NULL, then table iTable must be an intkey table. The
66629: ** integer value pointed to by pnChange is incremented by the number of
66630: ** entries in the table.
66631: */
66632: SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
66633:   int rc;
66634:   BtShared *pBt = p->pBt;
66635:   sqlite3BtreeEnter(p);
66636:   assert( p->inTrans==TRANS_WRITE );
66637: 
66638:   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
66639: 
66640:   if( SQLITE_OK==rc ){
66641:     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
66642:     ** is the root of a table b-tree - if it is not, the following call is
66643:     ** a no-op).  */
66644:     invalidateIncrblobCursors(p, 0, 1);
66645:     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
66646:   }
66647:   sqlite3BtreeLeave(p);
66648:   return rc;
66649: }
66650: 
66651: /*
66652: ** Delete all information from the single table that pCur is open on.
66653: **
66654: ** This routine only work for pCur on an ephemeral table.
66655: */
66656: SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
66657:   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
66658: }
66659: 
66660: /*
66661: ** Erase all information in a table and add the root of the table to
66662: ** the freelist.  Except, the root of the principle table (the one on
66663: ** page 1) is never added to the freelist.
66664: **
66665: ** This routine will fail with SQLITE_LOCKED if there are any open
66666: ** cursors on the table.
66667: **
66668: ** If AUTOVACUUM is enabled and the page at iTable is not the last
66669: ** root page in the database file, then the last root page 
66670: ** in the database file is moved into the slot formerly occupied by
66671: ** iTable and that last slot formerly occupied by the last root page
66672: ** is added to the freelist instead of iTable.  In this say, all
66673: ** root pages are kept at the beginning of the database file, which
66674: ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
66675: ** page number that used to be the last root page in the file before
66676: ** the move.  If no page gets moved, *piMoved is set to 0.
66677: ** The last root page is recorded in meta[3] and the value of
66678: ** meta[3] is updated by this procedure.
66679: */
66680: static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
66681:   int rc;
66682:   MemPage *pPage = 0;
66683:   BtShared *pBt = p->pBt;
66684: 
66685:   assert( sqlite3BtreeHoldsMutex(p) );
66686:   assert( p->inTrans==TRANS_WRITE );
66687: 
66688:   /* It is illegal to drop a table if any cursors are open on the
66689:   ** database. This is because in auto-vacuum mode the backend may
66690:   ** need to move another root-page to fill a gap left by the deleted
66691:   ** root page. If an open cursor was using this page a problem would 
66692:   ** occur.
66693:   **
66694:   ** This error is caught long before control reaches this point.
66695:   */
66696:   if( NEVER(pBt->pCursor) ){
66697:     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
66698:     return SQLITE_LOCKED_SHAREDCACHE;
66699:   }
66700: 
66701:   /*
66702:   ** It is illegal to drop the sqlite_master table on page 1.  But again,
66703:   ** this error is caught long before reaching this point.
66704:   */
66705:   if( NEVER(iTable<2) ){
66706:     return SQLITE_CORRUPT_BKPT;
66707:   }
66708: 
66709:   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
66710:   if( rc ) return rc;
66711:   rc = sqlite3BtreeClearTable(p, iTable, 0);
66712:   if( rc ){
66713:     releasePage(pPage);
66714:     return rc;
66715:   }
66716: 
66717:   *piMoved = 0;
66718: 
66719: #ifdef SQLITE_OMIT_AUTOVACUUM
66720:   freePage(pPage, &rc);
66721:   releasePage(pPage);
66722: #else
66723:   if( pBt->autoVacuum ){
66724:     Pgno maxRootPgno;
66725:     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
66726: 
66727:     if( iTable==maxRootPgno ){
66728:       /* If the table being dropped is the table with the largest root-page
66729:       ** number in the database, put the root page on the free list. 
66730:       */
66731:       freePage(pPage, &rc);
66732:       releasePage(pPage);
66733:       if( rc!=SQLITE_OK ){
66734:         return rc;
66735:       }
66736:     }else{
66737:       /* The table being dropped does not have the largest root-page
66738:       ** number in the database. So move the page that does into the 
66739:       ** gap left by the deleted root-page.
66740:       */
66741:       MemPage *pMove;
66742:       releasePage(pPage);
66743:       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66744:       if( rc!=SQLITE_OK ){
66745:         return rc;
66746:       }
66747:       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
66748:       releasePage(pMove);
66749:       if( rc!=SQLITE_OK ){
66750:         return rc;
66751:       }
66752:       pMove = 0;
66753:       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66754:       freePage(pMove, &rc);
66755:       releasePage(pMove);
66756:       if( rc!=SQLITE_OK ){
66757:         return rc;
66758:       }
66759:       *piMoved = maxRootPgno;
66760:     }
66761: 
66762:     /* Set the new 'max-root-page' value in the database header. This
66763:     ** is the old value less one, less one more if that happens to
66764:     ** be a root-page number, less one again if that is the
66765:     ** PENDING_BYTE_PAGE.
66766:     */
66767:     maxRootPgno--;
66768:     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
66769:            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
66770:       maxRootPgno--;
66771:     }
66772:     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
66773: 
66774:     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
66775:   }else{
66776:     freePage(pPage, &rc);
66777:     releasePage(pPage);
66778:   }
66779: #endif
66780:   return rc;  
66781: }
66782: SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
66783:   int rc;
66784:   sqlite3BtreeEnter(p);
66785:   rc = btreeDropTable(p, iTable, piMoved);
66786:   sqlite3BtreeLeave(p);
66787:   return rc;
66788: }
66789: 
66790: 
66791: /*
66792: ** This function may only be called if the b-tree connection already
66793: ** has a read or write transaction open on the database.
66794: **
66795: ** Read the meta-information out of a database file.  Meta[0]
66796: ** is the number of free pages currently in the database.  Meta[1]
66797: ** through meta[15] are available for use by higher layers.  Meta[0]
66798: ** is read-only, the others are read/write.
66799: ** 
66800: ** The schema layer numbers meta values differently.  At the schema
66801: ** layer (and the SetCookie and ReadCookie opcodes) the number of
66802: ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
66803: **
66804: ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
66805: ** of reading the value out of the header, it instead loads the "DataVersion"
66806: ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
66807: ** database file.  It is a number computed by the pager.  But its access
66808: ** pattern is the same as header meta values, and so it is convenient to
66809: ** read it from this routine.
66810: */
66811: SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
66812:   BtShared *pBt = p->pBt;
66813: 
66814:   sqlite3BtreeEnter(p);
66815:   assert( p->inTrans>TRANS_NONE );
66816:   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
66817:   assert( pBt->pPage1 );
66818:   assert( idx>=0 && idx<=15 );
66819: 
66820:   if( idx==BTREE_DATA_VERSION ){
66821:     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
66822:   }else{
66823:     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
66824:   }
66825: 
66826:   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
66827:   ** database, mark the database as read-only.  */
66828: #ifdef SQLITE_OMIT_AUTOVACUUM
66829:   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
66830:     pBt->btsFlags |= BTS_READ_ONLY;
66831:   }
66832: #endif
66833: 
66834:   sqlite3BtreeLeave(p);
66835: }
66836: 
66837: /*
66838: ** Write meta-information back into the database.  Meta[0] is
66839: ** read-only and may not be written.
66840: */
66841: SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
66842:   BtShared *pBt = p->pBt;
66843:   unsigned char *pP1;
66844:   int rc;
66845:   assert( idx>=1 && idx<=15 );
66846:   sqlite3BtreeEnter(p);
66847:   assert( p->inTrans==TRANS_WRITE );
66848:   assert( pBt->pPage1!=0 );
66849:   pP1 = pBt->pPage1->aData;
66850:   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
66851:   if( rc==SQLITE_OK ){
66852:     put4byte(&pP1[36 + idx*4], iMeta);
66853: #ifndef SQLITE_OMIT_AUTOVACUUM
66854:     if( idx==BTREE_INCR_VACUUM ){
66855:       assert( pBt->autoVacuum || iMeta==0 );
66856:       assert( iMeta==0 || iMeta==1 );
66857:       pBt->incrVacuum = (u8)iMeta;
66858:     }
66859: #endif
66860:   }
66861:   sqlite3BtreeLeave(p);
66862:   return rc;
66863: }
66864: 
66865: #ifndef SQLITE_OMIT_BTREECOUNT
66866: /*
66867: ** The first argument, pCur, is a cursor opened on some b-tree. Count the
66868: ** number of entries in the b-tree and write the result to *pnEntry.
66869: **
66870: ** SQLITE_OK is returned if the operation is successfully executed. 
66871: ** Otherwise, if an error is encountered (i.e. an IO error or database
66872: ** corruption) an SQLite error code is returned.
66873: */
66874: SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
66875:   i64 nEntry = 0;                      /* Value to return in *pnEntry */
66876:   int rc;                              /* Return code */
66877: 
66878:   if( pCur->pgnoRoot==0 ){
66879:     *pnEntry = 0;
66880:     return SQLITE_OK;
66881:   }
66882:   rc = moveToRoot(pCur);
66883: 
66884:   /* Unless an error occurs, the following loop runs one iteration for each
66885:   ** page in the B-Tree structure (not including overflow pages). 
66886:   */
66887:   while( rc==SQLITE_OK ){
66888:     int iIdx;                          /* Index of child node in parent */
66889:     MemPage *pPage;                    /* Current page of the b-tree */
66890: 
66891:     /* If this is a leaf page or the tree is not an int-key tree, then 
66892:     ** this page contains countable entries. Increment the entry counter
66893:     ** accordingly.
66894:     */
66895:     pPage = pCur->apPage[pCur->iPage];
66896:     if( pPage->leaf || !pPage->intKey ){
66897:       nEntry += pPage->nCell;
66898:     }
66899: 
66900:     /* pPage is a leaf node. This loop navigates the cursor so that it 
66901:     ** points to the first interior cell that it points to the parent of
66902:     ** the next page in the tree that has not yet been visited. The
66903:     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
66904:     ** of the page, or to the number of cells in the page if the next page
66905:     ** to visit is the right-child of its parent.
66906:     **
66907:     ** If all pages in the tree have been visited, return SQLITE_OK to the
66908:     ** caller.
66909:     */
66910:     if( pPage->leaf ){
66911:       do {
66912:         if( pCur->iPage==0 ){
66913:           /* All pages of the b-tree have been visited. Return successfully. */
66914:           *pnEntry = nEntry;
66915:           return moveToRoot(pCur);
66916:         }
66917:         moveToParent(pCur);
66918:       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
66919: 
66920:       pCur->aiIdx[pCur->iPage]++;
66921:       pPage = pCur->apPage[pCur->iPage];
66922:     }
66923: 
66924:     /* Descend to the child node of the cell that the cursor currently 
66925:     ** points at. This is the right-child if (iIdx==pPage->nCell).
66926:     */
66927:     iIdx = pCur->aiIdx[pCur->iPage];
66928:     if( iIdx==pPage->nCell ){
66929:       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
66930:     }else{
66931:       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
66932:     }
66933:   }
66934: 
66935:   /* An error has occurred. Return an error code. */
66936:   return rc;
66937: }
66938: #endif
66939: 
66940: /*
66941: ** Return the pager associated with a BTree.  This routine is used for
66942: ** testing and debugging only.
66943: */
66944: SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
66945:   return p->pBt->pPager;
66946: }
66947: 
66948: #ifndef SQLITE_OMIT_INTEGRITY_CHECK
66949: /*
66950: ** Append a message to the error message string.
66951: */
66952: static void checkAppendMsg(
66953:   IntegrityCk *pCheck,
66954:   const char *zFormat,
66955:   ...
66956: ){
66957:   va_list ap;
66958:   if( !pCheck->mxErr ) return;
66959:   pCheck->mxErr--;
66960:   pCheck->nErr++;
66961:   va_start(ap, zFormat);
66962:   if( pCheck->errMsg.nChar ){
66963:     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
66964:   }
66965:   if( pCheck->zPfx ){
66966:     sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
66967:   }
66968:   sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
66969:   va_end(ap);
66970:   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
66971:     pCheck->mallocFailed = 1;
66972:   }
66973: }
66974: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
66975: 
66976: #ifndef SQLITE_OMIT_INTEGRITY_CHECK
66977: 
66978: /*
66979: ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
66980: ** corresponds to page iPg is already set.
66981: */
66982: static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66983:   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66984:   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
66985: }
66986: 
66987: /*
66988: ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
66989: */
66990: static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66991:   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66992:   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
66993: }
66994: 
66995: 
66996: /*
66997: ** Add 1 to the reference count for page iPage.  If this is the second
66998: ** reference to the page, add an error message to pCheck->zErrMsg.
66999: ** Return 1 if there are 2 or more references to the page and 0 if
67000: ** if this is the first reference to the page.
67001: **
67002: ** Also check that the page number is in bounds.
67003: */
67004: static int checkRef(IntegrityCk *pCheck, Pgno iPage){
67005:   if( iPage==0 ) return 1;
67006:   if( iPage>pCheck->nPage ){
67007:     checkAppendMsg(pCheck, "invalid page number %d", iPage);
67008:     return 1;
67009:   }
67010:   if( getPageReferenced(pCheck, iPage) ){
67011:     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
67012:     return 1;
67013:   }
67014:   setPageReferenced(pCheck, iPage);
67015:   return 0;
67016: }
67017: 
67018: #ifndef SQLITE_OMIT_AUTOVACUUM
67019: /*
67020: ** Check that the entry in the pointer-map for page iChild maps to 
67021: ** page iParent, pointer type ptrType. If not, append an error message
67022: ** to pCheck.
67023: */
67024: static void checkPtrmap(
67025:   IntegrityCk *pCheck,   /* Integrity check context */
67026:   Pgno iChild,           /* Child page number */
67027:   u8 eType,              /* Expected pointer map type */
67028:   Pgno iParent           /* Expected pointer map parent page number */
67029: ){
67030:   int rc;
67031:   u8 ePtrmapType;
67032:   Pgno iPtrmapParent;
67033: 
67034:   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
67035:   if( rc!=SQLITE_OK ){
67036:     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
67037:     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
67038:     return;
67039:   }
67040: 
67041:   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
67042:     checkAppendMsg(pCheck,
67043:       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
67044:       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
67045:   }
67046: }
67047: #endif
67048: 
67049: /*
67050: ** Check the integrity of the freelist or of an overflow page list.
67051: ** Verify that the number of pages on the list is N.
67052: */
67053: static void checkList(
67054:   IntegrityCk *pCheck,  /* Integrity checking context */
67055:   int isFreeList,       /* True for a freelist.  False for overflow page list */
67056:   int iPage,            /* Page number for first page in the list */
67057:   int N                 /* Expected number of pages in the list */
67058: ){
67059:   int i;
67060:   int expected = N;
67061:   int iFirst = iPage;
67062:   while( N-- > 0 && pCheck->mxErr ){
67063:     DbPage *pOvflPage;
67064:     unsigned char *pOvflData;
67065:     if( iPage<1 ){
67066:       checkAppendMsg(pCheck,
67067:          "%d of %d pages missing from overflow list starting at %d",
67068:           N+1, expected, iFirst);
67069:       break;
67070:     }
67071:     if( checkRef(pCheck, iPage) ) break;
67072:     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
67073:       checkAppendMsg(pCheck, "failed to get page %d", iPage);
67074:       break;
67075:     }
67076:     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
67077:     if( isFreeList ){
67078:       int n = get4byte(&pOvflData[4]);
67079: #ifndef SQLITE_OMIT_AUTOVACUUM
67080:       if( pCheck->pBt->autoVacuum ){
67081:         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
67082:       }
67083: #endif
67084:       if( n>(int)pCheck->pBt->usableSize/4-2 ){
67085:         checkAppendMsg(pCheck,
67086:            "freelist leaf count too big on page %d", iPage);
67087:         N--;
67088:       }else{
67089:         for(i=0; i<n; i++){
67090:           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
67091: #ifndef SQLITE_OMIT_AUTOVACUUM
67092:           if( pCheck->pBt->autoVacuum ){
67093:             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
67094:           }
67095: #endif
67096:           checkRef(pCheck, iFreePage);
67097:         }
67098:         N -= n;
67099:       }
67100:     }
67101: #ifndef SQLITE_OMIT_AUTOVACUUM
67102:     else{
67103:       /* If this database supports auto-vacuum and iPage is not the last
67104:       ** page in this overflow list, check that the pointer-map entry for
67105:       ** the following page matches iPage.
67106:       */
67107:       if( pCheck->pBt->autoVacuum && N>0 ){
67108:         i = get4byte(pOvflData);
67109:         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
67110:       }
67111:     }
67112: #endif
67113:     iPage = get4byte(pOvflData);
67114:     sqlite3PagerUnref(pOvflPage);
67115: 
67116:     if( isFreeList && N<(iPage!=0) ){
67117:       checkAppendMsg(pCheck, "free-page count in header is too small");
67118:     }
67119:   }
67120: }
67121: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67122: 
67123: /*
67124: ** An implementation of a min-heap.
67125: **
67126: ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
67127: ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
67128: ** and aHeap[N*2+1].
67129: **
67130: ** The heap property is this:  Every node is less than or equal to both
67131: ** of its daughter nodes.  A consequence of the heap property is that the
67132: ** root node aHeap[1] is always the minimum value currently in the heap.
67133: **
67134: ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
67135: ** the heap, preserving the heap property.  The btreeHeapPull() routine
67136: ** removes the root element from the heap (the minimum value in the heap)
67137: ** and then moves other nodes around as necessary to preserve the heap
67138: ** property.
67139: **
67140: ** This heap is used for cell overlap and coverage testing.  Each u32
67141: ** entry represents the span of a cell or freeblock on a btree page.  
67142: ** The upper 16 bits are the index of the first byte of a range and the
67143: ** lower 16 bits are the index of the last byte of that range.
67144: */
67145: static void btreeHeapInsert(u32 *aHeap, u32 x){
67146:   u32 j, i = ++aHeap[0];
67147:   aHeap[i] = x;
67148:   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
67149:     x = aHeap[j];
67150:     aHeap[j] = aHeap[i];
67151:     aHeap[i] = x;
67152:     i = j;
67153:   }
67154: }
67155: static int btreeHeapPull(u32 *aHeap, u32 *pOut){
67156:   u32 j, i, x;
67157:   if( (x = aHeap[0])==0 ) return 0;
67158:   *pOut = aHeap[1];
67159:   aHeap[1] = aHeap[x];
67160:   aHeap[x] = 0xffffffff;
67161:   aHeap[0]--;
67162:   i = 1;
67163:   while( (j = i*2)<=aHeap[0] ){
67164:     if( aHeap[j]>aHeap[j+1] ) j++;
67165:     if( aHeap[i]<aHeap[j] ) break;
67166:     x = aHeap[i];
67167:     aHeap[i] = aHeap[j];
67168:     aHeap[j] = x;
67169:     i = j;
67170:   }
67171:   return 1;  
67172: }
67173: 
67174: #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67175: /*
67176: ** Do various sanity checks on a single page of a tree.  Return
67177: ** the tree depth.  Root pages return 0.  Parents of root pages
67178: ** return 1, and so forth.
67179: ** 
67180: ** These checks are done:
67181: **
67182: **      1.  Make sure that cells and freeblocks do not overlap
67183: **          but combine to completely cover the page.
67184: **      2.  Make sure integer cell keys are in order.
67185: **      3.  Check the integrity of overflow pages.
67186: **      4.  Recursively call checkTreePage on all children.
67187: **      5.  Verify that the depth of all children is the same.
67188: */
67189: static int checkTreePage(
67190:   IntegrityCk *pCheck,  /* Context for the sanity check */
67191:   int iPage,            /* Page number of the page to check */
67192:   i64 *piMinKey,        /* Write minimum integer primary key here */
67193:   i64 maxKey            /* Error if integer primary key greater than this */
67194: ){
67195:   MemPage *pPage = 0;      /* The page being analyzed */
67196:   int i;                   /* Loop counter */
67197:   int rc;                  /* Result code from subroutine call */
67198:   int depth = -1, d2;      /* Depth of a subtree */
67199:   int pgno;                /* Page number */
67200:   int nFrag;               /* Number of fragmented bytes on the page */
67201:   int hdr;                 /* Offset to the page header */
67202:   int cellStart;           /* Offset to the start of the cell pointer array */
67203:   int nCell;               /* Number of cells */
67204:   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
67205:   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
67206:                            ** False if IPK must be strictly less than maxKey */
67207:   u8 *data;                /* Page content */
67208:   u8 *pCell;               /* Cell content */
67209:   u8 *pCellIdx;            /* Next element of the cell pointer array */
67210:   BtShared *pBt;           /* The BtShared object that owns pPage */
67211:   u32 pc;                  /* Address of a cell */
67212:   u32 usableSize;          /* Usable size of the page */
67213:   u32 contentOffset;       /* Offset to the start of the cell content area */
67214:   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
67215:   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
67216:   const char *saved_zPfx = pCheck->zPfx;
67217:   int saved_v1 = pCheck->v1;
67218:   int saved_v2 = pCheck->v2;
67219:   u8 savedIsInit = 0;
67220: 
67221:   /* Check that the page exists
67222:   */
67223:   pBt = pCheck->pBt;
67224:   usableSize = pBt->usableSize;
67225:   if( iPage==0 ) return 0;
67226:   if( checkRef(pCheck, iPage) ) return 0;
67227:   pCheck->zPfx = "Page %d: ";
67228:   pCheck->v1 = iPage;
67229:   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
67230:     checkAppendMsg(pCheck,
67231:        "unable to get the page. error code=%d", rc);
67232:     goto end_of_check;
67233:   }
67234: 
67235:   /* Clear MemPage.isInit to make sure the corruption detection code in
67236:   ** btreeInitPage() is executed.  */
67237:   savedIsInit = pPage->isInit;
67238:   pPage->isInit = 0;
67239:   if( (rc = btreeInitPage(pPage))!=0 ){
67240:     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
67241:     checkAppendMsg(pCheck,
67242:                    "btreeInitPage() returns error code %d", rc);
67243:     goto end_of_check;
67244:   }
67245:   data = pPage->aData;
67246:   hdr = pPage->hdrOffset;
67247: 
67248:   /* Set up for cell analysis */
67249:   pCheck->zPfx = "On tree page %d cell %d: ";
67250:   contentOffset = get2byteNotZero(&data[hdr+5]);
67251:   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
67252: 
67253:   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
67254:   ** number of cells on the page. */
67255:   nCell = get2byte(&data[hdr+3]);
67256:   assert( pPage->nCell==nCell );
67257: 
67258:   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
67259:   ** immediately follows the b-tree page header. */
67260:   cellStart = hdr + 12 - 4*pPage->leaf;
67261:   assert( pPage->aCellIdx==&data[cellStart] );
67262:   pCellIdx = &data[cellStart + 2*(nCell-1)];
67263: 
67264:   if( !pPage->leaf ){
67265:     /* Analyze the right-child page of internal pages */
67266:     pgno = get4byte(&data[hdr+8]);
67267: #ifndef SQLITE_OMIT_AUTOVACUUM
67268:     if( pBt->autoVacuum ){
67269:       pCheck->zPfx = "On page %d at right child: ";
67270:       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67271:     }
67272: #endif
67273:     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67274:     keyCanBeEqual = 0;
67275:   }else{
67276:     /* For leaf pages, the coverage check will occur in the same loop
67277:     ** as the other cell checks, so initialize the heap.  */
67278:     heap = pCheck->heap;
67279:     heap[0] = 0;
67280:   }
67281: 
67282:   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
67283:   ** integer offsets to the cell contents. */
67284:   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
67285:     CellInfo info;
67286: 
67287:     /* Check cell size */
67288:     pCheck->v2 = i;
67289:     assert( pCellIdx==&data[cellStart + i*2] );
67290:     pc = get2byteAligned(pCellIdx);
67291:     pCellIdx -= 2;
67292:     if( pc<contentOffset || pc>usableSize-4 ){
67293:       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
67294:                              pc, contentOffset, usableSize-4);
67295:       doCoverageCheck = 0;
67296:       continue;
67297:     }
67298:     pCell = &data[pc];
67299:     pPage->xParseCell(pPage, pCell, &info);
67300:     if( pc+info.nSize>usableSize ){
67301:       checkAppendMsg(pCheck, "Extends off end of page");
67302:       doCoverageCheck = 0;
67303:       continue;
67304:     }
67305: 
67306:     /* Check for integer primary key out of range */
67307:     if( pPage->intKey ){
67308:       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
67309:         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
67310:       }
67311:       maxKey = info.nKey;
67312:     }
67313: 
67314:     /* Check the content overflow list */
67315:     if( info.nPayload>info.nLocal ){
67316:       int nPage;       /* Number of pages on the overflow chain */
67317:       Pgno pgnoOvfl;   /* First page of the overflow chain */
67318:       assert( pc + info.nSize - 4 <= usableSize );
67319:       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
67320:       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
67321: #ifndef SQLITE_OMIT_AUTOVACUUM
67322:       if( pBt->autoVacuum ){
67323:         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
67324:       }
67325: #endif
67326:       checkList(pCheck, 0, pgnoOvfl, nPage);
67327:     }
67328: 
67329:     if( !pPage->leaf ){
67330:       /* Check sanity of left child page for internal pages */
67331:       pgno = get4byte(pCell);
67332: #ifndef SQLITE_OMIT_AUTOVACUUM
67333:       if( pBt->autoVacuum ){
67334:         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
67335:       }
67336: #endif
67337:       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
67338:       keyCanBeEqual = 0;
67339:       if( d2!=depth ){
67340:         checkAppendMsg(pCheck, "Child page depth differs");
67341:         depth = d2;
67342:       }
67343:     }else{
67344:       /* Populate the coverage-checking heap for leaf pages */
67345:       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
67346:     }
67347:   }
67348:   *piMinKey = maxKey;
67349: 
67350:   /* Check for complete coverage of the page
67351:   */
67352:   pCheck->zPfx = 0;
67353:   if( doCoverageCheck && pCheck->mxErr>0 ){
67354:     /* For leaf pages, the min-heap has already been initialized and the
67355:     ** cells have already been inserted.  But for internal pages, that has
67356:     ** not yet been done, so do it now */
67357:     if( !pPage->leaf ){
67358:       heap = pCheck->heap;
67359:       heap[0] = 0;
67360:       for(i=nCell-1; i>=0; i--){
67361:         u32 size;
67362:         pc = get2byteAligned(&data[cellStart+i*2]);
67363:         size = pPage->xCellSize(pPage, &data[pc]);
67364:         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
67365:       }
67366:     }
67367:     /* Add the freeblocks to the min-heap
67368:     **
67369:     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
67370:     ** is the offset of the first freeblock, or zero if there are no
67371:     ** freeblocks on the page. 
67372:     */
67373:     i = get2byte(&data[hdr+1]);
67374:     while( i>0 ){
67375:       int size, j;
67376:       assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
67377:       size = get2byte(&data[i+2]);
67378:       assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
67379:       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
67380:       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
67381:       ** big-endian integer which is the offset in the b-tree page of the next
67382:       ** freeblock in the chain, or zero if the freeblock is the last on the
67383:       ** chain. */
67384:       j = get2byte(&data[i]);
67385:       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
67386:       ** increasing offset. */
67387:       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
67388:       assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
67389:       i = j;
67390:     }
67391:     /* Analyze the min-heap looking for overlap between cells and/or 
67392:     ** freeblocks, and counting the number of untracked bytes in nFrag.
67393:     ** 
67394:     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
67395:     ** There is an implied first entry the covers the page header, the cell
67396:     ** pointer index, and the gap between the cell pointer index and the start
67397:     ** of cell content.  
67398:     **
67399:     ** The loop below pulls entries from the min-heap in order and compares
67400:     ** the start_address against the previous end_address.  If there is an
67401:     ** overlap, that means bytes are used multiple times.  If there is a gap,
67402:     ** that gap is added to the fragmentation count.
67403:     */
67404:     nFrag = 0;
67405:     prev = contentOffset - 1;   /* Implied first min-heap entry */
67406:     while( btreeHeapPull(heap,&x) ){
67407:       if( (prev&0xffff)>=(x>>16) ){
67408:         checkAppendMsg(pCheck,
67409:           "Multiple uses for byte %u of page %d", x>>16, iPage);
67410:         break;
67411:       }else{
67412:         nFrag += (x>>16) - (prev&0xffff) - 1;
67413:         prev = x;
67414:       }
67415:     }
67416:     nFrag += usableSize - (prev&0xffff) - 1;
67417:     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
67418:     ** is stored in the fifth field of the b-tree page header.
67419:     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
67420:     ** number of fragmented free bytes within the cell content area.
67421:     */
67422:     if( heap[0]==0 && nFrag!=data[hdr+7] ){
67423:       checkAppendMsg(pCheck,
67424:           "Fragmentation of %d bytes reported as %d on page %d",
67425:           nFrag, data[hdr+7], iPage);
67426:     }
67427:   }
67428: 
67429: end_of_check:
67430:   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
67431:   releasePage(pPage);
67432:   pCheck->zPfx = saved_zPfx;
67433:   pCheck->v1 = saved_v1;
67434:   pCheck->v2 = saved_v2;
67435:   return depth+1;
67436: }
67437: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67438: 
67439: #ifndef SQLITE_OMIT_INTEGRITY_CHECK
67440: /*
67441: ** This routine does a complete check of the given BTree file.  aRoot[] is
67442: ** an array of pages numbers were each page number is the root page of
67443: ** a table.  nRoot is the number of entries in aRoot.
67444: **
67445: ** A read-only or read-write transaction must be opened before calling
67446: ** this function.
67447: **
67448: ** Write the number of error seen in *pnErr.  Except for some memory
67449: ** allocation errors,  an error message held in memory obtained from
67450: ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
67451: ** returned.  If a memory allocation error occurs, NULL is returned.
67452: */
67453: SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
67454:   Btree *p,     /* The btree to be checked */
67455:   int *aRoot,   /* An array of root pages numbers for individual trees */
67456:   int nRoot,    /* Number of entries in aRoot[] */
67457:   int mxErr,    /* Stop reporting errors after this many */
67458:   int *pnErr    /* Write number of errors seen to this variable */
67459: ){
67460:   Pgno i;
67461:   IntegrityCk sCheck;
67462:   BtShared *pBt = p->pBt;
67463:   int savedDbFlags = pBt->db->flags;
67464:   char zErr[100];
67465:   VVA_ONLY( int nRef );
67466: 
67467:   sqlite3BtreeEnter(p);
67468:   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
67469:   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
67470:   assert( nRef>=0 );
67471:   sCheck.pBt = pBt;
67472:   sCheck.pPager = pBt->pPager;
67473:   sCheck.nPage = btreePagecount(sCheck.pBt);
67474:   sCheck.mxErr = mxErr;
67475:   sCheck.nErr = 0;
67476:   sCheck.mallocFailed = 0;
67477:   sCheck.zPfx = 0;
67478:   sCheck.v1 = 0;
67479:   sCheck.v2 = 0;
67480:   sCheck.aPgRef = 0;
67481:   sCheck.heap = 0;
67482:   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
67483:   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
67484:   if( sCheck.nPage==0 ){
67485:     goto integrity_ck_cleanup;
67486:   }
67487: 
67488:   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
67489:   if( !sCheck.aPgRef ){
67490:     sCheck.mallocFailed = 1;
67491:     goto integrity_ck_cleanup;
67492:   }
67493:   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
67494:   if( sCheck.heap==0 ){
67495:     sCheck.mallocFailed = 1;
67496:     goto integrity_ck_cleanup;
67497:   }
67498: 
67499:   i = PENDING_BYTE_PAGE(pBt);
67500:   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
67501: 
67502:   /* Check the integrity of the freelist
67503:   */
67504:   sCheck.zPfx = "Main freelist: ";
67505:   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
67506:             get4byte(&pBt->pPage1->aData[36]));
67507:   sCheck.zPfx = 0;
67508: 
67509:   /* Check all the tables.
67510:   */
67511:   testcase( pBt->db->flags & SQLITE_CellSizeCk );
67512:   pBt->db->flags &= ~SQLITE_CellSizeCk;
67513:   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
67514:     i64 notUsed;
67515:     if( aRoot[i]==0 ) continue;
67516: #ifndef SQLITE_OMIT_AUTOVACUUM
67517:     if( pBt->autoVacuum && aRoot[i]>1 ){
67518:       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
67519:     }
67520: #endif
67521:     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
67522:   }
67523:   pBt->db->flags = savedDbFlags;
67524: 
67525:   /* Make sure every page in the file is referenced
67526:   */
67527:   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
67528: #ifdef SQLITE_OMIT_AUTOVACUUM
67529:     if( getPageReferenced(&sCheck, i)==0 ){
67530:       checkAppendMsg(&sCheck, "Page %d is never used", i);
67531:     }
67532: #else
67533:     /* If the database supports auto-vacuum, make sure no tables contain
67534:     ** references to pointer-map pages.
67535:     */
67536:     if( getPageReferenced(&sCheck, i)==0 && 
67537:        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
67538:       checkAppendMsg(&sCheck, "Page %d is never used", i);
67539:     }
67540:     if( getPageReferenced(&sCheck, i)!=0 && 
67541:        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
67542:       checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
67543:     }
67544: #endif
67545:   }
67546: 
67547:   /* Clean  up and report errors.
67548:   */
67549: integrity_ck_cleanup:
67550:   sqlite3PageFree(sCheck.heap);
67551:   sqlite3_free(sCheck.aPgRef);
67552:   if( sCheck.mallocFailed ){
67553:     sqlite3StrAccumReset(&sCheck.errMsg);
67554:     sCheck.nErr++;
67555:   }
67556:   *pnErr = sCheck.nErr;
67557:   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
67558:   /* Make sure this analysis did not leave any unref() pages. */
67559:   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
67560:   sqlite3BtreeLeave(p);
67561:   return sqlite3StrAccumFinish(&sCheck.errMsg);
67562: }
67563: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67564: 
67565: /*
67566: ** Return the full pathname of the underlying database file.  Return
67567: ** an empty string if the database is in-memory or a TEMP database.
67568: **
67569: ** The pager filename is invariant as long as the pager is
67570: ** open so it is safe to access without the BtShared mutex.
67571: */
67572: SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
67573:   assert( p->pBt->pPager!=0 );
67574:   return sqlite3PagerFilename(p->pBt->pPager, 1);
67575: }
67576: 
67577: /*
67578: ** Return the pathname of the journal file for this database. The return
67579: ** value of this routine is the same regardless of whether the journal file
67580: ** has been created or not.
67581: **
67582: ** The pager journal filename is invariant as long as the pager is
67583: ** open so it is safe to access without the BtShared mutex.
67584: */
67585: SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
67586:   assert( p->pBt->pPager!=0 );
67587:   return sqlite3PagerJournalname(p->pBt->pPager);
67588: }
67589: 
67590: /*
67591: ** Return non-zero if a transaction is active.
67592: */
67593: SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
67594:   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
67595:   return (p && (p->inTrans==TRANS_WRITE));
67596: }
67597: 
67598: #ifndef SQLITE_OMIT_WAL
67599: /*
67600: ** Run a checkpoint on the Btree passed as the first argument.
67601: **
67602: ** Return SQLITE_LOCKED if this or any other connection has an open 
67603: ** transaction on the shared-cache the argument Btree is connected to.
67604: **
67605: ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
67606: */
67607: SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
67608:   int rc = SQLITE_OK;
67609:   if( p ){
67610:     BtShared *pBt = p->pBt;
67611:     sqlite3BtreeEnter(p);
67612:     if( pBt->inTransaction!=TRANS_NONE ){
67613:       rc = SQLITE_LOCKED;
67614:     }else{
67615:       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
67616:     }
67617:     sqlite3BtreeLeave(p);
67618:   }
67619:   return rc;
67620: }
67621: #endif
67622: 
67623: /*
67624: ** Return non-zero if a read (or write) transaction is active.
67625: */
67626: SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
67627:   assert( p );
67628:   assert( sqlite3_mutex_held(p->db->mutex) );
67629:   return p->inTrans!=TRANS_NONE;
67630: }
67631: 
67632: SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
67633:   assert( p );
67634:   assert( sqlite3_mutex_held(p->db->mutex) );
67635:   return p->nBackup!=0;
67636: }
67637: 
67638: /*
67639: ** This function returns a pointer to a blob of memory associated with
67640: ** a single shared-btree. The memory is used by client code for its own
67641: ** purposes (for example, to store a high-level schema associated with 
67642: ** the shared-btree). The btree layer manages reference counting issues.
67643: **
67644: ** The first time this is called on a shared-btree, nBytes bytes of memory
67645: ** are allocated, zeroed, and returned to the caller. For each subsequent 
67646: ** call the nBytes parameter is ignored and a pointer to the same blob
67647: ** of memory returned. 
67648: **
67649: ** If the nBytes parameter is 0 and the blob of memory has not yet been
67650: ** allocated, a null pointer is returned. If the blob has already been
67651: ** allocated, it is returned as normal.
67652: **
67653: ** Just before the shared-btree is closed, the function passed as the 
67654: ** xFree argument when the memory allocation was made is invoked on the 
67655: ** blob of allocated memory. The xFree function should not call sqlite3_free()
67656: ** on the memory, the btree layer does that.
67657: */
67658: SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
67659:   BtShared *pBt = p->pBt;
67660:   sqlite3BtreeEnter(p);
67661:   if( !pBt->pSchema && nBytes ){
67662:     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
67663:     pBt->xFreeSchema = xFree;
67664:   }
67665:   sqlite3BtreeLeave(p);
67666:   return pBt->pSchema;
67667: }
67668: 
67669: /*
67670: ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
67671: ** btree as the argument handle holds an exclusive lock on the 
67672: ** sqlite_master table. Otherwise SQLITE_OK.
67673: */
67674: SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
67675:   int rc;
67676:   assert( sqlite3_mutex_held(p->db->mutex) );
67677:   sqlite3BtreeEnter(p);
67678:   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
67679:   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
67680:   sqlite3BtreeLeave(p);
67681:   return rc;
67682: }
67683: 
67684: 
67685: #ifndef SQLITE_OMIT_SHARED_CACHE
67686: /*
67687: ** Obtain a lock on the table whose root page is iTab.  The
67688: ** lock is a write lock if isWritelock is true or a read lock
67689: ** if it is false.
67690: */
67691: SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
67692:   int rc = SQLITE_OK;
67693:   assert( p->inTrans!=TRANS_NONE );
67694:   if( p->sharable ){
67695:     u8 lockType = READ_LOCK + isWriteLock;
67696:     assert( READ_LOCK+1==WRITE_LOCK );
67697:     assert( isWriteLock==0 || isWriteLock==1 );
67698: 
67699:     sqlite3BtreeEnter(p);
67700:     rc = querySharedCacheTableLock(p, iTab, lockType);
67701:     if( rc==SQLITE_OK ){
67702:       rc = setSharedCacheTableLock(p, iTab, lockType);
67703:     }
67704:     sqlite3BtreeLeave(p);
67705:   }
67706:   return rc;
67707: }
67708: #endif
67709: 
67710: #ifndef SQLITE_OMIT_INCRBLOB
67711: /*
67712: ** Argument pCsr must be a cursor opened for writing on an 
67713: ** INTKEY table currently pointing at a valid table entry. 
67714: ** This function modifies the data stored as part of that entry.
67715: **
67716: ** Only the data content may only be modified, it is not possible to 
67717: ** change the length of the data stored. If this function is called with
67718: ** parameters that attempt to write past the end of the existing data,
67719: ** no modifications are made and SQLITE_CORRUPT is returned.
67720: */
67721: SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
67722:   int rc;
67723:   assert( cursorOwnsBtShared(pCsr) );
67724:   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
67725:   assert( pCsr->curFlags & BTCF_Incrblob );
67726: 
67727:   rc = restoreCursorPosition(pCsr);
67728:   if( rc!=SQLITE_OK ){
67729:     return rc;
67730:   }
67731:   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
67732:   if( pCsr->eState!=CURSOR_VALID ){
67733:     return SQLITE_ABORT;
67734:   }
67735: 
67736:   /* Save the positions of all other cursors open on this table. This is
67737:   ** required in case any of them are holding references to an xFetch
67738:   ** version of the b-tree page modified by the accessPayload call below.
67739:   **
67740:   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
67741:   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
67742:   ** saveAllCursors can only return SQLITE_OK.
67743:   */
67744:   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
67745:   assert( rc==SQLITE_OK );
67746: 
67747:   /* Check some assumptions: 
67748:   **   (a) the cursor is open for writing,
67749:   **   (b) there is a read/write transaction open,
67750:   **   (c) the connection holds a write-lock on the table (if required),
67751:   **   (d) there are no conflicting read-locks, and
67752:   **   (e) the cursor points at a valid row of an intKey table.
67753:   */
67754:   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
67755:     return SQLITE_READONLY;
67756:   }
67757:   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
67758:               && pCsr->pBt->inTransaction==TRANS_WRITE );
67759:   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
67760:   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
67761:   assert( pCsr->apPage[pCsr->iPage]->intKey );
67762: 
67763:   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
67764: }
67765: 
67766: /* 
67767: ** Mark this cursor as an incremental blob cursor.
67768: */
67769: SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
67770:   pCur->curFlags |= BTCF_Incrblob;
67771:   pCur->pBtree->hasIncrblobCur = 1;
67772: }
67773: #endif
67774: 
67775: /*
67776: ** Set both the "read version" (single byte at byte offset 18) and 
67777: ** "write version" (single byte at byte offset 19) fields in the database
67778: ** header to iVersion.
67779: */
67780: SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
67781:   BtShared *pBt = pBtree->pBt;
67782:   int rc;                         /* Return code */
67783:  
67784:   assert( iVersion==1 || iVersion==2 );
67785: 
67786:   /* If setting the version fields to 1, do not automatically open the
67787:   ** WAL connection, even if the version fields are currently set to 2.
67788:   */
67789:   pBt->btsFlags &= ~BTS_NO_WAL;
67790:   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
67791: 
67792:   rc = sqlite3BtreeBeginTrans(pBtree, 0);
67793:   if( rc==SQLITE_OK ){
67794:     u8 *aData = pBt->pPage1->aData;
67795:     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
67796:       rc = sqlite3BtreeBeginTrans(pBtree, 2);
67797:       if( rc==SQLITE_OK ){
67798:         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
67799:         if( rc==SQLITE_OK ){
67800:           aData[18] = (u8)iVersion;
67801:           aData[19] = (u8)iVersion;
67802:         }
67803:       }
67804:     }
67805:   }
67806: 
67807:   pBt->btsFlags &= ~BTS_NO_WAL;
67808:   return rc;
67809: }
67810: 
67811: /*
67812: ** Return true if the cursor has a hint specified.  This routine is
67813: ** only used from within assert() statements
67814: */
67815: SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
67816:   return (pCsr->hints & mask)!=0;
67817: }
67818: 
67819: /*
67820: ** Return true if the given Btree is read-only.
67821: */
67822: SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
67823:   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
67824: }
67825: 
67826: /*
67827: ** Return the size of the header added to each page by this module.
67828: */
67829: SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
67830: 
67831: #if !defined(SQLITE_OMIT_SHARED_CACHE)
67832: /*
67833: ** Return true if the Btree passed as the only argument is sharable.
67834: */
67835: SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
67836:   return p->sharable;
67837: }
67838: 
67839: /*
67840: ** Return the number of connections to the BtShared object accessed by
67841: ** the Btree handle passed as the only argument. For private caches 
67842: ** this is always 1. For shared caches it may be 1 or greater.
67843: */
67844: SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
67845:   testcase( p->sharable );
67846:   return p->pBt->nRef;
67847: }
67848: #endif
67849: 
67850: /************** End of btree.c ***********************************************/
67851: /************** Begin file backup.c ******************************************/
67852: /*
67853: ** 2009 January 28
67854: **
67855: ** The author disclaims copyright to this source code.  In place of
67856: ** a legal notice, here is a blessing:
67857: **
67858: **    May you do good and not evil.
67859: **    May you find forgiveness for yourself and forgive others.
67860: **    May you share freely, never taking more than you give.
67861: **
67862: *************************************************************************
67863: ** This file contains the implementation of the sqlite3_backup_XXX() 
67864: ** API functions and the related features.
67865: */
67866: /* #include "sqliteInt.h" */
67867: /* #include "btreeInt.h" */
67868: 
67869: /*
67870: ** Structure allocated for each backup operation.
67871: */
67872: struct sqlite3_backup {
67873:   sqlite3* pDestDb;        /* Destination database handle */
67874:   Btree *pDest;            /* Destination b-tree file */
67875:   u32 iDestSchema;         /* Original schema cookie in destination */
67876:   int bDestLocked;         /* True once a write-transaction is open on pDest */
67877: 
67878:   Pgno iNext;              /* Page number of the next source page to copy */
67879:   sqlite3* pSrcDb;         /* Source database handle */
67880:   Btree *pSrc;             /* Source b-tree file */
67881: 
67882:   int rc;                  /* Backup process error code */
67883: 
67884:   /* These two variables are set by every call to backup_step(). They are
67885:   ** read by calls to backup_remaining() and backup_pagecount().
67886:   */
67887:   Pgno nRemaining;         /* Number of pages left to copy */
67888:   Pgno nPagecount;         /* Total number of pages to copy */
67889: 
67890:   int isAttached;          /* True once backup has been registered with pager */
67891:   sqlite3_backup *pNext;   /* Next backup associated with source pager */
67892: };
67893: 
67894: /*
67895: ** THREAD SAFETY NOTES:
67896: **
67897: **   Once it has been created using backup_init(), a single sqlite3_backup
67898: **   structure may be accessed via two groups of thread-safe entry points:
67899: **
67900: **     * Via the sqlite3_backup_XXX() API function backup_step() and 
67901: **       backup_finish(). Both these functions obtain the source database
67902: **       handle mutex and the mutex associated with the source BtShared 
67903: **       structure, in that order.
67904: **
67905: **     * Via the BackupUpdate() and BackupRestart() functions, which are
67906: **       invoked by the pager layer to report various state changes in
67907: **       the page cache associated with the source database. The mutex
67908: **       associated with the source database BtShared structure will always 
67909: **       be held when either of these functions are invoked.
67910: **
67911: **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
67912: **   backup_pagecount() are not thread-safe functions. If they are called
67913: **   while some other thread is calling backup_step() or backup_finish(),
67914: **   the values returned may be invalid. There is no way for a call to
67915: **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
67916: **   or backup_pagecount().
67917: **
67918: **   Depending on the SQLite configuration, the database handles and/or
67919: **   the Btree objects may have their own mutexes that require locking.
67920: **   Non-sharable Btrees (in-memory databases for example), do not have
67921: **   associated mutexes.
67922: */
67923: 
67924: /*
67925: ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
67926: ** in connection handle pDb. If such a database cannot be found, return
67927: ** a NULL pointer and write an error message to pErrorDb.
67928: **
67929: ** If the "temp" database is requested, it may need to be opened by this 
67930: ** function. If an error occurs while doing so, return 0 and write an 
67931: ** error message to pErrorDb.
67932: */
67933: static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
67934:   int i = sqlite3FindDbName(pDb, zDb);
67935: 
67936:   if( i==1 ){
67937:     Parse *pParse;
67938:     int rc = 0;
67939:     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
67940:     if( pParse==0 ){
67941:       sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
67942:       rc = SQLITE_NOMEM_BKPT;
67943:     }else{
67944:       pParse->db = pDb;
67945:       if( sqlite3OpenTempDatabase(pParse) ){
67946:         sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
67947:         rc = SQLITE_ERROR;
67948:       }
67949:       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
67950:       sqlite3ParserReset(pParse);
67951:       sqlite3StackFree(pErrorDb, pParse);
67952:     }
67953:     if( rc ){
67954:       return 0;
67955:     }
67956:   }
67957: 
67958:   if( i<0 ){
67959:     sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
67960:     return 0;
67961:   }
67962: 
67963:   return pDb->aDb[i].pBt;
67964: }
67965: 
67966: /*
67967: ** Attempt to set the page size of the destination to match the page size
67968: ** of the source.
67969: */
67970: static int setDestPgsz(sqlite3_backup *p){
67971:   int rc;
67972:   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
67973:   return rc;
67974: }
67975: 
67976: /*
67977: ** Check that there is no open read-transaction on the b-tree passed as the
67978: ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
67979: ** is an open read-transaction, return SQLITE_ERROR and leave an error 
67980: ** message in database handle db.
67981: */
67982: static int checkReadTransaction(sqlite3 *db, Btree *p){
67983:   if( sqlite3BtreeIsInReadTrans(p) ){
67984:     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
67985:     return SQLITE_ERROR;
67986:   }
67987:   return SQLITE_OK;
67988: }
67989: 
67990: /*
67991: ** Create an sqlite3_backup process to copy the contents of zSrcDb from
67992: ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
67993: ** a pointer to the new sqlite3_backup object.
67994: **
67995: ** If an error occurs, NULL is returned and an error code and error message
67996: ** stored in database handle pDestDb.
67997: */
67998: SQLITE_API sqlite3_backup *sqlite3_backup_init(
67999:   sqlite3* pDestDb,                     /* Database to write to */
68000:   const char *zDestDb,                  /* Name of database within pDestDb */
68001:   sqlite3* pSrcDb,                      /* Database connection to read from */
68002:   const char *zSrcDb                    /* Name of database within pSrcDb */
68003: ){
68004:   sqlite3_backup *p;                    /* Value to return */
68005: 
68006: #ifdef SQLITE_ENABLE_API_ARMOR
68007:   if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
68008:     (void)SQLITE_MISUSE_BKPT;
68009:     return 0;
68010:   }
68011: #endif
68012: 
68013:   /* Lock the source database handle. The destination database
68014:   ** handle is not locked in this routine, but it is locked in
68015:   ** sqlite3_backup_step(). The user is required to ensure that no
68016:   ** other thread accesses the destination handle for the duration
68017:   ** of the backup operation.  Any attempt to use the destination
68018:   ** database connection while a backup is in progress may cause
68019:   ** a malfunction or a deadlock.
68020:   */
68021:   sqlite3_mutex_enter(pSrcDb->mutex);
68022:   sqlite3_mutex_enter(pDestDb->mutex);
68023: 
68024:   if( pSrcDb==pDestDb ){
68025:     sqlite3ErrorWithMsg(
68026:         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
68027:     );
68028:     p = 0;
68029:   }else {
68030:     /* Allocate space for a new sqlite3_backup object...
68031:     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68032:     ** call to sqlite3_backup_init() and is destroyed by a call to
68033:     ** sqlite3_backup_finish(). */
68034:     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
68035:     if( !p ){
68036:       sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
68037:     }
68038:   }
68039: 
68040:   /* If the allocation succeeded, populate the new object. */
68041:   if( p ){
68042:     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
68043:     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
68044:     p->pDestDb = pDestDb;
68045:     p->pSrcDb = pSrcDb;
68046:     p->iNext = 1;
68047:     p->isAttached = 0;
68048: 
68049:     if( 0==p->pSrc || 0==p->pDest 
68050:      || setDestPgsz(p)==SQLITE_NOMEM 
68051:      || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK 
68052:      ){
68053:       /* One (or both) of the named databases did not exist or an OOM
68054:       ** error was hit. Or there is a transaction open on the destination
68055:       ** database. The error has already been written into the pDestDb 
68056:       ** handle. All that is left to do here is free the sqlite3_backup 
68057:       ** structure.  */
68058:       sqlite3_free(p);
68059:       p = 0;
68060:     }
68061:   }
68062:   if( p ){
68063:     p->pSrc->nBackup++;
68064:   }
68065: 
68066:   sqlite3_mutex_leave(pDestDb->mutex);
68067:   sqlite3_mutex_leave(pSrcDb->mutex);
68068:   return p;
68069: }
68070: 
68071: /*
68072: ** Argument rc is an SQLite error code. Return true if this error is 
68073: ** considered fatal if encountered during a backup operation. All errors
68074: ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
68075: */
68076: static int isFatalError(int rc){
68077:   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
68078: }
68079: 
68080: /*
68081: ** Parameter zSrcData points to a buffer containing the data for 
68082: ** page iSrcPg from the source database. Copy this data into the 
68083: ** destination database.
68084: */
68085: static int backupOnePage(
68086:   sqlite3_backup *p,              /* Backup handle */
68087:   Pgno iSrcPg,                    /* Source database page to backup */
68088:   const u8 *zSrcData,             /* Source database page data */
68089:   int bUpdate                     /* True for an update, false otherwise */
68090: ){
68091:   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
68092:   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
68093:   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
68094:   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
68095:   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
68096: #ifdef SQLITE_HAS_CODEC
68097:   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
68098:   ** guaranteed that the shared-mutex is held by this thread, handle
68099:   ** p->pSrc may not actually be the owner.  */
68100:   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
68101:   int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
68102: #endif
68103:   int rc = SQLITE_OK;
68104:   i64 iOff;
68105: 
68106:   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
68107:   assert( p->bDestLocked );
68108:   assert( !isFatalError(p->rc) );
68109:   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
68110:   assert( zSrcData );
68111: 
68112:   /* Catch the case where the destination is an in-memory database and the
68113:   ** page sizes of the source and destination differ. 
68114:   */
68115:   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
68116:     rc = SQLITE_READONLY;
68117:   }
68118: 
68119: #ifdef SQLITE_HAS_CODEC
68120:   /* Backup is not possible if the page size of the destination is changing
68121:   ** and a codec is in use.
68122:   */
68123:   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
68124:     rc = SQLITE_READONLY;
68125:   }
68126: 
68127:   /* Backup is not possible if the number of bytes of reserve space differ
68128:   ** between source and destination.  If there is a difference, try to
68129:   ** fix the destination to agree with the source.  If that is not possible,
68130:   ** then the backup cannot proceed.
68131:   */
68132:   if( nSrcReserve!=nDestReserve ){
68133:     u32 newPgsz = nSrcPgsz;
68134:     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
68135:     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
68136:   }
68137: #endif
68138: 
68139:   /* This loop runs once for each destination page spanned by the source 
68140:   ** page. For each iteration, variable iOff is set to the byte offset
68141:   ** of the destination page.
68142:   */
68143:   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
68144:     DbPage *pDestPg = 0;
68145:     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
68146:     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
68147:     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
68148:      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
68149:     ){
68150:       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
68151:       u8 *zDestData = sqlite3PagerGetData(pDestPg);
68152:       u8 *zOut = &zDestData[iOff%nDestPgsz];
68153: 
68154:       /* Copy the data from the source page into the destination page.
68155:       ** Then clear the Btree layer MemPage.isInit flag. Both this module
68156:       ** and the pager code use this trick (clearing the first byte
68157:       ** of the page 'extra' space to invalidate the Btree layers
68158:       ** cached parse of the page). MemPage.isInit is marked 
68159:       ** "MUST BE FIRST" for this purpose.
68160:       */
68161:       memcpy(zOut, zIn, nCopy);
68162:       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
68163:       if( iOff==0 && bUpdate==0 ){
68164:         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
68165:       }
68166:     }
68167:     sqlite3PagerUnref(pDestPg);
68168:   }
68169: 
68170:   return rc;
68171: }
68172: 
68173: /*
68174: ** If pFile is currently larger than iSize bytes, then truncate it to
68175: ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
68176: ** this function is a no-op.
68177: **
68178: ** Return SQLITE_OK if everything is successful, or an SQLite error 
68179: ** code if an error occurs.
68180: */
68181: static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
68182:   i64 iCurrent;
68183:   int rc = sqlite3OsFileSize(pFile, &iCurrent);
68184:   if( rc==SQLITE_OK && iCurrent>iSize ){
68185:     rc = sqlite3OsTruncate(pFile, iSize);
68186:   }
68187:   return rc;
68188: }
68189: 
68190: /*
68191: ** Register this backup object with the associated source pager for
68192: ** callbacks when pages are changed or the cache invalidated.
68193: */
68194: static void attachBackupObject(sqlite3_backup *p){
68195:   sqlite3_backup **pp;
68196:   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
68197:   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68198:   p->pNext = *pp;
68199:   *pp = p;
68200:   p->isAttached = 1;
68201: }
68202: 
68203: /*
68204: ** Copy nPage pages from the source b-tree to the destination.
68205: */
68206: SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
68207:   int rc;
68208:   int destMode;       /* Destination journal mode */
68209:   int pgszSrc = 0;    /* Source page size */
68210:   int pgszDest = 0;   /* Destination page size */
68211: 
68212: #ifdef SQLITE_ENABLE_API_ARMOR
68213:   if( p==0 ) return SQLITE_MISUSE_BKPT;
68214: #endif
68215:   sqlite3_mutex_enter(p->pSrcDb->mutex);
68216:   sqlite3BtreeEnter(p->pSrc);
68217:   if( p->pDestDb ){
68218:     sqlite3_mutex_enter(p->pDestDb->mutex);
68219:   }
68220: 
68221:   rc = p->rc;
68222:   if( !isFatalError(rc) ){
68223:     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
68224:     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
68225:     int ii;                            /* Iterator variable */
68226:     int nSrcPage = -1;                 /* Size of source db in pages */
68227:     int bCloseTrans = 0;               /* True if src db requires unlocking */
68228: 
68229:     /* If the source pager is currently in a write-transaction, return
68230:     ** SQLITE_BUSY immediately.
68231:     */
68232:     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
68233:       rc = SQLITE_BUSY;
68234:     }else{
68235:       rc = SQLITE_OK;
68236:     }
68237: 
68238:     /* Lock the destination database, if it is not locked already. */
68239:     if( SQLITE_OK==rc && p->bDestLocked==0
68240:      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
68241:     ){
68242:       p->bDestLocked = 1;
68243:       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
68244:     }
68245: 
68246:     /* If there is no open read-transaction on the source database, open
68247:     ** one now. If a transaction is opened here, then it will be closed
68248:     ** before this function exits.
68249:     */
68250:     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
68251:       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
68252:       bCloseTrans = 1;
68253:     }
68254: 
68255:     /* Do not allow backup if the destination database is in WAL mode
68256:     ** and the page sizes are different between source and destination */
68257:     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
68258:     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
68259:     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
68260:     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
68261:       rc = SQLITE_READONLY;
68262:     }
68263:   
68264:     /* Now that there is a read-lock on the source database, query the
68265:     ** source pager for the number of pages in the database.
68266:     */
68267:     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
68268:     assert( nSrcPage>=0 );
68269:     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
68270:       const Pgno iSrcPg = p->iNext;                 /* Source page number */
68271:       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
68272:         DbPage *pSrcPg;                             /* Source page object */
68273:         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
68274:         if( rc==SQLITE_OK ){
68275:           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
68276:           sqlite3PagerUnref(pSrcPg);
68277:         }
68278:       }
68279:       p->iNext++;
68280:     }
68281:     if( rc==SQLITE_OK ){
68282:       p->nPagecount = nSrcPage;
68283:       p->nRemaining = nSrcPage+1-p->iNext;
68284:       if( p->iNext>(Pgno)nSrcPage ){
68285:         rc = SQLITE_DONE;
68286:       }else if( !p->isAttached ){
68287:         attachBackupObject(p);
68288:       }
68289:     }
68290:   
68291:     /* Update the schema version field in the destination database. This
68292:     ** is to make sure that the schema-version really does change in
68293:     ** the case where the source and destination databases have the
68294:     ** same schema version.
68295:     */
68296:     if( rc==SQLITE_DONE ){
68297:       if( nSrcPage==0 ){
68298:         rc = sqlite3BtreeNewDb(p->pDest);
68299:         nSrcPage = 1;
68300:       }
68301:       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
68302:         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
68303:       }
68304:       if( rc==SQLITE_OK ){
68305:         if( p->pDestDb ){
68306:           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
68307:         }
68308:         if( destMode==PAGER_JOURNALMODE_WAL ){
68309:           rc = sqlite3BtreeSetVersion(p->pDest, 2);
68310:         }
68311:       }
68312:       if( rc==SQLITE_OK ){
68313:         int nDestTruncate;
68314:         /* Set nDestTruncate to the final number of pages in the destination
68315:         ** database. The complication here is that the destination page
68316:         ** size may be different to the source page size. 
68317:         **
68318:         ** If the source page size is smaller than the destination page size, 
68319:         ** round up. In this case the call to sqlite3OsTruncate() below will
68320:         ** fix the size of the file. However it is important to call
68321:         ** sqlite3PagerTruncateImage() here so that any pages in the 
68322:         ** destination file that lie beyond the nDestTruncate page mark are
68323:         ** journalled by PagerCommitPhaseOne() before they are destroyed
68324:         ** by the file truncation.
68325:         */
68326:         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
68327:         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
68328:         if( pgszSrc<pgszDest ){
68329:           int ratio = pgszDest/pgszSrc;
68330:           nDestTruncate = (nSrcPage+ratio-1)/ratio;
68331:           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
68332:             nDestTruncate--;
68333:           }
68334:         }else{
68335:           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
68336:         }
68337:         assert( nDestTruncate>0 );
68338: 
68339:         if( pgszSrc<pgszDest ){
68340:           /* If the source page-size is smaller than the destination page-size,
68341:           ** two extra things may need to happen:
68342:           **
68343:           **   * The destination may need to be truncated, and
68344:           **
68345:           **   * Data stored on the pages immediately following the 
68346:           **     pending-byte page in the source database may need to be
68347:           **     copied into the destination database.
68348:           */
68349:           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
68350:           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
68351:           Pgno iPg;
68352:           int nDstPage;
68353:           i64 iOff;
68354:           i64 iEnd;
68355: 
68356:           assert( pFile );
68357:           assert( nDestTruncate==0 
68358:               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
68359:                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
68360:              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
68361:           ));
68362: 
68363:           /* This block ensures that all data required to recreate the original
68364:           ** database has been stored in the journal for pDestPager and the
68365:           ** journal synced to disk. So at this point we may safely modify
68366:           ** the database file in any way, knowing that if a power failure
68367:           ** occurs, the original database will be reconstructed from the 
68368:           ** journal file.  */
68369:           sqlite3PagerPagecount(pDestPager, &nDstPage);
68370:           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
68371:             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
68372:               DbPage *pPg;
68373:               rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
68374:               if( rc==SQLITE_OK ){
68375:                 rc = sqlite3PagerWrite(pPg);
68376:                 sqlite3PagerUnref(pPg);
68377:               }
68378:             }
68379:           }
68380:           if( rc==SQLITE_OK ){
68381:             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
68382:           }
68383: 
68384:           /* Write the extra pages and truncate the database file as required */
68385:           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
68386:           for(
68387:             iOff=PENDING_BYTE+pgszSrc; 
68388:             rc==SQLITE_OK && iOff<iEnd; 
68389:             iOff+=pgszSrc
68390:           ){
68391:             PgHdr *pSrcPg = 0;
68392:             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
68393:             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
68394:             if( rc==SQLITE_OK ){
68395:               u8 *zData = sqlite3PagerGetData(pSrcPg);
68396:               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
68397:             }
68398:             sqlite3PagerUnref(pSrcPg);
68399:           }
68400:           if( rc==SQLITE_OK ){
68401:             rc = backupTruncateFile(pFile, iSize);
68402:           }
68403: 
68404:           /* Sync the database file to disk. */
68405:           if( rc==SQLITE_OK ){
68406:             rc = sqlite3PagerSync(pDestPager, 0);
68407:           }
68408:         }else{
68409:           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
68410:           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
68411:         }
68412:     
68413:         /* Finish committing the transaction to the destination database. */
68414:         if( SQLITE_OK==rc
68415:          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
68416:         ){
68417:           rc = SQLITE_DONE;
68418:         }
68419:       }
68420:     }
68421:   
68422:     /* If bCloseTrans is true, then this function opened a read transaction
68423:     ** on the source database. Close the read transaction here. There is
68424:     ** no need to check the return values of the btree methods here, as
68425:     ** "committing" a read-only transaction cannot fail.
68426:     */
68427:     if( bCloseTrans ){
68428:       TESTONLY( int rc2 );
68429:       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
68430:       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
68431:       assert( rc2==SQLITE_OK );
68432:     }
68433:   
68434:     if( rc==SQLITE_IOERR_NOMEM ){
68435:       rc = SQLITE_NOMEM_BKPT;
68436:     }
68437:     p->rc = rc;
68438:   }
68439:   if( p->pDestDb ){
68440:     sqlite3_mutex_leave(p->pDestDb->mutex);
68441:   }
68442:   sqlite3BtreeLeave(p->pSrc);
68443:   sqlite3_mutex_leave(p->pSrcDb->mutex);
68444:   return rc;
68445: }
68446: 
68447: /*
68448: ** Release all resources associated with an sqlite3_backup* handle.
68449: */
68450: SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
68451:   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
68452:   sqlite3 *pSrcDb;                     /* Source database connection */
68453:   int rc;                              /* Value to return */
68454: 
68455:   /* Enter the mutexes */
68456:   if( p==0 ) return SQLITE_OK;
68457:   pSrcDb = p->pSrcDb;
68458:   sqlite3_mutex_enter(pSrcDb->mutex);
68459:   sqlite3BtreeEnter(p->pSrc);
68460:   if( p->pDestDb ){
68461:     sqlite3_mutex_enter(p->pDestDb->mutex);
68462:   }
68463: 
68464:   /* Detach this backup from the source pager. */
68465:   if( p->pDestDb ){
68466:     p->pSrc->nBackup--;
68467:   }
68468:   if( p->isAttached ){
68469:     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
68470:     while( *pp!=p ){
68471:       pp = &(*pp)->pNext;
68472:     }
68473:     *pp = p->pNext;
68474:   }
68475: 
68476:   /* If a transaction is still open on the Btree, roll it back. */
68477:   sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
68478: 
68479:   /* Set the error code of the destination database handle. */
68480:   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
68481:   if( p->pDestDb ){
68482:     sqlite3Error(p->pDestDb, rc);
68483: 
68484:     /* Exit the mutexes and free the backup context structure. */
68485:     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
68486:   }
68487:   sqlite3BtreeLeave(p->pSrc);
68488:   if( p->pDestDb ){
68489:     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68490:     ** call to sqlite3_backup_init() and is destroyed by a call to
68491:     ** sqlite3_backup_finish(). */
68492:     sqlite3_free(p);
68493:   }
68494:   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
68495:   return rc;
68496: }
68497: 
68498: /*
68499: ** Return the number of pages still to be backed up as of the most recent
68500: ** call to sqlite3_backup_step().
68501: */
68502: SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
68503: #ifdef SQLITE_ENABLE_API_ARMOR
68504:   if( p==0 ){
68505:     (void)SQLITE_MISUSE_BKPT;
68506:     return 0;
68507:   }
68508: #endif
68509:   return p->nRemaining;
68510: }
68511: 
68512: /*
68513: ** Return the total number of pages in the source database as of the most 
68514: ** recent call to sqlite3_backup_step().
68515: */
68516: SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
68517: #ifdef SQLITE_ENABLE_API_ARMOR
68518:   if( p==0 ){
68519:     (void)SQLITE_MISUSE_BKPT;
68520:     return 0;
68521:   }
68522: #endif
68523:   return p->nPagecount;
68524: }
68525: 
68526: /*
68527: ** This function is called after the contents of page iPage of the
68528: ** source database have been modified. If page iPage has already been 
68529: ** copied into the destination database, then the data written to the
68530: ** destination is now invalidated. The destination copy of iPage needs
68531: ** to be updated with the new data before the backup operation is
68532: ** complete.
68533: **
68534: ** It is assumed that the mutex associated with the BtShared object
68535: ** corresponding to the source database is held when this function is
68536: ** called.
68537: */
68538: static SQLITE_NOINLINE void backupUpdate(
68539:   sqlite3_backup *p,
68540:   Pgno iPage,
68541:   const u8 *aData
68542: ){
68543:   assert( p!=0 );
68544:   do{
68545:     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68546:     if( !isFatalError(p->rc) && iPage<p->iNext ){
68547:       /* The backup process p has already copied page iPage. But now it
68548:       ** has been modified by a transaction on the source pager. Copy
68549:       ** the new data into the backup.
68550:       */
68551:       int rc;
68552:       assert( p->pDestDb );
68553:       sqlite3_mutex_enter(p->pDestDb->mutex);
68554:       rc = backupOnePage(p, iPage, aData, 1);
68555:       sqlite3_mutex_leave(p->pDestDb->mutex);
68556:       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
68557:       if( rc!=SQLITE_OK ){
68558:         p->rc = rc;
68559:       }
68560:     }
68561:   }while( (p = p->pNext)!=0 );
68562: }
68563: SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
68564:   if( pBackup ) backupUpdate(pBackup, iPage, aData);
68565: }
68566: 
68567: /*
68568: ** Restart the backup process. This is called when the pager layer
68569: ** detects that the database has been modified by an external database
68570: ** connection. In this case there is no way of knowing which of the
68571: ** pages that have been copied into the destination database are still 
68572: ** valid and which are not, so the entire process needs to be restarted.
68573: **
68574: ** It is assumed that the mutex associated with the BtShared object
68575: ** corresponding to the source database is held when this function is
68576: ** called.
68577: */
68578: SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
68579:   sqlite3_backup *p;                   /* Iterator variable */
68580:   for(p=pBackup; p; p=p->pNext){
68581:     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
68582:     p->iNext = 1;
68583:   }
68584: }
68585: 
68586: #ifndef SQLITE_OMIT_VACUUM
68587: /*
68588: ** Copy the complete content of pBtFrom into pBtTo.  A transaction
68589: ** must be active for both files.
68590: **
68591: ** The size of file pTo may be reduced by this operation. If anything 
68592: ** goes wrong, the transaction on pTo is rolled back. If successful, the 
68593: ** transaction is committed before returning.
68594: */
68595: SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
68596:   int rc;
68597:   sqlite3_file *pFd;              /* File descriptor for database pTo */
68598:   sqlite3_backup b;
68599:   sqlite3BtreeEnter(pTo);
68600:   sqlite3BtreeEnter(pFrom);
68601: 
68602:   assert( sqlite3BtreeIsInTrans(pTo) );
68603:   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
68604:   if( pFd->pMethods ){
68605:     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
68606:     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
68607:     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
68608:     if( rc ) goto copy_finished;
68609:   }
68610: 
68611:   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
68612:   ** to 0. This is used by the implementations of sqlite3_backup_step()
68613:   ** and sqlite3_backup_finish() to detect that they are being called
68614:   ** from this function, not directly by the user.
68615:   */
68616:   memset(&b, 0, sizeof(b));
68617:   b.pSrcDb = pFrom->db;
68618:   b.pSrc = pFrom;
68619:   b.pDest = pTo;
68620:   b.iNext = 1;
68621: 
68622: #ifdef SQLITE_HAS_CODEC
68623:   sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
68624: #endif
68625: 
68626:   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
68627:   ** file. By passing this as the number of pages to copy to
68628:   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
68629:   ** within a single call (unless an error occurs). The assert() statement
68630:   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
68631:   ** or an error code.  */
68632:   sqlite3_backup_step(&b, 0x7FFFFFFF);
68633:   assert( b.rc!=SQLITE_OK );
68634: 
68635:   rc = sqlite3_backup_finish(&b);
68636:   if( rc==SQLITE_OK ){
68637:     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
68638:   }else{
68639:     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
68640:   }
68641: 
68642:   assert( sqlite3BtreeIsInTrans(pTo)==0 );
68643: copy_finished:
68644:   sqlite3BtreeLeave(pFrom);
68645:   sqlite3BtreeLeave(pTo);
68646:   return rc;
68647: }
68648: #endif /* SQLITE_OMIT_VACUUM */
68649: 
68650: /************** End of backup.c **********************************************/
68651: /************** Begin file vdbemem.c *****************************************/
68652: /*
68653: ** 2004 May 26
68654: **
68655: ** The author disclaims copyright to this source code.  In place of
68656: ** a legal notice, here is a blessing:
68657: **
68658: **    May you do good and not evil.
68659: **    May you find forgiveness for yourself and forgive others.
68660: **    May you share freely, never taking more than you give.
68661: **
68662: *************************************************************************
68663: **
68664: ** This file contains code use to manipulate "Mem" structure.  A "Mem"
68665: ** stores a single value in the VDBE.  Mem is an opaque structure visible
68666: ** only within the VDBE.  Interface routines refer to a Mem using the
68667: ** name sqlite_value
68668: */
68669: /* #include "sqliteInt.h" */
68670: /* #include "vdbeInt.h" */
68671: 
68672: #ifdef SQLITE_DEBUG
68673: /*
68674: ** Check invariants on a Mem object.
68675: **
68676: ** This routine is intended for use inside of assert() statements, like
68677: ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
68678: */
68679: SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
68680:   /* If MEM_Dyn is set then Mem.xDel!=0.  
68681:   ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
68682:   */
68683:   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
68684: 
68685:   /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
68686:   ** ensure that if Mem.szMalloc>0 then it is safe to do
68687:   ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
68688:   ** That saves a few cycles in inner loops. */
68689:   assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
68690: 
68691:   /* Cannot be both MEM_Int and MEM_Real at the same time */
68692:   assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
68693: 
68694:   /* The szMalloc field holds the correct memory allocation size */
68695:   assert( p->szMalloc==0
68696:        || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
68697: 
68698:   /* If p holds a string or blob, the Mem.z must point to exactly
68699:   ** one of the following:
68700:   **
68701:   **   (1) Memory in Mem.zMalloc and managed by the Mem object
68702:   **   (2) Memory to be freed using Mem.xDel
68703:   **   (3) An ephemeral string or blob
68704:   **   (4) A static string or blob
68705:   */
68706:   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
68707:     assert( 
68708:       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
68709:       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
68710:       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
68711:       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
68712:     );
68713:   }
68714:   return 1;
68715: }
68716: #endif
68717: 
68718: 
68719: /*
68720: ** If pMem is an object with a valid string representation, this routine
68721: ** ensures the internal encoding for the string representation is
68722: ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
68723: **
68724: ** If pMem is not a string object, or the encoding of the string
68725: ** representation is already stored using the requested encoding, then this
68726: ** routine is a no-op.
68727: **
68728: ** SQLITE_OK is returned if the conversion is successful (or not required).
68729: ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
68730: ** between formats.
68731: */
68732: SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
68733: #ifndef SQLITE_OMIT_UTF16
68734:   int rc;
68735: #endif
68736:   assert( (pMem->flags&MEM_RowSet)==0 );
68737:   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
68738:            || desiredEnc==SQLITE_UTF16BE );
68739:   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
68740:     return SQLITE_OK;
68741:   }
68742:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68743: #ifdef SQLITE_OMIT_UTF16
68744:   return SQLITE_ERROR;
68745: #else
68746: 
68747:   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
68748:   ** then the encoding of the value may not have changed.
68749:   */
68750:   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
68751:   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
68752:   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
68753:   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
68754:   return rc;
68755: #endif
68756: }
68757: 
68758: /*
68759: ** Make sure pMem->z points to a writable allocation of at least 
68760: ** min(n,32) bytes.
68761: **
68762: ** If the bPreserve argument is true, then copy of the content of
68763: ** pMem->z into the new allocation.  pMem must be either a string or
68764: ** blob if bPreserve is true.  If bPreserve is false, any prior content
68765: ** in pMem->z is discarded.
68766: */
68767: SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
68768:   assert( sqlite3VdbeCheckMemInvariants(pMem) );
68769:   assert( (pMem->flags&MEM_RowSet)==0 );
68770:   testcase( pMem->db==0 );
68771: 
68772:   /* If the bPreserve flag is set to true, then the memory cell must already
68773:   ** contain a valid string or blob value.  */
68774:   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
68775:   testcase( bPreserve && pMem->z==0 );
68776: 
68777:   assert( pMem->szMalloc==0
68778:        || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
68779:   if( pMem->szMalloc<n ){
68780:     if( n<32 ) n = 32;
68781:     if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
68782:       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
68783:       bPreserve = 0;
68784:     }else{
68785:       if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68786:       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
68787:     }
68788:     if( pMem->zMalloc==0 ){
68789:       sqlite3VdbeMemSetNull(pMem);
68790:       pMem->z = 0;
68791:       pMem->szMalloc = 0;
68792:       return SQLITE_NOMEM_BKPT;
68793:     }else{
68794:       pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
68795:     }
68796:   }
68797: 
68798:   if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
68799:     memcpy(pMem->zMalloc, pMem->z, pMem->n);
68800:   }
68801:   if( (pMem->flags&MEM_Dyn)!=0 ){
68802:     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
68803:     pMem->xDel((void *)(pMem->z));
68804:   }
68805: 
68806:   pMem->z = pMem->zMalloc;
68807:   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
68808:   return SQLITE_OK;
68809: }
68810: 
68811: /*
68812: ** Change the pMem->zMalloc allocation to be at least szNew bytes.
68813: ** If pMem->zMalloc already meets or exceeds the requested size, this
68814: ** routine is a no-op.
68815: **
68816: ** Any prior string or blob content in the pMem object may be discarded.
68817: ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
68818: ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
68819: ** values are preserved.
68820: **
68821: ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
68822: ** if unable to complete the resizing.
68823: */
68824: SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
68825:   assert( szNew>0 );
68826:   assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
68827:   if( pMem->szMalloc<szNew ){
68828:     return sqlite3VdbeMemGrow(pMem, szNew, 0);
68829:   }
68830:   assert( (pMem->flags & MEM_Dyn)==0 );
68831:   pMem->z = pMem->zMalloc;
68832:   pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
68833:   return SQLITE_OK;
68834: }
68835: 
68836: /*
68837: ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
68838: ** MEM.zMalloc, where it can be safely written.
68839: **
68840: ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
68841: */
68842: SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
68843:   int f;
68844:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68845:   assert( (pMem->flags&MEM_RowSet)==0 );
68846:   ExpandBlob(pMem);
68847:   f = pMem->flags;
68848:   if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
68849:     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
68850:       return SQLITE_NOMEM_BKPT;
68851:     }
68852:     pMem->z[pMem->n] = 0;
68853:     pMem->z[pMem->n+1] = 0;
68854:     pMem->flags |= MEM_Term;
68855:   }
68856:   pMem->flags &= ~MEM_Ephem;
68857: #ifdef SQLITE_DEBUG
68858:   pMem->pScopyFrom = 0;
68859: #endif
68860: 
68861:   return SQLITE_OK;
68862: }
68863: 
68864: /*
68865: ** If the given Mem* has a zero-filled tail, turn it into an ordinary
68866: ** blob stored in dynamically allocated space.
68867: */
68868: #ifndef SQLITE_OMIT_INCRBLOB
68869: SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
68870:   if( pMem->flags & MEM_Zero ){
68871:     int nByte;
68872:     assert( pMem->flags&MEM_Blob );
68873:     assert( (pMem->flags&MEM_RowSet)==0 );
68874:     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68875: 
68876:     /* Set nByte to the number of bytes required to store the expanded blob. */
68877:     nByte = pMem->n + pMem->u.nZero;
68878:     if( nByte<=0 ){
68879:       nByte = 1;
68880:     }
68881:     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
68882:       return SQLITE_NOMEM_BKPT;
68883:     }
68884: 
68885:     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
68886:     pMem->n += pMem->u.nZero;
68887:     pMem->flags &= ~(MEM_Zero|MEM_Term);
68888:   }
68889:   return SQLITE_OK;
68890: }
68891: #endif
68892: 
68893: /*
68894: ** It is already known that pMem contains an unterminated string.
68895: ** Add the zero terminator.
68896: */
68897: static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
68898:   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
68899:     return SQLITE_NOMEM_BKPT;
68900:   }
68901:   pMem->z[pMem->n] = 0;
68902:   pMem->z[pMem->n+1] = 0;
68903:   pMem->flags |= MEM_Term;
68904:   return SQLITE_OK;
68905: }
68906: 
68907: /*
68908: ** Make sure the given Mem is \u0000 terminated.
68909: */
68910: SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
68911:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68912:   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
68913:   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
68914:   if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
68915:     return SQLITE_OK;   /* Nothing to do */
68916:   }else{
68917:     return vdbeMemAddTerminator(pMem);
68918:   }
68919: }
68920: 
68921: /*
68922: ** Add MEM_Str to the set of representations for the given Mem.  Numbers
68923: ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
68924: ** is a no-op.
68925: **
68926: ** Existing representations MEM_Int and MEM_Real are invalidated if
68927: ** bForce is true but are retained if bForce is false.
68928: **
68929: ** A MEM_Null value will never be passed to this function. This function is
68930: ** used for converting values to text for returning to the user (i.e. via
68931: ** sqlite3_value_text()), or for ensuring that values to be used as btree
68932: ** keys are strings. In the former case a NULL pointer is returned the
68933: ** user and the latter is an internal programming error.
68934: */
68935: SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
68936:   int fg = pMem->flags;
68937:   const int nByte = 32;
68938: 
68939:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68940:   assert( !(fg&MEM_Zero) );
68941:   assert( !(fg&(MEM_Str|MEM_Blob)) );
68942:   assert( fg&(MEM_Int|MEM_Real) );
68943:   assert( (pMem->flags&MEM_RowSet)==0 );
68944:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68945: 
68946: 
68947:   if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
68948:     return SQLITE_NOMEM_BKPT;
68949:   }
68950: 
68951:   /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
68952:   ** string representation of the value. Then, if the required encoding
68953:   ** is UTF-16le or UTF-16be do a translation.
68954:   ** 
68955:   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
68956:   */
68957:   if( fg & MEM_Int ){
68958:     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
68959:   }else{
68960:     assert( fg & MEM_Real );
68961:     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
68962:   }
68963:   pMem->n = sqlite3Strlen30(pMem->z);
68964:   pMem->enc = SQLITE_UTF8;
68965:   pMem->flags |= MEM_Str|MEM_Term;
68966:   if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
68967:   sqlite3VdbeChangeEncoding(pMem, enc);
68968:   return SQLITE_OK;
68969: }
68970: 
68971: /*
68972: ** Memory cell pMem contains the context of an aggregate function.
68973: ** This routine calls the finalize method for that function.  The
68974: ** result of the aggregate is stored back into pMem.
68975: **
68976: ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
68977: ** otherwise.
68978: */
68979: SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
68980:   int rc = SQLITE_OK;
68981:   if( ALWAYS(pFunc && pFunc->xFinalize) ){
68982:     sqlite3_context ctx;
68983:     Mem t;
68984:     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
68985:     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68986:     memset(&ctx, 0, sizeof(ctx));
68987:     memset(&t, 0, sizeof(t));
68988:     t.flags = MEM_Null;
68989:     t.db = pMem->db;
68990:     ctx.pOut = &t;
68991:     ctx.pMem = pMem;
68992:     ctx.pFunc = pFunc;
68993:     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
68994:     assert( (pMem->flags & MEM_Dyn)==0 );
68995:     if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68996:     memcpy(pMem, &t, sizeof(t));
68997:     rc = ctx.isError;
68998:   }
68999:   return rc;
69000: }
69001: 
69002: /*
69003: ** If the memory cell contains a value that must be freed by
69004: ** invoking the external callback in Mem.xDel, then this routine
69005: ** will free that value.  It also sets Mem.flags to MEM_Null.
69006: **
69007: ** This is a helper routine for sqlite3VdbeMemSetNull() and
69008: ** for sqlite3VdbeMemRelease().  Use those other routines as the
69009: ** entry point for releasing Mem resources.
69010: */
69011: static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
69012:   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
69013:   assert( VdbeMemDynamic(p) );
69014:   if( p->flags&MEM_Agg ){
69015:     sqlite3VdbeMemFinalize(p, p->u.pDef);
69016:     assert( (p->flags & MEM_Agg)==0 );
69017:     testcase( p->flags & MEM_Dyn );
69018:   }
69019:   if( p->flags&MEM_Dyn ){
69020:     assert( (p->flags&MEM_RowSet)==0 );
69021:     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
69022:     p->xDel((void *)p->z);
69023:   }else if( p->flags&MEM_RowSet ){
69024:     sqlite3RowSetClear(p->u.pRowSet);
69025:   }else if( p->flags&MEM_Frame ){
69026:     VdbeFrame *pFrame = p->u.pFrame;
69027:     pFrame->pParent = pFrame->v->pDelFrame;
69028:     pFrame->v->pDelFrame = pFrame;
69029:   }
69030:   p->flags = MEM_Null;
69031: }
69032: 
69033: /*
69034: ** Release memory held by the Mem p, both external memory cleared
69035: ** by p->xDel and memory in p->zMalloc.
69036: **
69037: ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
69038: ** the unusual case where there really is memory in p that needs
69039: ** to be freed.
69040: */
69041: static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
69042:   if( VdbeMemDynamic(p) ){
69043:     vdbeMemClearExternAndSetNull(p);
69044:   }
69045:   if( p->szMalloc ){
69046:     sqlite3DbFree(p->db, p->zMalloc);
69047:     p->szMalloc = 0;
69048:   }
69049:   p->z = 0;
69050: }
69051: 
69052: /*
69053: ** Release any memory resources held by the Mem.  Both the memory that is
69054: ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
69055: **
69056: ** Use this routine prior to clean up prior to abandoning a Mem, or to
69057: ** reset a Mem back to its minimum memory utilization.
69058: **
69059: ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
69060: ** prior to inserting new content into the Mem.
69061: */
69062: SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
69063:   assert( sqlite3VdbeCheckMemInvariants(p) );
69064:   if( VdbeMemDynamic(p) || p->szMalloc ){
69065:     vdbeMemClear(p);
69066:   }
69067: }
69068: 
69069: /*
69070: ** Convert a 64-bit IEEE double into a 64-bit signed integer.
69071: ** If the double is out of range of a 64-bit signed integer then
69072: ** return the closest available 64-bit signed integer.
69073: */
69074: static i64 doubleToInt64(double r){
69075: #ifdef SQLITE_OMIT_FLOATING_POINT
69076:   /* When floating-point is omitted, double and int64 are the same thing */
69077:   return r;
69078: #else
69079:   /*
69080:   ** Many compilers we encounter do not define constants for the
69081:   ** minimum and maximum 64-bit integers, or they define them
69082:   ** inconsistently.  And many do not understand the "LL" notation.
69083:   ** So we define our own static constants here using nothing
69084:   ** larger than a 32-bit integer constant.
69085:   */
69086:   static const i64 maxInt = LARGEST_INT64;
69087:   static const i64 minInt = SMALLEST_INT64;
69088: 
69089:   if( r<=(double)minInt ){
69090:     return minInt;
69091:   }else if( r>=(double)maxInt ){
69092:     return maxInt;
69093:   }else{
69094:     return (i64)r;
69095:   }
69096: #endif
69097: }
69098: 
69099: /*
69100: ** Return some kind of integer value which is the best we can do
69101: ** at representing the value that *pMem describes as an integer.
69102: ** If pMem is an integer, then the value is exact.  If pMem is
69103: ** a floating-point then the value returned is the integer part.
69104: ** If pMem is a string or blob, then we make an attempt to convert
69105: ** it into an integer and return that.  If pMem represents an
69106: ** an SQL-NULL value, return 0.
69107: **
69108: ** If pMem represents a string value, its encoding might be changed.
69109: */
69110: SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
69111:   int flags;
69112:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69113:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69114:   flags = pMem->flags;
69115:   if( flags & MEM_Int ){
69116:     return pMem->u.i;
69117:   }else if( flags & MEM_Real ){
69118:     return doubleToInt64(pMem->u.r);
69119:   }else if( flags & (MEM_Str|MEM_Blob) ){
69120:     i64 value = 0;
69121:     assert( pMem->z || pMem->n==0 );
69122:     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
69123:     return value;
69124:   }else{
69125:     return 0;
69126:   }
69127: }
69128: 
69129: /*
69130: ** Return the best representation of pMem that we can get into a
69131: ** double.  If pMem is already a double or an integer, return its
69132: ** value.  If it is a string or blob, try to convert it to a double.
69133: ** If it is a NULL, return 0.0.
69134: */
69135: SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
69136:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69137:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69138:   if( pMem->flags & MEM_Real ){
69139:     return pMem->u.r;
69140:   }else if( pMem->flags & MEM_Int ){
69141:     return (double)pMem->u.i;
69142:   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
69143:     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69144:     double val = (double)0;
69145:     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
69146:     return val;
69147:   }else{
69148:     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
69149:     return (double)0;
69150:   }
69151: }
69152: 
69153: /*
69154: ** The MEM structure is already a MEM_Real.  Try to also make it a
69155: ** MEM_Int if we can.
69156: */
69157: SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
69158:   i64 ix;
69159:   assert( pMem->flags & MEM_Real );
69160:   assert( (pMem->flags & MEM_RowSet)==0 );
69161:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69162:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69163: 
69164:   ix = doubleToInt64(pMem->u.r);
69165: 
69166:   /* Only mark the value as an integer if
69167:   **
69168:   **    (1) the round-trip conversion real->int->real is a no-op, and
69169:   **    (2) The integer is neither the largest nor the smallest
69170:   **        possible integer (ticket #3922)
69171:   **
69172:   ** The second and third terms in the following conditional enforces
69173:   ** the second condition under the assumption that addition overflow causes
69174:   ** values to wrap around.
69175:   */
69176:   if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
69177:     pMem->u.i = ix;
69178:     MemSetTypeFlag(pMem, MEM_Int);
69179:   }
69180: }
69181: 
69182: /*
69183: ** Convert pMem to type integer.  Invalidate any prior representations.
69184: */
69185: SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
69186:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69187:   assert( (pMem->flags & MEM_RowSet)==0 );
69188:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69189: 
69190:   pMem->u.i = sqlite3VdbeIntValue(pMem);
69191:   MemSetTypeFlag(pMem, MEM_Int);
69192:   return SQLITE_OK;
69193: }
69194: 
69195: /*
69196: ** Convert pMem so that it is of type MEM_Real.
69197: ** Invalidate any prior representations.
69198: */
69199: SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
69200:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69201:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
69202: 
69203:   pMem->u.r = sqlite3VdbeRealValue(pMem);
69204:   MemSetTypeFlag(pMem, MEM_Real);
69205:   return SQLITE_OK;
69206: }
69207: 
69208: /*
69209: ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
69210: ** Invalidate any prior representations.
69211: **
69212: ** Every effort is made to force the conversion, even if the input
69213: ** is a string that does not look completely like a number.  Convert
69214: ** as much of the string as we can and ignore the rest.
69215: */
69216: SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
69217:   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
69218:     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
69219:     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69220:     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
69221:       MemSetTypeFlag(pMem, MEM_Int);
69222:     }else{
69223:       pMem->u.r = sqlite3VdbeRealValue(pMem);
69224:       MemSetTypeFlag(pMem, MEM_Real);
69225:       sqlite3VdbeIntegerAffinity(pMem);
69226:     }
69227:   }
69228:   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
69229:   pMem->flags &= ~(MEM_Str|MEM_Blob);
69230:   return SQLITE_OK;
69231: }
69232: 
69233: /*
69234: ** Cast the datatype of the value in pMem according to the affinity
69235: ** "aff".  Casting is different from applying affinity in that a cast
69236: ** is forced.  In other words, the value is converted into the desired
69237: ** affinity even if that results in loss of data.  This routine is
69238: ** used (for example) to implement the SQL "cast()" operator.
69239: */
69240: SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
69241:   if( pMem->flags & MEM_Null ) return;
69242:   switch( aff ){
69243:     case SQLITE_AFF_BLOB: {   /* Really a cast to BLOB */
69244:       if( (pMem->flags & MEM_Blob)==0 ){
69245:         sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69246:         assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69247:         MemSetTypeFlag(pMem, MEM_Blob);
69248:       }else{
69249:         pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
69250:       }
69251:       break;
69252:     }
69253:     case SQLITE_AFF_NUMERIC: {
69254:       sqlite3VdbeMemNumerify(pMem);
69255:       break;
69256:     }
69257:     case SQLITE_AFF_INTEGER: {
69258:       sqlite3VdbeMemIntegerify(pMem);
69259:       break;
69260:     }
69261:     case SQLITE_AFF_REAL: {
69262:       sqlite3VdbeMemRealify(pMem);
69263:       break;
69264:     }
69265:     default: {
69266:       assert( aff==SQLITE_AFF_TEXT );
69267:       assert( MEM_Str==(MEM_Blob>>3) );
69268:       pMem->flags |= (pMem->flags&MEM_Blob)>>3;
69269:       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
69270:       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
69271:       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
69272:       break;
69273:     }
69274:   }
69275: }
69276: 
69277: /*
69278: ** Initialize bulk memory to be a consistent Mem object.
69279: **
69280: ** The minimum amount of initialization feasible is performed.
69281: */
69282: SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
69283:   assert( (flags & ~MEM_TypeMask)==0 );
69284:   pMem->flags = flags;
69285:   pMem->db = db;
69286:   pMem->szMalloc = 0;
69287: }
69288: 
69289: 
69290: /*
69291: ** Delete any previous value and set the value stored in *pMem to NULL.
69292: **
69293: ** This routine calls the Mem.xDel destructor to dispose of values that
69294: ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
69295: ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
69296: ** routine to invoke the destructor and deallocates Mem.zMalloc.
69297: **
69298: ** Use this routine to reset the Mem prior to insert a new value.
69299: **
69300: ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
69301: */
69302: SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
69303:   if( VdbeMemDynamic(pMem) ){
69304:     vdbeMemClearExternAndSetNull(pMem);
69305:   }else{
69306:     pMem->flags = MEM_Null;
69307:   }
69308: }
69309: SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
69310:   sqlite3VdbeMemSetNull((Mem*)p); 
69311: }
69312: 
69313: /*
69314: ** Delete any previous value and set the value to be a BLOB of length
69315: ** n containing all zeros.
69316: */
69317: SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
69318:   sqlite3VdbeMemRelease(pMem);
69319:   pMem->flags = MEM_Blob|MEM_Zero;
69320:   pMem->n = 0;
69321:   if( n<0 ) n = 0;
69322:   pMem->u.nZero = n;
69323:   pMem->enc = SQLITE_UTF8;
69324:   pMem->z = 0;
69325: }
69326: 
69327: /*
69328: ** The pMem is known to contain content that needs to be destroyed prior
69329: ** to a value change.  So invoke the destructor, then set the value to
69330: ** a 64-bit integer.
69331: */
69332: static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
69333:   sqlite3VdbeMemSetNull(pMem);
69334:   pMem->u.i = val;
69335:   pMem->flags = MEM_Int;
69336: }
69337: 
69338: /*
69339: ** Delete any previous value and set the value stored in *pMem to val,
69340: ** manifest type INTEGER.
69341: */
69342: SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
69343:   if( VdbeMemDynamic(pMem) ){
69344:     vdbeReleaseAndSetInt64(pMem, val);
69345:   }else{
69346:     pMem->u.i = val;
69347:     pMem->flags = MEM_Int;
69348:   }
69349: }
69350: 
69351: #ifndef SQLITE_OMIT_FLOATING_POINT
69352: /*
69353: ** Delete any previous value and set the value stored in *pMem to val,
69354: ** manifest type REAL.
69355: */
69356: SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
69357:   sqlite3VdbeMemSetNull(pMem);
69358:   if( !sqlite3IsNaN(val) ){
69359:     pMem->u.r = val;
69360:     pMem->flags = MEM_Real;
69361:   }
69362: }
69363: #endif
69364: 
69365: /*
69366: ** Delete any previous value and set the value of pMem to be an
69367: ** empty boolean index.
69368: */
69369: SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
69370:   sqlite3 *db = pMem->db;
69371:   assert( db!=0 );
69372:   assert( (pMem->flags & MEM_RowSet)==0 );
69373:   sqlite3VdbeMemRelease(pMem);
69374:   pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
69375:   if( db->mallocFailed ){
69376:     pMem->flags = MEM_Null;
69377:     pMem->szMalloc = 0;
69378:   }else{
69379:     assert( pMem->zMalloc );
69380:     pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
69381:     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
69382:     assert( pMem->u.pRowSet!=0 );
69383:     pMem->flags = MEM_RowSet;
69384:   }
69385: }
69386: 
69387: /*
69388: ** Return true if the Mem object contains a TEXT or BLOB that is
69389: ** too large - whose size exceeds SQLITE_MAX_LENGTH.
69390: */
69391: SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
69392:   assert( p->db!=0 );
69393:   if( p->flags & (MEM_Str|MEM_Blob) ){
69394:     int n = p->n;
69395:     if( p->flags & MEM_Zero ){
69396:       n += p->u.nZero;
69397:     }
69398:     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
69399:   }
69400:   return 0; 
69401: }
69402: 
69403: #ifdef SQLITE_DEBUG
69404: /*
69405: ** This routine prepares a memory cell for modification by breaking
69406: ** its link to a shallow copy and by marking any current shallow
69407: ** copies of this cell as invalid.
69408: **
69409: ** This is used for testing and debugging only - to make sure shallow
69410: ** copies are not misused.
69411: */
69412: SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
69413:   int i;
69414:   Mem *pX;
69415:   for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
69416:     if( pX->pScopyFrom==pMem ){
69417:       pX->flags |= MEM_Undefined;
69418:       pX->pScopyFrom = 0;
69419:     }
69420:   }
69421:   pMem->pScopyFrom = 0;
69422: }
69423: #endif /* SQLITE_DEBUG */
69424: 
69425: 
69426: /*
69427: ** Make an shallow copy of pFrom into pTo.  Prior contents of
69428: ** pTo are freed.  The pFrom->z field is not duplicated.  If
69429: ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
69430: ** and flags gets srcType (either MEM_Ephem or MEM_Static).
69431: */
69432: static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
69433:   vdbeMemClearExternAndSetNull(pTo);
69434:   assert( !VdbeMemDynamic(pTo) );
69435:   sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
69436: }
69437: SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
69438:   assert( (pFrom->flags & MEM_RowSet)==0 );
69439:   assert( pTo->db==pFrom->db );
69440:   if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
69441:   memcpy(pTo, pFrom, MEMCELLSIZE);
69442:   if( (pFrom->flags&MEM_Static)==0 ){
69443:     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
69444:     assert( srcType==MEM_Ephem || srcType==MEM_Static );
69445:     pTo->flags |= srcType;
69446:   }
69447: }
69448: 
69449: /*
69450: ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
69451: ** freed before the copy is made.
69452: */
69453: SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
69454:   int rc = SQLITE_OK;
69455: 
69456:   assert( (pFrom->flags & MEM_RowSet)==0 );
69457:   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
69458:   memcpy(pTo, pFrom, MEMCELLSIZE);
69459:   pTo->flags &= ~MEM_Dyn;
69460:   if( pTo->flags&(MEM_Str|MEM_Blob) ){
69461:     if( 0==(pFrom->flags&MEM_Static) ){
69462:       pTo->flags |= MEM_Ephem;
69463:       rc = sqlite3VdbeMemMakeWriteable(pTo);
69464:     }
69465:   }
69466: 
69467:   return rc;
69468: }
69469: 
69470: /*
69471: ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
69472: ** freed. If pFrom contains ephemeral data, a copy is made.
69473: **
69474: ** pFrom contains an SQL NULL when this routine returns.
69475: */
69476: SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
69477:   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
69478:   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
69479:   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
69480: 
69481:   sqlite3VdbeMemRelease(pTo);
69482:   memcpy(pTo, pFrom, sizeof(Mem));
69483:   pFrom->flags = MEM_Null;
69484:   pFrom->szMalloc = 0;
69485: }
69486: 
69487: /*
69488: ** Change the value of a Mem to be a string or a BLOB.
69489: **
69490: ** The memory management strategy depends on the value of the xDel
69491: ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
69492: ** string is copied into a (possibly existing) buffer managed by the 
69493: ** Mem structure. Otherwise, any existing buffer is freed and the
69494: ** pointer copied.
69495: **
69496: ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
69497: ** size limit) then no memory allocation occurs.  If the string can be
69498: ** stored without allocating memory, then it is.  If a memory allocation
69499: ** is required to store the string, then value of pMem is unchanged.  In
69500: ** either case, SQLITE_TOOBIG is returned.
69501: */
69502: SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
69503:   Mem *pMem,          /* Memory cell to set to string value */
69504:   const char *z,      /* String pointer */
69505:   int n,              /* Bytes in string, or negative */
69506:   u8 enc,             /* Encoding of z.  0 for BLOBs */
69507:   void (*xDel)(void*) /* Destructor function */
69508: ){
69509:   int nByte = n;      /* New value for pMem->n */
69510:   int iLimit;         /* Maximum allowed string or blob size */
69511:   u16 flags = 0;      /* New value for pMem->flags */
69512: 
69513:   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69514:   assert( (pMem->flags & MEM_RowSet)==0 );
69515: 
69516:   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
69517:   if( !z ){
69518:     sqlite3VdbeMemSetNull(pMem);
69519:     return SQLITE_OK;
69520:   }
69521: 
69522:   if( pMem->db ){
69523:     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
69524:   }else{
69525:     iLimit = SQLITE_MAX_LENGTH;
69526:   }
69527:   flags = (enc==0?MEM_Blob:MEM_Str);
69528:   if( nByte<0 ){
69529:     assert( enc!=0 );
69530:     if( enc==SQLITE_UTF8 ){
69531:       nByte = sqlite3Strlen30(z);
69532:       if( nByte>iLimit ) nByte = iLimit+1;
69533:     }else{
69534:       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
69535:     }
69536:     flags |= MEM_Term;
69537:   }
69538: 
69539:   /* The following block sets the new values of Mem.z and Mem.xDel. It
69540:   ** also sets a flag in local variable "flags" to indicate the memory
69541:   ** management (one of MEM_Dyn or MEM_Static).
69542:   */
69543:   if( xDel==SQLITE_TRANSIENT ){
69544:     int nAlloc = nByte;
69545:     if( flags&MEM_Term ){
69546:       nAlloc += (enc==SQLITE_UTF8?1:2);
69547:     }
69548:     if( nByte>iLimit ){
69549:       return SQLITE_TOOBIG;
69550:     }
69551:     testcase( nAlloc==0 );
69552:     testcase( nAlloc==31 );
69553:     testcase( nAlloc==32 );
69554:     if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
69555:       return SQLITE_NOMEM_BKPT;
69556:     }
69557:     memcpy(pMem->z, z, nAlloc);
69558:   }else if( xDel==SQLITE_DYNAMIC ){
69559:     sqlite3VdbeMemRelease(pMem);
69560:     pMem->zMalloc = pMem->z = (char *)z;
69561:     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
69562:   }else{
69563:     sqlite3VdbeMemRelease(pMem);
69564:     pMem->z = (char *)z;
69565:     pMem->xDel = xDel;
69566:     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
69567:   }
69568: 
69569:   pMem->n = nByte;
69570:   pMem->flags = flags;
69571:   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
69572: 
69573: #ifndef SQLITE_OMIT_UTF16
69574:   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
69575:     return SQLITE_NOMEM_BKPT;
69576:   }
69577: #endif
69578: 
69579:   if( nByte>iLimit ){
69580:     return SQLITE_TOOBIG;
69581:   }
69582: 
69583:   return SQLITE_OK;
69584: }
69585: 
69586: /*
69587: ** Move data out of a btree key or data field and into a Mem structure.
69588: ** The data or key is taken from the entry that pCur is currently pointing
69589: ** to.  offset and amt determine what portion of the data or key to retrieve.
69590: ** key is true to get the key or false to get data.  The result is written
69591: ** into the pMem element.
69592: **
69593: ** The pMem object must have been initialized.  This routine will use
69594: ** pMem->zMalloc to hold the content from the btree, if possible.  New
69595: ** pMem->zMalloc space will be allocated if necessary.  The calling routine
69596: ** is responsible for making sure that the pMem object is eventually
69597: ** destroyed.
69598: **
69599: ** If this routine fails for any reason (malloc returns NULL or unable
69600: ** to read from the disk) then the pMem is left in an inconsistent state.
69601: */
69602: static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
69603:   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
69604:   u32 offset,       /* Offset from the start of data to return bytes from. */
69605:   u32 amt,          /* Number of bytes to return. */
69606:   int key,          /* If true, retrieve from the btree key, not data. */
69607:   Mem *pMem         /* OUT: Return data in this Mem structure. */
69608: ){
69609:   int rc;
69610:   pMem->flags = MEM_Null;
69611:   if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
69612:     if( key ){
69613:       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
69614:     }else{
69615:       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
69616:     }
69617:     if( rc==SQLITE_OK ){
69618:       pMem->z[amt] = 0;
69619:       pMem->z[amt+1] = 0;
69620:       pMem->flags = MEM_Blob|MEM_Term;
69621:       pMem->n = (int)amt;
69622:     }else{
69623:       sqlite3VdbeMemRelease(pMem);
69624:     }
69625:   }
69626:   return rc;
69627: }
69628: SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
69629:   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
69630:   u32 offset,       /* Offset from the start of data to return bytes from. */
69631:   u32 amt,          /* Number of bytes to return. */
69632:   int key,          /* If true, retrieve from the btree key, not data. */
69633:   Mem *pMem         /* OUT: Return data in this Mem structure. */
69634: ){
69635:   char *zData;        /* Data from the btree layer */
69636:   u32 available = 0;  /* Number of bytes available on the local btree page */
69637:   int rc = SQLITE_OK; /* Return code */
69638: 
69639:   assert( sqlite3BtreeCursorIsValid(pCur) );
69640:   assert( !VdbeMemDynamic(pMem) );
69641: 
69642:   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
69643:   ** that both the BtShared and database handle mutexes are held. */
69644:   assert( (pMem->flags & MEM_RowSet)==0 );
69645:   zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
69646:   assert( zData!=0 );
69647: 
69648:   if( offset+amt<=available ){
69649:     pMem->z = &zData[offset];
69650:     pMem->flags = MEM_Blob|MEM_Ephem;
69651:     pMem->n = (int)amt;
69652:   }else{
69653:     rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
69654:   }
69655: 
69656:   return rc;
69657: }
69658: 
69659: /*
69660: ** The pVal argument is known to be a value other than NULL.
69661: ** Convert it into a string with encoding enc and return a pointer
69662: ** to a zero-terminated version of that string.
69663: */
69664: static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
69665:   assert( pVal!=0 );
69666:   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69667:   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69668:   assert( (pVal->flags & MEM_RowSet)==0 );
69669:   assert( (pVal->flags & (MEM_Null))==0 );
69670:   if( pVal->flags & (MEM_Blob|MEM_Str) ){
69671:     pVal->flags |= MEM_Str;
69672:     if( pVal->flags & MEM_Zero ){
69673:       sqlite3VdbeMemExpandBlob(pVal);
69674:     }
69675:     if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
69676:       sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
69677:     }
69678:     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
69679:       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
69680:       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
69681:         return 0;
69682:       }
69683:     }
69684:     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
69685:   }else{
69686:     sqlite3VdbeMemStringify(pVal, enc, 0);
69687:     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
69688:   }
69689:   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
69690:               || pVal->db->mallocFailed );
69691:   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
69692:     return pVal->z;
69693:   }else{
69694:     return 0;
69695:   }
69696: }
69697: 
69698: /* This function is only available internally, it is not part of the
69699: ** external API. It works in a similar way to sqlite3_value_text(),
69700: ** except the data returned is in the encoding specified by the second
69701: ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
69702: ** SQLITE_UTF8.
69703: **
69704: ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
69705: ** If that is the case, then the result must be aligned on an even byte
69706: ** boundary.
69707: */
69708: SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
69709:   if( !pVal ) return 0;
69710:   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69711:   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69712:   assert( (pVal->flags & MEM_RowSet)==0 );
69713:   if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
69714:     return pVal->z;
69715:   }
69716:   if( pVal->flags&MEM_Null ){
69717:     return 0;
69718:   }
69719:   return valueToText(pVal, enc);
69720: }
69721: 
69722: /*
69723: ** Create a new sqlite3_value object.
69724: */
69725: SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
69726:   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
69727:   if( p ){
69728:     p->flags = MEM_Null;
69729:     p->db = db;
69730:   }
69731:   return p;
69732: }
69733: 
69734: /*
69735: ** Context object passed by sqlite3Stat4ProbeSetValue() through to 
69736: ** valueNew(). See comments above valueNew() for details.
69737: */
69738: struct ValueNewStat4Ctx {
69739:   Parse *pParse;
69740:   Index *pIdx;
69741:   UnpackedRecord **ppRec;
69742:   int iVal;
69743: };
69744: 
69745: /*
69746: ** Allocate and return a pointer to a new sqlite3_value object. If
69747: ** the second argument to this function is NULL, the object is allocated
69748: ** by calling sqlite3ValueNew().
69749: **
69750: ** Otherwise, if the second argument is non-zero, then this function is 
69751: ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
69752: ** already been allocated, allocate the UnpackedRecord structure that 
69753: ** that function will return to its caller here. Then return a pointer to
69754: ** an sqlite3_value within the UnpackedRecord.a[] array.
69755: */
69756: static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
69757: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69758:   if( p ){
69759:     UnpackedRecord *pRec = p->ppRec[0];
69760: 
69761:     if( pRec==0 ){
69762:       Index *pIdx = p->pIdx;      /* Index being probed */
69763:       int nByte;                  /* Bytes of space to allocate */
69764:       int i;                      /* Counter variable */
69765:       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
69766:   
69767:       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
69768:       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
69769:       if( pRec ){
69770:         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
69771:         if( pRec->pKeyInfo ){
69772:           assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
69773:           assert( pRec->pKeyInfo->enc==ENC(db) );
69774:           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
69775:           for(i=0; i<nCol; i++){
69776:             pRec->aMem[i].flags = MEM_Null;
69777:             pRec->aMem[i].db = db;
69778:           }
69779:         }else{
69780:           sqlite3DbFree(db, pRec);
69781:           pRec = 0;
69782:         }
69783:       }
69784:       if( pRec==0 ) return 0;
69785:       p->ppRec[0] = pRec;
69786:     }
69787:   
69788:     pRec->nField = p->iVal+1;
69789:     return &pRec->aMem[p->iVal];
69790:   }
69791: #else
69792:   UNUSED_PARAMETER(p);
69793: #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69794:   return sqlite3ValueNew(db);
69795: }
69796: 
69797: /*
69798: ** The expression object indicated by the second argument is guaranteed
69799: ** to be a scalar SQL function. If
69800: **
69801: **   * all function arguments are SQL literals,
69802: **   * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
69803: **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
69804: **
69805: ** then this routine attempts to invoke the SQL function. Assuming no
69806: ** error occurs, output parameter (*ppVal) is set to point to a value 
69807: ** object containing the result before returning SQLITE_OK.
69808: **
69809: ** Affinity aff is applied to the result of the function before returning.
69810: ** If the result is a text value, the sqlite3_value object uses encoding 
69811: ** enc.
69812: **
69813: ** If the conditions above are not met, this function returns SQLITE_OK
69814: ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
69815: ** NULL and an SQLite error code returned.
69816: */
69817: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69818: static int valueFromFunction(
69819:   sqlite3 *db,                    /* The database connection */
69820:   Expr *p,                        /* The expression to evaluate */
69821:   u8 enc,                         /* Encoding to use */
69822:   u8 aff,                         /* Affinity to use */
69823:   sqlite3_value **ppVal,          /* Write the new value here */
69824:   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
69825: ){
69826:   sqlite3_context ctx;            /* Context object for function invocation */
69827:   sqlite3_value **apVal = 0;      /* Function arguments */
69828:   int nVal = 0;                   /* Size of apVal[] array */
69829:   FuncDef *pFunc = 0;             /* Function definition */
69830:   sqlite3_value *pVal = 0;        /* New value */
69831:   int rc = SQLITE_OK;             /* Return code */
69832:   ExprList *pList = 0;            /* Function arguments */
69833:   int i;                          /* Iterator variable */
69834: 
69835:   assert( pCtx!=0 );
69836:   assert( (p->flags & EP_TokenOnly)==0 );
69837:   pList = p->x.pList;
69838:   if( pList ) nVal = pList->nExpr;
69839:   pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
69840:   assert( pFunc );
69841:   if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 
69842:    || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
69843:   ){
69844:     return SQLITE_OK;
69845:   }
69846: 
69847:   if( pList ){
69848:     apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
69849:     if( apVal==0 ){
69850:       rc = SQLITE_NOMEM_BKPT;
69851:       goto value_from_function_out;
69852:     }
69853:     for(i=0; i<nVal; i++){
69854:       rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
69855:       if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
69856:     }
69857:   }
69858: 
69859:   pVal = valueNew(db, pCtx);
69860:   if( pVal==0 ){
69861:     rc = SQLITE_NOMEM_BKPT;
69862:     goto value_from_function_out;
69863:   }
69864: 
69865:   assert( pCtx->pParse->rc==SQLITE_OK );
69866:   memset(&ctx, 0, sizeof(ctx));
69867:   ctx.pOut = pVal;
69868:   ctx.pFunc = pFunc;
69869:   pFunc->xSFunc(&ctx, nVal, apVal);
69870:   if( ctx.isError ){
69871:     rc = ctx.isError;
69872:     sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
69873:   }else{
69874:     sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
69875:     assert( rc==SQLITE_OK );
69876:     rc = sqlite3VdbeChangeEncoding(pVal, enc);
69877:     if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
69878:       rc = SQLITE_TOOBIG;
69879:       pCtx->pParse->nErr++;
69880:     }
69881:   }
69882:   pCtx->pParse->rc = rc;
69883: 
69884:  value_from_function_out:
69885:   if( rc!=SQLITE_OK ){
69886:     pVal = 0;
69887:   }
69888:   if( apVal ){
69889:     for(i=0; i<nVal; i++){
69890:       sqlite3ValueFree(apVal[i]);
69891:     }
69892:     sqlite3DbFree(db, apVal);
69893:   }
69894: 
69895:   *ppVal = pVal;
69896:   return rc;
69897: }
69898: #else
69899: # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
69900: #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69901: 
69902: /*
69903: ** Extract a value from the supplied expression in the manner described
69904: ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
69905: ** using valueNew().
69906: **
69907: ** If pCtx is NULL and an error occurs after the sqlite3_value object
69908: ** has been allocated, it is freed before returning. Or, if pCtx is not
69909: ** NULL, it is assumed that the caller will free any allocated object
69910: ** in all cases.
69911: */
69912: static int valueFromExpr(
69913:   sqlite3 *db,                    /* The database connection */
69914:   Expr *pExpr,                    /* The expression to evaluate */
69915:   u8 enc,                         /* Encoding to use */
69916:   u8 affinity,                    /* Affinity to use */
69917:   sqlite3_value **ppVal,          /* Write the new value here */
69918:   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
69919: ){
69920:   int op;
69921:   char *zVal = 0;
69922:   sqlite3_value *pVal = 0;
69923:   int negInt = 1;
69924:   const char *zNeg = "";
69925:   int rc = SQLITE_OK;
69926: 
69927:   if( !pExpr ){
69928:     *ppVal = 0;
69929:     return SQLITE_OK;
69930:   }
69931:   while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
69932:   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
69933: 
69934:   /* Compressed expressions only appear when parsing the DEFAULT clause
69935:   ** on a table column definition, and hence only when pCtx==0.  This
69936:   ** check ensures that an EP_TokenOnly expression is never passed down
69937:   ** into valueFromFunction(). */
69938:   assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
69939: 
69940:   if( op==TK_CAST ){
69941:     u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
69942:     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
69943:     testcase( rc!=SQLITE_OK );
69944:     if( *ppVal ){
69945:       sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
69946:       sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
69947:     }
69948:     return rc;
69949:   }
69950: 
69951:   /* Handle negative integers in a single step.  This is needed in the
69952:   ** case when the value is -9223372036854775808.
69953:   */
69954:   if( op==TK_UMINUS
69955:    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
69956:     pExpr = pExpr->pLeft;
69957:     op = pExpr->op;
69958:     negInt = -1;
69959:     zNeg = "-";
69960:   }
69961: 
69962:   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
69963:     pVal = valueNew(db, pCtx);
69964:     if( pVal==0 ) goto no_mem;
69965:     if( ExprHasProperty(pExpr, EP_IntValue) ){
69966:       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
69967:     }else{
69968:       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
69969:       if( zVal==0 ) goto no_mem;
69970:       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
69971:     }
69972:     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
69973:       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
69974:     }else{
69975:       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
69976:     }
69977:     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
69978:     if( enc!=SQLITE_UTF8 ){
69979:       rc = sqlite3VdbeChangeEncoding(pVal, enc);
69980:     }
69981:   }else if( op==TK_UMINUS ) {
69982:     /* This branch happens for multiple negative signs.  Ex: -(-5) */
69983:     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) 
69984:      && pVal!=0
69985:     ){
69986:       sqlite3VdbeMemNumerify(pVal);
69987:       if( pVal->flags & MEM_Real ){
69988:         pVal->u.r = -pVal->u.r;
69989:       }else if( pVal->u.i==SMALLEST_INT64 ){
69990:         pVal->u.r = -(double)SMALLEST_INT64;
69991:         MemSetTypeFlag(pVal, MEM_Real);
69992:       }else{
69993:         pVal->u.i = -pVal->u.i;
69994:       }
69995:       sqlite3ValueApplyAffinity(pVal, affinity, enc);
69996:     }
69997:   }else if( op==TK_NULL ){
69998:     pVal = valueNew(db, pCtx);
69999:     if( pVal==0 ) goto no_mem;
70000:   }
70001: #ifndef SQLITE_OMIT_BLOB_LITERAL
70002:   else if( op==TK_BLOB ){
70003:     int nVal;
70004:     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70005:     assert( pExpr->u.zToken[1]=='\'' );
70006:     pVal = valueNew(db, pCtx);
70007:     if( !pVal ) goto no_mem;
70008:     zVal = &pExpr->u.zToken[2];
70009:     nVal = sqlite3Strlen30(zVal)-1;
70010:     assert( zVal[nVal]=='\'' );
70011:     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
70012:                          0, SQLITE_DYNAMIC);
70013:   }
70014: #endif
70015: 
70016: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70017:   else if( op==TK_FUNCTION && pCtx!=0 ){
70018:     rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
70019:   }
70020: #endif
70021: 
70022:   *ppVal = pVal;
70023:   return rc;
70024: 
70025: no_mem:
70026:   sqlite3OomFault(db);
70027:   sqlite3DbFree(db, zVal);
70028:   assert( *ppVal==0 );
70029: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70030:   if( pCtx==0 ) sqlite3ValueFree(pVal);
70031: #else
70032:   assert( pCtx==0 ); sqlite3ValueFree(pVal);
70033: #endif
70034:   return SQLITE_NOMEM_BKPT;
70035: }
70036: 
70037: /*
70038: ** Create a new sqlite3_value object, containing the value of pExpr.
70039: **
70040: ** This only works for very simple expressions that consist of one constant
70041: ** token (i.e. "5", "5.1", "'a string'"). If the expression can
70042: ** be converted directly into a value, then the value is allocated and
70043: ** a pointer written to *ppVal. The caller is responsible for deallocating
70044: ** the value by passing it to sqlite3ValueFree() later on. If the expression
70045: ** cannot be converted to a value, then *ppVal is set to NULL.
70046: */
70047: SQLITE_PRIVATE int sqlite3ValueFromExpr(
70048:   sqlite3 *db,              /* The database connection */
70049:   Expr *pExpr,              /* The expression to evaluate */
70050:   u8 enc,                   /* Encoding to use */
70051:   u8 affinity,              /* Affinity to use */
70052:   sqlite3_value **ppVal     /* Write the new value here */
70053: ){
70054:   return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
70055: }
70056: 
70057: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
70058: /*
70059: ** The implementation of the sqlite_record() function. This function accepts
70060: ** a single argument of any type. The return value is a formatted database 
70061: ** record (a blob) containing the argument value.
70062: **
70063: ** This is used to convert the value stored in the 'sample' column of the
70064: ** sqlite_stat3 table to the record format SQLite uses internally.
70065: */
70066: static void recordFunc(
70067:   sqlite3_context *context,
70068:   int argc,
70069:   sqlite3_value **argv
70070: ){
70071:   const int file_format = 1;
70072:   u32 iSerial;                    /* Serial type */
70073:   int nSerial;                    /* Bytes of space for iSerial as varint */
70074:   u32 nVal;                       /* Bytes of space required for argv[0] */
70075:   int nRet;
70076:   sqlite3 *db;
70077:   u8 *aRet;
70078: 
70079:   UNUSED_PARAMETER( argc );
70080:   iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
70081:   nSerial = sqlite3VarintLen(iSerial);
70082:   db = sqlite3_context_db_handle(context);
70083: 
70084:   nRet = 1 + nSerial + nVal;
70085:   aRet = sqlite3DbMallocRawNN(db, nRet);
70086:   if( aRet==0 ){
70087:     sqlite3_result_error_nomem(context);
70088:   }else{
70089:     aRet[0] = nSerial+1;
70090:     putVarint32(&aRet[1], iSerial);
70091:     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
70092:     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
70093:     sqlite3DbFree(db, aRet);
70094:   }
70095: }
70096: 
70097: /*
70098: ** Register built-in functions used to help read ANALYZE data.
70099: */
70100: SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
70101:   static FuncDef aAnalyzeTableFuncs[] = {
70102:     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
70103:   };
70104:   sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
70105: }
70106: 
70107: /*
70108: ** Attempt to extract a value from pExpr and use it to construct *ppVal.
70109: **
70110: ** If pAlloc is not NULL, then an UnpackedRecord object is created for
70111: ** pAlloc if one does not exist and the new value is added to the
70112: ** UnpackedRecord object.
70113: **
70114: ** A value is extracted in the following cases:
70115: **
70116: **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70117: **
70118: **  * The expression is a bound variable, and this is a reprepare, or
70119: **
70120: **  * The expression is a literal value.
70121: **
70122: ** On success, *ppVal is made to point to the extracted value.  The caller
70123: ** is responsible for ensuring that the value is eventually freed.
70124: */
70125: static int stat4ValueFromExpr(
70126:   Parse *pParse,                  /* Parse context */
70127:   Expr *pExpr,                    /* The expression to extract a value from */
70128:   u8 affinity,                    /* Affinity to use */
70129:   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
70130:   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
70131: ){
70132:   int rc = SQLITE_OK;
70133:   sqlite3_value *pVal = 0;
70134:   sqlite3 *db = pParse->db;
70135: 
70136:   /* Skip over any TK_COLLATE nodes */
70137:   pExpr = sqlite3ExprSkipCollate(pExpr);
70138: 
70139:   if( !pExpr ){
70140:     pVal = valueNew(db, pAlloc);
70141:     if( pVal ){
70142:       sqlite3VdbeMemSetNull((Mem*)pVal);
70143:     }
70144:   }else if( pExpr->op==TK_VARIABLE
70145:         || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
70146:   ){
70147:     Vdbe *v;
70148:     int iBindVar = pExpr->iColumn;
70149:     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
70150:     if( (v = pParse->pReprepare)!=0 ){
70151:       pVal = valueNew(db, pAlloc);
70152:       if( pVal ){
70153:         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
70154:         if( rc==SQLITE_OK ){
70155:           sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
70156:         }
70157:         pVal->db = pParse->db;
70158:       }
70159:     }
70160:   }else{
70161:     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
70162:   }
70163: 
70164:   assert( pVal==0 || pVal->db==db );
70165:   *ppVal = pVal;
70166:   return rc;
70167: }
70168: 
70169: /*
70170: ** This function is used to allocate and populate UnpackedRecord 
70171: ** structures intended to be compared against sample index keys stored 
70172: ** in the sqlite_stat4 table.
70173: **
70174: ** A single call to this function attempts to populates field iVal (leftmost 
70175: ** is 0 etc.) of the unpacked record with a value extracted from expression
70176: ** pExpr. Extraction of values is possible if:
70177: **
70178: **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
70179: **
70180: **  * The expression is a bound variable, and this is a reprepare, or
70181: **
70182: **  * The sqlite3ValueFromExpr() function is able to extract a value 
70183: **    from the expression (i.e. the expression is a literal value).
70184: **
70185: ** If a value can be extracted, the affinity passed as the 5th argument
70186: ** is applied to it before it is copied into the UnpackedRecord. Output
70187: ** parameter *pbOk is set to true if a value is extracted, or false 
70188: ** otherwise.
70189: **
70190: ** When this function is called, *ppRec must either point to an object
70191: ** allocated by an earlier call to this function, or must be NULL. If it
70192: ** is NULL and a value can be successfully extracted, a new UnpackedRecord
70193: ** is allocated (and *ppRec set to point to it) before returning.
70194: **
70195: ** Unless an error is encountered, SQLITE_OK is returned. It is not an
70196: ** error if a value cannot be extracted from pExpr. If an error does
70197: ** occur, an SQLite error code is returned.
70198: */
70199: SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
70200:   Parse *pParse,                  /* Parse context */
70201:   Index *pIdx,                    /* Index being probed */
70202:   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
70203:   Expr *pExpr,                    /* The expression to extract a value from */
70204:   u8 affinity,                    /* Affinity to use */
70205:   int iVal,                       /* Array element to populate */
70206:   int *pbOk                       /* OUT: True if value was extracted */
70207: ){
70208:   int rc;
70209:   sqlite3_value *pVal = 0;
70210:   struct ValueNewStat4Ctx alloc;
70211: 
70212:   alloc.pParse = pParse;
70213:   alloc.pIdx = pIdx;
70214:   alloc.ppRec = ppRec;
70215:   alloc.iVal = iVal;
70216: 
70217:   rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
70218:   assert( pVal==0 || pVal->db==pParse->db );
70219:   *pbOk = (pVal!=0);
70220:   return rc;
70221: }
70222: 
70223: /*
70224: ** Attempt to extract a value from expression pExpr using the methods
70225: ** as described for sqlite3Stat4ProbeSetValue() above. 
70226: **
70227: ** If successful, set *ppVal to point to a new value object and return 
70228: ** SQLITE_OK. If no value can be extracted, but no other error occurs
70229: ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
70230: ** does occur, return an SQLite error code. The final value of *ppVal
70231: ** is undefined in this case.
70232: */
70233: SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
70234:   Parse *pParse,                  /* Parse context */
70235:   Expr *pExpr,                    /* The expression to extract a value from */
70236:   u8 affinity,                    /* Affinity to use */
70237:   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
70238: ){
70239:   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
70240: }
70241: 
70242: /*
70243: ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
70244: ** the column value into *ppVal.  If *ppVal is initially NULL then a new
70245: ** sqlite3_value object is allocated.
70246: **
70247: ** If *ppVal is initially NULL then the caller is responsible for 
70248: ** ensuring that the value written into *ppVal is eventually freed.
70249: */
70250: SQLITE_PRIVATE int sqlite3Stat4Column(
70251:   sqlite3 *db,                    /* Database handle */
70252:   const void *pRec,               /* Pointer to buffer containing record */
70253:   int nRec,                       /* Size of buffer pRec in bytes */
70254:   int iCol,                       /* Column to extract */
70255:   sqlite3_value **ppVal           /* OUT: Extracted value */
70256: ){
70257:   u32 t;                          /* a column type code */
70258:   int nHdr;                       /* Size of the header in the record */
70259:   int iHdr;                       /* Next unread header byte */
70260:   int iField;                     /* Next unread data byte */
70261:   int szField;                    /* Size of the current data field */
70262:   int i;                          /* Column index */
70263:   u8 *a = (u8*)pRec;              /* Typecast byte array */
70264:   Mem *pMem = *ppVal;             /* Write result into this Mem object */
70265: 
70266:   assert( iCol>0 );
70267:   iHdr = getVarint32(a, nHdr);
70268:   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
70269:   iField = nHdr;
70270:   for(i=0; i<=iCol; i++){
70271:     iHdr += getVarint32(&a[iHdr], t);
70272:     testcase( iHdr==nHdr );
70273:     testcase( iHdr==nHdr+1 );
70274:     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
70275:     szField = sqlite3VdbeSerialTypeLen(t);
70276:     iField += szField;
70277:   }
70278:   testcase( iField==nRec );
70279:   testcase( iField==nRec+1 );
70280:   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
70281:   if( pMem==0 ){
70282:     pMem = *ppVal = sqlite3ValueNew(db);
70283:     if( pMem==0 ) return SQLITE_NOMEM_BKPT;
70284:   }
70285:   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
70286:   pMem->enc = ENC(db);
70287:   return SQLITE_OK;
70288: }
70289: 
70290: /*
70291: ** Unless it is NULL, the argument must be an UnpackedRecord object returned
70292: ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
70293: ** the object.
70294: */
70295: SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
70296:   if( pRec ){
70297:     int i;
70298:     int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
70299:     Mem *aMem = pRec->aMem;
70300:     sqlite3 *db = aMem[0].db;
70301:     for(i=0; i<nCol; i++){
70302:       sqlite3VdbeMemRelease(&aMem[i]);
70303:     }
70304:     sqlite3KeyInfoUnref(pRec->pKeyInfo);
70305:     sqlite3DbFree(db, pRec);
70306:   }
70307: }
70308: #endif /* ifdef SQLITE_ENABLE_STAT4 */
70309: 
70310: /*
70311: ** Change the string value of an sqlite3_value object
70312: */
70313: SQLITE_PRIVATE void sqlite3ValueSetStr(
70314:   sqlite3_value *v,     /* Value to be set */
70315:   int n,                /* Length of string z */
70316:   const void *z,        /* Text of the new string */
70317:   u8 enc,               /* Encoding to use */
70318:   void (*xDel)(void*)   /* Destructor for the string */
70319: ){
70320:   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
70321: }
70322: 
70323: /*
70324: ** Free an sqlite3_value object
70325: */
70326: SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
70327:   if( !v ) return;
70328:   sqlite3VdbeMemRelease((Mem *)v);
70329:   sqlite3DbFree(((Mem*)v)->db, v);
70330: }
70331: 
70332: /*
70333: ** The sqlite3ValueBytes() routine returns the number of bytes in the
70334: ** sqlite3_value object assuming that it uses the encoding "enc".
70335: ** The valueBytes() routine is a helper function.
70336: */
70337: static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
70338:   return valueToText(pVal, enc)!=0 ? pVal->n : 0;
70339: }
70340: SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
70341:   Mem *p = (Mem*)pVal;
70342:   assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
70343:   if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
70344:     return p->n;
70345:   }
70346:   if( (p->flags & MEM_Blob)!=0 ){
70347:     if( p->flags & MEM_Zero ){
70348:       return p->n + p->u.nZero;
70349:     }else{
70350:       return p->n;
70351:     }
70352:   }
70353:   if( p->flags & MEM_Null ) return 0;
70354:   return valueBytes(pVal, enc);
70355: }
70356: 
70357: /************** End of vdbemem.c *********************************************/
70358: /************** Begin file vdbeaux.c *****************************************/
70359: /*
70360: ** 2003 September 6
70361: **
70362: ** The author disclaims copyright to this source code.  In place of
70363: ** a legal notice, here is a blessing:
70364: **
70365: **    May you do good and not evil.
70366: **    May you find forgiveness for yourself and forgive others.
70367: **    May you share freely, never taking more than you give.
70368: **
70369: *************************************************************************
70370: ** This file contains code used for creating, destroying, and populating
70371: ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) 
70372: */
70373: /* #include "sqliteInt.h" */
70374: /* #include "vdbeInt.h" */
70375: 
70376: /*
70377: ** Create a new virtual database engine.
70378: */
70379: SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
70380:   sqlite3 *db = pParse->db;
70381:   Vdbe *p;
70382:   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
70383:   if( p==0 ) return 0;
70384:   p->db = db;
70385:   if( db->pVdbe ){
70386:     db->pVdbe->pPrev = p;
70387:   }
70388:   p->pNext = db->pVdbe;
70389:   p->pPrev = 0;
70390:   db->pVdbe = p;
70391:   p->magic = VDBE_MAGIC_INIT;
70392:   p->pParse = pParse;
70393:   assert( pParse->aLabel==0 );
70394:   assert( pParse->nLabel==0 );
70395:   assert( pParse->nOpAlloc==0 );
70396:   assert( pParse->szOpAlloc==0 );
70397:   return p;
70398: }
70399: 
70400: /*
70401: ** Change the error string stored in Vdbe.zErrMsg
70402: */
70403: SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
70404:   va_list ap;
70405:   sqlite3DbFree(p->db, p->zErrMsg);
70406:   va_start(ap, zFormat);
70407:   p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
70408:   va_end(ap);
70409: }
70410: 
70411: /*
70412: ** Remember the SQL string for a prepared statement.
70413: */
70414: SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
70415:   assert( isPrepareV2==1 || isPrepareV2==0 );
70416:   if( p==0 ) return;
70417: #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
70418:   if( !isPrepareV2 ) return;
70419: #endif
70420:   assert( p->zSql==0 );
70421:   p->zSql = sqlite3DbStrNDup(p->db, z, n);
70422:   p->isPrepareV2 = (u8)isPrepareV2;
70423: }
70424: 
70425: /*
70426: ** Swap all content between two VDBE structures.
70427: */
70428: SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
70429:   Vdbe tmp, *pTmp;
70430:   char *zTmp;
70431:   assert( pA->db==pB->db );
70432:   tmp = *pA;
70433:   *pA = *pB;
70434:   *pB = tmp;
70435:   pTmp = pA->pNext;
70436:   pA->pNext = pB->pNext;
70437:   pB->pNext = pTmp;
70438:   pTmp = pA->pPrev;
70439:   pA->pPrev = pB->pPrev;
70440:   pB->pPrev = pTmp;
70441:   zTmp = pA->zSql;
70442:   pA->zSql = pB->zSql;
70443:   pB->zSql = zTmp;
70444:   pB->isPrepareV2 = pA->isPrepareV2;
70445: }
70446: 
70447: /*
70448: ** Resize the Vdbe.aOp array so that it is at least nOp elements larger 
70449: ** than its current size. nOp is guaranteed to be less than or equal
70450: ** to 1024/sizeof(Op).
70451: **
70452: ** If an out-of-memory error occurs while resizing the array, return
70453: ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain 
70454: ** unchanged (this is so that any opcodes already allocated can be 
70455: ** correctly deallocated along with the rest of the Vdbe).
70456: */
70457: static int growOpArray(Vdbe *v, int nOp){
70458:   VdbeOp *pNew;
70459:   Parse *p = v->pParse;
70460: 
70461:   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
70462:   ** more frequent reallocs and hence provide more opportunities for 
70463:   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
70464:   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
70465:   ** by the minimum* amount required until the size reaches 512.  Normal
70466:   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
70467:   ** size of the op array or add 1KB of space, whichever is smaller. */
70468: #ifdef SQLITE_TEST_REALLOC_STRESS
70469:   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
70470: #else
70471:   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
70472:   UNUSED_PARAMETER(nOp);
70473: #endif
70474: 
70475:   assert( nOp<=(1024/sizeof(Op)) );
70476:   assert( nNew>=(p->nOpAlloc+nOp) );
70477:   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
70478:   if( pNew ){
70479:     p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
70480:     p->nOpAlloc = p->szOpAlloc/sizeof(Op);
70481:     v->aOp = pNew;
70482:   }
70483:   return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
70484: }
70485: 
70486: #ifdef SQLITE_DEBUG
70487: /* This routine is just a convenient place to set a breakpoint that will
70488: ** fire after each opcode is inserted and displayed using
70489: ** "PRAGMA vdbe_addoptrace=on".
70490: */
70491: static void test_addop_breakpoint(void){
70492:   static int n = 0;
70493:   n++;
70494: }
70495: #endif
70496: 
70497: /*
70498: ** Add a new instruction to the list of instructions current in the
70499: ** VDBE.  Return the address of the new instruction.
70500: **
70501: ** Parameters:
70502: **
70503: **    p               Pointer to the VDBE
70504: **
70505: **    op              The opcode for this instruction
70506: **
70507: **    p1, p2, p3      Operands
70508: **
70509: ** Use the sqlite3VdbeResolveLabel() function to fix an address and
70510: ** the sqlite3VdbeChangeP4() function to change the value of the P4
70511: ** operand.
70512: */
70513: static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
70514:   assert( p->pParse->nOpAlloc<=p->nOp );
70515:   if( growOpArray(p, 1) ) return 1;
70516:   assert( p->pParse->nOpAlloc>p->nOp );
70517:   return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70518: }
70519: SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
70520:   int i;
70521:   VdbeOp *pOp;
70522: 
70523:   i = p->nOp;
70524:   assert( p->magic==VDBE_MAGIC_INIT );
70525:   assert( op>=0 && op<0xff );
70526:   if( p->pParse->nOpAlloc<=i ){
70527:     return growOp3(p, op, p1, p2, p3);
70528:   }
70529:   p->nOp++;
70530:   pOp = &p->aOp[i];
70531:   pOp->opcode = (u8)op;
70532:   pOp->p5 = 0;
70533:   pOp->p1 = p1;
70534:   pOp->p2 = p2;
70535:   pOp->p3 = p3;
70536:   pOp->p4.p = 0;
70537:   pOp->p4type = P4_NOTUSED;
70538: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70539:   pOp->zComment = 0;
70540: #endif
70541: #ifdef SQLITE_DEBUG
70542:   if( p->db->flags & SQLITE_VdbeAddopTrace ){
70543:     int jj, kk;
70544:     Parse *pParse = p->pParse;
70545:     for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
70546:       struct yColCache *x = pParse->aColCache + jj;
70547:       if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
70548:       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
70549:       kk++;
70550:     }
70551:     if( kk ) printf("\n");
70552:     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
70553:     test_addop_breakpoint();
70554:   }
70555: #endif
70556: #ifdef VDBE_PROFILE
70557:   pOp->cycles = 0;
70558:   pOp->cnt = 0;
70559: #endif
70560: #ifdef SQLITE_VDBE_COVERAGE
70561:   pOp->iSrcLine = 0;
70562: #endif
70563:   return i;
70564: }
70565: SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
70566:   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
70567: }
70568: SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
70569:   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
70570: }
70571: SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
70572:   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
70573: }
70574: 
70575: /* Generate code for an unconditional jump to instruction iDest
70576: */
70577: SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
70578:   return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
70579: }
70580: 
70581: /* Generate code to cause the string zStr to be loaded into
70582: ** register iDest
70583: */
70584: SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
70585:   return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
70586: }
70587: 
70588: /*
70589: ** Generate code that initializes multiple registers to string or integer
70590: ** constants.  The registers begin with iDest and increase consecutively.
70591: ** One register is initialized for each characgter in zTypes[].  For each
70592: ** "s" character in zTypes[], the register is a string if the argument is
70593: ** not NULL, or OP_Null if the value is a null pointer.  For each "i" character
70594: ** in zTypes[], the register is initialized to an integer.
70595: */
70596: SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
70597:   va_list ap;
70598:   int i;
70599:   char c;
70600:   va_start(ap, zTypes);
70601:   for(i=0; (c = zTypes[i])!=0; i++){
70602:     if( c=='s' ){
70603:       const char *z = va_arg(ap, const char*);
70604:       sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
70605:     }else{
70606:       assert( c=='i' );
70607:       sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
70608:     }
70609:   }
70610:   va_end(ap);
70611: }
70612: 
70613: /*
70614: ** Add an opcode that includes the p4 value as a pointer.
70615: */
70616: SQLITE_PRIVATE int sqlite3VdbeAddOp4(
70617:   Vdbe *p,            /* Add the opcode to this VM */
70618:   int op,             /* The new opcode */
70619:   int p1,             /* The P1 operand */
70620:   int p2,             /* The P2 operand */
70621:   int p3,             /* The P3 operand */
70622:   const char *zP4,    /* The P4 operand */
70623:   int p4type          /* P4 operand type */
70624: ){
70625:   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70626:   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
70627:   return addr;
70628: }
70629: 
70630: /*
70631: ** Add an opcode that includes the p4 value with a P4_INT64 or
70632: ** P4_REAL type.
70633: */
70634: SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
70635:   Vdbe *p,            /* Add the opcode to this VM */
70636:   int op,             /* The new opcode */
70637:   int p1,             /* The P1 operand */
70638:   int p2,             /* The P2 operand */
70639:   int p3,             /* The P3 operand */
70640:   const u8 *zP4,      /* The P4 operand */
70641:   int p4type          /* P4 operand type */
70642: ){
70643:   char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
70644:   if( p4copy ) memcpy(p4copy, zP4, 8);
70645:   return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
70646: }
70647: 
70648: /*
70649: ** Add an OP_ParseSchema opcode.  This routine is broken out from
70650: ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
70651: ** as having been used.
70652: **
70653: ** The zWhere string must have been obtained from sqlite3_malloc().
70654: ** This routine will take ownership of the allocated memory.
70655: */
70656: SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
70657:   int j;
70658:   sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70659:   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
70660: }
70661: 
70662: /*
70663: ** Add an opcode that includes the p4 value as an integer.
70664: */
70665: SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
70666:   Vdbe *p,            /* Add the opcode to this VM */
70667:   int op,             /* The new opcode */
70668:   int p1,             /* The P1 operand */
70669:   int p2,             /* The P2 operand */
70670:   int p3,             /* The P3 operand */
70671:   int p4              /* The P4 operand as an integer */
70672: ){
70673:   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70674:   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
70675:   return addr;
70676: }
70677: 
70678: /* Insert the end of a co-routine
70679: */
70680: SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
70681:   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
70682: 
70683:   /* Clear the temporary register cache, thereby ensuring that each
70684:   ** co-routine has its own independent set of registers, because co-routines
70685:   ** might expect their registers to be preserved across an OP_Yield, and
70686:   ** that could cause problems if two or more co-routines are using the same
70687:   ** temporary register.
70688:   */
70689:   v->pParse->nTempReg = 0;
70690:   v->pParse->nRangeReg = 0;
70691: }
70692: 
70693: /*
70694: ** Create a new symbolic label for an instruction that has yet to be
70695: ** coded.  The symbolic label is really just a negative number.  The
70696: ** label can be used as the P2 value of an operation.  Later, when
70697: ** the label is resolved to a specific address, the VDBE will scan
70698: ** through its operation list and change all values of P2 which match
70699: ** the label into the resolved address.
70700: **
70701: ** The VDBE knows that a P2 value is a label because labels are
70702: ** always negative and P2 values are suppose to be non-negative.
70703: ** Hence, a negative P2 value is a label that has yet to be resolved.
70704: **
70705: ** Zero is returned if a malloc() fails.
70706: */
70707: SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
70708:   Parse *p = v->pParse;
70709:   int i = p->nLabel++;
70710:   assert( v->magic==VDBE_MAGIC_INIT );
70711:   if( (i & (i-1))==0 ){
70712:     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
70713:                                        (i*2+1)*sizeof(p->aLabel[0]));
70714:   }
70715:   if( p->aLabel ){
70716:     p->aLabel[i] = -1;
70717:   }
70718:   return ADDR(i);
70719: }
70720: 
70721: /*
70722: ** Resolve label "x" to be the address of the next instruction to
70723: ** be inserted.  The parameter "x" must have been obtained from
70724: ** a prior call to sqlite3VdbeMakeLabel().
70725: */
70726: SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
70727:   Parse *p = v->pParse;
70728:   int j = ADDR(x);
70729:   assert( v->magic==VDBE_MAGIC_INIT );
70730:   assert( j<p->nLabel );
70731:   assert( j>=0 );
70732:   if( p->aLabel ){
70733:     p->aLabel[j] = v->nOp;
70734:   }
70735:   p->iFixedOp = v->nOp - 1;
70736: }
70737: 
70738: /*
70739: ** Mark the VDBE as one that can only be run one time.
70740: */
70741: SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
70742:   p->runOnlyOnce = 1;
70743: }
70744: 
70745: /*
70746: ** Mark the VDBE as one that can only be run multiple times.
70747: */
70748: SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
70749:   p->runOnlyOnce = 0;
70750: }
70751: 
70752: #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
70753: 
70754: /*
70755: ** The following type and function are used to iterate through all opcodes
70756: ** in a Vdbe main program and each of the sub-programs (triggers) it may 
70757: ** invoke directly or indirectly. It should be used as follows:
70758: **
70759: **   Op *pOp;
70760: **   VdbeOpIter sIter;
70761: **
70762: **   memset(&sIter, 0, sizeof(sIter));
70763: **   sIter.v = v;                            // v is of type Vdbe* 
70764: **   while( (pOp = opIterNext(&sIter)) ){
70765: **     // Do something with pOp
70766: **   }
70767: **   sqlite3DbFree(v->db, sIter.apSub);
70768: ** 
70769: */
70770: typedef struct VdbeOpIter VdbeOpIter;
70771: struct VdbeOpIter {
70772:   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
70773:   SubProgram **apSub;        /* Array of subprograms */
70774:   int nSub;                  /* Number of entries in apSub */
70775:   int iAddr;                 /* Address of next instruction to return */
70776:   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
70777: };
70778: static Op *opIterNext(VdbeOpIter *p){
70779:   Vdbe *v = p->v;
70780:   Op *pRet = 0;
70781:   Op *aOp;
70782:   int nOp;
70783: 
70784:   if( p->iSub<=p->nSub ){
70785: 
70786:     if( p->iSub==0 ){
70787:       aOp = v->aOp;
70788:       nOp = v->nOp;
70789:     }else{
70790:       aOp = p->apSub[p->iSub-1]->aOp;
70791:       nOp = p->apSub[p->iSub-1]->nOp;
70792:     }
70793:     assert( p->iAddr<nOp );
70794: 
70795:     pRet = &aOp[p->iAddr];
70796:     p->iAddr++;
70797:     if( p->iAddr==nOp ){
70798:       p->iSub++;
70799:       p->iAddr = 0;
70800:     }
70801:   
70802:     if( pRet->p4type==P4_SUBPROGRAM ){
70803:       int nByte = (p->nSub+1)*sizeof(SubProgram*);
70804:       int j;
70805:       for(j=0; j<p->nSub; j++){
70806:         if( p->apSub[j]==pRet->p4.pProgram ) break;
70807:       }
70808:       if( j==p->nSub ){
70809:         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
70810:         if( !p->apSub ){
70811:           pRet = 0;
70812:         }else{
70813:           p->apSub[p->nSub++] = pRet->p4.pProgram;
70814:         }
70815:       }
70816:     }
70817:   }
70818: 
70819:   return pRet;
70820: }
70821: 
70822: /*
70823: ** Check if the program stored in the VM associated with pParse may
70824: ** throw an ABORT exception (causing the statement, but not entire transaction
70825: ** to be rolled back). This condition is true if the main program or any
70826: ** sub-programs contains any of the following:
70827: **
70828: **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70829: **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70830: **   *  OP_Destroy
70831: **   *  OP_VUpdate
70832: **   *  OP_VRename
70833: **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
70834: **   *  OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
70835: **
70836: ** Then check that the value of Parse.mayAbort is true if an
70837: ** ABORT may be thrown, or false otherwise. Return true if it does
70838: ** match, or false otherwise. This function is intended to be used as
70839: ** part of an assert statement in the compiler. Similar to:
70840: **
70841: **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
70842: */
70843: SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
70844:   int hasAbort = 0;
70845:   int hasFkCounter = 0;
70846:   int hasCreateTable = 0;
70847:   int hasInitCoroutine = 0;
70848:   Op *pOp;
70849:   VdbeOpIter sIter;
70850:   memset(&sIter, 0, sizeof(sIter));
70851:   sIter.v = v;
70852: 
70853:   while( (pOp = opIterNext(&sIter))!=0 ){
70854:     int opcode = pOp->opcode;
70855:     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
70856:      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
70857:       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
70858:     ){
70859:       hasAbort = 1;
70860:       break;
70861:     }
70862:     if( opcode==OP_CreateTable ) hasCreateTable = 1;
70863:     if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
70864: #ifndef SQLITE_OMIT_FOREIGN_KEY
70865:     if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
70866:       hasFkCounter = 1;
70867:     }
70868: #endif
70869:   }
70870:   sqlite3DbFree(v->db, sIter.apSub);
70871: 
70872:   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
70873:   ** If malloc failed, then the while() loop above may not have iterated
70874:   ** through all opcodes and hasAbort may be set incorrectly. Return
70875:   ** true for this case to prevent the assert() in the callers frame
70876:   ** from failing.  */
70877:   return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
70878:               || (hasCreateTable && hasInitCoroutine) );
70879: }
70880: #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
70881: 
70882: /*
70883: ** This routine is called after all opcodes have been inserted.  It loops
70884: ** through all the opcodes and fixes up some details.
70885: **
70886: ** (1) For each jump instruction with a negative P2 value (a label)
70887: **     resolve the P2 value to an actual address.
70888: **
70889: ** (2) Compute the maximum number of arguments used by any SQL function
70890: **     and store that value in *pMaxFuncArgs.
70891: **
70892: ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
70893: **     indicate what the prepared statement actually does.
70894: **
70895: ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
70896: **
70897: ** (5) Reclaim the memory allocated for storing labels.
70898: **
70899: ** This routine will only function correctly if the mkopcodeh.tcl generator
70900: ** script numbers the opcodes correctly.  Changes to this routine must be
70901: ** coordinated with changes to mkopcodeh.tcl.
70902: */
70903: static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
70904:   int nMaxArgs = *pMaxFuncArgs;
70905:   Op *pOp;
70906:   Parse *pParse = p->pParse;
70907:   int *aLabel = pParse->aLabel;
70908:   p->readOnly = 1;
70909:   p->bIsReader = 0;
70910:   pOp = &p->aOp[p->nOp-1];
70911:   while(1){
70912: 
70913:     /* Only JUMP opcodes and the short list of special opcodes in the switch
70914:     ** below need to be considered.  The mkopcodeh.tcl generator script groups
70915:     ** all these opcodes together near the front of the opcode list.  Skip
70916:     ** any opcode that does not need processing by virtual of the fact that
70917:     ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
70918:     */
70919:     if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
70920:       /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
70921:       ** cases from this switch! */
70922:       switch( pOp->opcode ){
70923:         case OP_Transaction: {
70924:           if( pOp->p2!=0 ) p->readOnly = 0;
70925:           /* fall thru */
70926:         }
70927:         case OP_AutoCommit:
70928:         case OP_Savepoint: {
70929:           p->bIsReader = 1;
70930:           break;
70931:         }
70932: #ifndef SQLITE_OMIT_WAL
70933:         case OP_Checkpoint:
70934: #endif
70935:         case OP_Vacuum:
70936:         case OP_JournalMode: {
70937:           p->readOnly = 0;
70938:           p->bIsReader = 1;
70939:           break;
70940:         }
70941: #ifndef SQLITE_OMIT_VIRTUALTABLE
70942:         case OP_VUpdate: {
70943:           if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
70944:           break;
70945:         }
70946:         case OP_VFilter: {
70947:           int n;
70948:           assert( (pOp - p->aOp) >= 3 );
70949:           assert( pOp[-1].opcode==OP_Integer );
70950:           n = pOp[-1].p1;
70951:           if( n>nMaxArgs ) nMaxArgs = n;
70952:           break;
70953:         }
70954: #endif
70955:         case OP_Next:
70956:         case OP_NextIfOpen:
70957:         case OP_SorterNext: {
70958:           pOp->p4.xAdvance = sqlite3BtreeNext;
70959:           pOp->p4type = P4_ADVANCE;
70960:           break;
70961:         }
70962:         case OP_Prev:
70963:         case OP_PrevIfOpen: {
70964:           pOp->p4.xAdvance = sqlite3BtreePrevious;
70965:           pOp->p4type = P4_ADVANCE;
70966:           break;
70967:         }
70968:       }
70969:       if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
70970:         assert( ADDR(pOp->p2)<pParse->nLabel );
70971:         pOp->p2 = aLabel[ADDR(pOp->p2)];
70972:       }
70973:     }
70974:     if( pOp==p->aOp ) break;
70975:     pOp--;
70976:   }
70977:   sqlite3DbFree(p->db, pParse->aLabel);
70978:   pParse->aLabel = 0;
70979:   pParse->nLabel = 0;
70980:   *pMaxFuncArgs = nMaxArgs;
70981:   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
70982: }
70983: 
70984: /*
70985: ** Return the address of the next instruction to be inserted.
70986: */
70987: SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
70988:   assert( p->magic==VDBE_MAGIC_INIT );
70989:   return p->nOp;
70990: }
70991: 
70992: /*
70993: ** Verify that at least N opcode slots are available in p without
70994: ** having to malloc for more space (except when compiled using
70995: ** SQLITE_TEST_REALLOC_STRESS).  This interface is used during testing
70996: ** to verify that certain calls to sqlite3VdbeAddOpList() can never
70997: ** fail due to a OOM fault and hence that the return value from
70998: ** sqlite3VdbeAddOpList() will always be non-NULL.
70999: */
71000: #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
71001: SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
71002:   assert( p->nOp + N <= p->pParse->nOpAlloc );
71003: }
71004: #endif
71005: 
71006: /*
71007: ** This function returns a pointer to the array of opcodes associated with
71008: ** the Vdbe passed as the first argument. It is the callers responsibility
71009: ** to arrange for the returned array to be eventually freed using the 
71010: ** vdbeFreeOpArray() function.
71011: **
71012: ** Before returning, *pnOp is set to the number of entries in the returned
71013: ** array. Also, *pnMaxArg is set to the larger of its current value and 
71014: ** the number of entries in the Vdbe.apArg[] array required to execute the 
71015: ** returned program.
71016: */
71017: SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
71018:   VdbeOp *aOp = p->aOp;
71019:   assert( aOp && !p->db->mallocFailed );
71020: 
71021:   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
71022:   assert( DbMaskAllZero(p->btreeMask) );
71023: 
71024:   resolveP2Values(p, pnMaxArg);
71025:   *pnOp = p->nOp;
71026:   p->aOp = 0;
71027:   return aOp;
71028: }
71029: 
71030: /*
71031: ** Add a whole list of operations to the operation stack.  Return a
71032: ** pointer to the first operation inserted.
71033: **
71034: ** Non-zero P2 arguments to jump instructions are automatically adjusted
71035: ** so that the jump target is relative to the first operation inserted.
71036: */
71037: SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
71038:   Vdbe *p,                     /* Add opcodes to the prepared statement */
71039:   int nOp,                     /* Number of opcodes to add */
71040:   VdbeOpList const *aOp,       /* The opcodes to be added */
71041:   int iLineno                  /* Source-file line number of first opcode */
71042: ){
71043:   int i;
71044:   VdbeOp *pOut, *pFirst;
71045:   assert( nOp>0 );
71046:   assert( p->magic==VDBE_MAGIC_INIT );
71047:   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
71048:     return 0;
71049:   }
71050:   pFirst = pOut = &p->aOp[p->nOp];
71051:   for(i=0; i<nOp; i++, aOp++, pOut++){
71052:     pOut->opcode = aOp->opcode;
71053:     pOut->p1 = aOp->p1;
71054:     pOut->p2 = aOp->p2;
71055:     assert( aOp->p2>=0 );
71056:     if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
71057:       pOut->p2 += p->nOp;
71058:     }
71059:     pOut->p3 = aOp->p3;
71060:     pOut->p4type = P4_NOTUSED;
71061:     pOut->p4.p = 0;
71062:     pOut->p5 = 0;
71063: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71064:     pOut->zComment = 0;
71065: #endif
71066: #ifdef SQLITE_VDBE_COVERAGE
71067:     pOut->iSrcLine = iLineno+i;
71068: #else
71069:     (void)iLineno;
71070: #endif
71071: #ifdef SQLITE_DEBUG
71072:     if( p->db->flags & SQLITE_VdbeAddopTrace ){
71073:       sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
71074:     }
71075: #endif
71076:   }
71077:   p->nOp += nOp;
71078:   return pFirst;
71079: }
71080: 
71081: #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
71082: /*
71083: ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
71084: */
71085: SQLITE_PRIVATE void sqlite3VdbeScanStatus(
71086:   Vdbe *p,                        /* VM to add scanstatus() to */
71087:   int addrExplain,                /* Address of OP_Explain (or 0) */
71088:   int addrLoop,                   /* Address of loop counter */ 
71089:   int addrVisit,                  /* Address of rows visited counter */
71090:   LogEst nEst,                    /* Estimated number of output rows */
71091:   const char *zName               /* Name of table or index being scanned */
71092: ){
71093:   int nByte = (p->nScan+1) * sizeof(ScanStatus);
71094:   ScanStatus *aNew;
71095:   aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
71096:   if( aNew ){
71097:     ScanStatus *pNew = &aNew[p->nScan++];
71098:     pNew->addrExplain = addrExplain;
71099:     pNew->addrLoop = addrLoop;
71100:     pNew->addrVisit = addrVisit;
71101:     pNew->nEst = nEst;
71102:     pNew->zName = sqlite3DbStrDup(p->db, zName);
71103:     p->aScan = aNew;
71104:   }
71105: }
71106: #endif
71107: 
71108: 
71109: /*
71110: ** Change the value of the opcode, or P1, P2, P3, or P5 operands
71111: ** for a specific instruction.
71112: */
71113: SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
71114:   sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
71115: }
71116: SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
71117:   sqlite3VdbeGetOp(p,addr)->p1 = val;
71118: }
71119: SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
71120:   sqlite3VdbeGetOp(p,addr)->p2 = val;
71121: }
71122: SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
71123:   sqlite3VdbeGetOp(p,addr)->p3 = val;
71124: }
71125: SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 p5){
71126:   if( !p->db->mallocFailed ) p->aOp[p->nOp-1].p5 = p5;
71127: }
71128: 
71129: /*
71130: ** Change the P2 operand of instruction addr so that it points to
71131: ** the address of the next instruction to be coded.
71132: */
71133: SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
71134:   p->pParse->iFixedOp = p->nOp - 1;
71135:   sqlite3VdbeChangeP2(p, addr, p->nOp);
71136: }
71137: 
71138: 
71139: /*
71140: ** If the input FuncDef structure is ephemeral, then free it.  If
71141: ** the FuncDef is not ephermal, then do nothing.
71142: */
71143: static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
71144:   if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
71145:     sqlite3DbFree(db, pDef);
71146:   }
71147: }
71148: 
71149: static void vdbeFreeOpArray(sqlite3 *, Op *, int);
71150: 
71151: /*
71152: ** Delete a P4 value if necessary.
71153: */
71154: static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
71155:   if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71156:   sqlite3DbFree(db, p);
71157: }
71158: static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
71159:   freeEphemeralFunction(db, p->pFunc);
71160:   sqlite3DbFree(db, p);
71161: }
71162: static void freeP4(sqlite3 *db, int p4type, void *p4){
71163:   assert( db );
71164:   switch( p4type ){
71165:     case P4_FUNCCTX: {
71166:       freeP4FuncCtx(db, (sqlite3_context*)p4);
71167:       break;
71168:     }
71169:     case P4_REAL:
71170:     case P4_INT64:
71171:     case P4_DYNAMIC:
71172:     case P4_INTARRAY: {
71173:       sqlite3DbFree(db, p4);
71174:       break;
71175:     }
71176:     case P4_KEYINFO: {
71177:       if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
71178:       break;
71179:     }
71180: #ifdef SQLITE_ENABLE_CURSOR_HINTS
71181:     case P4_EXPR: {
71182:       sqlite3ExprDelete(db, (Expr*)p4);
71183:       break;
71184:     }
71185: #endif
71186:     case P4_MPRINTF: {
71187:       if( db->pnBytesFreed==0 ) sqlite3_free(p4);
71188:       break;
71189:     }
71190:     case P4_FUNCDEF: {
71191:       freeEphemeralFunction(db, (FuncDef*)p4);
71192:       break;
71193:     }
71194:     case P4_MEM: {
71195:       if( db->pnBytesFreed==0 ){
71196:         sqlite3ValueFree((sqlite3_value*)p4);
71197:       }else{
71198:         freeP4Mem(db, (Mem*)p4);
71199:       }
71200:       break;
71201:     }
71202:     case P4_VTAB : {
71203:       if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
71204:       break;
71205:     }
71206:   }
71207: }
71208: 
71209: /*
71210: ** Free the space allocated for aOp and any p4 values allocated for the
71211: ** opcodes contained within. If aOp is not NULL it is assumed to contain 
71212: ** nOp entries. 
71213: */
71214: static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
71215:   if( aOp ){
71216:     Op *pOp;
71217:     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
71218:       if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
71219: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71220:       sqlite3DbFree(db, pOp->zComment);
71221: #endif     
71222:     }
71223:   }
71224:   sqlite3DbFree(db, aOp);
71225: }
71226: 
71227: /*
71228: ** Link the SubProgram object passed as the second argument into the linked
71229: ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
71230: ** objects when the VM is no longer required.
71231: */
71232: SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
71233:   p->pNext = pVdbe->pProgram;
71234:   pVdbe->pProgram = p;
71235: }
71236: 
71237: /*
71238: ** Change the opcode at addr into OP_Noop
71239: */
71240: SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
71241:   VdbeOp *pOp;
71242:   if( p->db->mallocFailed ) return 0;
71243:   assert( addr>=0 && addr<p->nOp );
71244:   pOp = &p->aOp[addr];
71245:   freeP4(p->db, pOp->p4type, pOp->p4.p);
71246:   pOp->p4type = P4_NOTUSED;
71247:   pOp->p4.z = 0;
71248:   pOp->opcode = OP_Noop;
71249:   return 1;
71250: }
71251: 
71252: /*
71253: ** If the last opcode is "op" and it is not a jump destination,
71254: ** then remove it.  Return true if and only if an opcode was removed.
71255: */
71256: SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
71257:   if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
71258:     return sqlite3VdbeChangeToNoop(p, p->nOp-1);
71259:   }else{
71260:     return 0;
71261:   }
71262: }
71263: 
71264: /*
71265: ** Change the value of the P4 operand for a specific instruction.
71266: ** This routine is useful when a large program is loaded from a
71267: ** static array using sqlite3VdbeAddOpList but we want to make a
71268: ** few minor changes to the program.
71269: **
71270: ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
71271: ** the string is made into memory obtained from sqlite3_malloc().
71272: ** A value of n==0 means copy bytes of zP4 up to and including the
71273: ** first null byte.  If n>0 then copy n+1 bytes of zP4.
71274: ** 
71275: ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
71276: ** to a string or structure that is guaranteed to exist for the lifetime of
71277: ** the Vdbe. In these cases we can just copy the pointer.
71278: **
71279: ** If addr<0 then change P4 on the most recently inserted instruction.
71280: */
71281: static void SQLITE_NOINLINE vdbeChangeP4Full(
71282:   Vdbe *p,
71283:   Op *pOp,
71284:   const char *zP4,
71285:   int n
71286: ){
71287:   if( pOp->p4type ){
71288:     freeP4(p->db, pOp->p4type, pOp->p4.p);
71289:     pOp->p4type = 0;
71290:     pOp->p4.p = 0;
71291:   }
71292:   if( n<0 ){
71293:     sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
71294:   }else{
71295:     if( n==0 ) n = sqlite3Strlen30(zP4);
71296:     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
71297:     pOp->p4type = P4_DYNAMIC;
71298:   }
71299: }
71300: SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
71301:   Op *pOp;
71302:   sqlite3 *db;
71303:   assert( p!=0 );
71304:   db = p->db;
71305:   assert( p->magic==VDBE_MAGIC_INIT );
71306:   assert( p->aOp!=0 || db->mallocFailed );
71307:   if( db->mallocFailed ){
71308:     if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
71309:     return;
71310:   }
71311:   assert( p->nOp>0 );
71312:   assert( addr<p->nOp );
71313:   if( addr<0 ){
71314:     addr = p->nOp - 1;
71315:   }
71316:   pOp = &p->aOp[addr];
71317:   if( n>=0 || pOp->p4type ){
71318:     vdbeChangeP4Full(p, pOp, zP4, n);
71319:     return;
71320:   }
71321:   if( n==P4_INT32 ){
71322:     /* Note: this cast is safe, because the origin data point was an int
71323:     ** that was cast to a (const char *). */
71324:     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
71325:     pOp->p4type = P4_INT32;
71326:   }else if( zP4!=0 ){
71327:     assert( n<0 );
71328:     pOp->p4.p = (void*)zP4;
71329:     pOp->p4type = (signed char)n;
71330:     if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
71331:   }
71332: }
71333: 
71334: /*
71335: ** Set the P4 on the most recently added opcode to the KeyInfo for the
71336: ** index given.
71337: */
71338: SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
71339:   Vdbe *v = pParse->pVdbe;
71340:   assert( v!=0 );
71341:   assert( pIdx!=0 );
71342:   sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
71343:                       P4_KEYINFO);
71344: }
71345: 
71346: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71347: /*
71348: ** Change the comment on the most recently coded instruction.  Or
71349: ** insert a No-op and add the comment to that new instruction.  This
71350: ** makes the code easier to read during debugging.  None of this happens
71351: ** in a production build.
71352: */
71353: static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
71354:   assert( p->nOp>0 || p->aOp==0 );
71355:   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
71356:   if( p->nOp ){
71357:     assert( p->aOp );
71358:     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
71359:     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
71360:   }
71361: }
71362: SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
71363:   va_list ap;
71364:   if( p ){
71365:     va_start(ap, zFormat);
71366:     vdbeVComment(p, zFormat, ap);
71367:     va_end(ap);
71368:   }
71369: }
71370: SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
71371:   va_list ap;
71372:   if( p ){
71373:     sqlite3VdbeAddOp0(p, OP_Noop);
71374:     va_start(ap, zFormat);
71375:     vdbeVComment(p, zFormat, ap);
71376:     va_end(ap);
71377:   }
71378: }
71379: #endif  /* NDEBUG */
71380: 
71381: #ifdef SQLITE_VDBE_COVERAGE
71382: /*
71383: ** Set the value if the iSrcLine field for the previously coded instruction.
71384: */
71385: SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
71386:   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
71387: }
71388: #endif /* SQLITE_VDBE_COVERAGE */
71389: 
71390: /*
71391: ** Return the opcode for a given address.  If the address is -1, then
71392: ** return the most recently inserted opcode.
71393: **
71394: ** If a memory allocation error has occurred prior to the calling of this
71395: ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
71396: ** is readable but not writable, though it is cast to a writable value.
71397: ** The return of a dummy opcode allows the call to continue functioning
71398: ** after an OOM fault without having to check to see if the return from 
71399: ** this routine is a valid pointer.  But because the dummy.opcode is 0,
71400: ** dummy will never be written to.  This is verified by code inspection and
71401: ** by running with Valgrind.
71402: */
71403: SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
71404:   /* C89 specifies that the constant "dummy" will be initialized to all
71405:   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
71406:   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
71407:   assert( p->magic==VDBE_MAGIC_INIT );
71408:   if( addr<0 ){
71409:     addr = p->nOp - 1;
71410:   }
71411:   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
71412:   if( p->db->mallocFailed ){
71413:     return (VdbeOp*)&dummy;
71414:   }else{
71415:     return &p->aOp[addr];
71416:   }
71417: }
71418: 
71419: #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
71420: /*
71421: ** Return an integer value for one of the parameters to the opcode pOp
71422: ** determined by character c.
71423: */
71424: static int translateP(char c, const Op *pOp){
71425:   if( c=='1' ) return pOp->p1;
71426:   if( c=='2' ) return pOp->p2;
71427:   if( c=='3' ) return pOp->p3;
71428:   if( c=='4' ) return pOp->p4.i;
71429:   return pOp->p5;
71430: }
71431: 
71432: /*
71433: ** Compute a string for the "comment" field of a VDBE opcode listing.
71434: **
71435: ** The Synopsis: field in comments in the vdbe.c source file gets converted
71436: ** to an extra string that is appended to the sqlite3OpcodeName().  In the
71437: ** absence of other comments, this synopsis becomes the comment on the opcode.
71438: ** Some translation occurs:
71439: **
71440: **       "PX"      ->  "r[X]"
71441: **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
71442: **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
71443: **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
71444: */
71445: static int displayComment(
71446:   const Op *pOp,     /* The opcode to be commented */
71447:   const char *zP4,   /* Previously obtained value for P4 */
71448:   char *zTemp,       /* Write result here */
71449:   int nTemp          /* Space available in zTemp[] */
71450: ){
71451:   const char *zOpName;
71452:   const char *zSynopsis;
71453:   int nOpName;
71454:   int ii, jj;
71455:   char zAlt[50];
71456:   zOpName = sqlite3OpcodeName(pOp->opcode);
71457:   nOpName = sqlite3Strlen30(zOpName);
71458:   if( zOpName[nOpName+1] ){
71459:     int seenCom = 0;
71460:     char c;
71461:     zSynopsis = zOpName += nOpName + 1;
71462:     if( strncmp(zSynopsis,"IF ",3)==0 ){
71463:       if( pOp->p5 & SQLITE_STOREP2 ){
71464:         sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
71465:       }else{
71466:         sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
71467:       }
71468:       zSynopsis = zAlt;
71469:     }
71470:     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
71471:       if( c=='P' ){
71472:         c = zSynopsis[++ii];
71473:         if( c=='4' ){
71474:           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
71475:         }else if( c=='X' ){
71476:           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
71477:           seenCom = 1;
71478:         }else{
71479:           int v1 = translateP(c, pOp);
71480:           int v2;
71481:           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
71482:           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
71483:             ii += 3;
71484:             jj += sqlite3Strlen30(zTemp+jj);
71485:             v2 = translateP(zSynopsis[ii], pOp);
71486:             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
71487:               ii += 2;
71488:               v2++;
71489:             }
71490:             if( v2>1 ){
71491:               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
71492:             }
71493:           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
71494:             ii += 4;
71495:           }
71496:         }
71497:         jj += sqlite3Strlen30(zTemp+jj);
71498:       }else{
71499:         zTemp[jj++] = c;
71500:       }
71501:     }
71502:     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
71503:       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
71504:       jj += sqlite3Strlen30(zTemp+jj);
71505:     }
71506:     if( jj<nTemp ) zTemp[jj] = 0;
71507:   }else if( pOp->zComment ){
71508:     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
71509:     jj = sqlite3Strlen30(zTemp);
71510:   }else{
71511:     zTemp[0] = 0;
71512:     jj = 0;
71513:   }
71514:   return jj;
71515: }
71516: #endif /* SQLITE_DEBUG */
71517: 
71518: #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
71519: /*
71520: ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
71521: ** that can be displayed in the P4 column of EXPLAIN output.
71522: */
71523: static void displayP4Expr(StrAccum *p, Expr *pExpr){
71524:   const char *zOp = 0;
71525:   switch( pExpr->op ){
71526:     case TK_STRING:
71527:       sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
71528:       break;
71529:     case TK_INTEGER:
71530:       sqlite3XPrintf(p, "%d", pExpr->u.iValue);
71531:       break;
71532:     case TK_NULL:
71533:       sqlite3XPrintf(p, "NULL");
71534:       break;
71535:     case TK_REGISTER: {
71536:       sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
71537:       break;
71538:     }
71539:     case TK_COLUMN: {
71540:       if( pExpr->iColumn<0 ){
71541:         sqlite3XPrintf(p, "rowid");
71542:       }else{
71543:         sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
71544:       }
71545:       break;
71546:     }
71547:     case TK_LT:      zOp = "LT";      break;
71548:     case TK_LE:      zOp = "LE";      break;
71549:     case TK_GT:      zOp = "GT";      break;
71550:     case TK_GE:      zOp = "GE";      break;
71551:     case TK_NE:      zOp = "NE";      break;
71552:     case TK_EQ:      zOp = "EQ";      break;
71553:     case TK_IS:      zOp = "IS";      break;
71554:     case TK_ISNOT:   zOp = "ISNOT";   break;
71555:     case TK_AND:     zOp = "AND";     break;
71556:     case TK_OR:      zOp = "OR";      break;
71557:     case TK_PLUS:    zOp = "ADD";     break;
71558:     case TK_STAR:    zOp = "MUL";     break;
71559:     case TK_MINUS:   zOp = "SUB";     break;
71560:     case TK_REM:     zOp = "REM";     break;
71561:     case TK_BITAND:  zOp = "BITAND";  break;
71562:     case TK_BITOR:   zOp = "BITOR";   break;
71563:     case TK_SLASH:   zOp = "DIV";     break;
71564:     case TK_LSHIFT:  zOp = "LSHIFT";  break;
71565:     case TK_RSHIFT:  zOp = "RSHIFT";  break;
71566:     case TK_CONCAT:  zOp = "CONCAT";  break;
71567:     case TK_UMINUS:  zOp = "MINUS";   break;
71568:     case TK_UPLUS:   zOp = "PLUS";    break;
71569:     case TK_BITNOT:  zOp = "BITNOT";  break;
71570:     case TK_NOT:     zOp = "NOT";     break;
71571:     case TK_ISNULL:  zOp = "ISNULL";  break;
71572:     case TK_NOTNULL: zOp = "NOTNULL"; break;
71573: 
71574:     default:
71575:       sqlite3XPrintf(p, "%s", "expr");
71576:       break;
71577:   }
71578: 
71579:   if( zOp ){
71580:     sqlite3XPrintf(p, "%s(", zOp);
71581:     displayP4Expr(p, pExpr->pLeft);
71582:     if( pExpr->pRight ){
71583:       sqlite3StrAccumAppend(p, ",", 1);
71584:       displayP4Expr(p, pExpr->pRight);
71585:     }
71586:     sqlite3StrAccumAppend(p, ")", 1);
71587:   }
71588: }
71589: #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
71590: 
71591: 
71592: #if VDBE_DISPLAY_P4
71593: /*
71594: ** Compute a string that describes the P4 parameter for an opcode.
71595: ** Use zTemp for any required temporary buffer space.
71596: */
71597: static char *displayP4(Op *pOp, char *zTemp, int nTemp){
71598:   char *zP4 = zTemp;
71599:   StrAccum x;
71600:   assert( nTemp>=20 );
71601:   sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
71602:   switch( pOp->p4type ){
71603:     case P4_KEYINFO: {
71604:       int j;
71605:       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
71606:       assert( pKeyInfo->aSortOrder!=0 );
71607:       sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
71608:       for(j=0; j<pKeyInfo->nField; j++){
71609:         CollSeq *pColl = pKeyInfo->aColl[j];
71610:         const char *zColl = pColl ? pColl->zName : "";
71611:         if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
71612:         sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
71613:       }
71614:       sqlite3StrAccumAppend(&x, ")", 1);
71615:       break;
71616:     }
71617: #ifdef SQLITE_ENABLE_CURSOR_HINTS
71618:     case P4_EXPR: {
71619:       displayP4Expr(&x, pOp->p4.pExpr);
71620:       break;
71621:     }
71622: #endif
71623:     case P4_COLLSEQ: {
71624:       CollSeq *pColl = pOp->p4.pColl;
71625:       sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
71626:       break;
71627:     }
71628:     case P4_FUNCDEF: {
71629:       FuncDef *pDef = pOp->p4.pFunc;
71630:       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71631:       break;
71632:     }
71633: #ifdef SQLITE_DEBUG
71634:     case P4_FUNCCTX: {
71635:       FuncDef *pDef = pOp->p4.pCtx->pFunc;
71636:       sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71637:       break;
71638:     }
71639: #endif
71640:     case P4_INT64: {
71641:       sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
71642:       break;
71643:     }
71644:     case P4_INT32: {
71645:       sqlite3XPrintf(&x, "%d", pOp->p4.i);
71646:       break;
71647:     }
71648:     case P4_REAL: {
71649:       sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
71650:       break;
71651:     }
71652:     case P4_MEM: {
71653:       Mem *pMem = pOp->p4.pMem;
71654:       if( pMem->flags & MEM_Str ){
71655:         zP4 = pMem->z;
71656:       }else if( pMem->flags & MEM_Int ){
71657:         sqlite3XPrintf(&x, "%lld", pMem->u.i);
71658:       }else if( pMem->flags & MEM_Real ){
71659:         sqlite3XPrintf(&x, "%.16g", pMem->u.r);
71660:       }else if( pMem->flags & MEM_Null ){
71661:         zP4 = "NULL";
71662:       }else{
71663:         assert( pMem->flags & MEM_Blob );
71664:         zP4 = "(blob)";
71665:       }
71666:       break;
71667:     }
71668: #ifndef SQLITE_OMIT_VIRTUALTABLE
71669:     case P4_VTAB: {
71670:       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
71671:       sqlite3XPrintf(&x, "vtab:%p", pVtab);
71672:       break;
71673:     }
71674: #endif
71675:     case P4_INTARRAY: {
71676:       int i;
71677:       int *ai = pOp->p4.ai;
71678:       int n = ai[0];   /* The first element of an INTARRAY is always the
71679:                        ** count of the number of elements to follow */
71680:       for(i=1; i<n; i++){
71681:         sqlite3XPrintf(&x, ",%d", ai[i]);
71682:       }
71683:       zTemp[0] = '[';
71684:       sqlite3StrAccumAppend(&x, "]", 1);
71685:       break;
71686:     }
71687:     case P4_SUBPROGRAM: {
71688:       sqlite3XPrintf(&x, "program");
71689:       break;
71690:     }
71691:     case P4_ADVANCE: {
71692:       zTemp[0] = 0;
71693:       break;
71694:     }
71695:     case P4_TABLE: {
71696:       sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71697:       break;
71698:     }
71699:     default: {
71700:       zP4 = pOp->p4.z;
71701:       if( zP4==0 ){
71702:         zP4 = zTemp;
71703:         zTemp[0] = 0;
71704:       }
71705:     }
71706:   }
71707:   sqlite3StrAccumFinish(&x);
71708:   assert( zP4!=0 );
71709:   return zP4;
71710: }
71711: #endif /* VDBE_DISPLAY_P4 */
71712: 
71713: /*
71714: ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
71715: **
71716: ** The prepared statements need to know in advance the complete set of
71717: ** attached databases that will be use.  A mask of these databases
71718: ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
71719: ** p->btreeMask of databases that will require a lock.
71720: */
71721: SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
71722:   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
71723:   assert( i<(int)sizeof(p->btreeMask)*8 );
71724:   DbMaskSet(p->btreeMask, i);
71725:   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
71726:     DbMaskSet(p->lockMask, i);
71727:   }
71728: }
71729: 
71730: #if !defined(SQLITE_OMIT_SHARED_CACHE)
71731: /*
71732: ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
71733: ** this routine obtains the mutex associated with each BtShared structure
71734: ** that may be accessed by the VM passed as an argument. In doing so it also
71735: ** sets the BtShared.db member of each of the BtShared structures, ensuring
71736: ** that the correct busy-handler callback is invoked if required.
71737: **
71738: ** If SQLite is not threadsafe but does support shared-cache mode, then
71739: ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
71740: ** of all of BtShared structures accessible via the database handle 
71741: ** associated with the VM.
71742: **
71743: ** If SQLite is not threadsafe and does not support shared-cache mode, this
71744: ** function is a no-op.
71745: **
71746: ** The p->btreeMask field is a bitmask of all btrees that the prepared 
71747: ** statement p will ever use.  Let N be the number of bits in p->btreeMask
71748: ** corresponding to btrees that use shared cache.  Then the runtime of
71749: ** this routine is N*N.  But as N is rarely more than 1, this should not
71750: ** be a problem.
71751: */
71752: SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
71753:   int i;
71754:   sqlite3 *db;
71755:   Db *aDb;
71756:   int nDb;
71757:   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
71758:   db = p->db;
71759:   aDb = db->aDb;
71760:   nDb = db->nDb;
71761:   for(i=0; i<nDb; i++){
71762:     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71763:       sqlite3BtreeEnter(aDb[i].pBt);
71764:     }
71765:   }
71766: }
71767: #endif
71768: 
71769: #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
71770: /*
71771: ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
71772: */
71773: static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
71774:   int i;
71775:   sqlite3 *db;
71776:   Db *aDb;
71777:   int nDb;
71778:   db = p->db;
71779:   aDb = db->aDb;
71780:   nDb = db->nDb;
71781:   for(i=0; i<nDb; i++){
71782:     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71783:       sqlite3BtreeLeave(aDb[i].pBt);
71784:     }
71785:   }
71786: }
71787: SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
71788:   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
71789:   vdbeLeave(p);
71790: }
71791: #endif
71792: 
71793: #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
71794: /*
71795: ** Print a single opcode.  This routine is used for debugging only.
71796: */
71797: SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
71798:   char *zP4;
71799:   char zPtr[50];
71800:   char zCom[100];
71801:   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
71802:   if( pOut==0 ) pOut = stdout;
71803:   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
71804: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71805:   displayComment(pOp, zP4, zCom, sizeof(zCom));
71806: #else
71807:   zCom[0] = 0;
71808: #endif
71809:   /* NB:  The sqlite3OpcodeName() function is implemented by code created
71810:   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
71811:   ** information from the vdbe.c source text */
71812:   fprintf(pOut, zFormat1, pc, 
71813:       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
71814:       zCom
71815:   );
71816:   fflush(pOut);
71817: }
71818: #endif
71819: 
71820: /*
71821: ** Release an array of N Mem elements
71822: */
71823: static void releaseMemArray(Mem *p, int N){
71824:   if( p && N ){
71825:     Mem *pEnd = &p[N];
71826:     sqlite3 *db = p->db;
71827:     if( db->pnBytesFreed ){
71828:       do{
71829:         if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71830:       }while( (++p)<pEnd );
71831:       return;
71832:     }
71833:     do{
71834:       assert( (&p[1])==pEnd || p[0].db==p[1].db );
71835:       assert( sqlite3VdbeCheckMemInvariants(p) );
71836: 
71837:       /* This block is really an inlined version of sqlite3VdbeMemRelease()
71838:       ** that takes advantage of the fact that the memory cell value is 
71839:       ** being set to NULL after releasing any dynamic resources.
71840:       **
71841:       ** The justification for duplicating code is that according to 
71842:       ** callgrind, this causes a certain test case to hit the CPU 4.7 
71843:       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
71844:       ** sqlite3MemRelease() were called from here. With -O2, this jumps
71845:       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
71846:       ** with no indexes using a single prepared INSERT statement, bind() 
71847:       ** and reset(). Inserts are grouped into a transaction.
71848:       */
71849:       testcase( p->flags & MEM_Agg );
71850:       testcase( p->flags & MEM_Dyn );
71851:       testcase( p->flags & MEM_Frame );
71852:       testcase( p->flags & MEM_RowSet );
71853:       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
71854:         sqlite3VdbeMemRelease(p);
71855:       }else if( p->szMalloc ){
71856:         sqlite3DbFree(db, p->zMalloc);
71857:         p->szMalloc = 0;
71858:       }
71859: 
71860:       p->flags = MEM_Undefined;
71861:     }while( (++p)<pEnd );
71862:   }
71863: }
71864: 
71865: /*
71866: ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
71867: ** allocated by the OP_Program opcode in sqlite3VdbeExec().
71868: */
71869: SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
71870:   int i;
71871:   Mem *aMem = VdbeFrameMem(p);
71872:   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
71873:   for(i=0; i<p->nChildCsr; i++){
71874:     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
71875:   }
71876:   releaseMemArray(aMem, p->nChildMem);
71877:   sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
71878:   sqlite3DbFree(p->v->db, p);
71879: }
71880: 
71881: #ifndef SQLITE_OMIT_EXPLAIN
71882: /*
71883: ** Give a listing of the program in the virtual machine.
71884: **
71885: ** The interface is the same as sqlite3VdbeExec().  But instead of
71886: ** running the code, it invokes the callback once for each instruction.
71887: ** This feature is used to implement "EXPLAIN".
71888: **
71889: ** When p->explain==1, each instruction is listed.  When
71890: ** p->explain==2, only OP_Explain instructions are listed and these
71891: ** are shown in a different format.  p->explain==2 is used to implement
71892: ** EXPLAIN QUERY PLAN.
71893: **
71894: ** When p->explain==1, first the main program is listed, then each of
71895: ** the trigger subprograms are listed one by one.
71896: */
71897: SQLITE_PRIVATE int sqlite3VdbeList(
71898:   Vdbe *p                   /* The VDBE */
71899: ){
71900:   int nRow;                            /* Stop when row count reaches this */
71901:   int nSub = 0;                        /* Number of sub-vdbes seen so far */
71902:   SubProgram **apSub = 0;              /* Array of sub-vdbes */
71903:   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
71904:   sqlite3 *db = p->db;                 /* The database connection */
71905:   int i;                               /* Loop counter */
71906:   int rc = SQLITE_OK;                  /* Return code */
71907:   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
71908: 
71909:   assert( p->explain );
71910:   assert( p->magic==VDBE_MAGIC_RUN );
71911:   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
71912: 
71913:   /* Even though this opcode does not use dynamic strings for
71914:   ** the result, result columns may become dynamic if the user calls
71915:   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
71916:   */
71917:   releaseMemArray(pMem, 8);
71918:   p->pResultSet = 0;
71919: 
71920:   if( p->rc==SQLITE_NOMEM_BKPT ){
71921:     /* This happens if a malloc() inside a call to sqlite3_column_text() or
71922:     ** sqlite3_column_text16() failed.  */
71923:     sqlite3OomFault(db);
71924:     return SQLITE_ERROR;
71925:   }
71926: 
71927:   /* When the number of output rows reaches nRow, that means the
71928:   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
71929:   ** nRow is the sum of the number of rows in the main program, plus
71930:   ** the sum of the number of rows in all trigger subprograms encountered
71931:   ** so far.  The nRow value will increase as new trigger subprograms are
71932:   ** encountered, but p->pc will eventually catch up to nRow.
71933:   */
71934:   nRow = p->nOp;
71935:   if( p->explain==1 ){
71936:     /* The first 8 memory cells are used for the result set.  So we will
71937:     ** commandeer the 9th cell to use as storage for an array of pointers
71938:     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
71939:     ** cells.  */
71940:     assert( p->nMem>9 );
71941:     pSub = &p->aMem[9];
71942:     if( pSub->flags&MEM_Blob ){
71943:       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
71944:       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
71945:       nSub = pSub->n/sizeof(Vdbe*);
71946:       apSub = (SubProgram **)pSub->z;
71947:     }
71948:     for(i=0; i<nSub; i++){
71949:       nRow += apSub[i]->nOp;
71950:     }
71951:   }
71952: 
71953:   do{
71954:     i = p->pc++;
71955:   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
71956:   if( i>=nRow ){
71957:     p->rc = SQLITE_OK;
71958:     rc = SQLITE_DONE;
71959:   }else if( db->u1.isInterrupted ){
71960:     p->rc = SQLITE_INTERRUPT;
71961:     rc = SQLITE_ERROR;
71962:     sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
71963:   }else{
71964:     char *zP4;
71965:     Op *pOp;
71966:     if( i<p->nOp ){
71967:       /* The output line number is small enough that we are still in the
71968:       ** main program. */
71969:       pOp = &p->aOp[i];
71970:     }else{
71971:       /* We are currently listing subprograms.  Figure out which one and
71972:       ** pick up the appropriate opcode. */
71973:       int j;
71974:       i -= p->nOp;
71975:       for(j=0; i>=apSub[j]->nOp; j++){
71976:         i -= apSub[j]->nOp;
71977:       }
71978:       pOp = &apSub[j]->aOp[i];
71979:     }
71980:     if( p->explain==1 ){
71981:       pMem->flags = MEM_Int;
71982:       pMem->u.i = i;                                /* Program counter */
71983:       pMem++;
71984:   
71985:       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
71986:       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
71987:       assert( pMem->z!=0 );
71988:       pMem->n = sqlite3Strlen30(pMem->z);
71989:       pMem->enc = SQLITE_UTF8;
71990:       pMem++;
71991: 
71992:       /* When an OP_Program opcode is encounter (the only opcode that has
71993:       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
71994:       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
71995:       ** has not already been seen.
71996:       */
71997:       if( pOp->p4type==P4_SUBPROGRAM ){
71998:         int nByte = (nSub+1)*sizeof(SubProgram*);
71999:         int j;
72000:         for(j=0; j<nSub; j++){
72001:           if( apSub[j]==pOp->p4.pProgram ) break;
72002:         }
72003:         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
72004:           apSub = (SubProgram **)pSub->z;
72005:           apSub[nSub++] = pOp->p4.pProgram;
72006:           pSub->flags |= MEM_Blob;
72007:           pSub->n = nSub*sizeof(SubProgram*);
72008:         }
72009:       }
72010:     }
72011: 
72012:     pMem->flags = MEM_Int;
72013:     pMem->u.i = pOp->p1;                          /* P1 */
72014:     pMem++;
72015: 
72016:     pMem->flags = MEM_Int;
72017:     pMem->u.i = pOp->p2;                          /* P2 */
72018:     pMem++;
72019: 
72020:     pMem->flags = MEM_Int;
72021:     pMem->u.i = pOp->p3;                          /* P3 */
72022:     pMem++;
72023: 
72024:     if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
72025:       assert( p->db->mallocFailed );
72026:       return SQLITE_ERROR;
72027:     }
72028:     pMem->flags = MEM_Str|MEM_Term;
72029:     zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
72030:     if( zP4!=pMem->z ){
72031:       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
72032:     }else{
72033:       assert( pMem->z!=0 );
72034:       pMem->n = sqlite3Strlen30(pMem->z);
72035:       pMem->enc = SQLITE_UTF8;
72036:     }
72037:     pMem++;
72038: 
72039:     if( p->explain==1 ){
72040:       if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
72041:         assert( p->db->mallocFailed );
72042:         return SQLITE_ERROR;
72043:       }
72044:       pMem->flags = MEM_Str|MEM_Term;
72045:       pMem->n = 2;
72046:       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
72047:       pMem->enc = SQLITE_UTF8;
72048:       pMem++;
72049:   
72050: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
72051:       if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
72052:         assert( p->db->mallocFailed );
72053:         return SQLITE_ERROR;
72054:       }
72055:       pMem->flags = MEM_Str|MEM_Term;
72056:       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
72057:       pMem->enc = SQLITE_UTF8;
72058: #else
72059:       pMem->flags = MEM_Null;                       /* Comment */
72060: #endif
72061:     }
72062: 
72063:     p->nResColumn = 8 - 4*(p->explain-1);
72064:     p->pResultSet = &p->aMem[1];
72065:     p->rc = SQLITE_OK;
72066:     rc = SQLITE_ROW;
72067:   }
72068:   return rc;
72069: }
72070: #endif /* SQLITE_OMIT_EXPLAIN */
72071: 
72072: #ifdef SQLITE_DEBUG
72073: /*
72074: ** Print the SQL that was used to generate a VDBE program.
72075: */
72076: SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
72077:   const char *z = 0;
72078:   if( p->zSql ){
72079:     z = p->zSql;
72080:   }else if( p->nOp>=1 ){
72081:     const VdbeOp *pOp = &p->aOp[0];
72082:     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72083:       z = pOp->p4.z;
72084:       while( sqlite3Isspace(*z) ) z++;
72085:     }
72086:   }
72087:   if( z ) printf("SQL: [%s]\n", z);
72088: }
72089: #endif
72090: 
72091: #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
72092: /*
72093: ** Print an IOTRACE message showing SQL content.
72094: */
72095: SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
72096:   int nOp = p->nOp;
72097:   VdbeOp *pOp;
72098:   if( sqlite3IoTrace==0 ) return;
72099:   if( nOp<1 ) return;
72100:   pOp = &p->aOp[0];
72101:   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
72102:     int i, j;
72103:     char z[1000];
72104:     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
72105:     for(i=0; sqlite3Isspace(z[i]); i++){}
72106:     for(j=0; z[i]; i++){
72107:       if( sqlite3Isspace(z[i]) ){
72108:         if( z[i-1]!=' ' ){
72109:           z[j++] = ' ';
72110:         }
72111:       }else{
72112:         z[j++] = z[i];
72113:       }
72114:     }
72115:     z[j] = 0;
72116:     sqlite3IoTrace("SQL %s\n", z);
72117:   }
72118: }
72119: #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
72120: 
72121: /* An instance of this object describes bulk memory available for use
72122: ** by subcomponents of a prepared statement.  Space is allocated out
72123: ** of a ReusableSpace object by the allocSpace() routine below.
72124: */
72125: struct ReusableSpace {
72126:   u8 *pSpace;          /* Available memory */
72127:   int nFree;           /* Bytes of available memory */
72128:   int nNeeded;         /* Total bytes that could not be allocated */
72129: };
72130: 
72131: /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
72132: ** from the ReusableSpace object.  Return a pointer to the allocated
72133: ** memory on success.  If insufficient memory is available in the
72134: ** ReusableSpace object, increase the ReusableSpace.nNeeded
72135: ** value by the amount needed and return NULL.
72136: **
72137: ** If pBuf is not initially NULL, that means that the memory has already
72138: ** been allocated by a prior call to this routine, so just return a copy
72139: ** of pBuf and leave ReusableSpace unchanged.
72140: **
72141: ** This allocator is employed to repurpose unused slots at the end of the
72142: ** opcode array of prepared state for other memory needs of the prepared
72143: ** statement.
72144: */
72145: static void *allocSpace(
72146:   struct ReusableSpace *p,  /* Bulk memory available for allocation */
72147:   void *pBuf,               /* Pointer to a prior allocation */
72148:   int nByte                 /* Bytes of memory needed */
72149: ){
72150:   assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
72151:   if( pBuf==0 ){
72152:     nByte = ROUND8(nByte);
72153:     if( nByte <= p->nFree ){
72154:       p->nFree -= nByte;
72155:       pBuf = &p->pSpace[p->nFree];
72156:     }else{
72157:       p->nNeeded += nByte;
72158:     }
72159:   }
72160:   assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
72161:   return pBuf;
72162: }
72163: 
72164: /*
72165: ** Rewind the VDBE back to the beginning in preparation for
72166: ** running it.
72167: */
72168: SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
72169: #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
72170:   int i;
72171: #endif
72172:   assert( p!=0 );
72173:   assert( p->magic==VDBE_MAGIC_INIT );
72174: 
72175:   /* There should be at least one opcode.
72176:   */
72177:   assert( p->nOp>0 );
72178: 
72179:   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
72180:   p->magic = VDBE_MAGIC_RUN;
72181: 
72182: #ifdef SQLITE_DEBUG
72183:   for(i=0; i<p->nMem; i++){
72184:     assert( p->aMem[i].db==p->db );
72185:   }
72186: #endif
72187:   p->pc = -1;
72188:   p->rc = SQLITE_OK;
72189:   p->errorAction = OE_Abort;
72190:   p->nChange = 0;
72191:   p->cacheCtr = 1;
72192:   p->minWriteFileFormat = 255;
72193:   p->iStatement = 0;
72194:   p->nFkConstraint = 0;
72195: #ifdef VDBE_PROFILE
72196:   for(i=0; i<p->nOp; i++){
72197:     p->aOp[i].cnt = 0;
72198:     p->aOp[i].cycles = 0;
72199:   }
72200: #endif
72201: }
72202: 
72203: /*
72204: ** Prepare a virtual machine for execution for the first time after
72205: ** creating the virtual machine.  This involves things such
72206: ** as allocating registers and initializing the program counter.
72207: ** After the VDBE has be prepped, it can be executed by one or more
72208: ** calls to sqlite3VdbeExec().  
72209: **
72210: ** This function may be called exactly once on each virtual machine.
72211: ** After this routine is called the VM has been "packaged" and is ready
72212: ** to run.  After this routine is called, further calls to 
72213: ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
72214: ** the Vdbe from the Parse object that helped generate it so that the
72215: ** the Vdbe becomes an independent entity and the Parse object can be
72216: ** destroyed.
72217: **
72218: ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
72219: ** to its initial state after it has been run.
72220: */
72221: SQLITE_PRIVATE void sqlite3VdbeMakeReady(
72222:   Vdbe *p,                       /* The VDBE */
72223:   Parse *pParse                  /* Parsing context */
72224: ){
72225:   sqlite3 *db;                   /* The database connection */
72226:   int nVar;                      /* Number of parameters */
72227:   int nMem;                      /* Number of VM memory registers */
72228:   int nCursor;                   /* Number of cursors required */
72229:   int nArg;                      /* Number of arguments in subprograms */
72230:   int nOnce;                     /* Number of OP_Once instructions */
72231:   int n;                         /* Loop counter */
72232:   struct ReusableSpace x;        /* Reusable bulk memory */
72233: 
72234:   assert( p!=0 );
72235:   assert( p->nOp>0 );
72236:   assert( pParse!=0 );
72237:   assert( p->magic==VDBE_MAGIC_INIT );
72238:   assert( pParse==p->pParse );
72239:   db = p->db;
72240:   assert( db->mallocFailed==0 );
72241:   nVar = pParse->nVar;
72242:   nMem = pParse->nMem;
72243:   nCursor = pParse->nTab;
72244:   nArg = pParse->nMaxArg;
72245:   nOnce = pParse->nOnce;
72246:   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
72247:   
72248:   /* Each cursor uses a memory cell.  The first cursor (cursor 0) can
72249:   ** use aMem[0] which is not otherwise used by the VDBE program.  Allocate
72250:   ** space at the end of aMem[] for cursors 1 and greater.
72251:   ** See also: allocateCursor().
72252:   */
72253:   nMem += nCursor;
72254:   if( nCursor==0 && nMem>0 ) nMem++;  /* Space for aMem[0] even if not used */
72255: 
72256:   /* Figure out how much reusable memory is available at the end of the
72257:   ** opcode array.  This extra memory will be reallocated for other elements
72258:   ** of the prepared statement.
72259:   */
72260:   n = ROUND8(sizeof(Op)*p->nOp);              /* Bytes of opcode memory used */
72261:   x.pSpace = &((u8*)p->aOp)[n];               /* Unused opcode memory */
72262:   assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
72263:   x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n);  /* Bytes of unused memory */
72264:   assert( x.nFree>=0 );
72265:   if( x.nFree>0 ){
72266:     memset(x.pSpace, 0, x.nFree);
72267:     assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
72268:   }
72269: 
72270:   resolveP2Values(p, &nArg);
72271:   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
72272:   if( pParse->explain && nMem<10 ){
72273:     nMem = 10;
72274:   }
72275:   p->expired = 0;
72276: 
72277:   /* Memory for registers, parameters, cursor, etc, is allocated in one or two
72278:   ** passes.  On the first pass, we try to reuse unused memory at the 
72279:   ** end of the opcode array.  If we are unable to satisfy all memory
72280:   ** requirements by reusing the opcode array tail, then the second
72281:   ** pass will fill in the remainder using a fresh memory allocation.  
72282:   **
72283:   ** This two-pass approach that reuses as much memory as possible from
72284:   ** the leftover memory at the end of the opcode array.  This can significantly
72285:   ** reduce the amount of memory held by a prepared statement.
72286:   */
72287:   do {
72288:     x.nNeeded = 0;
72289:     p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
72290:     p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
72291:     p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
72292:     p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
72293:     p->aOnceFlag = allocSpace(&x, p->aOnceFlag, nOnce);
72294: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72295:     p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
72296: #endif
72297:     if( x.nNeeded==0 ) break;
72298:     x.pSpace = p->pFree = sqlite3DbMallocZero(db, x.nNeeded);
72299:     x.nFree = x.nNeeded;
72300:   }while( !db->mallocFailed );
72301: 
72302:   p->nCursor = nCursor;
72303:   p->nOnceFlag = nOnce;
72304:   if( p->aVar ){
72305:     p->nVar = (ynVar)nVar;
72306:     for(n=0; n<nVar; n++){
72307:       p->aVar[n].flags = MEM_Null;
72308:       p->aVar[n].db = db;
72309:     }
72310:   }
72311:   p->nzVar = pParse->nzVar;
72312:   p->azVar = pParse->azVar;
72313:   pParse->nzVar =  0;
72314:   pParse->azVar = 0;
72315:   if( p->aMem ){
72316:     p->nMem = nMem;
72317:     for(n=0; n<nMem; n++){
72318:       p->aMem[n].flags = MEM_Undefined;
72319:       p->aMem[n].db = db;
72320:     }
72321:   }
72322:   p->explain = pParse->explain;
72323:   sqlite3VdbeRewind(p);
72324: }
72325: 
72326: /*
72327: ** Close a VDBE cursor and release all the resources that cursor 
72328: ** happens to hold.
72329: */
72330: SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
72331:   if( pCx==0 ){
72332:     return;
72333:   }
72334:   assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
72335:   switch( pCx->eCurType ){
72336:     case CURTYPE_SORTER: {
72337:       sqlite3VdbeSorterClose(p->db, pCx);
72338:       break;
72339:     }
72340:     case CURTYPE_BTREE: {
72341:       if( pCx->pBt ){
72342:         sqlite3BtreeClose(pCx->pBt);
72343:         /* The pCx->pCursor will be close automatically, if it exists, by
72344:         ** the call above. */
72345:       }else{
72346:         assert( pCx->uc.pCursor!=0 );
72347:         sqlite3BtreeCloseCursor(pCx->uc.pCursor);
72348:       }
72349:       break;
72350:     }
72351: #ifndef SQLITE_OMIT_VIRTUALTABLE
72352:     case CURTYPE_VTAB: {
72353:       sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
72354:       const sqlite3_module *pModule = pVCur->pVtab->pModule;
72355:       assert( pVCur->pVtab->nRef>0 );
72356:       pVCur->pVtab->nRef--;
72357:       pModule->xClose(pVCur);
72358:       break;
72359:     }
72360: #endif
72361:   }
72362: }
72363: 
72364: /*
72365: ** Close all cursors in the current frame.
72366: */
72367: static void closeCursorsInFrame(Vdbe *p){
72368:   if( p->apCsr ){
72369:     int i;
72370:     for(i=0; i<p->nCursor; i++){
72371:       VdbeCursor *pC = p->apCsr[i];
72372:       if( pC ){
72373:         sqlite3VdbeFreeCursor(p, pC);
72374:         p->apCsr[i] = 0;
72375:       }
72376:     }
72377:   }
72378: }
72379: 
72380: /*
72381: ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
72382: ** is used, for example, when a trigger sub-program is halted to restore
72383: ** control to the main program.
72384: */
72385: SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
72386:   Vdbe *v = pFrame->v;
72387:   closeCursorsInFrame(v);
72388: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72389:   v->anExec = pFrame->anExec;
72390: #endif
72391:   v->aOnceFlag = pFrame->aOnceFlag;
72392:   v->nOnceFlag = pFrame->nOnceFlag;
72393:   v->aOp = pFrame->aOp;
72394:   v->nOp = pFrame->nOp;
72395:   v->aMem = pFrame->aMem;
72396:   v->nMem = pFrame->nMem;
72397:   v->apCsr = pFrame->apCsr;
72398:   v->nCursor = pFrame->nCursor;
72399:   v->db->lastRowid = pFrame->lastRowid;
72400:   v->nChange = pFrame->nChange;
72401:   v->db->nChange = pFrame->nDbChange;
72402:   sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
72403:   v->pAuxData = pFrame->pAuxData;
72404:   pFrame->pAuxData = 0;
72405:   return pFrame->pc;
72406: }
72407: 
72408: /*
72409: ** Close all cursors.
72410: **
72411: ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
72412: ** cell array. This is necessary as the memory cell array may contain
72413: ** pointers to VdbeFrame objects, which may in turn contain pointers to
72414: ** open cursors.
72415: */
72416: static void closeAllCursors(Vdbe *p){
72417:   if( p->pFrame ){
72418:     VdbeFrame *pFrame;
72419:     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
72420:     sqlite3VdbeFrameRestore(pFrame);
72421:     p->pFrame = 0;
72422:     p->nFrame = 0;
72423:   }
72424:   assert( p->nFrame==0 );
72425:   closeCursorsInFrame(p);
72426:   if( p->aMem ){
72427:     releaseMemArray(p->aMem, p->nMem);
72428:   }
72429:   while( p->pDelFrame ){
72430:     VdbeFrame *pDel = p->pDelFrame;
72431:     p->pDelFrame = pDel->pParent;
72432:     sqlite3VdbeFrameDelete(pDel);
72433:   }
72434: 
72435:   /* Delete any auxdata allocations made by the VM */
72436:   if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
72437:   assert( p->pAuxData==0 );
72438: }
72439: 
72440: /*
72441: ** Clean up the VM after a single run.
72442: */
72443: static void Cleanup(Vdbe *p){
72444:   sqlite3 *db = p->db;
72445: 
72446: #ifdef SQLITE_DEBUG
72447:   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
72448:   ** Vdbe.aMem[] arrays have already been cleaned up.  */
72449:   int i;
72450:   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
72451:   if( p->aMem ){
72452:     for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
72453:   }
72454: #endif
72455: 
72456:   sqlite3DbFree(db, p->zErrMsg);
72457:   p->zErrMsg = 0;
72458:   p->pResultSet = 0;
72459: }
72460: 
72461: /*
72462: ** Set the number of result columns that will be returned by this SQL
72463: ** statement. This is now set at compile time, rather than during
72464: ** execution of the vdbe program so that sqlite3_column_count() can
72465: ** be called on an SQL statement before sqlite3_step().
72466: */
72467: SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
72468:   Mem *pColName;
72469:   int n;
72470:   sqlite3 *db = p->db;
72471: 
72472:   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
72473:   sqlite3DbFree(db, p->aColName);
72474:   n = nResColumn*COLNAME_N;
72475:   p->nResColumn = (u16)nResColumn;
72476:   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
72477:   if( p->aColName==0 ) return;
72478:   while( n-- > 0 ){
72479:     pColName->flags = MEM_Null;
72480:     pColName->db = p->db;
72481:     pColName++;
72482:   }
72483: }
72484: 
72485: /*
72486: ** Set the name of the idx'th column to be returned by the SQL statement.
72487: ** zName must be a pointer to a nul terminated string.
72488: **
72489: ** This call must be made after a call to sqlite3VdbeSetNumCols().
72490: **
72491: ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
72492: ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
72493: ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
72494: */
72495: SQLITE_PRIVATE int sqlite3VdbeSetColName(
72496:   Vdbe *p,                         /* Vdbe being configured */
72497:   int idx,                         /* Index of column zName applies to */
72498:   int var,                         /* One of the COLNAME_* constants */
72499:   const char *zName,               /* Pointer to buffer containing name */
72500:   void (*xDel)(void*)              /* Memory management strategy for zName */
72501: ){
72502:   int rc;
72503:   Mem *pColName;
72504:   assert( idx<p->nResColumn );
72505:   assert( var<COLNAME_N );
72506:   if( p->db->mallocFailed ){
72507:     assert( !zName || xDel!=SQLITE_DYNAMIC );
72508:     return SQLITE_NOMEM_BKPT;
72509:   }
72510:   assert( p->aColName!=0 );
72511:   pColName = &(p->aColName[idx+var*p->nResColumn]);
72512:   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
72513:   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
72514:   return rc;
72515: }
72516: 
72517: /*
72518: ** A read or write transaction may or may not be active on database handle
72519: ** db. If a transaction is active, commit it. If there is a
72520: ** write-transaction spanning more than one database file, this routine
72521: ** takes care of the master journal trickery.
72522: */
72523: static int vdbeCommit(sqlite3 *db, Vdbe *p){
72524:   int i;
72525:   int nTrans = 0;  /* Number of databases with an active write-transaction
72526:                    ** that are candidates for a two-phase commit using a
72527:                    ** master-journal */
72528:   int rc = SQLITE_OK;
72529:   int needXcommit = 0;
72530: 
72531: #ifdef SQLITE_OMIT_VIRTUALTABLE
72532:   /* With this option, sqlite3VtabSync() is defined to be simply 
72533:   ** SQLITE_OK so p is not used. 
72534:   */
72535:   UNUSED_PARAMETER(p);
72536: #endif
72537: 
72538:   /* Before doing anything else, call the xSync() callback for any
72539:   ** virtual module tables written in this transaction. This has to
72540:   ** be done before determining whether a master journal file is 
72541:   ** required, as an xSync() callback may add an attached database
72542:   ** to the transaction.
72543:   */
72544:   rc = sqlite3VtabSync(db, p);
72545: 
72546:   /* This loop determines (a) if the commit hook should be invoked and
72547:   ** (b) how many database files have open write transactions, not 
72548:   ** including the temp database. (b) is important because if more than 
72549:   ** one database file has an open write transaction, a master journal
72550:   ** file is required for an atomic commit.
72551:   */ 
72552:   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
72553:     Btree *pBt = db->aDb[i].pBt;
72554:     if( sqlite3BtreeIsInTrans(pBt) ){
72555:       /* Whether or not a database might need a master journal depends upon
72556:       ** its journal mode (among other things).  This matrix determines which
72557:       ** journal modes use a master journal and which do not */
72558:       static const u8 aMJNeeded[] = {
72559:         /* DELETE   */  1,
72560:         /* PERSIST   */ 1,
72561:         /* OFF       */ 0,
72562:         /* TRUNCATE  */ 1,
72563:         /* MEMORY    */ 0,
72564:         /* WAL       */ 0
72565:       };
72566:       Pager *pPager;   /* Pager associated with pBt */
72567:       needXcommit = 1;
72568:       sqlite3BtreeEnter(pBt);
72569:       pPager = sqlite3BtreePager(pBt);
72570:       if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
72571:        && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
72572:       ){ 
72573:         assert( i!=1 );
72574:         nTrans++;
72575:       }
72576:       rc = sqlite3PagerExclusiveLock(pPager);
72577:       sqlite3BtreeLeave(pBt);
72578:     }
72579:   }
72580:   if( rc!=SQLITE_OK ){
72581:     return rc;
72582:   }
72583: 
72584:   /* If there are any write-transactions at all, invoke the commit hook */
72585:   if( needXcommit && db->xCommitCallback ){
72586:     rc = db->xCommitCallback(db->pCommitArg);
72587:     if( rc ){
72588:       return SQLITE_CONSTRAINT_COMMITHOOK;
72589:     }
72590:   }
72591: 
72592:   /* The simple case - no more than one database file (not counting the
72593:   ** TEMP database) has a transaction active.   There is no need for the
72594:   ** master-journal.
72595:   **
72596:   ** If the return value of sqlite3BtreeGetFilename() is a zero length
72597:   ** string, it means the main database is :memory: or a temp file.  In 
72598:   ** that case we do not support atomic multi-file commits, so use the 
72599:   ** simple case then too.
72600:   */
72601:   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
72602:    || nTrans<=1
72603:   ){
72604:     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72605:       Btree *pBt = db->aDb[i].pBt;
72606:       if( pBt ){
72607:         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
72608:       }
72609:     }
72610: 
72611:     /* Do the commit only if all databases successfully complete phase 1. 
72612:     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
72613:     ** IO error while deleting or truncating a journal file. It is unlikely,
72614:     ** but could happen. In this case abandon processing and return the error.
72615:     */
72616:     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72617:       Btree *pBt = db->aDb[i].pBt;
72618:       if( pBt ){
72619:         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
72620:       }
72621:     }
72622:     if( rc==SQLITE_OK ){
72623:       sqlite3VtabCommit(db);
72624:     }
72625:   }
72626: 
72627:   /* The complex case - There is a multi-file write-transaction active.
72628:   ** This requires a master journal file to ensure the transaction is
72629:   ** committed atomically.
72630:   */
72631: #ifndef SQLITE_OMIT_DISKIO
72632:   else{
72633:     sqlite3_vfs *pVfs = db->pVfs;
72634:     char *zMaster = 0;   /* File-name for the master journal */
72635:     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
72636:     sqlite3_file *pMaster = 0;
72637:     i64 offset = 0;
72638:     int res;
72639:     int retryCount = 0;
72640:     int nMainFile;
72641: 
72642:     /* Select a master journal file name */
72643:     nMainFile = sqlite3Strlen30(zMainFile);
72644:     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
72645:     if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
72646:     do {
72647:       u32 iRandom;
72648:       if( retryCount ){
72649:         if( retryCount>100 ){
72650:           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
72651:           sqlite3OsDelete(pVfs, zMaster, 0);
72652:           break;
72653:         }else if( retryCount==1 ){
72654:           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
72655:         }
72656:       }
72657:       retryCount++;
72658:       sqlite3_randomness(sizeof(iRandom), &iRandom);
72659:       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
72660:                                (iRandom>>8)&0xffffff, iRandom&0xff);
72661:       /* The antipenultimate character of the master journal name must
72662:       ** be "9" to avoid name collisions when using 8+3 filenames. */
72663:       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
72664:       sqlite3FileSuffix3(zMainFile, zMaster);
72665:       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
72666:     }while( rc==SQLITE_OK && res );
72667:     if( rc==SQLITE_OK ){
72668:       /* Open the master journal. */
72669:       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
72670:           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
72671:           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
72672:       );
72673:     }
72674:     if( rc!=SQLITE_OK ){
72675:       sqlite3DbFree(db, zMaster);
72676:       return rc;
72677:     }
72678:  
72679:     /* Write the name of each database file in the transaction into the new
72680:     ** master journal file. If an error occurs at this point close
72681:     ** and delete the master journal file. All the individual journal files
72682:     ** still have 'null' as the master journal pointer, so they will roll
72683:     ** back independently if a failure occurs.
72684:     */
72685:     for(i=0; i<db->nDb; i++){
72686:       Btree *pBt = db->aDb[i].pBt;
72687:       if( sqlite3BtreeIsInTrans(pBt) ){
72688:         char const *zFile = sqlite3BtreeGetJournalname(pBt);
72689:         if( zFile==0 ){
72690:           continue;  /* Ignore TEMP and :memory: databases */
72691:         }
72692:         assert( zFile[0]!=0 );
72693:         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
72694:         offset += sqlite3Strlen30(zFile)+1;
72695:         if( rc!=SQLITE_OK ){
72696:           sqlite3OsCloseFree(pMaster);
72697:           sqlite3OsDelete(pVfs, zMaster, 0);
72698:           sqlite3DbFree(db, zMaster);
72699:           return rc;
72700:         }
72701:       }
72702:     }
72703: 
72704:     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
72705:     ** flag is set this is not required.
72706:     */
72707:     if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
72708:      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
72709:     ){
72710:       sqlite3OsCloseFree(pMaster);
72711:       sqlite3OsDelete(pVfs, zMaster, 0);
72712:       sqlite3DbFree(db, zMaster);
72713:       return rc;
72714:     }
72715: 
72716:     /* Sync all the db files involved in the transaction. The same call
72717:     ** sets the master journal pointer in each individual journal. If
72718:     ** an error occurs here, do not delete the master journal file.
72719:     **
72720:     ** If the error occurs during the first call to
72721:     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
72722:     ** master journal file will be orphaned. But we cannot delete it,
72723:     ** in case the master journal file name was written into the journal
72724:     ** file before the failure occurred.
72725:     */
72726:     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
72727:       Btree *pBt = db->aDb[i].pBt;
72728:       if( pBt ){
72729:         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
72730:       }
72731:     }
72732:     sqlite3OsCloseFree(pMaster);
72733:     assert( rc!=SQLITE_BUSY );
72734:     if( rc!=SQLITE_OK ){
72735:       sqlite3DbFree(db, zMaster);
72736:       return rc;
72737:     }
72738: 
72739:     /* Delete the master journal file. This commits the transaction. After
72740:     ** doing this the directory is synced again before any individual
72741:     ** transaction files are deleted.
72742:     */
72743:     rc = sqlite3OsDelete(pVfs, zMaster, 1);
72744:     sqlite3DbFree(db, zMaster);
72745:     zMaster = 0;
72746:     if( rc ){
72747:       return rc;
72748:     }
72749: 
72750:     /* All files and directories have already been synced, so the following
72751:     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
72752:     ** deleting or truncating journals. If something goes wrong while
72753:     ** this is happening we don't really care. The integrity of the
72754:     ** transaction is already guaranteed, but some stray 'cold' journals
72755:     ** may be lying around. Returning an error code won't help matters.
72756:     */
72757:     disable_simulated_io_errors();
72758:     sqlite3BeginBenignMalloc();
72759:     for(i=0; i<db->nDb; i++){ 
72760:       Btree *pBt = db->aDb[i].pBt;
72761:       if( pBt ){
72762:         sqlite3BtreeCommitPhaseTwo(pBt, 1);
72763:       }
72764:     }
72765:     sqlite3EndBenignMalloc();
72766:     enable_simulated_io_errors();
72767: 
72768:     sqlite3VtabCommit(db);
72769:   }
72770: #endif
72771: 
72772:   return rc;
72773: }
72774: 
72775: /* 
72776: ** This routine checks that the sqlite3.nVdbeActive count variable
72777: ** matches the number of vdbe's in the list sqlite3.pVdbe that are
72778: ** currently active. An assertion fails if the two counts do not match.
72779: ** This is an internal self-check only - it is not an essential processing
72780: ** step.
72781: **
72782: ** This is a no-op if NDEBUG is defined.
72783: */
72784: #ifndef NDEBUG
72785: static void checkActiveVdbeCnt(sqlite3 *db){
72786:   Vdbe *p;
72787:   int cnt = 0;
72788:   int nWrite = 0;
72789:   int nRead = 0;
72790:   p = db->pVdbe;
72791:   while( p ){
72792:     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
72793:       cnt++;
72794:       if( p->readOnly==0 ) nWrite++;
72795:       if( p->bIsReader ) nRead++;
72796:     }
72797:     p = p->pNext;
72798:   }
72799:   assert( cnt==db->nVdbeActive );
72800:   assert( nWrite==db->nVdbeWrite );
72801:   assert( nRead==db->nVdbeRead );
72802: }
72803: #else
72804: #define checkActiveVdbeCnt(x)
72805: #endif
72806: 
72807: /*
72808: ** If the Vdbe passed as the first argument opened a statement-transaction,
72809: ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
72810: ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
72811: ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
72812: ** statement transaction is committed.
72813: **
72814: ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
72815: ** Otherwise SQLITE_OK.
72816: */
72817: SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
72818:   sqlite3 *const db = p->db;
72819:   int rc = SQLITE_OK;
72820: 
72821:   /* If p->iStatement is greater than zero, then this Vdbe opened a 
72822:   ** statement transaction that should be closed here. The only exception
72823:   ** is that an IO error may have occurred, causing an emergency rollback.
72824:   ** In this case (db->nStatement==0), and there is nothing to do.
72825:   */
72826:   if( db->nStatement && p->iStatement ){
72827:     int i;
72828:     const int iSavepoint = p->iStatement-1;
72829: 
72830:     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
72831:     assert( db->nStatement>0 );
72832:     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
72833: 
72834:     for(i=0; i<db->nDb; i++){ 
72835:       int rc2 = SQLITE_OK;
72836:       Btree *pBt = db->aDb[i].pBt;
72837:       if( pBt ){
72838:         if( eOp==SAVEPOINT_ROLLBACK ){
72839:           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
72840:         }
72841:         if( rc2==SQLITE_OK ){
72842:           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
72843:         }
72844:         if( rc==SQLITE_OK ){
72845:           rc = rc2;
72846:         }
72847:       }
72848:     }
72849:     db->nStatement--;
72850:     p->iStatement = 0;
72851: 
72852:     if( rc==SQLITE_OK ){
72853:       if( eOp==SAVEPOINT_ROLLBACK ){
72854:         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
72855:       }
72856:       if( rc==SQLITE_OK ){
72857:         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
72858:       }
72859:     }
72860: 
72861:     /* If the statement transaction is being rolled back, also restore the 
72862:     ** database handles deferred constraint counter to the value it had when 
72863:     ** the statement transaction was opened.  */
72864:     if( eOp==SAVEPOINT_ROLLBACK ){
72865:       db->nDeferredCons = p->nStmtDefCons;
72866:       db->nDeferredImmCons = p->nStmtDefImmCons;
72867:     }
72868:   }
72869:   return rc;
72870: }
72871: 
72872: /*
72873: ** This function is called when a transaction opened by the database 
72874: ** handle associated with the VM passed as an argument is about to be 
72875: ** committed. If there are outstanding deferred foreign key constraint
72876: ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
72877: **
72878: ** If there are outstanding FK violations and this function returns 
72879: ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
72880: ** and write an error message to it. Then return SQLITE_ERROR.
72881: */
72882: #ifndef SQLITE_OMIT_FOREIGN_KEY
72883: SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
72884:   sqlite3 *db = p->db;
72885:   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) 
72886:    || (!deferred && p->nFkConstraint>0) 
72887:   ){
72888:     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
72889:     p->errorAction = OE_Abort;
72890:     sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
72891:     return SQLITE_ERROR;
72892:   }
72893:   return SQLITE_OK;
72894: }
72895: #endif
72896: 
72897: /*
72898: ** This routine is called the when a VDBE tries to halt.  If the VDBE
72899: ** has made changes and is in autocommit mode, then commit those
72900: ** changes.  If a rollback is needed, then do the rollback.
72901: **
72902: ** This routine is the only way to move the state of a VM from
72903: ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
72904: ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
72905: **
72906: ** Return an error code.  If the commit could not complete because of
72907: ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
72908: ** means the close did not happen and needs to be repeated.
72909: */
72910: SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
72911:   int rc;                         /* Used to store transient return codes */
72912:   sqlite3 *db = p->db;
72913: 
72914:   /* This function contains the logic that determines if a statement or
72915:   ** transaction will be committed or rolled back as a result of the
72916:   ** execution of this virtual machine. 
72917:   **
72918:   ** If any of the following errors occur:
72919:   **
72920:   **     SQLITE_NOMEM
72921:   **     SQLITE_IOERR
72922:   **     SQLITE_FULL
72923:   **     SQLITE_INTERRUPT
72924:   **
72925:   ** Then the internal cache might have been left in an inconsistent
72926:   ** state.  We need to rollback the statement transaction, if there is
72927:   ** one, or the complete transaction if there is no statement transaction.
72928:   */
72929: 
72930:   if( db->mallocFailed ){
72931:     p->rc = SQLITE_NOMEM_BKPT;
72932:   }
72933:   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
72934:   closeAllCursors(p);
72935:   if( p->magic!=VDBE_MAGIC_RUN ){
72936:     return SQLITE_OK;
72937:   }
72938:   checkActiveVdbeCnt(db);
72939: 
72940:   /* No commit or rollback needed if the program never started or if the
72941:   ** SQL statement does not read or write a database file.  */
72942:   if( p->pc>=0 && p->bIsReader ){
72943:     int mrc;   /* Primary error code from p->rc */
72944:     int eStatementOp = 0;
72945:     int isSpecialError;            /* Set to true if a 'special' error */
72946: 
72947:     /* Lock all btrees used by the statement */
72948:     sqlite3VdbeEnter(p);
72949: 
72950:     /* Check for one of the special errors */
72951:     mrc = p->rc & 0xff;
72952:     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
72953:                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
72954:     if( isSpecialError ){
72955:       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
72956:       ** no rollback is necessary. Otherwise, at least a savepoint 
72957:       ** transaction must be rolled back to restore the database to a 
72958:       ** consistent state.
72959:       **
72960:       ** Even if the statement is read-only, it is important to perform
72961:       ** a statement or transaction rollback operation. If the error 
72962:       ** occurred while writing to the journal, sub-journal or database
72963:       ** file as part of an effort to free up cache space (see function
72964:       ** pagerStress() in pager.c), the rollback is required to restore 
72965:       ** the pager to a consistent state.
72966:       */
72967:       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
72968:         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
72969:           eStatementOp = SAVEPOINT_ROLLBACK;
72970:         }else{
72971:           /* We are forced to roll back the active transaction. Before doing
72972:           ** so, abort any other statements this handle currently has active.
72973:           */
72974:           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
72975:           sqlite3CloseSavepoints(db);
72976:           db->autoCommit = 1;
72977:           p->nChange = 0;
72978:         }
72979:       }
72980:     }
72981: 
72982:     /* Check for immediate foreign key violations. */
72983:     if( p->rc==SQLITE_OK ){
72984:       sqlite3VdbeCheckFk(p, 0);
72985:     }
72986:   
72987:     /* If the auto-commit flag is set and this is the only active writer 
72988:     ** VM, then we do either a commit or rollback of the current transaction. 
72989:     **
72990:     ** Note: This block also runs if one of the special errors handled 
72991:     ** above has occurred. 
72992:     */
72993:     if( !sqlite3VtabInSync(db) 
72994:      && db->autoCommit 
72995:      && db->nVdbeWrite==(p->readOnly==0) 
72996:     ){
72997:       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
72998:         rc = sqlite3VdbeCheckFk(p, 1);
72999:         if( rc!=SQLITE_OK ){
73000:           if( NEVER(p->readOnly) ){
73001:             sqlite3VdbeLeave(p);
73002:             return SQLITE_ERROR;
73003:           }
73004:           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
73005:         }else{ 
73006:           /* The auto-commit flag is true, the vdbe program was successful 
73007:           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
73008:           ** key constraints to hold up the transaction. This means a commit 
73009:           ** is required. */
73010:           rc = vdbeCommit(db, p);
73011:         }
73012:         if( rc==SQLITE_BUSY && p->readOnly ){
73013:           sqlite3VdbeLeave(p);
73014:           return SQLITE_BUSY;
73015:         }else if( rc!=SQLITE_OK ){
73016:           p->rc = rc;
73017:           sqlite3RollbackAll(db, SQLITE_OK);
73018:           p->nChange = 0;
73019:         }else{
73020:           db->nDeferredCons = 0;
73021:           db->nDeferredImmCons = 0;
73022:           db->flags &= ~SQLITE_DeferFKs;
73023:           sqlite3CommitInternalChanges(db);
73024:         }
73025:       }else{
73026:         sqlite3RollbackAll(db, SQLITE_OK);
73027:         p->nChange = 0;
73028:       }
73029:       db->nStatement = 0;
73030:     }else if( eStatementOp==0 ){
73031:       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
73032:         eStatementOp = SAVEPOINT_RELEASE;
73033:       }else if( p->errorAction==OE_Abort ){
73034:         eStatementOp = SAVEPOINT_ROLLBACK;
73035:       }else{
73036:         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73037:         sqlite3CloseSavepoints(db);
73038:         db->autoCommit = 1;
73039:         p->nChange = 0;
73040:       }
73041:     }
73042:   
73043:     /* If eStatementOp is non-zero, then a statement transaction needs to
73044:     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
73045:     ** do so. If this operation returns an error, and the current statement
73046:     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
73047:     ** current statement error code.
73048:     */
73049:     if( eStatementOp ){
73050:       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
73051:       if( rc ){
73052:         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
73053:           p->rc = rc;
73054:           sqlite3DbFree(db, p->zErrMsg);
73055:           p->zErrMsg = 0;
73056:         }
73057:         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73058:         sqlite3CloseSavepoints(db);
73059:         db->autoCommit = 1;
73060:         p->nChange = 0;
73061:       }
73062:     }
73063:   
73064:     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
73065:     ** has been rolled back, update the database connection change-counter. 
73066:     */
73067:     if( p->changeCntOn ){
73068:       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
73069:         sqlite3VdbeSetChanges(db, p->nChange);
73070:       }else{
73071:         sqlite3VdbeSetChanges(db, 0);
73072:       }
73073:       p->nChange = 0;
73074:     }
73075: 
73076:     /* Release the locks */
73077:     sqlite3VdbeLeave(p);
73078:   }
73079: 
73080:   /* We have successfully halted and closed the VM.  Record this fact. */
73081:   if( p->pc>=0 ){
73082:     db->nVdbeActive--;
73083:     if( !p->readOnly ) db->nVdbeWrite--;
73084:     if( p->bIsReader ) db->nVdbeRead--;
73085:     assert( db->nVdbeActive>=db->nVdbeRead );
73086:     assert( db->nVdbeRead>=db->nVdbeWrite );
73087:     assert( db->nVdbeWrite>=0 );
73088:   }
73089:   p->magic = VDBE_MAGIC_HALT;
73090:   checkActiveVdbeCnt(db);
73091:   if( db->mallocFailed ){
73092:     p->rc = SQLITE_NOMEM_BKPT;
73093:   }
73094: 
73095:   /* If the auto-commit flag is set to true, then any locks that were held
73096:   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
73097:   ** to invoke any required unlock-notify callbacks.
73098:   */
73099:   if( db->autoCommit ){
73100:     sqlite3ConnectionUnlocked(db);
73101:   }
73102: 
73103:   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
73104:   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
73105: }
73106: 
73107: 
73108: /*
73109: ** Each VDBE holds the result of the most recent sqlite3_step() call
73110: ** in p->rc.  This routine sets that result back to SQLITE_OK.
73111: */
73112: SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
73113:   p->rc = SQLITE_OK;
73114: }
73115: 
73116: /*
73117: ** Copy the error code and error message belonging to the VDBE passed
73118: ** as the first argument to its database handle (so that they will be 
73119: ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
73120: **
73121: ** This function does not clear the VDBE error code or message, just
73122: ** copies them to the database handle.
73123: */
73124: SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
73125:   sqlite3 *db = p->db;
73126:   int rc = p->rc;
73127:   if( p->zErrMsg ){
73128:     db->bBenignMalloc++;
73129:     sqlite3BeginBenignMalloc();
73130:     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
73131:     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
73132:     sqlite3EndBenignMalloc();
73133:     db->bBenignMalloc--;
73134:     db->errCode = rc;
73135:   }else{
73136:     sqlite3Error(db, rc);
73137:   }
73138:   return rc;
73139: }
73140: 
73141: #ifdef SQLITE_ENABLE_SQLLOG
73142: /*
73143: ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
73144: ** invoke it.
73145: */
73146: static void vdbeInvokeSqllog(Vdbe *v){
73147:   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
73148:     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
73149:     assert( v->db->init.busy==0 );
73150:     if( zExpanded ){
73151:       sqlite3GlobalConfig.xSqllog(
73152:           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
73153:       );
73154:       sqlite3DbFree(v->db, zExpanded);
73155:     }
73156:   }
73157: }
73158: #else
73159: # define vdbeInvokeSqllog(x)
73160: #endif
73161: 
73162: /*
73163: ** Clean up a VDBE after execution but do not delete the VDBE just yet.
73164: ** Write any error messages into *pzErrMsg.  Return the result code.
73165: **
73166: ** After this routine is run, the VDBE should be ready to be executed
73167: ** again.
73168: **
73169: ** To look at it another way, this routine resets the state of the
73170: ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
73171: ** VDBE_MAGIC_INIT.
73172: */
73173: SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
73174:   sqlite3 *db;
73175:   db = p->db;
73176: 
73177:   /* If the VM did not run to completion or if it encountered an
73178:   ** error, then it might not have been halted properly.  So halt
73179:   ** it now.
73180:   */
73181:   sqlite3VdbeHalt(p);
73182: 
73183:   /* If the VDBE has be run even partially, then transfer the error code
73184:   ** and error message from the VDBE into the main database structure.  But
73185:   ** if the VDBE has just been set to run but has not actually executed any
73186:   ** instructions yet, leave the main database error information unchanged.
73187:   */
73188:   if( p->pc>=0 ){
73189:     vdbeInvokeSqllog(p);
73190:     sqlite3VdbeTransferError(p);
73191:     sqlite3DbFree(db, p->zErrMsg);
73192:     p->zErrMsg = 0;
73193:     if( p->runOnlyOnce ) p->expired = 1;
73194:   }else if( p->rc && p->expired ){
73195:     /* The expired flag was set on the VDBE before the first call
73196:     ** to sqlite3_step(). For consistency (since sqlite3_step() was
73197:     ** called), set the database error in this case as well.
73198:     */
73199:     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
73200:     sqlite3DbFree(db, p->zErrMsg);
73201:     p->zErrMsg = 0;
73202:   }
73203: 
73204:   /* Reclaim all memory used by the VDBE
73205:   */
73206:   Cleanup(p);
73207: 
73208:   /* Save profiling information from this VDBE run.
73209:   */
73210: #ifdef VDBE_PROFILE
73211:   {
73212:     FILE *out = fopen("vdbe_profile.out", "a");
73213:     if( out ){
73214:       int i;
73215:       fprintf(out, "---- ");
73216:       for(i=0; i<p->nOp; i++){
73217:         fprintf(out, "%02x", p->aOp[i].opcode);
73218:       }
73219:       fprintf(out, "\n");
73220:       if( p->zSql ){
73221:         char c, pc = 0;
73222:         fprintf(out, "-- ");
73223:         for(i=0; (c = p->zSql[i])!=0; i++){
73224:           if( pc=='\n' ) fprintf(out, "-- ");
73225:           putc(c, out);
73226:           pc = c;
73227:         }
73228:         if( pc!='\n' ) fprintf(out, "\n");
73229:       }
73230:       for(i=0; i<p->nOp; i++){
73231:         char zHdr[100];
73232:         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
73233:            p->aOp[i].cnt,
73234:            p->aOp[i].cycles,
73235:            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
73236:         );
73237:         fprintf(out, "%s", zHdr);
73238:         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
73239:       }
73240:       fclose(out);
73241:     }
73242:   }
73243: #endif
73244:   p->iCurrentTime = 0;
73245:   p->magic = VDBE_MAGIC_INIT;
73246:   return p->rc & db->errMask;
73247: }
73248:  
73249: /*
73250: ** Clean up and delete a VDBE after execution.  Return an integer which is
73251: ** the result code.  Write any error message text into *pzErrMsg.
73252: */
73253: SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
73254:   int rc = SQLITE_OK;
73255:   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
73256:     rc = sqlite3VdbeReset(p);
73257:     assert( (rc & p->db->errMask)==rc );
73258:   }
73259:   sqlite3VdbeDelete(p);
73260:   return rc;
73261: }
73262: 
73263: /*
73264: ** If parameter iOp is less than zero, then invoke the destructor for
73265: ** all auxiliary data pointers currently cached by the VM passed as
73266: ** the first argument.
73267: **
73268: ** Or, if iOp is greater than or equal to zero, then the destructor is
73269: ** only invoked for those auxiliary data pointers created by the user 
73270: ** function invoked by the OP_Function opcode at instruction iOp of 
73271: ** VM pVdbe, and only then if:
73272: **
73273: **    * the associated function parameter is the 32nd or later (counting
73274: **      from left to right), or
73275: **
73276: **    * the corresponding bit in argument mask is clear (where the first
73277: **      function parameter corresponds to bit 0 etc.).
73278: */
73279: SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
73280:   while( *pp ){
73281:     AuxData *pAux = *pp;
73282:     if( (iOp<0)
73283:      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
73284:     ){
73285:       testcase( pAux->iArg==31 );
73286:       if( pAux->xDelete ){
73287:         pAux->xDelete(pAux->pAux);
73288:       }
73289:       *pp = pAux->pNext;
73290:       sqlite3DbFree(db, pAux);
73291:     }else{
73292:       pp= &pAux->pNext;
73293:     }
73294:   }
73295: }
73296: 
73297: /*
73298: ** Free all memory associated with the Vdbe passed as the second argument,
73299: ** except for object itself, which is preserved.
73300: **
73301: ** The difference between this function and sqlite3VdbeDelete() is that
73302: ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
73303: ** the database connection and frees the object itself.
73304: */
73305: SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
73306:   SubProgram *pSub, *pNext;
73307:   int i;
73308:   assert( p->db==0 || p->db==db );
73309:   releaseMemArray(p->aVar, p->nVar);
73310:   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
73311:   for(pSub=p->pProgram; pSub; pSub=pNext){
73312:     pNext = pSub->pNext;
73313:     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
73314:     sqlite3DbFree(db, pSub);
73315:   }
73316:   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
73317:   sqlite3DbFree(db, p->azVar);
73318:   vdbeFreeOpArray(db, p->aOp, p->nOp);
73319:   sqlite3DbFree(db, p->aColName);
73320:   sqlite3DbFree(db, p->zSql);
73321:   sqlite3DbFree(db, p->pFree);
73322: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
73323:   for(i=0; i<p->nScan; i++){
73324:     sqlite3DbFree(db, p->aScan[i].zName);
73325:   }
73326:   sqlite3DbFree(db, p->aScan);
73327: #endif
73328: }
73329: 
73330: /*
73331: ** Delete an entire VDBE.
73332: */
73333: SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
73334:   sqlite3 *db;
73335: 
73336:   if( NEVER(p==0) ) return;
73337:   db = p->db;
73338:   assert( sqlite3_mutex_held(db->mutex) );
73339:   sqlite3VdbeClearObject(db, p);
73340:   if( p->pPrev ){
73341:     p->pPrev->pNext = p->pNext;
73342:   }else{
73343:     assert( db->pVdbe==p );
73344:     db->pVdbe = p->pNext;
73345:   }
73346:   if( p->pNext ){
73347:     p->pNext->pPrev = p->pPrev;
73348:   }
73349:   p->magic = VDBE_MAGIC_DEAD;
73350:   p->db = 0;
73351:   sqlite3DbFree(db, p);
73352: }
73353: 
73354: /*
73355: ** The cursor "p" has a pending seek operation that has not yet been
73356: ** carried out.  Seek the cursor now.  If an error occurs, return
73357: ** the appropriate error code.
73358: */
73359: static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
73360:   int res, rc;
73361: #ifdef SQLITE_TEST
73362:   extern int sqlite3_search_count;
73363: #endif
73364:   assert( p->deferredMoveto );
73365:   assert( p->isTable );
73366:   assert( p->eCurType==CURTYPE_BTREE );
73367:   rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
73368:   if( rc ) return rc;
73369:   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
73370: #ifdef SQLITE_TEST
73371:   sqlite3_search_count++;
73372: #endif
73373:   p->deferredMoveto = 0;
73374:   p->cacheStatus = CACHE_STALE;
73375:   return SQLITE_OK;
73376: }
73377: 
73378: /*
73379: ** Something has moved cursor "p" out of place.  Maybe the row it was
73380: ** pointed to was deleted out from under it.  Or maybe the btree was
73381: ** rebalanced.  Whatever the cause, try to restore "p" to the place it
73382: ** is supposed to be pointing.  If the row was deleted out from under the
73383: ** cursor, set the cursor to point to a NULL row.
73384: */
73385: static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
73386:   int isDifferentRow, rc;
73387:   assert( p->eCurType==CURTYPE_BTREE );
73388:   assert( p->uc.pCursor!=0 );
73389:   assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
73390:   rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
73391:   p->cacheStatus = CACHE_STALE;
73392:   if( isDifferentRow ) p->nullRow = 1;
73393:   return rc;
73394: }
73395: 
73396: /*
73397: ** Check to ensure that the cursor is valid.  Restore the cursor
73398: ** if need be.  Return any I/O error from the restore operation.
73399: */
73400: SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
73401:   assert( p->eCurType==CURTYPE_BTREE );
73402:   if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73403:     return handleMovedCursor(p);
73404:   }
73405:   return SQLITE_OK;
73406: }
73407: 
73408: /*
73409: ** Make sure the cursor p is ready to read or write the row to which it
73410: ** was last positioned.  Return an error code if an OOM fault or I/O error
73411: ** prevents us from positioning the cursor to its correct position.
73412: **
73413: ** If a MoveTo operation is pending on the given cursor, then do that
73414: ** MoveTo now.  If no move is pending, check to see if the row has been
73415: ** deleted out from under the cursor and if it has, mark the row as
73416: ** a NULL row.
73417: **
73418: ** If the cursor is already pointing to the correct row and that row has
73419: ** not been deleted out from under the cursor, then this routine is a no-op.
73420: */
73421: SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
73422:   VdbeCursor *p = *pp;
73423:   if( p->eCurType==CURTYPE_BTREE ){
73424:     if( p->deferredMoveto ){
73425:       int iMap;
73426:       if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
73427:         *pp = p->pAltCursor;
73428:         *piCol = iMap - 1;
73429:         return SQLITE_OK;
73430:       }
73431:       return handleDeferredMoveto(p);
73432:     }
73433:     if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
73434:       return handleMovedCursor(p);
73435:     }
73436:   }
73437:   return SQLITE_OK;
73438: }
73439: 
73440: /*
73441: ** The following functions:
73442: **
73443: ** sqlite3VdbeSerialType()
73444: ** sqlite3VdbeSerialTypeLen()
73445: ** sqlite3VdbeSerialLen()
73446: ** sqlite3VdbeSerialPut()
73447: ** sqlite3VdbeSerialGet()
73448: **
73449: ** encapsulate the code that serializes values for storage in SQLite
73450: ** data and index records. Each serialized value consists of a
73451: ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
73452: ** integer, stored as a varint.
73453: **
73454: ** In an SQLite index record, the serial type is stored directly before
73455: ** the blob of data that it corresponds to. In a table record, all serial
73456: ** types are stored at the start of the record, and the blobs of data at
73457: ** the end. Hence these functions allow the caller to handle the
73458: ** serial-type and data blob separately.
73459: **
73460: ** The following table describes the various storage classes for data:
73461: **
73462: **   serial type        bytes of data      type
73463: **   --------------     ---------------    ---------------
73464: **      0                     0            NULL
73465: **      1                     1            signed integer
73466: **      2                     2            signed integer
73467: **      3                     3            signed integer
73468: **      4                     4            signed integer
73469: **      5                     6            signed integer
73470: **      6                     8            signed integer
73471: **      7                     8            IEEE float
73472: **      8                     0            Integer constant 0
73473: **      9                     0            Integer constant 1
73474: **     10,11                               reserved for expansion
73475: **    N>=12 and even       (N-12)/2        BLOB
73476: **    N>=13 and odd        (N-13)/2        text
73477: **
73478: ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
73479: ** of SQLite will not understand those serial types.
73480: */
73481: 
73482: /*
73483: ** Return the serial-type for the value stored in pMem.
73484: */
73485: SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
73486:   int flags = pMem->flags;
73487:   u32 n;
73488: 
73489:   assert( pLen!=0 );
73490:   if( flags&MEM_Null ){
73491:     *pLen = 0;
73492:     return 0;
73493:   }
73494:   if( flags&MEM_Int ){
73495:     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
73496: #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
73497:     i64 i = pMem->u.i;
73498:     u64 u;
73499:     if( i<0 ){
73500:       u = ~i;
73501:     }else{
73502:       u = i;
73503:     }
73504:     if( u<=127 ){
73505:       if( (i&1)==i && file_format>=4 ){
73506:         *pLen = 0;
73507:         return 8+(u32)u;
73508:       }else{
73509:         *pLen = 1;
73510:         return 1;
73511:       }
73512:     }
73513:     if( u<=32767 ){ *pLen = 2; return 2; }
73514:     if( u<=8388607 ){ *pLen = 3; return 3; }
73515:     if( u<=2147483647 ){ *pLen = 4; return 4; }
73516:     if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
73517:     *pLen = 8;
73518:     return 6;
73519:   }
73520:   if( flags&MEM_Real ){
73521:     *pLen = 8;
73522:     return 7;
73523:   }
73524:   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
73525:   assert( pMem->n>=0 );
73526:   n = (u32)pMem->n;
73527:   if( flags & MEM_Zero ){
73528:     n += pMem->u.nZero;
73529:   }
73530:   *pLen = n;
73531:   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
73532: }
73533: 
73534: /*
73535: ** The sizes for serial types less than 128
73536: */
73537: static const u8 sqlite3SmallTypeSizes[] = {
73538:         /*  0   1   2   3   4   5   6   7   8   9 */   
73539: /*   0 */   0,  1,  2,  3,  4,  6,  8,  8,  0,  0,
73540: /*  10 */   0,  0,  0,  0,  1,  1,  2,  2,  3,  3,
73541: /*  20 */   4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
73542: /*  30 */   9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
73543: /*  40 */  14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
73544: /*  50 */  19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
73545: /*  60 */  24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
73546: /*  70 */  29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
73547: /*  80 */  34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
73548: /*  90 */  39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
73549: /* 100 */  44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
73550: /* 110 */  49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
73551: /* 120 */  54, 54, 55, 55, 56, 56, 57, 57
73552: };
73553: 
73554: /*
73555: ** Return the length of the data corresponding to the supplied serial-type.
73556: */
73557: SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
73558:   if( serial_type>=128 ){
73559:     return (serial_type-12)/2;
73560:   }else{
73561:     assert( serial_type<12 
73562:             || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
73563:     return sqlite3SmallTypeSizes[serial_type];
73564:   }
73565: }
73566: SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
73567:   assert( serial_type<128 );
73568:   return sqlite3SmallTypeSizes[serial_type];  
73569: }
73570: 
73571: /*
73572: ** If we are on an architecture with mixed-endian floating 
73573: ** points (ex: ARM7) then swap the lower 4 bytes with the 
73574: ** upper 4 bytes.  Return the result.
73575: **
73576: ** For most architectures, this is a no-op.
73577: **
73578: ** (later):  It is reported to me that the mixed-endian problem
73579: ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
73580: ** that early versions of GCC stored the two words of a 64-bit
73581: ** float in the wrong order.  And that error has been propagated
73582: ** ever since.  The blame is not necessarily with GCC, though.
73583: ** GCC might have just copying the problem from a prior compiler.
73584: ** I am also told that newer versions of GCC that follow a different
73585: ** ABI get the byte order right.
73586: **
73587: ** Developers using SQLite on an ARM7 should compile and run their
73588: ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
73589: ** enabled, some asserts below will ensure that the byte order of
73590: ** floating point values is correct.
73591: **
73592: ** (2007-08-30)  Frank van Vugt has studied this problem closely
73593: ** and has send his findings to the SQLite developers.  Frank
73594: ** writes that some Linux kernels offer floating point hardware
73595: ** emulation that uses only 32-bit mantissas instead of a full 
73596: ** 48-bits as required by the IEEE standard.  (This is the
73597: ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
73598: ** byte swapping becomes very complicated.  To avoid problems,
73599: ** the necessary byte swapping is carried out using a 64-bit integer
73600: ** rather than a 64-bit float.  Frank assures us that the code here
73601: ** works for him.  We, the developers, have no way to independently
73602: ** verify this, but Frank seems to know what he is talking about
73603: ** so we trust him.
73604: */
73605: #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
73606: static u64 floatSwap(u64 in){
73607:   union {
73608:     u64 r;
73609:     u32 i[2];
73610:   } u;
73611:   u32 t;
73612: 
73613:   u.r = in;
73614:   t = u.i[0];
73615:   u.i[0] = u.i[1];
73616:   u.i[1] = t;
73617:   return u.r;
73618: }
73619: # define swapMixedEndianFloat(X)  X = floatSwap(X)
73620: #else
73621: # define swapMixedEndianFloat(X)
73622: #endif
73623: 
73624: /*
73625: ** Write the serialized data blob for the value stored in pMem into 
73626: ** buf. It is assumed that the caller has allocated sufficient space.
73627: ** Return the number of bytes written.
73628: **
73629: ** nBuf is the amount of space left in buf[].  The caller is responsible
73630: ** for allocating enough space to buf[] to hold the entire field, exclusive
73631: ** of the pMem->u.nZero bytes for a MEM_Zero value.
73632: **
73633: ** Return the number of bytes actually written into buf[].  The number
73634: ** of bytes in the zero-filled tail is included in the return value only
73635: ** if those bytes were zeroed in buf[].
73636: */ 
73637: SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
73638:   u32 len;
73639: 
73640:   /* Integer and Real */
73641:   if( serial_type<=7 && serial_type>0 ){
73642:     u64 v;
73643:     u32 i;
73644:     if( serial_type==7 ){
73645:       assert( sizeof(v)==sizeof(pMem->u.r) );
73646:       memcpy(&v, &pMem->u.r, sizeof(v));
73647:       swapMixedEndianFloat(v);
73648:     }else{
73649:       v = pMem->u.i;
73650:     }
73651:     len = i = sqlite3SmallTypeSizes[serial_type];
73652:     assert( i>0 );
73653:     do{
73654:       buf[--i] = (u8)(v&0xFF);
73655:       v >>= 8;
73656:     }while( i );
73657:     return len;
73658:   }
73659: 
73660:   /* String or blob */
73661:   if( serial_type>=12 ){
73662:     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
73663:              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
73664:     len = pMem->n;
73665:     if( len>0 ) memcpy(buf, pMem->z, len);
73666:     return len;
73667:   }
73668: 
73669:   /* NULL or constants 0 or 1 */
73670:   return 0;
73671: }
73672: 
73673: /* Input "x" is a sequence of unsigned characters that represent a
73674: ** big-endian integer.  Return the equivalent native integer
73675: */
73676: #define ONE_BYTE_INT(x)    ((i8)(x)[0])
73677: #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
73678: #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
73679: #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73680: #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73681: 
73682: /*
73683: ** Deserialize the data blob pointed to by buf as serial type serial_type
73684: ** and store the result in pMem.  Return the number of bytes read.
73685: **
73686: ** This function is implemented as two separate routines for performance.
73687: ** The few cases that require local variables are broken out into a separate
73688: ** routine so that in most cases the overhead of moving the stack pointer
73689: ** is avoided.
73690: */ 
73691: static u32 SQLITE_NOINLINE serialGet(
73692:   const unsigned char *buf,     /* Buffer to deserialize from */
73693:   u32 serial_type,              /* Serial type to deserialize */
73694:   Mem *pMem                     /* Memory cell to write value into */
73695: ){
73696:   u64 x = FOUR_BYTE_UINT(buf);
73697:   u32 y = FOUR_BYTE_UINT(buf+4);
73698:   x = (x<<32) + y;
73699:   if( serial_type==6 ){
73700:     /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
73701:     ** twos-complement integer. */
73702:     pMem->u.i = *(i64*)&x;
73703:     pMem->flags = MEM_Int;
73704:     testcase( pMem->u.i<0 );
73705:   }else{
73706:     /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
73707:     ** floating point number. */
73708: #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
73709:     /* Verify that integers and floating point values use the same
73710:     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
73711:     ** defined that 64-bit floating point values really are mixed
73712:     ** endian.
73713:     */
73714:     static const u64 t1 = ((u64)0x3ff00000)<<32;
73715:     static const double r1 = 1.0;
73716:     u64 t2 = t1;
73717:     swapMixedEndianFloat(t2);
73718:     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
73719: #endif
73720:     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
73721:     swapMixedEndianFloat(x);
73722:     memcpy(&pMem->u.r, &x, sizeof(x));
73723:     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
73724:   }
73725:   return 8;
73726: }
73727: SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
73728:   const unsigned char *buf,     /* Buffer to deserialize from */
73729:   u32 serial_type,              /* Serial type to deserialize */
73730:   Mem *pMem                     /* Memory cell to write value into */
73731: ){
73732:   switch( serial_type ){
73733:     case 10:   /* Reserved for future use */
73734:     case 11:   /* Reserved for future use */
73735:     case 0: {  /* Null */
73736:       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
73737:       pMem->flags = MEM_Null;
73738:       break;
73739:     }
73740:     case 1: {
73741:       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
73742:       ** integer. */
73743:       pMem->u.i = ONE_BYTE_INT(buf);
73744:       pMem->flags = MEM_Int;
73745:       testcase( pMem->u.i<0 );
73746:       return 1;
73747:     }
73748:     case 2: { /* 2-byte signed integer */
73749:       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
73750:       ** twos-complement integer. */
73751:       pMem->u.i = TWO_BYTE_INT(buf);
73752:       pMem->flags = MEM_Int;
73753:       testcase( pMem->u.i<0 );
73754:       return 2;
73755:     }
73756:     case 3: { /* 3-byte signed integer */
73757:       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
73758:       ** twos-complement integer. */
73759:       pMem->u.i = THREE_BYTE_INT(buf);
73760:       pMem->flags = MEM_Int;
73761:       testcase( pMem->u.i<0 );
73762:       return 3;
73763:     }
73764:     case 4: { /* 4-byte signed integer */
73765:       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
73766:       ** twos-complement integer. */
73767:       pMem->u.i = FOUR_BYTE_INT(buf);
73768: #ifdef __HP_cc 
73769:       /* Work around a sign-extension bug in the HP compiler for HP/UX */
73770:       if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
73771: #endif
73772:       pMem->flags = MEM_Int;
73773:       testcase( pMem->u.i<0 );
73774:       return 4;
73775:     }
73776:     case 5: { /* 6-byte signed integer */
73777:       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
73778:       ** twos-complement integer. */
73779:       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
73780:       pMem->flags = MEM_Int;
73781:       testcase( pMem->u.i<0 );
73782:       return 6;
73783:     }
73784:     case 6:   /* 8-byte signed integer */
73785:     case 7: { /* IEEE floating point */
73786:       /* These use local variables, so do them in a separate routine
73787:       ** to avoid having to move the frame pointer in the common case */
73788:       return serialGet(buf,serial_type,pMem);
73789:     }
73790:     case 8:    /* Integer 0 */
73791:     case 9: {  /* Integer 1 */
73792:       /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
73793:       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
73794:       pMem->u.i = serial_type-8;
73795:       pMem->flags = MEM_Int;
73796:       return 0;
73797:     }
73798:     default: {
73799:       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
73800:       ** length.
73801:       ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
73802:       ** (N-13)/2 bytes in length. */
73803:       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
73804:       pMem->z = (char *)buf;
73805:       pMem->n = (serial_type-12)/2;
73806:       pMem->flags = aFlag[serial_type&1];
73807:       return pMem->n;
73808:     }
73809:   }
73810:   return 0;
73811: }
73812: /*
73813: ** This routine is used to allocate sufficient space for an UnpackedRecord
73814: ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
73815: ** the first argument is a pointer to KeyInfo structure pKeyInfo.
73816: **
73817: ** The space is either allocated using sqlite3DbMallocRaw() or from within
73818: ** the unaligned buffer passed via the second and third arguments (presumably
73819: ** stack space). If the former, then *ppFree is set to a pointer that should
73820: ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
73821: ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
73822: ** before returning.
73823: **
73824: ** If an OOM error occurs, NULL is returned.
73825: */
73826: SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
73827:   KeyInfo *pKeyInfo,              /* Description of the record */
73828:   char *pSpace,                   /* Unaligned space available */
73829:   int szSpace,                    /* Size of pSpace[] in bytes */
73830:   char **ppFree                   /* OUT: Caller should free this pointer */
73831: ){
73832:   UnpackedRecord *p;              /* Unpacked record to return */
73833:   int nOff;                       /* Increment pSpace by nOff to align it */
73834:   int nByte;                      /* Number of bytes required for *p */
73835: 
73836:   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
73837:   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
73838:   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
73839:   */
73840:   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
73841:   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
73842:   if( nByte>szSpace+nOff ){
73843:     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
73844:     *ppFree = (char *)p;
73845:     if( !p ) return 0;
73846:   }else{
73847:     p = (UnpackedRecord*)&pSpace[nOff];
73848:     *ppFree = 0;
73849:   }
73850: 
73851:   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
73852:   assert( pKeyInfo->aSortOrder!=0 );
73853:   p->pKeyInfo = pKeyInfo;
73854:   p->nField = pKeyInfo->nField + 1;
73855:   return p;
73856: }
73857: 
73858: /*
73859: ** Given the nKey-byte encoding of a record in pKey[], populate the 
73860: ** UnpackedRecord structure indicated by the fourth argument with the
73861: ** contents of the decoded record.
73862: */ 
73863: SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
73864:   KeyInfo *pKeyInfo,     /* Information about the record format */
73865:   int nKey,              /* Size of the binary record */
73866:   const void *pKey,      /* The binary record */
73867:   UnpackedRecord *p      /* Populate this structure before returning. */
73868: ){
73869:   const unsigned char *aKey = (const unsigned char *)pKey;
73870:   int d; 
73871:   u32 idx;                        /* Offset in aKey[] to read from */
73872:   u16 u;                          /* Unsigned loop counter */
73873:   u32 szHdr;
73874:   Mem *pMem = p->aMem;
73875: 
73876:   p->default_rc = 0;
73877:   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
73878:   idx = getVarint32(aKey, szHdr);
73879:   d = szHdr;
73880:   u = 0;
73881:   while( idx<szHdr && d<=nKey ){
73882:     u32 serial_type;
73883: 
73884:     idx += getVarint32(&aKey[idx], serial_type);
73885:     pMem->enc = pKeyInfo->enc;
73886:     pMem->db = pKeyInfo->db;
73887:     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
73888:     pMem->szMalloc = 0;
73889:     pMem->z = 0;
73890:     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
73891:     pMem++;
73892:     if( (++u)>=p->nField ) break;
73893:   }
73894:   assert( u<=pKeyInfo->nField + 1 );
73895:   p->nField = u;
73896: }
73897: 
73898: #if SQLITE_DEBUG
73899: /*
73900: ** This function compares two index or table record keys in the same way
73901: ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
73902: ** this function deserializes and compares values using the
73903: ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
73904: ** in assert() statements to ensure that the optimized code in
73905: ** sqlite3VdbeRecordCompare() returns results with these two primitives.
73906: **
73907: ** Return true if the result of comparison is equivalent to desiredResult.
73908: ** Return false if there is a disagreement.
73909: */
73910: static int vdbeRecordCompareDebug(
73911:   int nKey1, const void *pKey1, /* Left key */
73912:   const UnpackedRecord *pPKey2, /* Right key */
73913:   int desiredResult             /* Correct answer */
73914: ){
73915:   u32 d1;            /* Offset into aKey[] of next data element */
73916:   u32 idx1;          /* Offset into aKey[] of next header element */
73917:   u32 szHdr1;        /* Number of bytes in header */
73918:   int i = 0;
73919:   int rc = 0;
73920:   const unsigned char *aKey1 = (const unsigned char *)pKey1;
73921:   KeyInfo *pKeyInfo;
73922:   Mem mem1;
73923: 
73924:   pKeyInfo = pPKey2->pKeyInfo;
73925:   if( pKeyInfo->db==0 ) return 1;
73926:   mem1.enc = pKeyInfo->enc;
73927:   mem1.db = pKeyInfo->db;
73928:   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
73929:   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
73930: 
73931:   /* Compilers may complain that mem1.u.i is potentially uninitialized.
73932:   ** We could initialize it, as shown here, to silence those complaints.
73933:   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
73934:   ** the unnecessary initialization has a measurable negative performance
73935:   ** impact, since this routine is a very high runner.  And so, we choose
73936:   ** to ignore the compiler warnings and leave this variable uninitialized.
73937:   */
73938:   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
73939:   
73940:   idx1 = getVarint32(aKey1, szHdr1);
73941:   if( szHdr1>98307 ) return SQLITE_CORRUPT;
73942:   d1 = szHdr1;
73943:   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
73944:   assert( pKeyInfo->aSortOrder!=0 );
73945:   assert( pKeyInfo->nField>0 );
73946:   assert( idx1<=szHdr1 || CORRUPT_DB );
73947:   do{
73948:     u32 serial_type1;
73949: 
73950:     /* Read the serial types for the next element in each key. */
73951:     idx1 += getVarint32( aKey1+idx1, serial_type1 );
73952: 
73953:     /* Verify that there is enough key space remaining to avoid
73954:     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
73955:     ** always be greater than or equal to the amount of required key space.
73956:     ** Use that approximation to avoid the more expensive call to
73957:     ** sqlite3VdbeSerialTypeLen() in the common case.
73958:     */
73959:     if( d1+serial_type1+2>(u32)nKey1
73960:      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 
73961:     ){
73962:       break;
73963:     }
73964: 
73965:     /* Extract the values to be compared.
73966:     */
73967:     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
73968: 
73969:     /* Do the comparison
73970:     */
73971:     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
73972:     if( rc!=0 ){
73973:       assert( mem1.szMalloc==0 );  /* See comment below */
73974:       if( pKeyInfo->aSortOrder[i] ){
73975:         rc = -rc;  /* Invert the result for DESC sort order. */
73976:       }
73977:       goto debugCompareEnd;
73978:     }
73979:     i++;
73980:   }while( idx1<szHdr1 && i<pPKey2->nField );
73981: 
73982:   /* No memory allocation is ever used on mem1.  Prove this using
73983:   ** the following assert().  If the assert() fails, it indicates a
73984:   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
73985:   */
73986:   assert( mem1.szMalloc==0 );
73987: 
73988:   /* rc==0 here means that one of the keys ran out of fields and
73989:   ** all the fields up to that point were equal. Return the default_rc
73990:   ** value.  */
73991:   rc = pPKey2->default_rc;
73992: 
73993: debugCompareEnd:
73994:   if( desiredResult==0 && rc==0 ) return 1;
73995:   if( desiredResult<0 && rc<0 ) return 1;
73996:   if( desiredResult>0 && rc>0 ) return 1;
73997:   if( CORRUPT_DB ) return 1;
73998:   if( pKeyInfo->db->mallocFailed ) return 1;
73999:   return 0;
74000: }
74001: #endif
74002: 
74003: #if SQLITE_DEBUG
74004: /*
74005: ** Count the number of fields (a.k.a. columns) in the record given by
74006: ** pKey,nKey.  The verify that this count is less than or equal to the
74007: ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
74008: **
74009: ** If this constraint is not satisfied, it means that the high-speed
74010: ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
74011: ** not work correctly.  If this assert() ever fires, it probably means
74012: ** that the KeyInfo.nField or KeyInfo.nXField values were computed
74013: ** incorrectly.
74014: */
74015: static void vdbeAssertFieldCountWithinLimits(
74016:   int nKey, const void *pKey,   /* The record to verify */ 
74017:   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
74018: ){
74019:   int nField = 0;
74020:   u32 szHdr;
74021:   u32 idx;
74022:   u32 notUsed;
74023:   const unsigned char *aKey = (const unsigned char*)pKey;
74024: 
74025:   if( CORRUPT_DB ) return;
74026:   idx = getVarint32(aKey, szHdr);
74027:   assert( nKey>=0 );
74028:   assert( szHdr<=(u32)nKey );
74029:   while( idx<szHdr ){
74030:     idx += getVarint32(aKey+idx, notUsed);
74031:     nField++;
74032:   }
74033:   assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
74034: }
74035: #else
74036: # define vdbeAssertFieldCountWithinLimits(A,B,C)
74037: #endif
74038: 
74039: /*
74040: ** Both *pMem1 and *pMem2 contain string values. Compare the two values
74041: ** using the collation sequence pColl. As usual, return a negative , zero
74042: ** or positive value if *pMem1 is less than, equal to or greater than 
74043: ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
74044: */
74045: static int vdbeCompareMemString(
74046:   const Mem *pMem1,
74047:   const Mem *pMem2,
74048:   const CollSeq *pColl,
74049:   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
74050: ){
74051:   if( pMem1->enc==pColl->enc ){
74052:     /* The strings are already in the correct encoding.  Call the
74053:      ** comparison function directly */
74054:     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
74055:   }else{
74056:     int rc;
74057:     const void *v1, *v2;
74058:     int n1, n2;
74059:     Mem c1;
74060:     Mem c2;
74061:     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
74062:     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
74063:     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
74064:     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
74065:     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
74066:     n1 = v1==0 ? 0 : c1.n;
74067:     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
74068:     n2 = v2==0 ? 0 : c2.n;
74069:     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
74070:     if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
74071:     sqlite3VdbeMemRelease(&c1);
74072:     sqlite3VdbeMemRelease(&c2);
74073:     return rc;
74074:   }
74075: }
74076: 
74077: /*
74078: ** Compare two blobs.  Return negative, zero, or positive if the first
74079: ** is less than, equal to, or greater than the second, respectively.
74080: ** If one blob is a prefix of the other, then the shorter is the lessor.
74081: */
74082: static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
74083:   int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
74084:   if( c ) return c;
74085:   return pB1->n - pB2->n;
74086: }
74087: 
74088: /*
74089: ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
74090: ** number.  Return negative, zero, or positive if the first (i64) is less than,
74091: ** equal to, or greater than the second (double).
74092: */
74093: static int sqlite3IntFloatCompare(i64 i, double r){
74094:   if( sizeof(LONGDOUBLE_TYPE)>8 ){
74095:     LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
74096:     if( x<r ) return -1;
74097:     if( x>r ) return +1;
74098:     return 0;
74099:   }else{
74100:     i64 y;
74101:     double s;
74102:     if( r<-9223372036854775808.0 ) return +1;
74103:     if( r>9223372036854775807.0 ) return -1;
74104:     y = (i64)r;
74105:     if( i<y ) return -1;
74106:     if( i>y ){
74107:       if( y==SMALLEST_INT64 && r>0.0 ) return -1;
74108:       return +1;
74109:     }
74110:     s = (double)i;
74111:     if( s<r ) return -1;
74112:     if( s>r ) return +1;
74113:     return 0;
74114:   }
74115: }
74116: 
74117: /*
74118: ** Compare the values contained by the two memory cells, returning
74119: ** negative, zero or positive if pMem1 is less than, equal to, or greater
74120: ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
74121: ** and reals) sorted numerically, followed by text ordered by the collating
74122: ** sequence pColl and finally blob's ordered by memcmp().
74123: **
74124: ** Two NULL values are considered equal by this function.
74125: */
74126: SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
74127:   int f1, f2;
74128:   int combined_flags;
74129: 
74130:   f1 = pMem1->flags;
74131:   f2 = pMem2->flags;
74132:   combined_flags = f1|f2;
74133:   assert( (combined_flags & MEM_RowSet)==0 );
74134:  
74135:   /* If one value is NULL, it is less than the other. If both values
74136:   ** are NULL, return 0.
74137:   */
74138:   if( combined_flags&MEM_Null ){
74139:     return (f2&MEM_Null) - (f1&MEM_Null);
74140:   }
74141: 
74142:   /* At least one of the two values is a number
74143:   */
74144:   if( combined_flags&(MEM_Int|MEM_Real) ){
74145:     if( (f1 & f2 & MEM_Int)!=0 ){
74146:       if( pMem1->u.i < pMem2->u.i ) return -1;
74147:       if( pMem1->u.i > pMem2->u.i ) return +1;
74148:       return 0;
74149:     }
74150:     if( (f1 & f2 & MEM_Real)!=0 ){
74151:       if( pMem1->u.r < pMem2->u.r ) return -1;
74152:       if( pMem1->u.r > pMem2->u.r ) return +1;
74153:       return 0;
74154:     }
74155:     if( (f1&MEM_Int)!=0 ){
74156:       if( (f2&MEM_Real)!=0 ){
74157:         return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
74158:       }else{
74159:         return -1;
74160:       }
74161:     }
74162:     if( (f1&MEM_Real)!=0 ){
74163:       if( (f2&MEM_Int)!=0 ){
74164:         return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
74165:       }else{
74166:         return -1;
74167:       }
74168:     }
74169:     return +1;
74170:   }
74171: 
74172:   /* If one value is a string and the other is a blob, the string is less.
74173:   ** If both are strings, compare using the collating functions.
74174:   */
74175:   if( combined_flags&MEM_Str ){
74176:     if( (f1 & MEM_Str)==0 ){
74177:       return 1;
74178:     }
74179:     if( (f2 & MEM_Str)==0 ){
74180:       return -1;
74181:     }
74182: 
74183:     assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
74184:     assert( pMem1->enc==SQLITE_UTF8 || 
74185:             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
74186: 
74187:     /* The collation sequence must be defined at this point, even if
74188:     ** the user deletes the collation sequence after the vdbe program is
74189:     ** compiled (this was not always the case).
74190:     */
74191:     assert( !pColl || pColl->xCmp );
74192: 
74193:     if( pColl ){
74194:       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
74195:     }
74196:     /* If a NULL pointer was passed as the collate function, fall through
74197:     ** to the blob case and use memcmp().  */
74198:   }
74199:  
74200:   /* Both values must be blobs.  Compare using memcmp().  */
74201:   return sqlite3BlobCompare(pMem1, pMem2);
74202: }
74203: 
74204: 
74205: /*
74206: ** The first argument passed to this function is a serial-type that
74207: ** corresponds to an integer - all values between 1 and 9 inclusive 
74208: ** except 7. The second points to a buffer containing an integer value
74209: ** serialized according to serial_type. This function deserializes
74210: ** and returns the value.
74211: */
74212: static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
74213:   u32 y;
74214:   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
74215:   switch( serial_type ){
74216:     case 0:
74217:     case 1:
74218:       testcase( aKey[0]&0x80 );
74219:       return ONE_BYTE_INT(aKey);
74220:     case 2:
74221:       testcase( aKey[0]&0x80 );
74222:       return TWO_BYTE_INT(aKey);
74223:     case 3:
74224:       testcase( aKey[0]&0x80 );
74225:       return THREE_BYTE_INT(aKey);
74226:     case 4: {
74227:       testcase( aKey[0]&0x80 );
74228:       y = FOUR_BYTE_UINT(aKey);
74229:       return (i64)*(int*)&y;
74230:     }
74231:     case 5: {
74232:       testcase( aKey[0]&0x80 );
74233:       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74234:     }
74235:     case 6: {
74236:       u64 x = FOUR_BYTE_UINT(aKey);
74237:       testcase( aKey[0]&0x80 );
74238:       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74239:       return (i64)*(i64*)&x;
74240:     }
74241:   }
74242: 
74243:   return (serial_type - 8);
74244: }
74245: 
74246: /*
74247: ** This function compares the two table rows or index records
74248: ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
74249: ** or positive integer if key1 is less than, equal to or 
74250: ** greater than key2.  The {nKey1, pKey1} key must be a blob
74251: ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
74252: ** key must be a parsed key such as obtained from
74253: ** sqlite3VdbeParseRecord.
74254: **
74255: ** If argument bSkip is non-zero, it is assumed that the caller has already
74256: ** determined that the first fields of the keys are equal.
74257: **
74258: ** Key1 and Key2 do not have to contain the same number of fields. If all 
74259: ** fields that appear in both keys are equal, then pPKey2->default_rc is 
74260: ** returned.
74261: **
74262: ** If database corruption is discovered, set pPKey2->errCode to 
74263: ** SQLITE_CORRUPT and return 0. If an OOM error is encountered, 
74264: ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
74265: ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
74266: */
74267: SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
74268:   int nKey1, const void *pKey1,   /* Left key */
74269:   UnpackedRecord *pPKey2,         /* Right key */
74270:   int bSkip                       /* If true, skip the first field */
74271: ){
74272:   u32 d1;                         /* Offset into aKey[] of next data element */
74273:   int i;                          /* Index of next field to compare */
74274:   u32 szHdr1;                     /* Size of record header in bytes */
74275:   u32 idx1;                       /* Offset of first type in header */
74276:   int rc = 0;                     /* Return value */
74277:   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
74278:   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
74279:   const unsigned char *aKey1 = (const unsigned char *)pKey1;
74280:   Mem mem1;
74281: 
74282:   /* If bSkip is true, then the caller has already determined that the first
74283:   ** two elements in the keys are equal. Fix the various stack variables so
74284:   ** that this routine begins comparing at the second field. */
74285:   if( bSkip ){
74286:     u32 s1;
74287:     idx1 = 1 + getVarint32(&aKey1[1], s1);
74288:     szHdr1 = aKey1[0];
74289:     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
74290:     i = 1;
74291:     pRhs++;
74292:   }else{
74293:     idx1 = getVarint32(aKey1, szHdr1);
74294:     d1 = szHdr1;
74295:     if( d1>(unsigned)nKey1 ){ 
74296:       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74297:       return 0;  /* Corruption */
74298:     }
74299:     i = 0;
74300:   }
74301: 
74302:   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
74303:   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField 
74304:        || CORRUPT_DB );
74305:   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
74306:   assert( pPKey2->pKeyInfo->nField>0 );
74307:   assert( idx1<=szHdr1 || CORRUPT_DB );
74308:   do{
74309:     u32 serial_type;
74310: 
74311:     /* RHS is an integer */
74312:     if( pRhs->flags & MEM_Int ){
74313:       serial_type = aKey1[idx1];
74314:       testcase( serial_type==12 );
74315:       if( serial_type>=10 ){
74316:         rc = +1;
74317:       }else if( serial_type==0 ){
74318:         rc = -1;
74319:       }else if( serial_type==7 ){
74320:         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74321:         rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
74322:       }else{
74323:         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
74324:         i64 rhs = pRhs->u.i;
74325:         if( lhs<rhs ){
74326:           rc = -1;
74327:         }else if( lhs>rhs ){
74328:           rc = +1;
74329:         }
74330:       }
74331:     }
74332: 
74333:     /* RHS is real */
74334:     else if( pRhs->flags & MEM_Real ){
74335:       serial_type = aKey1[idx1];
74336:       if( serial_type>=10 ){
74337:         /* Serial types 12 or greater are strings and blobs (greater than
74338:         ** numbers). Types 10 and 11 are currently "reserved for future 
74339:         ** use", so it doesn't really matter what the results of comparing
74340:         ** them to numberic values are.  */
74341:         rc = +1;
74342:       }else if( serial_type==0 ){
74343:         rc = -1;
74344:       }else{
74345:         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
74346:         if( serial_type==7 ){
74347:           if( mem1.u.r<pRhs->u.r ){
74348:             rc = -1;
74349:           }else if( mem1.u.r>pRhs->u.r ){
74350:             rc = +1;
74351:           }
74352:         }else{
74353:           rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
74354:         }
74355:       }
74356:     }
74357: 
74358:     /* RHS is a string */
74359:     else if( pRhs->flags & MEM_Str ){
74360:       getVarint32(&aKey1[idx1], serial_type);
74361:       testcase( serial_type==12 );
74362:       if( serial_type<12 ){
74363:         rc = -1;
74364:       }else if( !(serial_type & 0x01) ){
74365:         rc = +1;
74366:       }else{
74367:         mem1.n = (serial_type - 12) / 2;
74368:         testcase( (d1+mem1.n)==(unsigned)nKey1 );
74369:         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
74370:         if( (d1+mem1.n) > (unsigned)nKey1 ){
74371:           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74372:           return 0;                /* Corruption */
74373:         }else if( pKeyInfo->aColl[i] ){
74374:           mem1.enc = pKeyInfo->enc;
74375:           mem1.db = pKeyInfo->db;
74376:           mem1.flags = MEM_Str;
74377:           mem1.z = (char*)&aKey1[d1];
74378:           rc = vdbeCompareMemString(
74379:               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
74380:           );
74381:         }else{
74382:           int nCmp = MIN(mem1.n, pRhs->n);
74383:           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74384:           if( rc==0 ) rc = mem1.n - pRhs->n; 
74385:         }
74386:       }
74387:     }
74388: 
74389:     /* RHS is a blob */
74390:     else if( pRhs->flags & MEM_Blob ){
74391:       getVarint32(&aKey1[idx1], serial_type);
74392:       testcase( serial_type==12 );
74393:       if( serial_type<12 || (serial_type & 0x01) ){
74394:         rc = -1;
74395:       }else{
74396:         int nStr = (serial_type - 12) / 2;
74397:         testcase( (d1+nStr)==(unsigned)nKey1 );
74398:         testcase( (d1+nStr+1)==(unsigned)nKey1 );
74399:         if( (d1+nStr) > (unsigned)nKey1 ){
74400:           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74401:           return 0;                /* Corruption */
74402:         }else{
74403:           int nCmp = MIN(nStr, pRhs->n);
74404:           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
74405:           if( rc==0 ) rc = nStr - pRhs->n;
74406:         }
74407:       }
74408:     }
74409: 
74410:     /* RHS is null */
74411:     else{
74412:       serial_type = aKey1[idx1];
74413:       rc = (serial_type!=0);
74414:     }
74415: 
74416:     if( rc!=0 ){
74417:       if( pKeyInfo->aSortOrder[i] ){
74418:         rc = -rc;
74419:       }
74420:       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
74421:       assert( mem1.szMalloc==0 );  /* See comment below */
74422:       return rc;
74423:     }
74424: 
74425:     i++;
74426:     pRhs++;
74427:     d1 += sqlite3VdbeSerialTypeLen(serial_type);
74428:     idx1 += sqlite3VarintLen(serial_type);
74429:   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
74430: 
74431:   /* No memory allocation is ever used on mem1.  Prove this using
74432:   ** the following assert().  If the assert() fails, it indicates a
74433:   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
74434:   assert( mem1.szMalloc==0 );
74435: 
74436:   /* rc==0 here means that one or both of the keys ran out of fields and
74437:   ** all the fields up to that point were equal. Return the default_rc
74438:   ** value.  */
74439:   assert( CORRUPT_DB 
74440:        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) 
74441:        || pKeyInfo->db->mallocFailed
74442:   );
74443:   pPKey2->eqSeen = 1;
74444:   return pPKey2->default_rc;
74445: }
74446: SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
74447:   int nKey1, const void *pKey1,   /* Left key */
74448:   UnpackedRecord *pPKey2          /* Right key */
74449: ){
74450:   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
74451: }
74452: 
74453: 
74454: /*
74455: ** This function is an optimized version of sqlite3VdbeRecordCompare() 
74456: ** that (a) the first field of pPKey2 is an integer, and (b) the 
74457: ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
74458: ** byte (i.e. is less than 128).
74459: **
74460: ** To avoid concerns about buffer overreads, this routine is only used
74461: ** on schemas where the maximum valid header size is 63 bytes or less.
74462: */
74463: static int vdbeRecordCompareInt(
74464:   int nKey1, const void *pKey1, /* Left key */
74465:   UnpackedRecord *pPKey2        /* Right key */
74466: ){
74467:   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
74468:   int serial_type = ((const u8*)pKey1)[1];
74469:   int res;
74470:   u32 y;
74471:   u64 x;
74472:   i64 v = pPKey2->aMem[0].u.i;
74473:   i64 lhs;
74474: 
74475:   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74476:   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
74477:   switch( serial_type ){
74478:     case 1: { /* 1-byte signed integer */
74479:       lhs = ONE_BYTE_INT(aKey);
74480:       testcase( lhs<0 );
74481:       break;
74482:     }
74483:     case 2: { /* 2-byte signed integer */
74484:       lhs = TWO_BYTE_INT(aKey);
74485:       testcase( lhs<0 );
74486:       break;
74487:     }
74488:     case 3: { /* 3-byte signed integer */
74489:       lhs = THREE_BYTE_INT(aKey);
74490:       testcase( lhs<0 );
74491:       break;
74492:     }
74493:     case 4: { /* 4-byte signed integer */
74494:       y = FOUR_BYTE_UINT(aKey);
74495:       lhs = (i64)*(int*)&y;
74496:       testcase( lhs<0 );
74497:       break;
74498:     }
74499:     case 5: { /* 6-byte signed integer */
74500:       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74501:       testcase( lhs<0 );
74502:       break;
74503:     }
74504:     case 6: { /* 8-byte signed integer */
74505:       x = FOUR_BYTE_UINT(aKey);
74506:       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74507:       lhs = *(i64*)&x;
74508:       testcase( lhs<0 );
74509:       break;
74510:     }
74511:     case 8: 
74512:       lhs = 0;
74513:       break;
74514:     case 9:
74515:       lhs = 1;
74516:       break;
74517: 
74518:     /* This case could be removed without changing the results of running
74519:     ** this code. Including it causes gcc to generate a faster switch 
74520:     ** statement (since the range of switch targets now starts at zero and
74521:     ** is contiguous) but does not cause any duplicate code to be generated
74522:     ** (as gcc is clever enough to combine the two like cases). Other 
74523:     ** compilers might be similar.  */ 
74524:     case 0: case 7:
74525:       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74526: 
74527:     default:
74528:       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74529:   }
74530: 
74531:   if( v>lhs ){
74532:     res = pPKey2->r1;
74533:   }else if( v<lhs ){
74534:     res = pPKey2->r2;
74535:   }else if( pPKey2->nField>1 ){
74536:     /* The first fields of the two keys are equal. Compare the trailing 
74537:     ** fields.  */
74538:     res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74539:   }else{
74540:     /* The first fields of the two keys are equal and there are no trailing
74541:     ** fields. Return pPKey2->default_rc in this case. */
74542:     res = pPKey2->default_rc;
74543:     pPKey2->eqSeen = 1;
74544:   }
74545: 
74546:   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
74547:   return res;
74548: }
74549: 
74550: /*
74551: ** This function is an optimized version of sqlite3VdbeRecordCompare() 
74552: ** that (a) the first field of pPKey2 is a string, that (b) the first field
74553: ** uses the collation sequence BINARY and (c) that the size-of-header varint 
74554: ** at the start of (pKey1/nKey1) fits in a single byte.
74555: */
74556: static int vdbeRecordCompareString(
74557:   int nKey1, const void *pKey1, /* Left key */
74558:   UnpackedRecord *pPKey2        /* Right key */
74559: ){
74560:   const u8 *aKey1 = (const u8*)pKey1;
74561:   int serial_type;
74562:   int res;
74563: 
74564:   assert( pPKey2->aMem[0].flags & MEM_Str );
74565:   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74566:   getVarint32(&aKey1[1], serial_type);
74567:   if( serial_type<12 ){
74568:     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
74569:   }else if( !(serial_type & 0x01) ){ 
74570:     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
74571:   }else{
74572:     int nCmp;
74573:     int nStr;
74574:     int szHdr = aKey1[0];
74575: 
74576:     nStr = (serial_type-12) / 2;
74577:     if( (szHdr + nStr) > nKey1 ){
74578:       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74579:       return 0;    /* Corruption */
74580:     }
74581:     nCmp = MIN( pPKey2->aMem[0].n, nStr );
74582:     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
74583: 
74584:     if( res==0 ){
74585:       res = nStr - pPKey2->aMem[0].n;
74586:       if( res==0 ){
74587:         if( pPKey2->nField>1 ){
74588:           res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74589:         }else{
74590:           res = pPKey2->default_rc;
74591:           pPKey2->eqSeen = 1;
74592:         }
74593:       }else if( res>0 ){
74594:         res = pPKey2->r2;
74595:       }else{
74596:         res = pPKey2->r1;
74597:       }
74598:     }else if( res>0 ){
74599:       res = pPKey2->r2;
74600:     }else{
74601:       res = pPKey2->r1;
74602:     }
74603:   }
74604: 
74605:   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
74606:        || CORRUPT_DB
74607:        || pPKey2->pKeyInfo->db->mallocFailed
74608:   );
74609:   return res;
74610: }
74611: 
74612: /*
74613: ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
74614: ** suitable for comparing serialized records to the unpacked record passed
74615: ** as the only argument.
74616: */
74617: SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
74618:   /* varintRecordCompareInt() and varintRecordCompareString() both assume
74619:   ** that the size-of-header varint that occurs at the start of each record
74620:   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
74621:   ** also assumes that it is safe to overread a buffer by at least the 
74622:   ** maximum possible legal header size plus 8 bytes. Because there is
74623:   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
74624:   ** buffer passed to varintRecordCompareInt() this makes it convenient to
74625:   ** limit the size of the header to 64 bytes in cases where the first field
74626:   ** is an integer.
74627:   **
74628:   ** The easiest way to enforce this limit is to consider only records with
74629:   ** 13 fields or less. If the first field is an integer, the maximum legal
74630:   ** header size is (12*5 + 1 + 1) bytes.  */
74631:   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
74632:     int flags = p->aMem[0].flags;
74633:     if( p->pKeyInfo->aSortOrder[0] ){
74634:       p->r1 = 1;
74635:       p->r2 = -1;
74636:     }else{
74637:       p->r1 = -1;
74638:       p->r2 = 1;
74639:     }
74640:     if( (flags & MEM_Int) ){
74641:       return vdbeRecordCompareInt;
74642:     }
74643:     testcase( flags & MEM_Real );
74644:     testcase( flags & MEM_Null );
74645:     testcase( flags & MEM_Blob );
74646:     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
74647:       assert( flags & MEM_Str );
74648:       return vdbeRecordCompareString;
74649:     }
74650:   }
74651: 
74652:   return sqlite3VdbeRecordCompare;
74653: }
74654: 
74655: /*
74656: ** pCur points at an index entry created using the OP_MakeRecord opcode.
74657: ** Read the rowid (the last field in the record) and store it in *rowid.
74658: ** Return SQLITE_OK if everything works, or an error code otherwise.
74659: **
74660: ** pCur might be pointing to text obtained from a corrupt database file.
74661: ** So the content cannot be trusted.  Do appropriate checks on the content.
74662: */
74663: SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
74664:   i64 nCellKey = 0;
74665:   int rc;
74666:   u32 szHdr;        /* Size of the header */
74667:   u32 typeRowid;    /* Serial type of the rowid */
74668:   u32 lenRowid;     /* Size of the rowid */
74669:   Mem m, v;
74670: 
74671:   /* Get the size of the index entry.  Only indices entries of less
74672:   ** than 2GiB are support - anything large must be database corruption.
74673:   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
74674:   ** this code can safely assume that nCellKey is 32-bits  
74675:   */
74676:   assert( sqlite3BtreeCursorIsValid(pCur) );
74677:   nCellKey = sqlite3BtreePayloadSize(pCur);
74678:   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
74679: 
74680:   /* Read in the complete content of the index entry */
74681:   sqlite3VdbeMemInit(&m, db, 0);
74682:   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74683:   if( rc ){
74684:     return rc;
74685:   }
74686: 
74687:   /* The index entry must begin with a header size */
74688:   (void)getVarint32((u8*)m.z, szHdr);
74689:   testcase( szHdr==3 );
74690:   testcase( szHdr==m.n );
74691:   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
74692:     goto idx_rowid_corruption;
74693:   }
74694: 
74695:   /* The last field of the index should be an integer - the ROWID.
74696:   ** Verify that the last entry really is an integer. */
74697:   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
74698:   testcase( typeRowid==1 );
74699:   testcase( typeRowid==2 );
74700:   testcase( typeRowid==3 );
74701:   testcase( typeRowid==4 );
74702:   testcase( typeRowid==5 );
74703:   testcase( typeRowid==6 );
74704:   testcase( typeRowid==8 );
74705:   testcase( typeRowid==9 );
74706:   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
74707:     goto idx_rowid_corruption;
74708:   }
74709:   lenRowid = sqlite3SmallTypeSizes[typeRowid];
74710:   testcase( (u32)m.n==szHdr+lenRowid );
74711:   if( unlikely((u32)m.n<szHdr+lenRowid) ){
74712:     goto idx_rowid_corruption;
74713:   }
74714: 
74715:   /* Fetch the integer off the end of the index record */
74716:   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
74717:   *rowid = v.u.i;
74718:   sqlite3VdbeMemRelease(&m);
74719:   return SQLITE_OK;
74720: 
74721:   /* Jump here if database corruption is detected after m has been
74722:   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
74723: idx_rowid_corruption:
74724:   testcase( m.szMalloc!=0 );
74725:   sqlite3VdbeMemRelease(&m);
74726:   return SQLITE_CORRUPT_BKPT;
74727: }
74728: 
74729: /*
74730: ** Compare the key of the index entry that cursor pC is pointing to against
74731: ** the key string in pUnpacked.  Write into *pRes a number
74732: ** that is negative, zero, or positive if pC is less than, equal to,
74733: ** or greater than pUnpacked.  Return SQLITE_OK on success.
74734: **
74735: ** pUnpacked is either created without a rowid or is truncated so that it
74736: ** omits the rowid at the end.  The rowid at the end of the index entry
74737: ** is ignored as well.  Hence, this routine only compares the prefixes 
74738: ** of the keys prior to the final rowid, not the entire key.
74739: */
74740: SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
74741:   sqlite3 *db,                     /* Database connection */
74742:   VdbeCursor *pC,                  /* The cursor to compare against */
74743:   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
74744:   int *res                         /* Write the comparison result here */
74745: ){
74746:   i64 nCellKey = 0;
74747:   int rc;
74748:   BtCursor *pCur;
74749:   Mem m;
74750: 
74751:   assert( pC->eCurType==CURTYPE_BTREE );
74752:   pCur = pC->uc.pCursor;
74753:   assert( sqlite3BtreeCursorIsValid(pCur) );
74754:   nCellKey = sqlite3BtreePayloadSize(pCur);
74755:   /* nCellKey will always be between 0 and 0xffffffff because of the way
74756:   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
74757:   if( nCellKey<=0 || nCellKey>0x7fffffff ){
74758:     *res = 0;
74759:     return SQLITE_CORRUPT_BKPT;
74760:   }
74761:   sqlite3VdbeMemInit(&m, db, 0);
74762:   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74763:   if( rc ){
74764:     return rc;
74765:   }
74766:   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
74767:   sqlite3VdbeMemRelease(&m);
74768:   return SQLITE_OK;
74769: }
74770: 
74771: /*
74772: ** This routine sets the value to be returned by subsequent calls to
74773: ** sqlite3_changes() on the database handle 'db'. 
74774: */
74775: SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
74776:   assert( sqlite3_mutex_held(db->mutex) );
74777:   db->nChange = nChange;
74778:   db->nTotalChange += nChange;
74779: }
74780: 
74781: /*
74782: ** Set a flag in the vdbe to update the change counter when it is finalised
74783: ** or reset.
74784: */
74785: SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
74786:   v->changeCntOn = 1;
74787: }
74788: 
74789: /*
74790: ** Mark every prepared statement associated with a database connection
74791: ** as expired.
74792: **
74793: ** An expired statement means that recompilation of the statement is
74794: ** recommend.  Statements expire when things happen that make their
74795: ** programs obsolete.  Removing user-defined functions or collating
74796: ** sequences, or changing an authorization function are the types of
74797: ** things that make prepared statements obsolete.
74798: */
74799: SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
74800:   Vdbe *p;
74801:   for(p = db->pVdbe; p; p=p->pNext){
74802:     p->expired = 1;
74803:   }
74804: }
74805: 
74806: /*
74807: ** Return the database associated with the Vdbe.
74808: */
74809: SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
74810:   return v->db;
74811: }
74812: 
74813: /*
74814: ** Return a pointer to an sqlite3_value structure containing the value bound
74815: ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
74816: ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
74817: ** constants) to the value before returning it.
74818: **
74819: ** The returned value must be freed by the caller using sqlite3ValueFree().
74820: */
74821: SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
74822:   assert( iVar>0 );
74823:   if( v ){
74824:     Mem *pMem = &v->aVar[iVar-1];
74825:     if( 0==(pMem->flags & MEM_Null) ){
74826:       sqlite3_value *pRet = sqlite3ValueNew(v->db);
74827:       if( pRet ){
74828:         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
74829:         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
74830:       }
74831:       return pRet;
74832:     }
74833:   }
74834:   return 0;
74835: }
74836: 
74837: /*
74838: ** Configure SQL variable iVar so that binding a new value to it signals
74839: ** to sqlite3_reoptimize() that re-preparing the statement may result
74840: ** in a better query plan.
74841: */
74842: SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
74843:   assert( iVar>0 );
74844:   if( iVar>32 ){
74845:     v->expmask = 0xffffffff;
74846:   }else{
74847:     v->expmask |= ((u32)1 << (iVar-1));
74848:   }
74849: }
74850: 
74851: #ifndef SQLITE_OMIT_VIRTUALTABLE
74852: /*
74853: ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
74854: ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
74855: ** in memory obtained from sqlite3DbMalloc).
74856: */
74857: SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
74858:   if( pVtab->zErrMsg ){
74859:     sqlite3 *db = p->db;
74860:     sqlite3DbFree(db, p->zErrMsg);
74861:     p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
74862:     sqlite3_free(pVtab->zErrMsg);
74863:     pVtab->zErrMsg = 0;
74864:   }
74865: }
74866: #endif /* SQLITE_OMIT_VIRTUALTABLE */
74867: 
74868: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74869: 
74870: /*
74871: ** If the second argument is not NULL, release any allocations associated 
74872: ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
74873: ** structure itself, using sqlite3DbFree().
74874: **
74875: ** This function is used to free UnpackedRecord structures allocated by
74876: ** the vdbeUnpackRecord() function found in vdbeapi.c.
74877: */
74878: static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
74879:   if( p ){
74880:     int i;
74881:     for(i=0; i<p->nField; i++){
74882:       Mem *pMem = &p->aMem[i];
74883:       if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
74884:     }
74885:     sqlite3DbFree(db, p);
74886:   }
74887: }
74888: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74889: 
74890: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74891: /*
74892: ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
74893: ** then cursor passed as the second argument should point to the row about
74894: ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
74895: ** the required value will be read from the row the cursor points to.
74896: */
74897: SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
74898:   Vdbe *v,                        /* Vdbe pre-update hook is invoked by */
74899:   VdbeCursor *pCsr,               /* Cursor to grab old.* values from */
74900:   int op,                         /* SQLITE_INSERT, UPDATE or DELETE */
74901:   const char *zDb,                /* Database name */
74902:   Table *pTab,                    /* Modified table */
74903:   i64 iKey1,                      /* Initial key value */
74904:   int iReg                        /* Register for new.* record */
74905: ){
74906:   sqlite3 *db = v->db;
74907:   i64 iKey2;
74908:   PreUpdate preupdate;
74909:   const char *zTbl = pTab->zName;
74910:   static const u8 fakeSortOrder = 0;
74911: 
74912:   assert( db->pPreUpdate==0 );
74913:   memset(&preupdate, 0, sizeof(PreUpdate));
74914:   if( op==SQLITE_UPDATE ){
74915:     iKey2 = v->aMem[iReg].u.i;
74916:   }else{
74917:     iKey2 = iKey1;
74918:   }
74919: 
74920:   assert( pCsr->nField==pTab->nCol 
74921:        || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
74922:   );
74923: 
74924:   preupdate.v = v;
74925:   preupdate.pCsr = pCsr;
74926:   preupdate.op = op;
74927:   preupdate.iNewReg = iReg;
74928:   preupdate.keyinfo.db = db;
74929:   preupdate.keyinfo.enc = ENC(db);
74930:   preupdate.keyinfo.nField = pTab->nCol;
74931:   preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
74932:   preupdate.iKey1 = iKey1;
74933:   preupdate.iKey2 = iKey2;
74934:   preupdate.iPKey = pTab->iPKey;
74935: 
74936:   db->pPreUpdate = &preupdate;
74937:   db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
74938:   db->pPreUpdate = 0;
74939:   sqlite3DbFree(db, preupdate.aRecord);
74940:   vdbeFreeUnpacked(db, preupdate.pUnpacked);
74941:   vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
74942:   if( preupdate.aNew ){
74943:     int i;
74944:     for(i=0; i<pCsr->nField; i++){
74945:       sqlite3VdbeMemRelease(&preupdate.aNew[i]);
74946:     }
74947:     sqlite3DbFree(db, preupdate.aNew);
74948:   }
74949: }
74950: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74951: 
74952: /************** End of vdbeaux.c *********************************************/
74953: /************** Begin file vdbeapi.c *****************************************/
74954: /*
74955: ** 2004 May 26
74956: **
74957: ** The author disclaims copyright to this source code.  In place of
74958: ** a legal notice, here is a blessing:
74959: **
74960: **    May you do good and not evil.
74961: **    May you find forgiveness for yourself and forgive others.
74962: **    May you share freely, never taking more than you give.
74963: **
74964: *************************************************************************
74965: **
74966: ** This file contains code use to implement APIs that are part of the
74967: ** VDBE.
74968: */
74969: /* #include "sqliteInt.h" */
74970: /* #include "vdbeInt.h" */
74971: 
74972: #ifndef SQLITE_OMIT_DEPRECATED
74973: /*
74974: ** Return TRUE (non-zero) of the statement supplied as an argument needs
74975: ** to be recompiled.  A statement needs to be recompiled whenever the
74976: ** execution environment changes in a way that would alter the program
74977: ** that sqlite3_prepare() generates.  For example, if new functions or
74978: ** collating sequences are registered or if an authorizer function is
74979: ** added or changed.
74980: */
74981: SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
74982:   Vdbe *p = (Vdbe*)pStmt;
74983:   return p==0 || p->expired;
74984: }
74985: #endif
74986: 
74987: /*
74988: ** Check on a Vdbe to make sure it has not been finalized.  Log
74989: ** an error and return true if it has been finalized (or is otherwise
74990: ** invalid).  Return false if it is ok.
74991: */
74992: static int vdbeSafety(Vdbe *p){
74993:   if( p->db==0 ){
74994:     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
74995:     return 1;
74996:   }else{
74997:     return 0;
74998:   }
74999: }
75000: static int vdbeSafetyNotNull(Vdbe *p){
75001:   if( p==0 ){
75002:     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
75003:     return 1;
75004:   }else{
75005:     return vdbeSafety(p);
75006:   }
75007: }
75008: 
75009: #ifndef SQLITE_OMIT_TRACE
75010: /*
75011: ** Invoke the profile callback.  This routine is only called if we already
75012: ** know that the profile callback is defined and needs to be invoked.
75013: */
75014: static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
75015:   sqlite3_int64 iNow;
75016:   sqlite3_int64 iElapse;
75017:   assert( p->startTime>0 );
75018:   assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
75019:   assert( db->init.busy==0 );
75020:   assert( p->zSql!=0 );
75021:   sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
75022:   iElapse = (iNow - p->startTime)*1000000;
75023:   if( db->xProfile ){
75024:     db->xProfile(db->pProfileArg, p->zSql, iElapse);
75025:   }
75026:   if( db->mTrace & SQLITE_TRACE_PROFILE ){
75027:     db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
75028:   }
75029:   p->startTime = 0;
75030: }
75031: /*
75032: ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
75033: ** is needed, and it invokes the callback if it is needed.
75034: */
75035: # define checkProfileCallback(DB,P) \
75036:    if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
75037: #else
75038: # define checkProfileCallback(DB,P)  /*no-op*/
75039: #endif
75040: 
75041: /*
75042: ** The following routine destroys a virtual machine that is created by
75043: ** the sqlite3_compile() routine. The integer returned is an SQLITE_
75044: ** success/failure code that describes the result of executing the virtual
75045: ** machine.
75046: **
75047: ** This routine sets the error code and string returned by
75048: ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75049: */
75050: SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
75051:   int rc;
75052:   if( pStmt==0 ){
75053:     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
75054:     ** pointer is a harmless no-op. */
75055:     rc = SQLITE_OK;
75056:   }else{
75057:     Vdbe *v = (Vdbe*)pStmt;
75058:     sqlite3 *db = v->db;
75059:     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
75060:     sqlite3_mutex_enter(db->mutex);
75061:     checkProfileCallback(db, v);
75062:     rc = sqlite3VdbeFinalize(v);
75063:     rc = sqlite3ApiExit(db, rc);
75064:     sqlite3LeaveMutexAndCloseZombie(db);
75065:   }
75066:   return rc;
75067: }
75068: 
75069: /*
75070: ** Terminate the current execution of an SQL statement and reset it
75071: ** back to its starting state so that it can be reused. A success code from
75072: ** the prior execution is returned.
75073: **
75074: ** This routine sets the error code and string returned by
75075: ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
75076: */
75077: SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
75078:   int rc;
75079:   if( pStmt==0 ){
75080:     rc = SQLITE_OK;
75081:   }else{
75082:     Vdbe *v = (Vdbe*)pStmt;
75083:     sqlite3 *db = v->db;
75084:     sqlite3_mutex_enter(db->mutex);
75085:     checkProfileCallback(db, v);
75086:     rc = sqlite3VdbeReset(v);
75087:     sqlite3VdbeRewind(v);
75088:     assert( (rc & (db->errMask))==rc );
75089:     rc = sqlite3ApiExit(db, rc);
75090:     sqlite3_mutex_leave(db->mutex);
75091:   }
75092:   return rc;
75093: }
75094: 
75095: /*
75096: ** Set all the parameters in the compiled SQL statement to NULL.
75097: */
75098: SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
75099:   int i;
75100:   int rc = SQLITE_OK;
75101:   Vdbe *p = (Vdbe*)pStmt;
75102: #if SQLITE_THREADSAFE
75103:   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
75104: #endif
75105:   sqlite3_mutex_enter(mutex);
75106:   for(i=0; i<p->nVar; i++){
75107:     sqlite3VdbeMemRelease(&p->aVar[i]);
75108:     p->aVar[i].flags = MEM_Null;
75109:   }
75110:   if( p->isPrepareV2 && p->expmask ){
75111:     p->expired = 1;
75112:   }
75113:   sqlite3_mutex_leave(mutex);
75114:   return rc;
75115: }
75116: 
75117: 
75118: /**************************** sqlite3_value_  *******************************
75119: ** The following routines extract information from a Mem or sqlite3_value
75120: ** structure.
75121: */
75122: SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
75123:   Mem *p = (Mem*)pVal;
75124:   if( p->flags & (MEM_Blob|MEM_Str) ){
75125:     if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
75126:       assert( p->flags==MEM_Null && p->z==0 );
75127:       return 0;
75128:     }
75129:     p->flags |= MEM_Blob;
75130:     return p->n ? p->z : 0;
75131:   }else{
75132:     return sqlite3_value_text(pVal);
75133:   }
75134: }
75135: SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
75136:   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
75137: }
75138: SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
75139:   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
75140: }
75141: SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
75142:   return sqlite3VdbeRealValue((Mem*)pVal);
75143: }
75144: SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
75145:   return (int)sqlite3VdbeIntValue((Mem*)pVal);
75146: }
75147: SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
75148:   return sqlite3VdbeIntValue((Mem*)pVal);
75149: }
75150: SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
75151:   Mem *pMem = (Mem*)pVal;
75152:   return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
75153: }
75154: SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
75155:   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
75156: }
75157: #ifndef SQLITE_OMIT_UTF16
75158: SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
75159:   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
75160: }
75161: SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
75162:   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
75163: }
75164: SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
75165:   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
75166: }
75167: #endif /* SQLITE_OMIT_UTF16 */
75168: /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
75169: ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
75170: ** point number string BLOB NULL
75171: */
75172: SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
75173:   static const u8 aType[] = {
75174:      SQLITE_BLOB,     /* 0x00 */
75175:      SQLITE_NULL,     /* 0x01 */
75176:      SQLITE_TEXT,     /* 0x02 */
75177:      SQLITE_NULL,     /* 0x03 */
75178:      SQLITE_INTEGER,  /* 0x04 */
75179:      SQLITE_NULL,     /* 0x05 */
75180:      SQLITE_INTEGER,  /* 0x06 */
75181:      SQLITE_NULL,     /* 0x07 */
75182:      SQLITE_FLOAT,    /* 0x08 */
75183:      SQLITE_NULL,     /* 0x09 */
75184:      SQLITE_FLOAT,    /* 0x0a */
75185:      SQLITE_NULL,     /* 0x0b */
75186:      SQLITE_INTEGER,  /* 0x0c */
75187:      SQLITE_NULL,     /* 0x0d */
75188:      SQLITE_INTEGER,  /* 0x0e */
75189:      SQLITE_NULL,     /* 0x0f */
75190:      SQLITE_BLOB,     /* 0x10 */
75191:      SQLITE_NULL,     /* 0x11 */
75192:      SQLITE_TEXT,     /* 0x12 */
75193:      SQLITE_NULL,     /* 0x13 */
75194:      SQLITE_INTEGER,  /* 0x14 */
75195:      SQLITE_NULL,     /* 0x15 */
75196:      SQLITE_INTEGER,  /* 0x16 */
75197:      SQLITE_NULL,     /* 0x17 */
75198:      SQLITE_FLOAT,    /* 0x18 */
75199:      SQLITE_NULL,     /* 0x19 */
75200:      SQLITE_FLOAT,    /* 0x1a */
75201:      SQLITE_NULL,     /* 0x1b */
75202:      SQLITE_INTEGER,  /* 0x1c */
75203:      SQLITE_NULL,     /* 0x1d */
75204:      SQLITE_INTEGER,  /* 0x1e */
75205:      SQLITE_NULL,     /* 0x1f */
75206:   };
75207:   return aType[pVal->flags&MEM_AffMask];
75208: }
75209: 
75210: /* Make a copy of an sqlite3_value object
75211: */
75212: SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
75213:   sqlite3_value *pNew;
75214:   if( pOrig==0 ) return 0;
75215:   pNew = sqlite3_malloc( sizeof(*pNew) );
75216:   if( pNew==0 ) return 0;
75217:   memset(pNew, 0, sizeof(*pNew));
75218:   memcpy(pNew, pOrig, MEMCELLSIZE);
75219:   pNew->flags &= ~MEM_Dyn;
75220:   pNew->db = 0;
75221:   if( pNew->flags&(MEM_Str|MEM_Blob) ){
75222:     pNew->flags &= ~(MEM_Static|MEM_Dyn);
75223:     pNew->flags |= MEM_Ephem;
75224:     if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
75225:       sqlite3ValueFree(pNew);
75226:       pNew = 0;
75227:     }
75228:   }
75229:   return pNew;
75230: }
75231: 
75232: /* Destroy an sqlite3_value object previously obtained from
75233: ** sqlite3_value_dup().
75234: */
75235: SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
75236:   sqlite3ValueFree(pOld);
75237: }
75238:   
75239: 
75240: /**************************** sqlite3_result_  *******************************
75241: ** The following routines are used by user-defined functions to specify
75242: ** the function result.
75243: **
75244: ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
75245: ** result as a string or blob but if the string or blob is too large, it
75246: ** then sets the error code to SQLITE_TOOBIG
75247: **
75248: ** The invokeValueDestructor(P,X) routine invokes destructor function X()
75249: ** on value P is not going to be used and need to be destroyed.
75250: */
75251: static void setResultStrOrError(
75252:   sqlite3_context *pCtx,  /* Function context */
75253:   const char *z,          /* String pointer */
75254:   int n,                  /* Bytes in string, or negative */
75255:   u8 enc,                 /* Encoding of z.  0 for BLOBs */
75256:   void (*xDel)(void*)     /* Destructor function */
75257: ){
75258:   if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
75259:     sqlite3_result_error_toobig(pCtx);
75260:   }
75261: }
75262: static int invokeValueDestructor(
75263:   const void *p,             /* Value to destroy */
75264:   void (*xDel)(void*),       /* The destructor */
75265:   sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
75266: ){
75267:   assert( xDel!=SQLITE_DYNAMIC );
75268:   if( xDel==0 ){
75269:     /* noop */
75270:   }else if( xDel==SQLITE_TRANSIENT ){
75271:     /* noop */
75272:   }else{
75273:     xDel((void*)p);
75274:   }
75275:   if( pCtx ) sqlite3_result_error_toobig(pCtx);
75276:   return SQLITE_TOOBIG;
75277: }
75278: SQLITE_API void sqlite3_result_blob(
75279:   sqlite3_context *pCtx, 
75280:   const void *z, 
75281:   int n, 
75282:   void (*xDel)(void *)
75283: ){
75284:   assert( n>=0 );
75285:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75286:   setResultStrOrError(pCtx, z, n, 0, xDel);
75287: }
75288: SQLITE_API void sqlite3_result_blob64(
75289:   sqlite3_context *pCtx, 
75290:   const void *z, 
75291:   sqlite3_uint64 n,
75292:   void (*xDel)(void *)
75293: ){
75294:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75295:   assert( xDel!=SQLITE_DYNAMIC );
75296:   if( n>0x7fffffff ){
75297:     (void)invokeValueDestructor(z, xDel, pCtx);
75298:   }else{
75299:     setResultStrOrError(pCtx, z, (int)n, 0, xDel);
75300:   }
75301: }
75302: SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
75303:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75304:   sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
75305: }
75306: SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
75307:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75308:   pCtx->isError = SQLITE_ERROR;
75309:   pCtx->fErrorOrAux = 1;
75310:   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
75311: }
75312: #ifndef SQLITE_OMIT_UTF16
75313: SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
75314:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75315:   pCtx->isError = SQLITE_ERROR;
75316:   pCtx->fErrorOrAux = 1;
75317:   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
75318: }
75319: #endif
75320: SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
75321:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75322:   sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
75323: }
75324: SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
75325:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75326:   sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
75327: }
75328: SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
75329:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75330:   sqlite3VdbeMemSetNull(pCtx->pOut);
75331: }
75332: SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
75333:   Mem *pOut = pCtx->pOut;
75334:   assert( sqlite3_mutex_held(pOut->db->mutex) );
75335:   pOut->eSubtype = eSubtype & 0xff;
75336:   pOut->flags |= MEM_Subtype;
75337: }
75338: SQLITE_API void sqlite3_result_text(
75339:   sqlite3_context *pCtx, 
75340:   const char *z, 
75341:   int n,
75342:   void (*xDel)(void *)
75343: ){
75344:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75345:   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
75346: }
75347: SQLITE_API void sqlite3_result_text64(
75348:   sqlite3_context *pCtx, 
75349:   const char *z, 
75350:   sqlite3_uint64 n,
75351:   void (*xDel)(void *),
75352:   unsigned char enc
75353: ){
75354:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75355:   assert( xDel!=SQLITE_DYNAMIC );
75356:   if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
75357:   if( n>0x7fffffff ){
75358:     (void)invokeValueDestructor(z, xDel, pCtx);
75359:   }else{
75360:     setResultStrOrError(pCtx, z, (int)n, enc, xDel);
75361:   }
75362: }
75363: #ifndef SQLITE_OMIT_UTF16
75364: SQLITE_API void sqlite3_result_text16(
75365:   sqlite3_context *pCtx, 
75366:   const void *z, 
75367:   int n, 
75368:   void (*xDel)(void *)
75369: ){
75370:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75371:   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
75372: }
75373: SQLITE_API void sqlite3_result_text16be(
75374:   sqlite3_context *pCtx, 
75375:   const void *z, 
75376:   int n, 
75377:   void (*xDel)(void *)
75378: ){
75379:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75380:   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
75381: }
75382: SQLITE_API void sqlite3_result_text16le(
75383:   sqlite3_context *pCtx, 
75384:   const void *z, 
75385:   int n, 
75386:   void (*xDel)(void *)
75387: ){
75388:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75389:   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
75390: }
75391: #endif /* SQLITE_OMIT_UTF16 */
75392: SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
75393:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75394:   sqlite3VdbeMemCopy(pCtx->pOut, pValue);
75395: }
75396: SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
75397:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75398:   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
75399: }
75400: SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
75401:   Mem *pOut = pCtx->pOut;
75402:   assert( sqlite3_mutex_held(pOut->db->mutex) );
75403:   if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
75404:     return SQLITE_TOOBIG;
75405:   }
75406:   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
75407:   return SQLITE_OK;
75408: }
75409: SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
75410:   pCtx->isError = errCode;
75411:   pCtx->fErrorOrAux = 1;
75412: #ifdef SQLITE_DEBUG
75413:   if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
75414: #endif
75415:   if( pCtx->pOut->flags & MEM_Null ){
75416:     sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, 
75417:                          SQLITE_UTF8, SQLITE_STATIC);
75418:   }
75419: }
75420: 
75421: /* Force an SQLITE_TOOBIG error. */
75422: SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
75423:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75424:   pCtx->isError = SQLITE_TOOBIG;
75425:   pCtx->fErrorOrAux = 1;
75426:   sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, 
75427:                        SQLITE_UTF8, SQLITE_STATIC);
75428: }
75429: 
75430: /* An SQLITE_NOMEM error. */
75431: SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
75432:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75433:   sqlite3VdbeMemSetNull(pCtx->pOut);
75434:   pCtx->isError = SQLITE_NOMEM_BKPT;
75435:   pCtx->fErrorOrAux = 1;
75436:   sqlite3OomFault(pCtx->pOut->db);
75437: }
75438: 
75439: /*
75440: ** This function is called after a transaction has been committed. It 
75441: ** invokes callbacks registered with sqlite3_wal_hook() as required.
75442: */
75443: static int doWalCallbacks(sqlite3 *db){
75444:   int rc = SQLITE_OK;
75445: #ifndef SQLITE_OMIT_WAL
75446:   int i;
75447:   for(i=0; i<db->nDb; i++){
75448:     Btree *pBt = db->aDb[i].pBt;
75449:     if( pBt ){
75450:       int nEntry;
75451:       sqlite3BtreeEnter(pBt);
75452:       nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
75453:       sqlite3BtreeLeave(pBt);
75454:       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
75455:         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
75456:       }
75457:     }
75458:   }
75459: #endif
75460:   return rc;
75461: }
75462: 
75463: 
75464: /*
75465: ** Execute the statement pStmt, either until a row of data is ready, the
75466: ** statement is completely executed or an error occurs.
75467: **
75468: ** This routine implements the bulk of the logic behind the sqlite_step()
75469: ** API.  The only thing omitted is the automatic recompile if a 
75470: ** schema change has occurred.  That detail is handled by the
75471: ** outer sqlite3_step() wrapper procedure.
75472: */
75473: static int sqlite3Step(Vdbe *p){
75474:   sqlite3 *db;
75475:   int rc;
75476: 
75477:   assert(p);
75478:   if( p->magic!=VDBE_MAGIC_RUN ){
75479:     /* We used to require that sqlite3_reset() be called before retrying
75480:     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
75481:     ** with version 3.7.0, we changed this so that sqlite3_reset() would
75482:     ** be called automatically instead of throwing the SQLITE_MISUSE error.
75483:     ** This "automatic-reset" change is not technically an incompatibility, 
75484:     ** since any application that receives an SQLITE_MISUSE is broken by
75485:     ** definition.
75486:     **
75487:     ** Nevertheless, some published applications that were originally written
75488:     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
75489:     ** returns, and those were broken by the automatic-reset change.  As a
75490:     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
75491:     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
75492:     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
75493:     ** or SQLITE_BUSY error.
75494:     */
75495: #ifdef SQLITE_OMIT_AUTORESET
75496:     if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
75497:       sqlite3_reset((sqlite3_stmt*)p);
75498:     }else{
75499:       return SQLITE_MISUSE_BKPT;
75500:     }
75501: #else
75502:     sqlite3_reset((sqlite3_stmt*)p);
75503: #endif
75504:   }
75505: 
75506:   /* Check that malloc() has not failed. If it has, return early. */
75507:   db = p->db;
75508:   if( db->mallocFailed ){
75509:     p->rc = SQLITE_NOMEM;
75510:     return SQLITE_NOMEM_BKPT;
75511:   }
75512: 
75513:   if( p->pc<=0 && p->expired ){
75514:     p->rc = SQLITE_SCHEMA;
75515:     rc = SQLITE_ERROR;
75516:     goto end_of_step;
75517:   }
75518:   if( p->pc<0 ){
75519:     /* If there are no other statements currently running, then
75520:     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
75521:     ** from interrupting a statement that has not yet started.
75522:     */
75523:     if( db->nVdbeActive==0 ){
75524:       db->u1.isInterrupted = 0;
75525:     }
75526: 
75527:     assert( db->nVdbeWrite>0 || db->autoCommit==0 
75528:         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
75529:     );
75530: 
75531: #ifndef SQLITE_OMIT_TRACE
75532:     if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
75533:         && !db->init.busy && p->zSql ){
75534:       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
75535:     }else{
75536:       assert( p->startTime==0 );
75537:     }
75538: #endif
75539: 
75540:     db->nVdbeActive++;
75541:     if( p->readOnly==0 ) db->nVdbeWrite++;
75542:     if( p->bIsReader ) db->nVdbeRead++;
75543:     p->pc = 0;
75544:   }
75545: #ifdef SQLITE_DEBUG
75546:   p->rcApp = SQLITE_OK;
75547: #endif
75548: #ifndef SQLITE_OMIT_EXPLAIN
75549:   if( p->explain ){
75550:     rc = sqlite3VdbeList(p);
75551:   }else
75552: #endif /* SQLITE_OMIT_EXPLAIN */
75553:   {
75554:     db->nVdbeExec++;
75555:     rc = sqlite3VdbeExec(p);
75556:     db->nVdbeExec--;
75557:   }
75558: 
75559: #ifndef SQLITE_OMIT_TRACE
75560:   /* If the statement completed successfully, invoke the profile callback */
75561:   if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
75562: #endif
75563: 
75564:   if( rc==SQLITE_DONE ){
75565:     assert( p->rc==SQLITE_OK );
75566:     p->rc = doWalCallbacks(db);
75567:     if( p->rc!=SQLITE_OK ){
75568:       rc = SQLITE_ERROR;
75569:     }
75570:   }
75571: 
75572:   db->errCode = rc;
75573:   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
75574:     p->rc = SQLITE_NOMEM_BKPT;
75575:   }
75576: end_of_step:
75577:   /* At this point local variable rc holds the value that should be 
75578:   ** returned if this statement was compiled using the legacy 
75579:   ** sqlite3_prepare() interface. According to the docs, this can only
75580:   ** be one of the values in the first assert() below. Variable p->rc 
75581:   ** contains the value that would be returned if sqlite3_finalize() 
75582:   ** were called on statement p.
75583:   */
75584:   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
75585:        || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
75586:   );
75587:   assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
75588:   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
75589:     /* If this statement was prepared using sqlite3_prepare_v2(), and an
75590:     ** error has occurred, then return the error code in p->rc to the
75591:     ** caller. Set the error code in the database handle to the same value.
75592:     */ 
75593:     rc = sqlite3VdbeTransferError(p);
75594:   }
75595:   return (rc&db->errMask);
75596: }
75597: 
75598: /*
75599: ** This is the top-level implementation of sqlite3_step().  Call
75600: ** sqlite3Step() to do most of the work.  If a schema error occurs,
75601: ** call sqlite3Reprepare() and try again.
75602: */
75603: SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
75604:   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
75605:   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
75606:   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
75607:   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
75608:   sqlite3 *db;             /* The database connection */
75609: 
75610:   if( vdbeSafetyNotNull(v) ){
75611:     return SQLITE_MISUSE_BKPT;
75612:   }
75613:   db = v->db;
75614:   sqlite3_mutex_enter(db->mutex);
75615:   v->doingRerun = 0;
75616:   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
75617:          && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
75618:     int savedPc = v->pc;
75619:     rc2 = rc = sqlite3Reprepare(v);
75620:     if( rc!=SQLITE_OK) break;
75621:     sqlite3_reset(pStmt);
75622:     if( savedPc>=0 ) v->doingRerun = 1;
75623:     assert( v->expired==0 );
75624:   }
75625:   if( rc2!=SQLITE_OK ){
75626:     /* This case occurs after failing to recompile an sql statement. 
75627:     ** The error message from the SQL compiler has already been loaded 
75628:     ** into the database handle. This block copies the error message 
75629:     ** from the database handle into the statement and sets the statement
75630:     ** program counter to 0 to ensure that when the statement is 
75631:     ** finalized or reset the parser error message is available via
75632:     ** sqlite3_errmsg() and sqlite3_errcode().
75633:     */
75634:     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
75635:     sqlite3DbFree(db, v->zErrMsg);
75636:     if( !db->mallocFailed ){
75637:       v->zErrMsg = sqlite3DbStrDup(db, zErr);
75638:       v->rc = rc2;
75639:     } else {
75640:       v->zErrMsg = 0;
75641:       v->rc = rc = SQLITE_NOMEM_BKPT;
75642:     }
75643:   }
75644:   rc = sqlite3ApiExit(db, rc);
75645:   sqlite3_mutex_leave(db->mutex);
75646:   return rc;
75647: }
75648: 
75649: 
75650: /*
75651: ** Extract the user data from a sqlite3_context structure and return a
75652: ** pointer to it.
75653: */
75654: SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
75655:   assert( p && p->pFunc );
75656:   return p->pFunc->pUserData;
75657: }
75658: 
75659: /*
75660: ** Extract the user data from a sqlite3_context structure and return a
75661: ** pointer to it.
75662: **
75663: ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
75664: ** returns a copy of the pointer to the database connection (the 1st
75665: ** parameter) of the sqlite3_create_function() and
75666: ** sqlite3_create_function16() routines that originally registered the
75667: ** application defined function.
75668: */
75669: SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
75670:   assert( p && p->pOut );
75671:   return p->pOut->db;
75672: }
75673: 
75674: /*
75675: ** Return the current time for a statement.  If the current time
75676: ** is requested more than once within the same run of a single prepared
75677: ** statement, the exact same time is returned for each invocation regardless
75678: ** of the amount of time that elapses between invocations.  In other words,
75679: ** the time returned is always the time of the first call.
75680: */
75681: SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
75682:   int rc;
75683: #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
75684:   sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
75685:   assert( p->pVdbe!=0 );
75686: #else
75687:   sqlite3_int64 iTime = 0;
75688:   sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
75689: #endif
75690:   if( *piTime==0 ){
75691:     rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
75692:     if( rc ) *piTime = 0;
75693:   }
75694:   return *piTime;
75695: }
75696: 
75697: /*
75698: ** The following is the implementation of an SQL function that always
75699: ** fails with an error message stating that the function is used in the
75700: ** wrong context.  The sqlite3_overload_function() API might construct
75701: ** SQL function that use this routine so that the functions will exist
75702: ** for name resolution but are actually overloaded by the xFindFunction
75703: ** method of virtual tables.
75704: */
75705: SQLITE_PRIVATE void sqlite3InvalidFunction(
75706:   sqlite3_context *context,  /* The function calling context */
75707:   int NotUsed,               /* Number of arguments to the function */
75708:   sqlite3_value **NotUsed2   /* Value of each argument */
75709: ){
75710:   const char *zName = context->pFunc->zName;
75711:   char *zErr;
75712:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
75713:   zErr = sqlite3_mprintf(
75714:       "unable to use function %s in the requested context", zName);
75715:   sqlite3_result_error(context, zErr, -1);
75716:   sqlite3_free(zErr);
75717: }
75718: 
75719: /*
75720: ** Create a new aggregate context for p and return a pointer to
75721: ** its pMem->z element.
75722: */
75723: static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
75724:   Mem *pMem = p->pMem;
75725:   assert( (pMem->flags & MEM_Agg)==0 );
75726:   if( nByte<=0 ){
75727:     sqlite3VdbeMemSetNull(pMem);
75728:     pMem->z = 0;
75729:   }else{
75730:     sqlite3VdbeMemClearAndResize(pMem, nByte);
75731:     pMem->flags = MEM_Agg;
75732:     pMem->u.pDef = p->pFunc;
75733:     if( pMem->z ){
75734:       memset(pMem->z, 0, nByte);
75735:     }
75736:   }
75737:   return (void*)pMem->z;
75738: }
75739: 
75740: /*
75741: ** Allocate or return the aggregate context for a user function.  A new
75742: ** context is allocated on the first call.  Subsequent calls return the
75743: ** same context that was returned on prior calls.
75744: */
75745: SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
75746:   assert( p && p->pFunc && p->pFunc->xFinalize );
75747:   assert( sqlite3_mutex_held(p->pOut->db->mutex) );
75748:   testcase( nByte<0 );
75749:   if( (p->pMem->flags & MEM_Agg)==0 ){
75750:     return createAggContext(p, nByte);
75751:   }else{
75752:     return (void*)p->pMem->z;
75753:   }
75754: }
75755: 
75756: /*
75757: ** Return the auxiliary data pointer, if any, for the iArg'th argument to
75758: ** the user-function defined by pCtx.
75759: */
75760: SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
75761:   AuxData *pAuxData;
75762: 
75763:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75764: #if SQLITE_ENABLE_STAT3_OR_STAT4
75765:   if( pCtx->pVdbe==0 ) return 0;
75766: #else
75767:   assert( pCtx->pVdbe!=0 );
75768: #endif
75769:   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75770:     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75771:   }
75772: 
75773:   return (pAuxData ? pAuxData->pAux : 0);
75774: }
75775: 
75776: /*
75777: ** Set the auxiliary data pointer and delete function, for the iArg'th
75778: ** argument to the user-function defined by pCtx. Any previous value is
75779: ** deleted by calling the delete function specified when it was set.
75780: */
75781: SQLITE_API void sqlite3_set_auxdata(
75782:   sqlite3_context *pCtx, 
75783:   int iArg, 
75784:   void *pAux, 
75785:   void (*xDelete)(void*)
75786: ){
75787:   AuxData *pAuxData;
75788:   Vdbe *pVdbe = pCtx->pVdbe;
75789: 
75790:   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75791:   if( iArg<0 ) goto failed;
75792: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
75793:   if( pVdbe==0 ) goto failed;
75794: #else
75795:   assert( pVdbe!=0 );
75796: #endif
75797: 
75798:   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75799:     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75800:   }
75801:   if( pAuxData==0 ){
75802:     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
75803:     if( !pAuxData ) goto failed;
75804:     pAuxData->iOp = pCtx->iOp;
75805:     pAuxData->iArg = iArg;
75806:     pAuxData->pNext = pVdbe->pAuxData;
75807:     pVdbe->pAuxData = pAuxData;
75808:     if( pCtx->fErrorOrAux==0 ){
75809:       pCtx->isError = 0;
75810:       pCtx->fErrorOrAux = 1;
75811:     }
75812:   }else if( pAuxData->xDelete ){
75813:     pAuxData->xDelete(pAuxData->pAux);
75814:   }
75815: 
75816:   pAuxData->pAux = pAux;
75817:   pAuxData->xDelete = xDelete;
75818:   return;
75819: 
75820: failed:
75821:   if( xDelete ){
75822:     xDelete(pAux);
75823:   }
75824: }
75825: 
75826: #ifndef SQLITE_OMIT_DEPRECATED
75827: /*
75828: ** Return the number of times the Step function of an aggregate has been 
75829: ** called.
75830: **
75831: ** This function is deprecated.  Do not use it for new code.  It is
75832: ** provide only to avoid breaking legacy code.  New aggregate function
75833: ** implementations should keep their own counts within their aggregate
75834: ** context.
75835: */
75836: SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
75837:   assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
75838:   return p->pMem->n;
75839: }
75840: #endif
75841: 
75842: /*
75843: ** Return the number of columns in the result set for the statement pStmt.
75844: */
75845: SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
75846:   Vdbe *pVm = (Vdbe *)pStmt;
75847:   return pVm ? pVm->nResColumn : 0;
75848: }
75849: 
75850: /*
75851: ** Return the number of values available from the current row of the
75852: ** currently executing statement pStmt.
75853: */
75854: SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
75855:   Vdbe *pVm = (Vdbe *)pStmt;
75856:   if( pVm==0 || pVm->pResultSet==0 ) return 0;
75857:   return pVm->nResColumn;
75858: }
75859: 
75860: /*
75861: ** Return a pointer to static memory containing an SQL NULL value.
75862: */
75863: static const Mem *columnNullValue(void){
75864:   /* Even though the Mem structure contains an element
75865:   ** of type i64, on certain architectures (x86) with certain compiler
75866:   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
75867:   ** instead of an 8-byte one. This all works fine, except that when
75868:   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
75869:   ** that a Mem structure is located on an 8-byte boundary. To prevent
75870:   ** these assert()s from failing, when building with SQLITE_DEBUG defined
75871:   ** using gcc, we force nullMem to be 8-byte aligned using the magical
75872:   ** __attribute__((aligned(8))) macro.  */
75873:   static const Mem nullMem 
75874: #if defined(SQLITE_DEBUG) && defined(__GNUC__)
75875:     __attribute__((aligned(8))) 
75876: #endif
75877:     = {
75878:         /* .u          = */ {0},
75879:         /* .flags      = */ (u16)MEM_Null,
75880:         /* .enc        = */ (u8)0,
75881:         /* .eSubtype   = */ (u8)0,
75882:         /* .n          = */ (int)0,
75883:         /* .z          = */ (char*)0,
75884:         /* .zMalloc    = */ (char*)0,
75885:         /* .szMalloc   = */ (int)0,
75886:         /* .uTemp      = */ (u32)0,
75887:         /* .db         = */ (sqlite3*)0,
75888:         /* .xDel       = */ (void(*)(void*))0,
75889: #ifdef SQLITE_DEBUG
75890:         /* .pScopyFrom = */ (Mem*)0,
75891:         /* .pFiller    = */ (void*)0,
75892: #endif
75893:       };
75894:   return &nullMem;
75895: }
75896: 
75897: /*
75898: ** Check to see if column iCol of the given statement is valid.  If
75899: ** it is, return a pointer to the Mem for the value of that column.
75900: ** If iCol is not valid, return a pointer to a Mem which has a value
75901: ** of NULL.
75902: */
75903: static Mem *columnMem(sqlite3_stmt *pStmt, int i){
75904:   Vdbe *pVm;
75905:   Mem *pOut;
75906: 
75907:   pVm = (Vdbe *)pStmt;
75908:   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
75909:     sqlite3_mutex_enter(pVm->db->mutex);
75910:     pOut = &pVm->pResultSet[i];
75911:   }else{
75912:     if( pVm && ALWAYS(pVm->db) ){
75913:       sqlite3_mutex_enter(pVm->db->mutex);
75914:       sqlite3Error(pVm->db, SQLITE_RANGE);
75915:     }
75916:     pOut = (Mem*)columnNullValue();
75917:   }
75918:   return pOut;
75919: }
75920: 
75921: /*
75922: ** This function is called after invoking an sqlite3_value_XXX function on a 
75923: ** column value (i.e. a value returned by evaluating an SQL expression in the
75924: ** select list of a SELECT statement) that may cause a malloc() failure. If 
75925: ** malloc() has failed, the threads mallocFailed flag is cleared and the result
75926: ** code of statement pStmt set to SQLITE_NOMEM.
75927: **
75928: ** Specifically, this is called from within:
75929: **
75930: **     sqlite3_column_int()
75931: **     sqlite3_column_int64()
75932: **     sqlite3_column_text()
75933: **     sqlite3_column_text16()
75934: **     sqlite3_column_real()
75935: **     sqlite3_column_bytes()
75936: **     sqlite3_column_bytes16()
75937: **     sqiite3_column_blob()
75938: */
75939: static void columnMallocFailure(sqlite3_stmt *pStmt)
75940: {
75941:   /* If malloc() failed during an encoding conversion within an
75942:   ** sqlite3_column_XXX API, then set the return code of the statement to
75943:   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
75944:   ** and _finalize() will return NOMEM.
75945:   */
75946:   Vdbe *p = (Vdbe *)pStmt;
75947:   if( p ){
75948:     p->rc = sqlite3ApiExit(p->db, p->rc);
75949:     sqlite3_mutex_leave(p->db->mutex);
75950:   }
75951: }
75952: 
75953: /**************************** sqlite3_column_  *******************************
75954: ** The following routines are used to access elements of the current row
75955: ** in the result set.
75956: */
75957: SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
75958:   const void *val;
75959:   val = sqlite3_value_blob( columnMem(pStmt,i) );
75960:   /* Even though there is no encoding conversion, value_blob() might
75961:   ** need to call malloc() to expand the result of a zeroblob() 
75962:   ** expression. 
75963:   */
75964:   columnMallocFailure(pStmt);
75965:   return val;
75966: }
75967: SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
75968:   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
75969:   columnMallocFailure(pStmt);
75970:   return val;
75971: }
75972: SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
75973:   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
75974:   columnMallocFailure(pStmt);
75975:   return val;
75976: }
75977: SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
75978:   double val = sqlite3_value_double( columnMem(pStmt,i) );
75979:   columnMallocFailure(pStmt);
75980:   return val;
75981: }
75982: SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
75983:   int val = sqlite3_value_int( columnMem(pStmt,i) );
75984:   columnMallocFailure(pStmt);
75985:   return val;
75986: }
75987: SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
75988:   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
75989:   columnMallocFailure(pStmt);
75990:   return val;
75991: }
75992: SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
75993:   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
75994:   columnMallocFailure(pStmt);
75995:   return val;
75996: }
75997: SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
75998:   Mem *pOut = columnMem(pStmt, i);
75999:   if( pOut->flags&MEM_Static ){
76000:     pOut->flags &= ~MEM_Static;
76001:     pOut->flags |= MEM_Ephem;
76002:   }
76003:   columnMallocFailure(pStmt);
76004:   return (sqlite3_value *)pOut;
76005: }
76006: #ifndef SQLITE_OMIT_UTF16
76007: SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
76008:   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
76009:   columnMallocFailure(pStmt);
76010:   return val;
76011: }
76012: #endif /* SQLITE_OMIT_UTF16 */
76013: SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
76014:   int iType = sqlite3_value_type( columnMem(pStmt,i) );
76015:   columnMallocFailure(pStmt);
76016:   return iType;
76017: }
76018: 
76019: /*
76020: ** Convert the N-th element of pStmt->pColName[] into a string using
76021: ** xFunc() then return that string.  If N is out of range, return 0.
76022: **
76023: ** There are up to 5 names for each column.  useType determines which
76024: ** name is returned.  Here are the names:
76025: **
76026: **    0      The column name as it should be displayed for output
76027: **    1      The datatype name for the column
76028: **    2      The name of the database that the column derives from
76029: **    3      The name of the table that the column derives from
76030: **    4      The name of the table column that the result column derives from
76031: **
76032: ** If the result is not a simple column reference (if it is an expression
76033: ** or a constant) then useTypes 2, 3, and 4 return NULL.
76034: */
76035: static const void *columnName(
76036:   sqlite3_stmt *pStmt,
76037:   int N,
76038:   const void *(*xFunc)(Mem*),
76039:   int useType
76040: ){
76041:   const void *ret;
76042:   Vdbe *p;
76043:   int n;
76044:   sqlite3 *db;
76045: #ifdef SQLITE_ENABLE_API_ARMOR
76046:   if( pStmt==0 ){
76047:     (void)SQLITE_MISUSE_BKPT;
76048:     return 0;
76049:   }
76050: #endif
76051:   ret = 0;
76052:   p = (Vdbe *)pStmt;
76053:   db = p->db;
76054:   assert( db!=0 );
76055:   n = sqlite3_column_count(pStmt);
76056:   if( N<n && N>=0 ){
76057:     N += useType*n;
76058:     sqlite3_mutex_enter(db->mutex);
76059:     assert( db->mallocFailed==0 );
76060:     ret = xFunc(&p->aColName[N]);
76061:      /* A malloc may have failed inside of the xFunc() call. If this
76062:     ** is the case, clear the mallocFailed flag and return NULL.
76063:     */
76064:     if( db->mallocFailed ){
76065:       sqlite3OomClear(db);
76066:       ret = 0;
76067:     }
76068:     sqlite3_mutex_leave(db->mutex);
76069:   }
76070:   return ret;
76071: }
76072: 
76073: /*
76074: ** Return the name of the Nth column of the result set returned by SQL
76075: ** statement pStmt.
76076: */
76077: SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
76078:   return columnName(
76079:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
76080: }
76081: #ifndef SQLITE_OMIT_UTF16
76082: SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
76083:   return columnName(
76084:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
76085: }
76086: #endif
76087: 
76088: /*
76089: ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
76090: ** not define OMIT_DECLTYPE.
76091: */
76092: #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
76093: # error "Must not define both SQLITE_OMIT_DECLTYPE \
76094:          and SQLITE_ENABLE_COLUMN_METADATA"
76095: #endif
76096: 
76097: #ifndef SQLITE_OMIT_DECLTYPE
76098: /*
76099: ** Return the column declaration type (if applicable) of the 'i'th column
76100: ** of the result set of SQL statement pStmt.
76101: */
76102: SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
76103:   return columnName(
76104:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
76105: }
76106: #ifndef SQLITE_OMIT_UTF16
76107: SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
76108:   return columnName(
76109:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
76110: }
76111: #endif /* SQLITE_OMIT_UTF16 */
76112: #endif /* SQLITE_OMIT_DECLTYPE */
76113: 
76114: #ifdef SQLITE_ENABLE_COLUMN_METADATA
76115: /*
76116: ** Return the name of the database from which a result column derives.
76117: ** NULL is returned if the result column is an expression or constant or
76118: ** anything else which is not an unambiguous reference to a database column.
76119: */
76120: SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
76121:   return columnName(
76122:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
76123: }
76124: #ifndef SQLITE_OMIT_UTF16
76125: SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
76126:   return columnName(
76127:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
76128: }
76129: #endif /* SQLITE_OMIT_UTF16 */
76130: 
76131: /*
76132: ** Return the name of the table from which a result column derives.
76133: ** NULL is returned if the result column is an expression or constant or
76134: ** anything else which is not an unambiguous reference to a database column.
76135: */
76136: SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
76137:   return columnName(
76138:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
76139: }
76140: #ifndef SQLITE_OMIT_UTF16
76141: SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
76142:   return columnName(
76143:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
76144: }
76145: #endif /* SQLITE_OMIT_UTF16 */
76146: 
76147: /*
76148: ** Return the name of the table column from which a result column derives.
76149: ** NULL is returned if the result column is an expression or constant or
76150: ** anything else which is not an unambiguous reference to a database column.
76151: */
76152: SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
76153:   return columnName(
76154:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
76155: }
76156: #ifndef SQLITE_OMIT_UTF16
76157: SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
76158:   return columnName(
76159:       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
76160: }
76161: #endif /* SQLITE_OMIT_UTF16 */
76162: #endif /* SQLITE_ENABLE_COLUMN_METADATA */
76163: 
76164: 
76165: /******************************* sqlite3_bind_  ***************************
76166: ** 
76167: ** Routines used to attach values to wildcards in a compiled SQL statement.
76168: */
76169: /*
76170: ** Unbind the value bound to variable i in virtual machine p. This is the 
76171: ** the same as binding a NULL value to the column. If the "i" parameter is
76172: ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
76173: **
76174: ** A successful evaluation of this routine acquires the mutex on p.
76175: ** the mutex is released if any kind of error occurs.
76176: **
76177: ** The error code stored in database p->db is overwritten with the return
76178: ** value in any case.
76179: */
76180: static int vdbeUnbind(Vdbe *p, int i){
76181:   Mem *pVar;
76182:   if( vdbeSafetyNotNull(p) ){
76183:     return SQLITE_MISUSE_BKPT;
76184:   }
76185:   sqlite3_mutex_enter(p->db->mutex);
76186:   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
76187:     sqlite3Error(p->db, SQLITE_MISUSE);
76188:     sqlite3_mutex_leave(p->db->mutex);
76189:     sqlite3_log(SQLITE_MISUSE, 
76190:         "bind on a busy prepared statement: [%s]", p->zSql);
76191:     return SQLITE_MISUSE_BKPT;
76192:   }
76193:   if( i<1 || i>p->nVar ){
76194:     sqlite3Error(p->db, SQLITE_RANGE);
76195:     sqlite3_mutex_leave(p->db->mutex);
76196:     return SQLITE_RANGE;
76197:   }
76198:   i--;
76199:   pVar = &p->aVar[i];
76200:   sqlite3VdbeMemRelease(pVar);
76201:   pVar->flags = MEM_Null;
76202:   sqlite3Error(p->db, SQLITE_OK);
76203: 
76204:   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
76205:   ** binding a new value to this variable invalidates the current query plan.
76206:   **
76207:   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
76208:   ** parameter in the WHERE clause might influence the choice of query plan
76209:   ** for a statement, then the statement will be automatically recompiled,
76210:   ** as if there had been a schema change, on the first sqlite3_step() call
76211:   ** following any change to the bindings of that parameter.
76212:   */
76213:   if( p->isPrepareV2 &&
76214:      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
76215:   ){
76216:     p->expired = 1;
76217:   }
76218:   return SQLITE_OK;
76219: }
76220: 
76221: /*
76222: ** Bind a text or BLOB value.
76223: */
76224: static int bindText(
76225:   sqlite3_stmt *pStmt,   /* The statement to bind against */
76226:   int i,                 /* Index of the parameter to bind */
76227:   const void *zData,     /* Pointer to the data to be bound */
76228:   int nData,             /* Number of bytes of data to be bound */
76229:   void (*xDel)(void*),   /* Destructor for the data */
76230:   u8 encoding            /* Encoding for the data */
76231: ){
76232:   Vdbe *p = (Vdbe *)pStmt;
76233:   Mem *pVar;
76234:   int rc;
76235: 
76236:   rc = vdbeUnbind(p, i);
76237:   if( rc==SQLITE_OK ){
76238:     if( zData!=0 ){
76239:       pVar = &p->aVar[i-1];
76240:       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
76241:       if( rc==SQLITE_OK && encoding!=0 ){
76242:         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
76243:       }
76244:       sqlite3Error(p->db, rc);
76245:       rc = sqlite3ApiExit(p->db, rc);
76246:     }
76247:     sqlite3_mutex_leave(p->db->mutex);
76248:   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
76249:     xDel((void*)zData);
76250:   }
76251:   return rc;
76252: }
76253: 
76254: 
76255: /*
76256: ** Bind a blob value to an SQL statement variable.
76257: */
76258: SQLITE_API int sqlite3_bind_blob(
76259:   sqlite3_stmt *pStmt, 
76260:   int i, 
76261:   const void *zData, 
76262:   int nData, 
76263:   void (*xDel)(void*)
76264: ){
76265: #ifdef SQLITE_ENABLE_API_ARMOR
76266:   if( nData<0 ) return SQLITE_MISUSE_BKPT;
76267: #endif
76268:   return bindText(pStmt, i, zData, nData, xDel, 0);
76269: }
76270: SQLITE_API int sqlite3_bind_blob64(
76271:   sqlite3_stmt *pStmt, 
76272:   int i, 
76273:   const void *zData, 
76274:   sqlite3_uint64 nData, 
76275:   void (*xDel)(void*)
76276: ){
76277:   assert( xDel!=SQLITE_DYNAMIC );
76278:   if( nData>0x7fffffff ){
76279:     return invokeValueDestructor(zData, xDel, 0);
76280:   }else{
76281:     return bindText(pStmt, i, zData, (int)nData, xDel, 0);
76282:   }
76283: }
76284: SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
76285:   int rc;
76286:   Vdbe *p = (Vdbe *)pStmt;
76287:   rc = vdbeUnbind(p, i);
76288:   if( rc==SQLITE_OK ){
76289:     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
76290:     sqlite3_mutex_leave(p->db->mutex);
76291:   }
76292:   return rc;
76293: }
76294: SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
76295:   return sqlite3_bind_int64(p, i, (i64)iValue);
76296: }
76297: SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
76298:   int rc;
76299:   Vdbe *p = (Vdbe *)pStmt;
76300:   rc = vdbeUnbind(p, i);
76301:   if( rc==SQLITE_OK ){
76302:     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
76303:     sqlite3_mutex_leave(p->db->mutex);
76304:   }
76305:   return rc;
76306: }
76307: SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
76308:   int rc;
76309:   Vdbe *p = (Vdbe*)pStmt;
76310:   rc = vdbeUnbind(p, i);
76311:   if( rc==SQLITE_OK ){
76312:     sqlite3_mutex_leave(p->db->mutex);
76313:   }
76314:   return rc;
76315: }
76316: SQLITE_API int sqlite3_bind_text( 
76317:   sqlite3_stmt *pStmt, 
76318:   int i, 
76319:   const char *zData, 
76320:   int nData, 
76321:   void (*xDel)(void*)
76322: ){
76323:   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
76324: }
76325: SQLITE_API int sqlite3_bind_text64( 
76326:   sqlite3_stmt *pStmt, 
76327:   int i, 
76328:   const char *zData, 
76329:   sqlite3_uint64 nData, 
76330:   void (*xDel)(void*),
76331:   unsigned char enc
76332: ){
76333:   assert( xDel!=SQLITE_DYNAMIC );
76334:   if( nData>0x7fffffff ){
76335:     return invokeValueDestructor(zData, xDel, 0);
76336:   }else{
76337:     if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
76338:     return bindText(pStmt, i, zData, (int)nData, xDel, enc);
76339:   }
76340: }
76341: #ifndef SQLITE_OMIT_UTF16
76342: SQLITE_API int sqlite3_bind_text16(
76343:   sqlite3_stmt *pStmt, 
76344:   int i, 
76345:   const void *zData, 
76346:   int nData, 
76347:   void (*xDel)(void*)
76348: ){
76349:   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
76350: }
76351: #endif /* SQLITE_OMIT_UTF16 */
76352: SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
76353:   int rc;
76354:   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
76355:     case SQLITE_INTEGER: {
76356:       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
76357:       break;
76358:     }
76359:     case SQLITE_FLOAT: {
76360:       rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
76361:       break;
76362:     }
76363:     case SQLITE_BLOB: {
76364:       if( pValue->flags & MEM_Zero ){
76365:         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
76366:       }else{
76367:         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
76368:       }
76369:       break;
76370:     }
76371:     case SQLITE_TEXT: {
76372:       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
76373:                               pValue->enc);
76374:       break;
76375:     }
76376:     default: {
76377:       rc = sqlite3_bind_null(pStmt, i);
76378:       break;
76379:     }
76380:   }
76381:   return rc;
76382: }
76383: SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
76384:   int rc;
76385:   Vdbe *p = (Vdbe *)pStmt;
76386:   rc = vdbeUnbind(p, i);
76387:   if( rc==SQLITE_OK ){
76388:     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
76389:     sqlite3_mutex_leave(p->db->mutex);
76390:   }
76391:   return rc;
76392: }
76393: SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
76394:   int rc;
76395:   Vdbe *p = (Vdbe *)pStmt;
76396:   sqlite3_mutex_enter(p->db->mutex);
76397:   if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
76398:     rc = SQLITE_TOOBIG;
76399:   }else{
76400:     assert( (n & 0x7FFFFFFF)==n );
76401:     rc = sqlite3_bind_zeroblob(pStmt, i, n);
76402:   }
76403:   rc = sqlite3ApiExit(p->db, rc);
76404:   sqlite3_mutex_leave(p->db->mutex);
76405:   return rc;
76406: }
76407: 
76408: /*
76409: ** Return the number of wildcards that can be potentially bound to.
76410: ** This routine is added to support DBD::SQLite.  
76411: */
76412: SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
76413:   Vdbe *p = (Vdbe*)pStmt;
76414:   return p ? p->nVar : 0;
76415: }
76416: 
76417: /*
76418: ** Return the name of a wildcard parameter.  Return NULL if the index
76419: ** is out of range or if the wildcard is unnamed.
76420: **
76421: ** The result is always UTF-8.
76422: */
76423: SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
76424:   Vdbe *p = (Vdbe*)pStmt;
76425:   if( p==0 || i<1 || i>p->nzVar ){
76426:     return 0;
76427:   }
76428:   return p->azVar[i-1];
76429: }
76430: 
76431: /*
76432: ** Given a wildcard parameter name, return the index of the variable
76433: ** with that name.  If there is no variable with the given name,
76434: ** return 0.
76435: */
76436: SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
76437:   int i;
76438:   if( p==0 ){
76439:     return 0;
76440:   }
76441:   if( zName ){
76442:     for(i=0; i<p->nzVar; i++){
76443:       const char *z = p->azVar[i];
76444:       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
76445:         return i+1;
76446:       }
76447:     }
76448:   }
76449:   return 0;
76450: }
76451: SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
76452:   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
76453: }
76454: 
76455: /*
76456: ** Transfer all bindings from the first statement over to the second.
76457: */
76458: SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76459:   Vdbe *pFrom = (Vdbe*)pFromStmt;
76460:   Vdbe *pTo = (Vdbe*)pToStmt;
76461:   int i;
76462:   assert( pTo->db==pFrom->db );
76463:   assert( pTo->nVar==pFrom->nVar );
76464:   sqlite3_mutex_enter(pTo->db->mutex);
76465:   for(i=0; i<pFrom->nVar; i++){
76466:     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
76467:   }
76468:   sqlite3_mutex_leave(pTo->db->mutex);
76469:   return SQLITE_OK;
76470: }
76471: 
76472: #ifndef SQLITE_OMIT_DEPRECATED
76473: /*
76474: ** Deprecated external interface.  Internal/core SQLite code
76475: ** should call sqlite3TransferBindings.
76476: **
76477: ** It is misuse to call this routine with statements from different
76478: ** database connections.  But as this is a deprecated interface, we
76479: ** will not bother to check for that condition.
76480: **
76481: ** If the two statements contain a different number of bindings, then
76482: ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
76483: ** SQLITE_OK is returned.
76484: */
76485: SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
76486:   Vdbe *pFrom = (Vdbe*)pFromStmt;
76487:   Vdbe *pTo = (Vdbe*)pToStmt;
76488:   if( pFrom->nVar!=pTo->nVar ){
76489:     return SQLITE_ERROR;
76490:   }
76491:   if( pTo->isPrepareV2 && pTo->expmask ){
76492:     pTo->expired = 1;
76493:   }
76494:   if( pFrom->isPrepareV2 && pFrom->expmask ){
76495:     pFrom->expired = 1;
76496:   }
76497:   return sqlite3TransferBindings(pFromStmt, pToStmt);
76498: }
76499: #endif
76500: 
76501: /*
76502: ** Return the sqlite3* database handle to which the prepared statement given
76503: ** in the argument belongs.  This is the same database handle that was
76504: ** the first argument to the sqlite3_prepare() that was used to create
76505: ** the statement in the first place.
76506: */
76507: SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
76508:   return pStmt ? ((Vdbe*)pStmt)->db : 0;
76509: }
76510: 
76511: /*
76512: ** Return true if the prepared statement is guaranteed to not modify the
76513: ** database.
76514: */
76515: SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
76516:   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
76517: }
76518: 
76519: /*
76520: ** Return true if the prepared statement is in need of being reset.
76521: */
76522: SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
76523:   Vdbe *v = (Vdbe*)pStmt;
76524:   return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
76525: }
76526: 
76527: /*
76528: ** Return a pointer to the next prepared statement after pStmt associated
76529: ** with database connection pDb.  If pStmt is NULL, return the first
76530: ** prepared statement for the database connection.  Return NULL if there
76531: ** are no more.
76532: */
76533: SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
76534:   sqlite3_stmt *pNext;
76535: #ifdef SQLITE_ENABLE_API_ARMOR
76536:   if( !sqlite3SafetyCheckOk(pDb) ){
76537:     (void)SQLITE_MISUSE_BKPT;
76538:     return 0;
76539:   }
76540: #endif
76541:   sqlite3_mutex_enter(pDb->mutex);
76542:   if( pStmt==0 ){
76543:     pNext = (sqlite3_stmt*)pDb->pVdbe;
76544:   }else{
76545:     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
76546:   }
76547:   sqlite3_mutex_leave(pDb->mutex);
76548:   return pNext;
76549: }
76550: 
76551: /*
76552: ** Return the value of a status counter for a prepared statement
76553: */
76554: SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
76555:   Vdbe *pVdbe = (Vdbe*)pStmt;
76556:   u32 v;
76557: #ifdef SQLITE_ENABLE_API_ARMOR
76558:   if( !pStmt ){
76559:     (void)SQLITE_MISUSE_BKPT;
76560:     return 0;
76561:   }
76562: #endif
76563:   v = pVdbe->aCounter[op];
76564:   if( resetFlag ) pVdbe->aCounter[op] = 0;
76565:   return (int)v;
76566: }
76567: 
76568: /*
76569: ** Return the SQL associated with a prepared statement
76570: */
76571: SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
76572:   Vdbe *p = (Vdbe *)pStmt;
76573:   return p ? p->zSql : 0;
76574: }
76575: 
76576: /*
76577: ** Return the SQL associated with a prepared statement with
76578: ** bound parameters expanded.  Space to hold the returned string is
76579: ** obtained from sqlite3_malloc().  The caller is responsible for
76580: ** freeing the returned string by passing it to sqlite3_free().
76581: **
76582: ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
76583: ** expanded bound parameters.
76584: */
76585: SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
76586: #ifdef SQLITE_OMIT_TRACE
76587:   return 0;
76588: #else
76589:   char *z = 0;
76590:   const char *zSql = sqlite3_sql(pStmt);
76591:   if( zSql ){
76592:     Vdbe *p = (Vdbe *)pStmt;
76593:     sqlite3_mutex_enter(p->db->mutex);
76594:     z = sqlite3VdbeExpandSql(p, zSql);
76595:     sqlite3_mutex_leave(p->db->mutex);
76596:   }
76597:   return z;
76598: #endif
76599: }
76600: 
76601: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76602: /*
76603: ** Allocate and populate an UnpackedRecord structure based on the serialized
76604: ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76605: ** if successful, or a NULL pointer if an OOM error is encountered.
76606: */
76607: static UnpackedRecord *vdbeUnpackRecord(
76608:   KeyInfo *pKeyInfo, 
76609:   int nKey, 
76610:   const void *pKey
76611: ){
76612:   char *dummy;                    /* Dummy argument for AllocUnpackedRecord() */
76613:   UnpackedRecord *pRet;           /* Return value */
76614: 
76615:   pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76616:   if( pRet ){
76617:     memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76618:     sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76619:   }
76620:   return pRet;
76621: }
76622: 
76623: /*
76624: ** This function is called from within a pre-update callback to retrieve
76625: ** a field of the row currently being updated or deleted.
76626: */
76627: SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76628:   PreUpdate *p = db->pPreUpdate;
76629:   int rc = SQLITE_OK;
76630: 
76631:   /* Test that this call is being made from within an SQLITE_DELETE or
76632:   ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76633:   if( !p || p->op==SQLITE_INSERT ){
76634:     rc = SQLITE_MISUSE_BKPT;
76635:     goto preupdate_old_out;
76636:   }
76637:   if( iIdx>=p->pCsr->nField || iIdx<0 ){
76638:     rc = SQLITE_RANGE;
76639:     goto preupdate_old_out;
76640:   }
76641: 
76642:   /* If the old.* record has not yet been loaded into memory, do so now. */
76643:   if( p->pUnpacked==0 ){
76644:     u32 nRec;
76645:     u8 *aRec;
76646: 
76647:     nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
76648:     aRec = sqlite3DbMallocRaw(db, nRec);
76649:     if( !aRec ) goto preupdate_old_out;
76650:     rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76651:     if( rc==SQLITE_OK ){
76652:       p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76653:       if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76654:     }
76655:     if( rc!=SQLITE_OK ){
76656:       sqlite3DbFree(db, aRec);
76657:       goto preupdate_old_out;
76658:     }
76659:     p->aRecord = aRec;
76660:   }
76661: 
76662:   if( iIdx>=p->pUnpacked->nField ){
76663:     *ppValue = (sqlite3_value *)columnNullValue();
76664:   }else{
76665:     *ppValue = &p->pUnpacked->aMem[iIdx];
76666:     if( iIdx==p->iPKey ){
76667:       sqlite3VdbeMemSetInt64(*ppValue, p->iKey1);
76668:     }
76669:   }
76670: 
76671:  preupdate_old_out:
76672:   sqlite3Error(db, rc);
76673:   return sqlite3ApiExit(db, rc);
76674: }
76675: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76676: 
76677: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76678: /*
76679: ** This function is called from within a pre-update callback to retrieve
76680: ** the number of columns in the row being updated, deleted or inserted.
76681: */
76682: SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
76683:   PreUpdate *p = db->pPreUpdate;
76684:   return (p ? p->keyinfo.nField : 0);
76685: }
76686: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76687: 
76688: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76689: /*
76690: ** This function is designed to be called from within a pre-update callback
76691: ** only. It returns zero if the change that caused the callback was made
76692: ** immediately by a user SQL statement. Or, if the change was made by a
76693: ** trigger program, it returns the number of trigger programs currently
76694: ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a 
76695: ** top-level trigger etc.).
76696: **
76697: ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76698: ** or SET DEFAULT action is considered a trigger.
76699: */
76700: SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
76701:   PreUpdate *p = db->pPreUpdate;
76702:   return (p ? p->v->nFrame : 0);
76703: }
76704: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76705: 
76706: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76707: /*
76708: ** This function is called from within a pre-update callback to retrieve
76709: ** a field of the row currently being updated or inserted.
76710: */
76711: SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
76712:   PreUpdate *p = db->pPreUpdate;
76713:   int rc = SQLITE_OK;
76714:   Mem *pMem;
76715: 
76716:   if( !p || p->op==SQLITE_DELETE ){
76717:     rc = SQLITE_MISUSE_BKPT;
76718:     goto preupdate_new_out;
76719:   }
76720:   if( iIdx>=p->pCsr->nField || iIdx<0 ){
76721:     rc = SQLITE_RANGE;
76722:     goto preupdate_new_out;
76723:   }
76724: 
76725:   if( p->op==SQLITE_INSERT ){
76726:     /* For an INSERT, memory cell p->iNewReg contains the serialized record
76727:     ** that is being inserted. Deserialize it. */
76728:     UnpackedRecord *pUnpack = p->pNewUnpacked;
76729:     if( !pUnpack ){
76730:       Mem *pData = &p->v->aMem[p->iNewReg];
76731:       rc = sqlite3VdbeMemExpandBlob(pData);
76732:       if( rc!=SQLITE_OK ) goto preupdate_new_out;
76733:       pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76734:       if( !pUnpack ){
76735:         rc = SQLITE_NOMEM;
76736:         goto preupdate_new_out;
76737:       }
76738:       p->pNewUnpacked = pUnpack;
76739:     }
76740:     if( iIdx>=pUnpack->nField ){
76741:       pMem = (sqlite3_value *)columnNullValue();
76742:     }else{
76743:       pMem = &pUnpack->aMem[iIdx];
76744:       if( iIdx==p->iPKey ){
76745:         sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76746:       }
76747:     }
76748:   }else{
76749:     /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76750:     ** value. Make a copy of the cell contents and return a pointer to it.
76751:     ** It is not safe to return a pointer to the memory cell itself as the
76752:     ** caller may modify the value text encoding.
76753:     */
76754:     assert( p->op==SQLITE_UPDATE );
76755:     if( !p->aNew ){
76756:       p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76757:       if( !p->aNew ){
76758:         rc = SQLITE_NOMEM;
76759:         goto preupdate_new_out;
76760:       }
76761:     }
76762:     assert( iIdx>=0 && iIdx<p->pCsr->nField );
76763:     pMem = &p->aNew[iIdx];
76764:     if( pMem->flags==0 ){
76765:       if( iIdx==p->iPKey ){
76766:         sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76767:       }else{
76768:         rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76769:         if( rc!=SQLITE_OK ) goto preupdate_new_out;
76770:       }
76771:     }
76772:   }
76773:   *ppValue = pMem;
76774: 
76775:  preupdate_new_out:
76776:   sqlite3Error(db, rc);
76777:   return sqlite3ApiExit(db, rc);
76778: }
76779: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76780: 
76781: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76782: /*
76783: ** Return status data for a single loop within query pStmt.
76784: */
76785: SQLITE_API int sqlite3_stmt_scanstatus(
76786:   sqlite3_stmt *pStmt,            /* Prepared statement being queried */
76787:   int idx,                        /* Index of loop to report on */
76788:   int iScanStatusOp,              /* Which metric to return */
76789:   void *pOut                      /* OUT: Write the answer here */
76790: ){
76791:   Vdbe *p = (Vdbe*)pStmt;
76792:   ScanStatus *pScan;
76793:   if( idx<0 || idx>=p->nScan ) return 1;
76794:   pScan = &p->aScan[idx];
76795:   switch( iScanStatusOp ){
76796:     case SQLITE_SCANSTAT_NLOOP: {
76797:       *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
76798:       break;
76799:     }
76800:     case SQLITE_SCANSTAT_NVISIT: {
76801:       *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
76802:       break;
76803:     }
76804:     case SQLITE_SCANSTAT_EST: {
76805:       double r = 1.0;
76806:       LogEst x = pScan->nEst;
76807:       while( x<100 ){
76808:         x += 10;
76809:         r *= 0.5;
76810:       }
76811:       *(double*)pOut = r*sqlite3LogEstToInt(x);
76812:       break;
76813:     }
76814:     case SQLITE_SCANSTAT_NAME: {
76815:       *(const char**)pOut = pScan->zName;
76816:       break;
76817:     }
76818:     case SQLITE_SCANSTAT_EXPLAIN: {
76819:       if( pScan->addrExplain ){
76820:         *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
76821:       }else{
76822:         *(const char**)pOut = 0;
76823:       }
76824:       break;
76825:     }
76826:     case SQLITE_SCANSTAT_SELECTID: {
76827:       if( pScan->addrExplain ){
76828:         *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
76829:       }else{
76830:         *(int*)pOut = -1;
76831:       }
76832:       break;
76833:     }
76834:     default: {
76835:       return 1;
76836:     }
76837:   }
76838:   return 0;
76839: }
76840: 
76841: /*
76842: ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
76843: */
76844: SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
76845:   Vdbe *p = (Vdbe*)pStmt;
76846:   memset(p->anExec, 0, p->nOp * sizeof(i64));
76847: }
76848: #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
76849: 
76850: /************** End of vdbeapi.c *********************************************/
76851: /************** Begin file vdbetrace.c ***************************************/
76852: /*
76853: ** 2009 November 25
76854: **
76855: ** The author disclaims copyright to this source code.  In place of
76856: ** a legal notice, here is a blessing:
76857: **
76858: **    May you do good and not evil.
76859: **    May you find forgiveness for yourself and forgive others.
76860: **    May you share freely, never taking more than you give.
76861: **
76862: *************************************************************************
76863: **
76864: ** This file contains code used to insert the values of host parameters
76865: ** (aka "wildcards") into the SQL text output by sqlite3_trace().
76866: **
76867: ** The Vdbe parse-tree explainer is also found here.
76868: */
76869: /* #include "sqliteInt.h" */
76870: /* #include "vdbeInt.h" */
76871: 
76872: #ifndef SQLITE_OMIT_TRACE
76873: 
76874: /*
76875: ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
76876: ** bytes in this text up to but excluding the first character in
76877: ** a host parameter.  If the text contains no host parameters, return
76878: ** the total number of bytes in the text.
76879: */
76880: static int findNextHostParameter(const char *zSql, int *pnToken){
76881:   int tokenType;
76882:   int nTotal = 0;
76883:   int n;
76884: 
76885:   *pnToken = 0;
76886:   while( zSql[0] ){
76887:     n = sqlite3GetToken((u8*)zSql, &tokenType);
76888:     assert( n>0 && tokenType!=TK_ILLEGAL );
76889:     if( tokenType==TK_VARIABLE ){
76890:       *pnToken = n;
76891:       break;
76892:     }
76893:     nTotal += n;
76894:     zSql += n;
76895:   }
76896:   return nTotal;
76897: }
76898: 
76899: /*
76900: ** This function returns a pointer to a nul-terminated string in memory
76901: ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
76902: ** string contains a copy of zRawSql but with host parameters expanded to 
76903: ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, 
76904: ** then the returned string holds a copy of zRawSql with "-- " prepended
76905: ** to each line of text.
76906: **
76907: ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
76908: ** then long strings and blobs are truncated to that many bytes.  This
76909: ** can be used to prevent unreasonably large trace strings when dealing
76910: ** with large (multi-megabyte) strings and blobs.
76911: **
76912: ** The calling function is responsible for making sure the memory returned
76913: ** is eventually freed.
76914: **
76915: ** ALGORITHM:  Scan the input string looking for host parameters in any of
76916: ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
76917: ** string literals, quoted identifier names, and comments.  For text forms,
76918: ** the host parameter index is found by scanning the prepared
76919: ** statement for the corresponding OP_Variable opcode.  Once the host
76920: ** parameter index is known, locate the value in p->aVar[].  Then render
76921: ** the value as a literal in place of the host parameter name.
76922: */
76923: SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
76924:   Vdbe *p,                 /* The prepared statement being evaluated */
76925:   const char *zRawSql      /* Raw text of the SQL statement */
76926: ){
76927:   sqlite3 *db;             /* The database connection */
76928:   int idx = 0;             /* Index of a host parameter */
76929:   int nextIndex = 1;       /* Index of next ? host parameter */
76930:   int n;                   /* Length of a token prefix */
76931:   int nToken;              /* Length of the parameter token */
76932:   int i;                   /* Loop counter */
76933:   Mem *pVar;               /* Value of a host parameter */
76934:   StrAccum out;            /* Accumulate the output here */
76935: #ifndef SQLITE_OMIT_UTF16
76936:   Mem utf8;                /* Used to convert UTF16 parameters into UTF8 for display */
76937: #endif
76938:   char zBase[100];         /* Initial working space */
76939: 
76940:   db = p->db;
76941:   sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase), 
76942:                       db->aLimit[SQLITE_LIMIT_LENGTH]);
76943:   if( db->nVdbeExec>1 ){
76944:     while( *zRawSql ){
76945:       const char *zStart = zRawSql;
76946:       while( *(zRawSql++)!='\n' && *zRawSql );
76947:       sqlite3StrAccumAppend(&out, "-- ", 3);
76948:       assert( (zRawSql - zStart) > 0 );
76949:       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
76950:     }
76951:   }else if( p->nVar==0 ){
76952:     sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
76953:   }else{
76954:     while( zRawSql[0] ){
76955:       n = findNextHostParameter(zRawSql, &nToken);
76956:       assert( n>0 );
76957:       sqlite3StrAccumAppend(&out, zRawSql, n);
76958:       zRawSql += n;
76959:       assert( zRawSql[0] || nToken==0 );
76960:       if( nToken==0 ) break;
76961:       if( zRawSql[0]=='?' ){
76962:         if( nToken>1 ){
76963:           assert( sqlite3Isdigit(zRawSql[1]) );
76964:           sqlite3GetInt32(&zRawSql[1], &idx);
76965:         }else{
76966:           idx = nextIndex;
76967:         }
76968:       }else{
76969:         assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
76970:                 zRawSql[0]=='@' || zRawSql[0]=='#' );
76971:         testcase( zRawSql[0]==':' );
76972:         testcase( zRawSql[0]=='$' );
76973:         testcase( zRawSql[0]=='@' );
76974:         testcase( zRawSql[0]=='#' );
76975:         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
76976:         assert( idx>0 );
76977:       }
76978:       zRawSql += nToken;
76979:       nextIndex = idx + 1;
76980:       assert( idx>0 && idx<=p->nVar );
76981:       pVar = &p->aVar[idx-1];
76982:       if( pVar->flags & MEM_Null ){
76983:         sqlite3StrAccumAppend(&out, "NULL", 4);
76984:       }else if( pVar->flags & MEM_Int ){
76985:         sqlite3XPrintf(&out, "%lld", pVar->u.i);
76986:       }else if( pVar->flags & MEM_Real ){
76987:         sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
76988:       }else if( pVar->flags & MEM_Str ){
76989:         int nOut;  /* Number of bytes of the string text to include in output */
76990: #ifndef SQLITE_OMIT_UTF16
76991:         u8 enc = ENC(db);
76992:         if( enc!=SQLITE_UTF8 ){
76993:           memset(&utf8, 0, sizeof(utf8));
76994:           utf8.db = db;
76995:           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
76996:           if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
76997:             out.accError = STRACCUM_NOMEM;
76998:             out.nAlloc = 0;
76999:           }
77000:           pVar = &utf8;
77001:         }
77002: #endif
77003:         nOut = pVar->n;
77004: #ifdef SQLITE_TRACE_SIZE_LIMIT
77005:         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
77006:           nOut = SQLITE_TRACE_SIZE_LIMIT;
77007:           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
77008:         }
77009: #endif    
77010:         sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
77011: #ifdef SQLITE_TRACE_SIZE_LIMIT
77012:         if( nOut<pVar->n ){
77013:           sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77014:         }
77015: #endif
77016: #ifndef SQLITE_OMIT_UTF16
77017:         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
77018: #endif
77019:       }else if( pVar->flags & MEM_Zero ){
77020:         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
77021:       }else{
77022:         int nOut;  /* Number of bytes of the blob to include in output */
77023:         assert( pVar->flags & MEM_Blob );
77024:         sqlite3StrAccumAppend(&out, "x'", 2);
77025:         nOut = pVar->n;
77026: #ifdef SQLITE_TRACE_SIZE_LIMIT
77027:         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
77028: #endif
77029:         for(i=0; i<nOut; i++){
77030:           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
77031:         }
77032:         sqlite3StrAccumAppend(&out, "'", 1);
77033: #ifdef SQLITE_TRACE_SIZE_LIMIT
77034:         if( nOut<pVar->n ){
77035:           sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
77036:         }
77037: #endif
77038:       }
77039:     }
77040:   }
77041:   if( out.accError ) sqlite3StrAccumReset(&out);
77042:   return sqlite3StrAccumFinish(&out);
77043: }
77044: 
77045: #endif /* #ifndef SQLITE_OMIT_TRACE */
77046: 
77047: /************** End of vdbetrace.c *******************************************/
77048: /************** Begin file vdbe.c ********************************************/
77049: /*
77050: ** 2001 September 15
77051: **
77052: ** The author disclaims copyright to this source code.  In place of
77053: ** a legal notice, here is a blessing:
77054: **
77055: **    May you do good and not evil.
77056: **    May you find forgiveness for yourself and forgive others.
77057: **    May you share freely, never taking more than you give.
77058: **
77059: *************************************************************************
77060: ** The code in this file implements the function that runs the
77061: ** bytecode of a prepared statement.
77062: **
77063: ** Various scripts scan this source file in order to generate HTML
77064: ** documentation, headers files, or other derived files.  The formatting
77065: ** of the code in this file is, therefore, important.  See other comments
77066: ** in this file for details.  If in doubt, do not deviate from existing
77067: ** commenting and indentation practices when changing or adding code.
77068: */
77069: /* #include "sqliteInt.h" */
77070: /* #include "vdbeInt.h" */
77071: 
77072: /*
77073: ** Invoke this macro on memory cells just prior to changing the
77074: ** value of the cell.  This macro verifies that shallow copies are
77075: ** not misused.  A shallow copy of a string or blob just copies a
77076: ** pointer to the string or blob, not the content.  If the original
77077: ** is changed while the copy is still in use, the string or blob might
77078: ** be changed out from under the copy.  This macro verifies that nothing
77079: ** like that ever happens.
77080: */
77081: #ifdef SQLITE_DEBUG
77082: # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
77083: #else
77084: # define memAboutToChange(P,M)
77085: #endif
77086: 
77087: /*
77088: ** The following global variable is incremented every time a cursor
77089: ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
77090: ** procedures use this information to make sure that indices are
77091: ** working correctly.  This variable has no function other than to
77092: ** help verify the correct operation of the library.
77093: */
77094: #ifdef SQLITE_TEST
77095: SQLITE_API int sqlite3_search_count = 0;
77096: #endif
77097: 
77098: /*
77099: ** When this global variable is positive, it gets decremented once before
77100: ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
77101: ** field of the sqlite3 structure is set in order to simulate an interrupt.
77102: **
77103: ** This facility is used for testing purposes only.  It does not function
77104: ** in an ordinary build.
77105: */
77106: #ifdef SQLITE_TEST
77107: SQLITE_API int sqlite3_interrupt_count = 0;
77108: #endif
77109: 
77110: /*
77111: ** The next global variable is incremented each type the OP_Sort opcode
77112: ** is executed.  The test procedures use this information to make sure that
77113: ** sorting is occurring or not occurring at appropriate times.   This variable
77114: ** has no function other than to help verify the correct operation of the
77115: ** library.
77116: */
77117: #ifdef SQLITE_TEST
77118: SQLITE_API int sqlite3_sort_count = 0;
77119: #endif
77120: 
77121: /*
77122: ** The next global variable records the size of the largest MEM_Blob
77123: ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
77124: ** use this information to make sure that the zero-blob functionality
77125: ** is working correctly.   This variable has no function other than to
77126: ** help verify the correct operation of the library.
77127: */
77128: #ifdef SQLITE_TEST
77129: SQLITE_API int sqlite3_max_blobsize = 0;
77130: static void updateMaxBlobsize(Mem *p){
77131:   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
77132:     sqlite3_max_blobsize = p->n;
77133:   }
77134: }
77135: #endif
77136: 
77137: /*
77138: ** This macro evaluates to true if either the update hook or the preupdate
77139: ** hook are enabled for database connect DB.
77140: */
77141: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
77142: # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
77143: #else
77144: # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
77145: #endif
77146: 
77147: /*
77148: ** The next global variable is incremented each time the OP_Found opcode
77149: ** is executed. This is used to test whether or not the foreign key
77150: ** operation implemented using OP_FkIsZero is working. This variable
77151: ** has no function other than to help verify the correct operation of the
77152: ** library.
77153: */
77154: #ifdef SQLITE_TEST
77155: SQLITE_API int sqlite3_found_count = 0;
77156: #endif
77157: 
77158: /*
77159: ** Test a register to see if it exceeds the current maximum blob size.
77160: ** If it does, record the new maximum blob size.
77161: */
77162: #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
77163: # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
77164: #else
77165: # define UPDATE_MAX_BLOBSIZE(P)
77166: #endif
77167: 
77168: /*
77169: ** Invoke the VDBE coverage callback, if that callback is defined.  This
77170: ** feature is used for test suite validation only and does not appear an
77171: ** production builds.
77172: **
77173: ** M is an integer, 2 or 3, that indices how many different ways the
77174: ** branch can go.  It is usually 2.  "I" is the direction the branch
77175: ** goes.  0 means falls through.  1 means branch is taken.  2 means the
77176: ** second alternative branch is taken.
77177: **
77178: ** iSrcLine is the source code line (from the __LINE__ macro) that
77179: ** generated the VDBE instruction.  This instrumentation assumes that all
77180: ** source code is in a single file (the amalgamation).  Special values 1
77181: ** and 2 for the iSrcLine parameter mean that this particular branch is
77182: ** always taken or never taken, respectively.
77183: */
77184: #if !defined(SQLITE_VDBE_COVERAGE)
77185: # define VdbeBranchTaken(I,M)
77186: #else
77187: # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
77188:   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
77189:     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
77190:       M = iSrcLine;
77191:       /* Assert the truth of VdbeCoverageAlwaysTaken() and 
77192:       ** VdbeCoverageNeverTaken() */
77193:       assert( (M & I)==I );
77194:     }else{
77195:       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
77196:       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
77197:                                       iSrcLine,I,M);
77198:     }
77199:   }
77200: #endif
77201: 
77202: /*
77203: ** Convert the given register into a string if it isn't one
77204: ** already. Return non-zero if a malloc() fails.
77205: */
77206: #define Stringify(P, enc) \
77207:    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
77208:      { goto no_mem; }
77209: 
77210: /*
77211: ** An ephemeral string value (signified by the MEM_Ephem flag) contains
77212: ** a pointer to a dynamically allocated string where some other entity
77213: ** is responsible for deallocating that string.  Because the register
77214: ** does not control the string, it might be deleted without the register
77215: ** knowing it.
77216: **
77217: ** This routine converts an ephemeral string into a dynamically allocated
77218: ** string that the register itself controls.  In other words, it
77219: ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
77220: */
77221: #define Deephemeralize(P) \
77222:    if( ((P)->flags&MEM_Ephem)!=0 \
77223:        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
77224: 
77225: /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
77226: #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
77227: 
77228: /*
77229: ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
77230: ** if we run out of memory.
77231: */
77232: static VdbeCursor *allocateCursor(
77233:   Vdbe *p,              /* The virtual machine */
77234:   int iCur,             /* Index of the new VdbeCursor */
77235:   int nField,           /* Number of fields in the table or index */
77236:   int iDb,              /* Database the cursor belongs to, or -1 */
77237:   u8 eCurType           /* Type of the new cursor */
77238: ){
77239:   /* Find the memory cell that will be used to store the blob of memory
77240:   ** required for this VdbeCursor structure. It is convenient to use a 
77241:   ** vdbe memory cell to manage the memory allocation required for a
77242:   ** VdbeCursor structure for the following reasons:
77243:   **
77244:   **   * Sometimes cursor numbers are used for a couple of different
77245:   **     purposes in a vdbe program. The different uses might require
77246:   **     different sized allocations. Memory cells provide growable
77247:   **     allocations.
77248:   **
77249:   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
77250:   **     be freed lazily via the sqlite3_release_memory() API. This
77251:   **     minimizes the number of malloc calls made by the system.
77252:   **
77253:   ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
77254:   ** the top of the register space.  Cursor 1 is at Mem[p->nMem-1].
77255:   ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
77256:   */
77257:   Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
77258: 
77259:   int nByte;
77260:   VdbeCursor *pCx = 0;
77261:   nByte = 
77262:       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
77263:       (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
77264: 
77265:   assert( iCur>=0 && iCur<p->nCursor );
77266:   if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
77267:     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
77268:     p->apCsr[iCur] = 0;
77269:   }
77270:   if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
77271:     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
77272:     memset(pCx, 0, sizeof(VdbeCursor));
77273:     pCx->eCurType = eCurType;
77274:     pCx->iDb = iDb;
77275:     pCx->nField = nField;
77276:     pCx->aOffset = &pCx->aType[nField];
77277:     if( eCurType==CURTYPE_BTREE ){
77278:       pCx->uc.pCursor = (BtCursor*)
77279:           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
77280:       sqlite3BtreeCursorZero(pCx->uc.pCursor);
77281:     }
77282:   }
77283:   return pCx;
77284: }
77285: 
77286: /*
77287: ** Try to convert a value into a numeric representation if we can
77288: ** do so without loss of information.  In other words, if the string
77289: ** looks like a number, convert it into a number.  If it does not
77290: ** look like a number, leave it alone.
77291: **
77292: ** If the bTryForInt flag is true, then extra effort is made to give
77293: ** an integer representation.  Strings that look like floating point
77294: ** values but which have no fractional component (example: '48.00')
77295: ** will have a MEM_Int representation when bTryForInt is true.
77296: **
77297: ** If bTryForInt is false, then if the input string contains a decimal
77298: ** point or exponential notation, the result is only MEM_Real, even
77299: ** if there is an exact integer representation of the quantity.
77300: */
77301: static void applyNumericAffinity(Mem *pRec, int bTryForInt){
77302:   double rValue;
77303:   i64 iValue;
77304:   u8 enc = pRec->enc;
77305:   assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
77306:   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
77307:   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
77308:     pRec->u.i = iValue;
77309:     pRec->flags |= MEM_Int;
77310:   }else{
77311:     pRec->u.r = rValue;
77312:     pRec->flags |= MEM_Real;
77313:     if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
77314:   }
77315: }
77316: 
77317: /*
77318: ** Processing is determine by the affinity parameter:
77319: **
77320: ** SQLITE_AFF_INTEGER:
77321: ** SQLITE_AFF_REAL:
77322: ** SQLITE_AFF_NUMERIC:
77323: **    Try to convert pRec to an integer representation or a 
77324: **    floating-point representation if an integer representation
77325: **    is not possible.  Note that the integer representation is
77326: **    always preferred, even if the affinity is REAL, because
77327: **    an integer representation is more space efficient on disk.
77328: **
77329: ** SQLITE_AFF_TEXT:
77330: **    Convert pRec to a text representation.
77331: **
77332: ** SQLITE_AFF_BLOB:
77333: **    No-op.  pRec is unchanged.
77334: */
77335: static void applyAffinity(
77336:   Mem *pRec,          /* The value to apply affinity to */
77337:   char affinity,      /* The affinity to be applied */
77338:   u8 enc              /* Use this text encoding */
77339: ){
77340:   if( affinity>=SQLITE_AFF_NUMERIC ){
77341:     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
77342:              || affinity==SQLITE_AFF_NUMERIC );
77343:     if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
77344:       if( (pRec->flags & MEM_Real)==0 ){
77345:         if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
77346:       }else{
77347:         sqlite3VdbeIntegerAffinity(pRec);
77348:       }
77349:     }
77350:   }else if( affinity==SQLITE_AFF_TEXT ){
77351:     /* Only attempt the conversion to TEXT if there is an integer or real
77352:     ** representation (blob and NULL do not get converted) but no string
77353:     ** representation.  It would be harmless to repeat the conversion if 
77354:     ** there is already a string rep, but it is pointless to waste those
77355:     ** CPU cycles. */
77356:     if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
77357:       if( (pRec->flags&(MEM_Real|MEM_Int)) ){
77358:         sqlite3VdbeMemStringify(pRec, enc, 1);
77359:       }
77360:     }
77361:     pRec->flags &= ~(MEM_Real|MEM_Int);
77362:   }
77363: }
77364: 
77365: /*
77366: ** Try to convert the type of a function argument or a result column
77367: ** into a numeric representation.  Use either INTEGER or REAL whichever
77368: ** is appropriate.  But only do the conversion if it is possible without
77369: ** loss of information and return the revised type of the argument.
77370: */
77371: SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
77372:   int eType = sqlite3_value_type(pVal);
77373:   if( eType==SQLITE_TEXT ){
77374:     Mem *pMem = (Mem*)pVal;
77375:     applyNumericAffinity(pMem, 0);
77376:     eType = sqlite3_value_type(pVal);
77377:   }
77378:   return eType;
77379: }
77380: 
77381: /*
77382: ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
77383: ** not the internal Mem* type.
77384: */
77385: SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
77386:   sqlite3_value *pVal, 
77387:   u8 affinity, 
77388:   u8 enc
77389: ){
77390:   applyAffinity((Mem *)pVal, affinity, enc);
77391: }
77392: 
77393: /*
77394: ** pMem currently only holds a string type (or maybe a BLOB that we can
77395: ** interpret as a string if we want to).  Compute its corresponding
77396: ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
77397: ** accordingly.
77398: */
77399: static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
77400:   assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
77401:   assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
77402:   if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
77403:     return 0;
77404:   }
77405:   if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
77406:     return MEM_Int;
77407:   }
77408:   return MEM_Real;
77409: }
77410: 
77411: /*
77412: ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
77413: ** none.  
77414: **
77415: ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
77416: ** But it does set pMem->u.r and pMem->u.i appropriately.
77417: */
77418: static u16 numericType(Mem *pMem){
77419:   if( pMem->flags & (MEM_Int|MEM_Real) ){
77420:     return pMem->flags & (MEM_Int|MEM_Real);
77421:   }
77422:   if( pMem->flags & (MEM_Str|MEM_Blob) ){
77423:     return computeNumericType(pMem);
77424:   }
77425:   return 0;
77426: }
77427: 
77428: #ifdef SQLITE_DEBUG
77429: /*
77430: ** Write a nice string representation of the contents of cell pMem
77431: ** into buffer zBuf, length nBuf.
77432: */
77433: SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
77434:   char *zCsr = zBuf;
77435:   int f = pMem->flags;
77436: 
77437:   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
77438: 
77439:   if( f&MEM_Blob ){
77440:     int i;
77441:     char c;
77442:     if( f & MEM_Dyn ){
77443:       c = 'z';
77444:       assert( (f & (MEM_Static|MEM_Ephem))==0 );
77445:     }else if( f & MEM_Static ){
77446:       c = 't';
77447:       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77448:     }else if( f & MEM_Ephem ){
77449:       c = 'e';
77450:       assert( (f & (MEM_Static|MEM_Dyn))==0 );
77451:     }else{
77452:       c = 's';
77453:     }
77454: 
77455:     sqlite3_snprintf(100, zCsr, "%c", c);
77456:     zCsr += sqlite3Strlen30(zCsr);
77457:     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
77458:     zCsr += sqlite3Strlen30(zCsr);
77459:     for(i=0; i<16 && i<pMem->n; i++){
77460:       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
77461:       zCsr += sqlite3Strlen30(zCsr);
77462:     }
77463:     for(i=0; i<16 && i<pMem->n; i++){
77464:       char z = pMem->z[i];
77465:       if( z<32 || z>126 ) *zCsr++ = '.';
77466:       else *zCsr++ = z;
77467:     }
77468: 
77469:     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
77470:     zCsr += sqlite3Strlen30(zCsr);
77471:     if( f & MEM_Zero ){
77472:       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
77473:       zCsr += sqlite3Strlen30(zCsr);
77474:     }
77475:     *zCsr = '\0';
77476:   }else if( f & MEM_Str ){
77477:     int j, k;
77478:     zBuf[0] = ' ';
77479:     if( f & MEM_Dyn ){
77480:       zBuf[1] = 'z';
77481:       assert( (f & (MEM_Static|MEM_Ephem))==0 );
77482:     }else if( f & MEM_Static ){
77483:       zBuf[1] = 't';
77484:       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
77485:     }else if( f & MEM_Ephem ){
77486:       zBuf[1] = 'e';
77487:       assert( (f & (MEM_Static|MEM_Dyn))==0 );
77488:     }else{
77489:       zBuf[1] = 's';
77490:     }
77491:     k = 2;
77492:     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
77493:     k += sqlite3Strlen30(&zBuf[k]);
77494:     zBuf[k++] = '[';
77495:     for(j=0; j<15 && j<pMem->n; j++){
77496:       u8 c = pMem->z[j];
77497:       if( c>=0x20 && c<0x7f ){
77498:         zBuf[k++] = c;
77499:       }else{
77500:         zBuf[k++] = '.';
77501:       }
77502:     }
77503:     zBuf[k++] = ']';
77504:     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
77505:     k += sqlite3Strlen30(&zBuf[k]);
77506:     zBuf[k++] = 0;
77507:   }
77508: }
77509: #endif
77510: 
77511: #ifdef SQLITE_DEBUG
77512: /*
77513: ** Print the value of a register for tracing purposes:
77514: */
77515: static void memTracePrint(Mem *p){
77516:   if( p->flags & MEM_Undefined ){
77517:     printf(" undefined");
77518:   }else if( p->flags & MEM_Null ){
77519:     printf(" NULL");
77520:   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
77521:     printf(" si:%lld", p->u.i);
77522:   }else if( p->flags & MEM_Int ){
77523:     printf(" i:%lld", p->u.i);
77524: #ifndef SQLITE_OMIT_FLOATING_POINT
77525:   }else if( p->flags & MEM_Real ){
77526:     printf(" r:%g", p->u.r);
77527: #endif
77528:   }else if( p->flags & MEM_RowSet ){
77529:     printf(" (rowset)");
77530:   }else{
77531:     char zBuf[200];
77532:     sqlite3VdbeMemPrettyPrint(p, zBuf);
77533:     printf(" %s", zBuf);
77534:   }
77535:   if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
77536: }
77537: static void registerTrace(int iReg, Mem *p){
77538:   printf("REG[%d] = ", iReg);
77539:   memTracePrint(p);
77540:   printf("\n");
77541: }
77542: #endif
77543: 
77544: #ifdef SQLITE_DEBUG
77545: #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
77546: #else
77547: #  define REGISTER_TRACE(R,M)
77548: #endif
77549: 
77550: 
77551: #ifdef VDBE_PROFILE
77552: 
77553: /* 
77554: ** hwtime.h contains inline assembler code for implementing 
77555: ** high-performance timing routines.
77556: */
77557: /************** Include hwtime.h in the middle of vdbe.c *********************/
77558: /************** Begin file hwtime.h ******************************************/
77559: /*
77560: ** 2008 May 27
77561: **
77562: ** The author disclaims copyright to this source code.  In place of
77563: ** a legal notice, here is a blessing:
77564: **
77565: **    May you do good and not evil.
77566: **    May you find forgiveness for yourself and forgive others.
77567: **    May you share freely, never taking more than you give.
77568: **
77569: ******************************************************************************
77570: **
77571: ** This file contains inline asm code for retrieving "high-performance"
77572: ** counters for x86 class CPUs.
77573: */
77574: #ifndef SQLITE_HWTIME_H
77575: #define SQLITE_HWTIME_H
77576: 
77577: /*
77578: ** The following routine only works on pentium-class (or newer) processors.
77579: ** It uses the RDTSC opcode to read the cycle count value out of the
77580: ** processor and returns that value.  This can be used for high-res
77581: ** profiling.
77582: */
77583: #if (defined(__GNUC__) || defined(_MSC_VER)) && \
77584:       (defined(i386) || defined(__i386__) || defined(_M_IX86))
77585: 
77586:   #if defined(__GNUC__)
77587: 
77588:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
77589:      unsigned int lo, hi;
77590:      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
77591:      return (sqlite_uint64)hi << 32 | lo;
77592:   }
77593: 
77594:   #elif defined(_MSC_VER)
77595: 
77596:   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
77597:      __asm {
77598:         rdtsc
77599:         ret       ; return value at EDX:EAX
77600:      }
77601:   }
77602: 
77603:   #endif
77604: 
77605: #elif (defined(__GNUC__) && defined(__x86_64__))
77606: 
77607:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
77608:       unsigned long val;
77609:       __asm__ __volatile__ ("rdtsc" : "=A" (val));
77610:       return val;
77611:   }
77612:  
77613: #elif (defined(__GNUC__) && defined(__ppc__))
77614: 
77615:   __inline__ sqlite_uint64 sqlite3Hwtime(void){
77616:       unsigned long long retval;
77617:       unsigned long junk;
77618:       __asm__ __volatile__ ("\n\
77619:           1:      mftbu   %1\n\
77620:                   mftb    %L0\n\
77621:                   mftbu   %0\n\
77622:                   cmpw    %0,%1\n\
77623:                   bne     1b"
77624:                   : "=r" (retval), "=r" (junk));
77625:       return retval;
77626:   }
77627: 
77628: #else
77629: 
77630:   #error Need implementation of sqlite3Hwtime() for your platform.
77631: 
77632:   /*
77633:   ** To compile without implementing sqlite3Hwtime() for your platform,
77634:   ** you can remove the above #error and use the following
77635:   ** stub function.  You will lose timing support for many
77636:   ** of the debugging and testing utilities, but it should at
77637:   ** least compile and run.
77638:   */
77639: SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
77640: 
77641: #endif
77642: 
77643: #endif /* !defined(SQLITE_HWTIME_H) */
77644: 
77645: /************** End of hwtime.h **********************************************/
77646: /************** Continuing where we left off in vdbe.c ***********************/
77647: 
77648: #endif
77649: 
77650: #ifndef NDEBUG
77651: /*
77652: ** This function is only called from within an assert() expression. It
77653: ** checks that the sqlite3.nTransaction variable is correctly set to
77654: ** the number of non-transaction savepoints currently in the 
77655: ** linked list starting at sqlite3.pSavepoint.
77656: ** 
77657: ** Usage:
77658: **
77659: **     assert( checkSavepointCount(db) );
77660: */
77661: static int checkSavepointCount(sqlite3 *db){
77662:   int n = 0;
77663:   Savepoint *p;
77664:   for(p=db->pSavepoint; p; p=p->pNext) n++;
77665:   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
77666:   return 1;
77667: }
77668: #endif
77669: 
77670: /*
77671: ** Return the register of pOp->p2 after first preparing it to be
77672: ** overwritten with an integer value.
77673: */
77674: static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
77675:   sqlite3VdbeMemSetNull(pOut);
77676:   pOut->flags = MEM_Int;
77677:   return pOut;
77678: }
77679: static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
77680:   Mem *pOut;
77681:   assert( pOp->p2>0 );
77682:   assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77683:   pOut = &p->aMem[pOp->p2];
77684:   memAboutToChange(p, pOut);
77685:   if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
77686:     return out2PrereleaseWithClear(pOut);
77687:   }else{
77688:     pOut->flags = MEM_Int;
77689:     return pOut;
77690:   }
77691: }
77692: 
77693: 
77694: /*
77695: ** Execute as much of a VDBE program as we can.
77696: ** This is the core of sqlite3_step().  
77697: */
77698: SQLITE_PRIVATE int sqlite3VdbeExec(
77699:   Vdbe *p                    /* The VDBE */
77700: ){
77701:   Op *aOp = p->aOp;          /* Copy of p->aOp */
77702:   Op *pOp = aOp;             /* Current operation */
77703: #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77704:   Op *pOrigOp;               /* Value of pOp at the top of the loop */
77705: #endif
77706: #ifdef SQLITE_DEBUG
77707:   int nExtraDelete = 0;      /* Verifies FORDELETE and AUXDELETE flags */
77708: #endif
77709:   int rc = SQLITE_OK;        /* Value to return */
77710:   sqlite3 *db = p->db;       /* The database */
77711:   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
77712:   u8 encoding = ENC(db);     /* The database encoding */
77713:   int iCompare = 0;          /* Result of last OP_Compare operation */
77714:   unsigned nVmStep = 0;      /* Number of virtual machine steps */
77715: #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77716:   unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
77717: #endif
77718:   Mem *aMem = p->aMem;       /* Copy of p->aMem */
77719:   Mem *pIn1 = 0;             /* 1st input operand */
77720:   Mem *pIn2 = 0;             /* 2nd input operand */
77721:   Mem *pIn3 = 0;             /* 3rd input operand */
77722:   Mem *pOut = 0;             /* Output operand */
77723:   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
77724:   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
77725: #ifdef VDBE_PROFILE
77726:   u64 start;                 /* CPU clock count at start of opcode */
77727: #endif
77728:   /*** INSERT STACK UNION HERE ***/
77729: 
77730:   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
77731:   sqlite3VdbeEnter(p);
77732:   if( p->rc==SQLITE_NOMEM ){
77733:     /* This happens if a malloc() inside a call to sqlite3_column_text() or
77734:     ** sqlite3_column_text16() failed.  */
77735:     goto no_mem;
77736:   }
77737:   assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
77738:   assert( p->bIsReader || p->readOnly!=0 );
77739:   p->rc = SQLITE_OK;
77740:   p->iCurrentTime = 0;
77741:   assert( p->explain==0 );
77742:   p->pResultSet = 0;
77743:   db->busyHandler.nBusy = 0;
77744:   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77745:   sqlite3VdbeIOTraceSql(p);
77746: #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77747:   if( db->xProgress ){
77748:     u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
77749:     assert( 0 < db->nProgressOps );
77750:     nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
77751:   }
77752: #endif
77753: #ifdef SQLITE_DEBUG
77754:   sqlite3BeginBenignMalloc();
77755:   if( p->pc==0
77756:    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
77757:   ){
77758:     int i;
77759:     int once = 1;
77760:     sqlite3VdbePrintSql(p);
77761:     if( p->db->flags & SQLITE_VdbeListing ){
77762:       printf("VDBE Program Listing:\n");
77763:       for(i=0; i<p->nOp; i++){
77764:         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
77765:       }
77766:     }
77767:     if( p->db->flags & SQLITE_VdbeEQP ){
77768:       for(i=0; i<p->nOp; i++){
77769:         if( aOp[i].opcode==OP_Explain ){
77770:           if( once ) printf("VDBE Query Plan:\n");
77771:           printf("%s\n", aOp[i].p4.z);
77772:           once = 0;
77773:         }
77774:       }
77775:     }
77776:     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
77777:   }
77778:   sqlite3EndBenignMalloc();
77779: #endif
77780:   for(pOp=&aOp[p->pc]; 1; pOp++){
77781:     /* Errors are detected by individual opcodes, with an immediate
77782:     ** jumps to abort_due_to_error. */
77783:     assert( rc==SQLITE_OK );
77784: 
77785:     assert( pOp>=aOp && pOp<&aOp[p->nOp]);
77786: #ifdef VDBE_PROFILE
77787:     start = sqlite3Hwtime();
77788: #endif
77789:     nVmStep++;
77790: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
77791:     if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
77792: #endif
77793: 
77794:     /* Only allow tracing if SQLITE_DEBUG is defined.
77795:     */
77796: #ifdef SQLITE_DEBUG
77797:     if( db->flags & SQLITE_VdbeTrace ){
77798:       sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
77799:     }
77800: #endif
77801:       
77802: 
77803:     /* Check to see if we need to simulate an interrupt.  This only happens
77804:     ** if we have a special test build.
77805:     */
77806: #ifdef SQLITE_TEST
77807:     if( sqlite3_interrupt_count>0 ){
77808:       sqlite3_interrupt_count--;
77809:       if( sqlite3_interrupt_count==0 ){
77810:         sqlite3_interrupt(db);
77811:       }
77812:     }
77813: #endif
77814: 
77815:     /* Sanity checking on other operands */
77816: #ifdef SQLITE_DEBUG
77817:     {
77818:       u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
77819:       if( (opProperty & OPFLG_IN1)!=0 ){
77820:         assert( pOp->p1>0 );
77821:         assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
77822:         assert( memIsValid(&aMem[pOp->p1]) );
77823:         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
77824:         REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
77825:       }
77826:       if( (opProperty & OPFLG_IN2)!=0 ){
77827:         assert( pOp->p2>0 );
77828:         assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77829:         assert( memIsValid(&aMem[pOp->p2]) );
77830:         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
77831:         REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
77832:       }
77833:       if( (opProperty & OPFLG_IN3)!=0 ){
77834:         assert( pOp->p3>0 );
77835:         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77836:         assert( memIsValid(&aMem[pOp->p3]) );
77837:         assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
77838:         REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
77839:       }
77840:       if( (opProperty & OPFLG_OUT2)!=0 ){
77841:         assert( pOp->p2>0 );
77842:         assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77843:         memAboutToChange(p, &aMem[pOp->p2]);
77844:       }
77845:       if( (opProperty & OPFLG_OUT3)!=0 ){
77846:         assert( pOp->p3>0 );
77847:         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77848:         memAboutToChange(p, &aMem[pOp->p3]);
77849:       }
77850:     }
77851: #endif
77852: #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77853:     pOrigOp = pOp;
77854: #endif
77855:   
77856:     switch( pOp->opcode ){
77857: 
77858: /*****************************************************************************
77859: ** What follows is a massive switch statement where each case implements a
77860: ** separate instruction in the virtual machine.  If we follow the usual
77861: ** indentation conventions, each case should be indented by 6 spaces.  But
77862: ** that is a lot of wasted space on the left margin.  So the code within
77863: ** the switch statement will break with convention and be flush-left. Another
77864: ** big comment (similar to this one) will mark the point in the code where
77865: ** we transition back to normal indentation.
77866: **
77867: ** The formatting of each case is important.  The makefile for SQLite
77868: ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
77869: ** file looking for lines that begin with "case OP_".  The opcodes.h files
77870: ** will be filled with #defines that give unique integer values to each
77871: ** opcode and the opcodes.c file is filled with an array of strings where
77872: ** each string is the symbolic name for the corresponding opcode.  If the
77873: ** case statement is followed by a comment of the form "/# same as ... #/"
77874: ** that comment is used to determine the particular value of the opcode.
77875: **
77876: ** Other keywords in the comment that follows each case are used to
77877: ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
77878: ** Keywords include: in1, in2, in3, out2, out3.  See
77879: ** the mkopcodeh.awk script for additional information.
77880: **
77881: ** Documentation about VDBE opcodes is generated by scanning this file
77882: ** for lines of that contain "Opcode:".  That line and all subsequent
77883: ** comment lines are used in the generation of the opcode.html documentation
77884: ** file.
77885: **
77886: ** SUMMARY:
77887: **
77888: **     Formatting is important to scripts that scan this file.
77889: **     Do not deviate from the formatting style currently in use.
77890: **
77891: *****************************************************************************/
77892: 
77893: /* Opcode:  Goto * P2 * * *
77894: **
77895: ** An unconditional jump to address P2.
77896: ** The next instruction executed will be 
77897: ** the one at index P2 from the beginning of
77898: ** the program.
77899: **
77900: ** The P1 parameter is not actually used by this opcode.  However, it
77901: ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
77902: ** that this Goto is the bottom of a loop and that the lines from P2 down
77903: ** to the current line should be indented for EXPLAIN output.
77904: */
77905: case OP_Goto: {             /* jump */
77906: jump_to_p2_and_check_for_interrupt:
77907:   pOp = &aOp[pOp->p2 - 1];
77908: 
77909:   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
77910:   ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
77911:   ** completion.  Check to see if sqlite3_interrupt() has been called
77912:   ** or if the progress callback needs to be invoked. 
77913:   **
77914:   ** This code uses unstructured "goto" statements and does not look clean.
77915:   ** But that is not due to sloppy coding habits. The code is written this
77916:   ** way for performance, to avoid having to run the interrupt and progress
77917:   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
77918:   ** faster according to "valgrind --tool=cachegrind" */
77919: check_for_interrupt:
77920:   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77921: #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77922:   /* Call the progress callback if it is configured and the required number
77923:   ** of VDBE ops have been executed (either since this invocation of
77924:   ** sqlite3VdbeExec() or since last time the progress callback was called).
77925:   ** If the progress callback returns non-zero, exit the virtual machine with
77926:   ** a return code SQLITE_ABORT.
77927:   */
77928:   if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
77929:     assert( db->nProgressOps!=0 );
77930:     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
77931:     if( db->xProgress(db->pProgressArg) ){
77932:       rc = SQLITE_INTERRUPT;
77933:       goto abort_due_to_error;
77934:     }
77935:   }
77936: #endif
77937:   
77938:   break;
77939: }
77940: 
77941: /* Opcode:  Gosub P1 P2 * * *
77942: **
77943: ** Write the current address onto register P1
77944: ** and then jump to address P2.
77945: */
77946: case OP_Gosub: {            /* jump */
77947:   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
77948:   pIn1 = &aMem[pOp->p1];
77949:   assert( VdbeMemDynamic(pIn1)==0 );
77950:   memAboutToChange(p, pIn1);
77951:   pIn1->flags = MEM_Int;
77952:   pIn1->u.i = (int)(pOp-aOp);
77953:   REGISTER_TRACE(pOp->p1, pIn1);
77954: 
77955:   /* Most jump operations do a goto to this spot in order to update
77956:   ** the pOp pointer. */
77957: jump_to_p2:
77958:   pOp = &aOp[pOp->p2 - 1];
77959:   break;
77960: }
77961: 
77962: /* Opcode:  Return P1 * * * *
77963: **
77964: ** Jump to the next instruction after the address in register P1.  After
77965: ** the jump, register P1 becomes undefined.
77966: */
77967: case OP_Return: {           /* in1 */
77968:   pIn1 = &aMem[pOp->p1];
77969:   assert( pIn1->flags==MEM_Int );
77970:   pOp = &aOp[pIn1->u.i];
77971:   pIn1->flags = MEM_Undefined;
77972:   break;
77973: }
77974: 
77975: /* Opcode: InitCoroutine P1 P2 P3 * *
77976: **
77977: ** Set up register P1 so that it will Yield to the coroutine
77978: ** located at address P3.
77979: **
77980: ** If P2!=0 then the coroutine implementation immediately follows
77981: ** this opcode.  So jump over the coroutine implementation to
77982: ** address P2.
77983: **
77984: ** See also: EndCoroutine
77985: */
77986: case OP_InitCoroutine: {     /* jump */
77987:   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem+1 - p->nCursor) );
77988:   assert( pOp->p2>=0 && pOp->p2<p->nOp );
77989:   assert( pOp->p3>=0 && pOp->p3<p->nOp );
77990:   pOut = &aMem[pOp->p1];
77991:   assert( !VdbeMemDynamic(pOut) );
77992:   pOut->u.i = pOp->p3 - 1;
77993:   pOut->flags = MEM_Int;
77994:   if( pOp->p2 ) goto jump_to_p2;
77995:   break;
77996: }
77997: 
77998: /* Opcode:  EndCoroutine P1 * * * *
77999: **
78000: ** The instruction at the address in register P1 is a Yield.
78001: ** Jump to the P2 parameter of that Yield.
78002: ** After the jump, register P1 becomes undefined.
78003: **
78004: ** See also: InitCoroutine
78005: */
78006: case OP_EndCoroutine: {           /* in1 */
78007:   VdbeOp *pCaller;
78008:   pIn1 = &aMem[pOp->p1];
78009:   assert( pIn1->flags==MEM_Int );
78010:   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
78011:   pCaller = &aOp[pIn1->u.i];
78012:   assert( pCaller->opcode==OP_Yield );
78013:   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
78014:   pOp = &aOp[pCaller->p2 - 1];
78015:   pIn1->flags = MEM_Undefined;
78016:   break;
78017: }
78018: 
78019: /* Opcode:  Yield P1 P2 * * *
78020: **
78021: ** Swap the program counter with the value in register P1.  This
78022: ** has the effect of yielding to a coroutine.
78023: **
78024: ** If the coroutine that is launched by this instruction ends with
78025: ** Yield or Return then continue to the next instruction.  But if
78026: ** the coroutine launched by this instruction ends with
78027: ** EndCoroutine, then jump to P2 rather than continuing with the
78028: ** next instruction.
78029: **
78030: ** See also: InitCoroutine
78031: */
78032: case OP_Yield: {            /* in1, jump */
78033:   int pcDest;
78034:   pIn1 = &aMem[pOp->p1];
78035:   assert( VdbeMemDynamic(pIn1)==0 );
78036:   pIn1->flags = MEM_Int;
78037:   pcDest = (int)pIn1->u.i;
78038:   pIn1->u.i = (int)(pOp - aOp);
78039:   REGISTER_TRACE(pOp->p1, pIn1);
78040:   pOp = &aOp[pcDest];
78041:   break;
78042: }
78043: 
78044: /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
78045: ** Synopsis:  if r[P3]=null halt
78046: **
78047: ** Check the value in register P3.  If it is NULL then Halt using
78048: ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
78049: ** value in register P3 is not NULL, then this routine is a no-op.
78050: ** The P5 parameter should be 1.
78051: */
78052: case OP_HaltIfNull: {      /* in3 */
78053:   pIn3 = &aMem[pOp->p3];
78054:   if( (pIn3->flags & MEM_Null)==0 ) break;
78055:   /* Fall through into OP_Halt */
78056: }
78057: 
78058: /* Opcode:  Halt P1 P2 * P4 P5
78059: **
78060: ** Exit immediately.  All open cursors, etc are closed
78061: ** automatically.
78062: **
78063: ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
78064: ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
78065: ** For errors, it can be some other value.  If P1!=0 then P2 will determine
78066: ** whether or not to rollback the current transaction.  Do not rollback
78067: ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
78068: ** then back out all changes that have occurred during this execution of the
78069: ** VDBE, but do not rollback the transaction. 
78070: **
78071: ** If P4 is not null then it is an error message string.
78072: **
78073: ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
78074: **
78075: **    0:  (no change)
78076: **    1:  NOT NULL contraint failed: P4
78077: **    2:  UNIQUE constraint failed: P4
78078: **    3:  CHECK constraint failed: P4
78079: **    4:  FOREIGN KEY constraint failed: P4
78080: **
78081: ** If P5 is not zero and P4 is NULL, then everything after the ":" is
78082: ** omitted.
78083: **
78084: ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
78085: ** every program.  So a jump past the last instruction of the program
78086: ** is the same as executing Halt.
78087: */
78088: case OP_Halt: {
78089:   VdbeFrame *pFrame;
78090:   int pcx;
78091: 
78092:   pcx = (int)(pOp - aOp);
78093:   if( pOp->p1==SQLITE_OK && p->pFrame ){
78094:     /* Halt the sub-program. Return control to the parent frame. */
78095:     pFrame = p->pFrame;
78096:     p->pFrame = pFrame->pParent;
78097:     p->nFrame--;
78098:     sqlite3VdbeSetChanges(db, p->nChange);
78099:     pcx = sqlite3VdbeFrameRestore(pFrame);
78100:     lastRowid = db->lastRowid;
78101:     if( pOp->p2==OE_Ignore ){
78102:       /* Instruction pcx is the OP_Program that invoked the sub-program 
78103:       ** currently being halted. If the p2 instruction of this OP_Halt
78104:       ** instruction is set to OE_Ignore, then the sub-program is throwing
78105:       ** an IGNORE exception. In this case jump to the address specified
78106:       ** as the p2 of the calling OP_Program.  */
78107:       pcx = p->aOp[pcx].p2-1;
78108:     }
78109:     aOp = p->aOp;
78110:     aMem = p->aMem;
78111:     pOp = &aOp[pcx];
78112:     break;
78113:   }
78114:   p->rc = pOp->p1;
78115:   p->errorAction = (u8)pOp->p2;
78116:   p->pc = pcx;
78117:   assert( pOp->p5>=0 && pOp->p5<=4 );
78118:   if( p->rc ){
78119:     if( pOp->p5 ){
78120:       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
78121:                                              "FOREIGN KEY" };
78122:       testcase( pOp->p5==1 );
78123:       testcase( pOp->p5==2 );
78124:       testcase( pOp->p5==3 );
78125:       testcase( pOp->p5==4 );
78126:       sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
78127:       if( pOp->p4.z ){
78128:         p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
78129:       }
78130:     }else{
78131:       sqlite3VdbeError(p, "%s", pOp->p4.z);
78132:     }
78133:     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
78134:   }
78135:   rc = sqlite3VdbeHalt(p);
78136:   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
78137:   if( rc==SQLITE_BUSY ){
78138:     p->rc = SQLITE_BUSY;
78139:   }else{
78140:     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
78141:     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
78142:     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
78143:   }
78144:   goto vdbe_return;
78145: }
78146: 
78147: /* Opcode: Integer P1 P2 * * *
78148: ** Synopsis: r[P2]=P1
78149: **
78150: ** The 32-bit integer value P1 is written into register P2.
78151: */
78152: case OP_Integer: {         /* out2 */
78153:   pOut = out2Prerelease(p, pOp);
78154:   pOut->u.i = pOp->p1;
78155:   break;
78156: }
78157: 
78158: /* Opcode: Int64 * P2 * P4 *
78159: ** Synopsis: r[P2]=P4
78160: **
78161: ** P4 is a pointer to a 64-bit integer value.
78162: ** Write that value into register P2.
78163: */
78164: case OP_Int64: {           /* out2 */
78165:   pOut = out2Prerelease(p, pOp);
78166:   assert( pOp->p4.pI64!=0 );
78167:   pOut->u.i = *pOp->p4.pI64;
78168:   break;
78169: }
78170: 
78171: #ifndef SQLITE_OMIT_FLOATING_POINT
78172: /* Opcode: Real * P2 * P4 *
78173: ** Synopsis: r[P2]=P4
78174: **
78175: ** P4 is a pointer to a 64-bit floating point value.
78176: ** Write that value into register P2.
78177: */
78178: case OP_Real: {            /* same as TK_FLOAT, out2 */
78179:   pOut = out2Prerelease(p, pOp);
78180:   pOut->flags = MEM_Real;
78181:   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
78182:   pOut->u.r = *pOp->p4.pReal;
78183:   break;
78184: }
78185: #endif
78186: 
78187: /* Opcode: String8 * P2 * P4 *
78188: ** Synopsis: r[P2]='P4'
78189: **
78190: ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
78191: ** into a String opcode before it is executed for the first time.  During
78192: ** this transformation, the length of string P4 is computed and stored
78193: ** as the P1 parameter.
78194: */
78195: case OP_String8: {         /* same as TK_STRING, out2 */
78196:   assert( pOp->p4.z!=0 );
78197:   pOut = out2Prerelease(p, pOp);
78198:   pOp->opcode = OP_String;
78199:   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
78200: 
78201: #ifndef SQLITE_OMIT_UTF16
78202:   if( encoding!=SQLITE_UTF8 ){
78203:     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
78204:     assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
78205:     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
78206:     assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
78207:     assert( VdbeMemDynamic(pOut)==0 );
78208:     pOut->szMalloc = 0;
78209:     pOut->flags |= MEM_Static;
78210:     if( pOp->p4type==P4_DYNAMIC ){
78211:       sqlite3DbFree(db, pOp->p4.z);
78212:     }
78213:     pOp->p4type = P4_DYNAMIC;
78214:     pOp->p4.z = pOut->z;
78215:     pOp->p1 = pOut->n;
78216:   }
78217:   testcase( rc==SQLITE_TOOBIG );
78218: #endif
78219:   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78220:     goto too_big;
78221:   }
78222:   assert( rc==SQLITE_OK );
78223:   /* Fall through to the next case, OP_String */
78224: }
78225:   
78226: /* Opcode: String P1 P2 P3 P4 P5
78227: ** Synopsis: r[P2]='P4' (len=P1)
78228: **
78229: ** The string value P4 of length P1 (bytes) is stored in register P2.
78230: **
78231: ** If P3 is not zero and the content of register P3 is equal to P5, then
78232: ** the datatype of the register P2 is converted to BLOB.  The content is
78233: ** the same sequence of bytes, it is merely interpreted as a BLOB instead
78234: ** of a string, as if it had been CAST.  In other words:
78235: **
78236: ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
78237: */
78238: case OP_String: {          /* out2 */
78239:   assert( pOp->p4.z!=0 );
78240:   pOut = out2Prerelease(p, pOp);
78241:   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
78242:   pOut->z = pOp->p4.z;
78243:   pOut->n = pOp->p1;
78244:   pOut->enc = encoding;
78245:   UPDATE_MAX_BLOBSIZE(pOut);
78246: #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
78247:   if( pOp->p3>0 ){
78248:     assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78249:     pIn3 = &aMem[pOp->p3];
78250:     assert( pIn3->flags & MEM_Int );
78251:     if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
78252:   }
78253: #endif
78254:   break;
78255: }
78256: 
78257: /* Opcode: Null P1 P2 P3 * *
78258: ** Synopsis:  r[P2..P3]=NULL
78259: **
78260: ** Write a NULL into registers P2.  If P3 greater than P2, then also write
78261: ** NULL into register P3 and every register in between P2 and P3.  If P3
78262: ** is less than P2 (typically P3 is zero) then only register P2 is
78263: ** set to NULL.
78264: **
78265: ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
78266: ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
78267: ** OP_Ne or OP_Eq.
78268: */
78269: case OP_Null: {           /* out2 */
78270:   int cnt;
78271:   u16 nullFlag;
78272:   pOut = out2Prerelease(p, pOp);
78273:   cnt = pOp->p3-pOp->p2;
78274:   assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
78275:   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
78276:   while( cnt>0 ){
78277:     pOut++;
78278:     memAboutToChange(p, pOut);
78279:     sqlite3VdbeMemSetNull(pOut);
78280:     pOut->flags = nullFlag;
78281:     cnt--;
78282:   }
78283:   break;
78284: }
78285: 
78286: /* Opcode: SoftNull P1 * * * *
78287: ** Synopsis:  r[P1]=NULL
78288: **
78289: ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
78290: ** instruction, but do not free any string or blob memory associated with
78291: ** the register, so that if the value was a string or blob that was
78292: ** previously copied using OP_SCopy, the copies will continue to be valid.
78293: */
78294: case OP_SoftNull: {
78295:   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
78296:   pOut = &aMem[pOp->p1];
78297:   pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
78298:   break;
78299: }
78300: 
78301: /* Opcode: Blob P1 P2 * P4 *
78302: ** Synopsis: r[P2]=P4 (len=P1)
78303: **
78304: ** P4 points to a blob of data P1 bytes long.  Store this
78305: ** blob in register P2.
78306: */
78307: case OP_Blob: {                /* out2 */
78308:   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
78309:   pOut = out2Prerelease(p, pOp);
78310:   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
78311:   pOut->enc = encoding;
78312:   UPDATE_MAX_BLOBSIZE(pOut);
78313:   break;
78314: }
78315: 
78316: /* Opcode: Variable P1 P2 * P4 *
78317: ** Synopsis: r[P2]=parameter(P1,P4)
78318: **
78319: ** Transfer the values of bound parameter P1 into register P2
78320: **
78321: ** If the parameter is named, then its name appears in P4.
78322: ** The P4 value is used by sqlite3_bind_parameter_name().
78323: */
78324: case OP_Variable: {            /* out2 */
78325:   Mem *pVar;       /* Value being transferred */
78326: 
78327:   assert( pOp->p1>0 && pOp->p1<=p->nVar );
78328:   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
78329:   pVar = &p->aVar[pOp->p1 - 1];
78330:   if( sqlite3VdbeMemTooBig(pVar) ){
78331:     goto too_big;
78332:   }
78333:   pOut = out2Prerelease(p, pOp);
78334:   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
78335:   UPDATE_MAX_BLOBSIZE(pOut);
78336:   break;
78337: }
78338: 
78339: /* Opcode: Move P1 P2 P3 * *
78340: ** Synopsis:  r[P2@P3]=r[P1@P3]
78341: **
78342: ** Move the P3 values in register P1..P1+P3-1 over into
78343: ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
78344: ** left holding a NULL.  It is an error for register ranges
78345: ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
78346: ** for P3 to be less than 1.
78347: */
78348: case OP_Move: {
78349:   int n;           /* Number of registers left to copy */
78350:   int p1;          /* Register to copy from */
78351:   int p2;          /* Register to copy to */
78352: 
78353:   n = pOp->p3;
78354:   p1 = pOp->p1;
78355:   p2 = pOp->p2;
78356:   assert( n>0 && p1>0 && p2>0 );
78357:   assert( p1+n<=p2 || p2+n<=p1 );
78358: 
78359:   pIn1 = &aMem[p1];
78360:   pOut = &aMem[p2];
78361:   do{
78362:     assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
78363:     assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
78364:     assert( memIsValid(pIn1) );
78365:     memAboutToChange(p, pOut);
78366:     sqlite3VdbeMemMove(pOut, pIn1);
78367: #ifdef SQLITE_DEBUG
78368:     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
78369:       pOut->pScopyFrom += pOp->p2 - p1;
78370:     }
78371: #endif
78372:     Deephemeralize(pOut);
78373:     REGISTER_TRACE(p2++, pOut);
78374:     pIn1++;
78375:     pOut++;
78376:   }while( --n );
78377:   break;
78378: }
78379: 
78380: /* Opcode: Copy P1 P2 P3 * *
78381: ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
78382: **
78383: ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
78384: **
78385: ** This instruction makes a deep copy of the value.  A duplicate
78386: ** is made of any string or blob constant.  See also OP_SCopy.
78387: */
78388: case OP_Copy: {
78389:   int n;
78390: 
78391:   n = pOp->p3;
78392:   pIn1 = &aMem[pOp->p1];
78393:   pOut = &aMem[pOp->p2];
78394:   assert( pOut!=pIn1 );
78395:   while( 1 ){
78396:     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78397:     Deephemeralize(pOut);
78398: #ifdef SQLITE_DEBUG
78399:     pOut->pScopyFrom = 0;
78400: #endif
78401:     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
78402:     if( (n--)==0 ) break;
78403:     pOut++;
78404:     pIn1++;
78405:   }
78406:   break;
78407: }
78408: 
78409: /* Opcode: SCopy P1 P2 * * *
78410: ** Synopsis: r[P2]=r[P1]
78411: **
78412: ** Make a shallow copy of register P1 into register P2.
78413: **
78414: ** This instruction makes a shallow copy of the value.  If the value
78415: ** is a string or blob, then the copy is only a pointer to the
78416: ** original and hence if the original changes so will the copy.
78417: ** Worse, if the original is deallocated, the copy becomes invalid.
78418: ** Thus the program must guarantee that the original will not change
78419: ** during the lifetime of the copy.  Use OP_Copy to make a complete
78420: ** copy.
78421: */
78422: case OP_SCopy: {            /* out2 */
78423:   pIn1 = &aMem[pOp->p1];
78424:   pOut = &aMem[pOp->p2];
78425:   assert( pOut!=pIn1 );
78426:   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
78427: #ifdef SQLITE_DEBUG
78428:   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
78429: #endif
78430:   break;
78431: }
78432: 
78433: /* Opcode: IntCopy P1 P2 * * *
78434: ** Synopsis: r[P2]=r[P1]
78435: **
78436: ** Transfer the integer value held in register P1 into register P2.
78437: **
78438: ** This is an optimized version of SCopy that works only for integer
78439: ** values.
78440: */
78441: case OP_IntCopy: {            /* out2 */
78442:   pIn1 = &aMem[pOp->p1];
78443:   assert( (pIn1->flags & MEM_Int)!=0 );
78444:   pOut = &aMem[pOp->p2];
78445:   sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
78446:   break;
78447: }
78448: 
78449: /* Opcode: ResultRow P1 P2 * * *
78450: ** Synopsis:  output=r[P1@P2]
78451: **
78452: ** The registers P1 through P1+P2-1 contain a single row of
78453: ** results. This opcode causes the sqlite3_step() call to terminate
78454: ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
78455: ** structure to provide access to the r(P1)..r(P1+P2-1) values as
78456: ** the result row.
78457: */
78458: case OP_ResultRow: {
78459:   Mem *pMem;
78460:   int i;
78461:   assert( p->nResColumn==pOp->p2 );
78462:   assert( pOp->p1>0 );
78463:   assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
78464: 
78465: #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
78466:   /* Run the progress counter just before returning.
78467:   */
78468:   if( db->xProgress!=0
78469:    && nVmStep>=nProgressLimit
78470:    && db->xProgress(db->pProgressArg)!=0
78471:   ){
78472:     rc = SQLITE_INTERRUPT;
78473:     goto abort_due_to_error;
78474:   }
78475: #endif
78476: 
78477:   /* If this statement has violated immediate foreign key constraints, do
78478:   ** not return the number of rows modified. And do not RELEASE the statement
78479:   ** transaction. It needs to be rolled back.  */
78480:   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
78481:     assert( db->flags&SQLITE_CountRows );
78482:     assert( p->usesStmtJournal );
78483:     goto abort_due_to_error;
78484:   }
78485: 
78486:   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
78487:   ** DML statements invoke this opcode to return the number of rows 
78488:   ** modified to the user. This is the only way that a VM that
78489:   ** opens a statement transaction may invoke this opcode.
78490:   **
78491:   ** In case this is such a statement, close any statement transaction
78492:   ** opened by this VM before returning control to the user. This is to
78493:   ** ensure that statement-transactions are always nested, not overlapping.
78494:   ** If the open statement-transaction is not closed here, then the user
78495:   ** may step another VM that opens its own statement transaction. This
78496:   ** may lead to overlapping statement transactions.
78497:   **
78498:   ** The statement transaction is never a top-level transaction.  Hence
78499:   ** the RELEASE call below can never fail.
78500:   */
78501:   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
78502:   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
78503:   assert( rc==SQLITE_OK );
78504: 
78505:   /* Invalidate all ephemeral cursor row caches */
78506:   p->cacheCtr = (p->cacheCtr + 2)|1;
78507: 
78508:   /* Make sure the results of the current row are \000 terminated
78509:   ** and have an assigned type.  The results are de-ephemeralized as
78510:   ** a side effect.
78511:   */
78512:   pMem = p->pResultSet = &aMem[pOp->p1];
78513:   for(i=0; i<pOp->p2; i++){
78514:     assert( memIsValid(&pMem[i]) );
78515:     Deephemeralize(&pMem[i]);
78516:     assert( (pMem[i].flags & MEM_Ephem)==0
78517:             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
78518:     sqlite3VdbeMemNulTerminate(&pMem[i]);
78519:     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
78520:   }
78521:   if( db->mallocFailed ) goto no_mem;
78522: 
78523:   if( db->mTrace & SQLITE_TRACE_ROW ){
78524:     db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
78525:   }
78526: 
78527:   /* Return SQLITE_ROW
78528:   */
78529:   p->pc = (int)(pOp - aOp) + 1;
78530:   rc = SQLITE_ROW;
78531:   goto vdbe_return;
78532: }
78533: 
78534: /* Opcode: Concat P1 P2 P3 * *
78535: ** Synopsis: r[P3]=r[P2]+r[P1]
78536: **
78537: ** Add the text in register P1 onto the end of the text in
78538: ** register P2 and store the result in register P3.
78539: ** If either the P1 or P2 text are NULL then store NULL in P3.
78540: **
78541: **   P3 = P2 || P1
78542: **
78543: ** It is illegal for P1 and P3 to be the same register. Sometimes,
78544: ** if P3 is the same register as P2, the implementation is able
78545: ** to avoid a memcpy().
78546: */
78547: case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
78548:   i64 nByte;
78549: 
78550:   pIn1 = &aMem[pOp->p1];
78551:   pIn2 = &aMem[pOp->p2];
78552:   pOut = &aMem[pOp->p3];
78553:   assert( pIn1!=pOut );
78554:   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78555:     sqlite3VdbeMemSetNull(pOut);
78556:     break;
78557:   }
78558:   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
78559:   Stringify(pIn1, encoding);
78560:   Stringify(pIn2, encoding);
78561:   nByte = pIn1->n + pIn2->n;
78562:   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78563:     goto too_big;
78564:   }
78565:   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
78566:     goto no_mem;
78567:   }
78568:   MemSetTypeFlag(pOut, MEM_Str);
78569:   if( pOut!=pIn2 ){
78570:     memcpy(pOut->z, pIn2->z, pIn2->n);
78571:   }
78572:   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
78573:   pOut->z[nByte]=0;
78574:   pOut->z[nByte+1] = 0;
78575:   pOut->flags |= MEM_Term;
78576:   pOut->n = (int)nByte;
78577:   pOut->enc = encoding;
78578:   UPDATE_MAX_BLOBSIZE(pOut);
78579:   break;
78580: }
78581: 
78582: /* Opcode: Add P1 P2 P3 * *
78583: ** Synopsis:  r[P3]=r[P1]+r[P2]
78584: **
78585: ** Add the value in register P1 to the value in register P2
78586: ** and store the result in register P3.
78587: ** If either input is NULL, the result is NULL.
78588: */
78589: /* Opcode: Multiply P1 P2 P3 * *
78590: ** Synopsis:  r[P3]=r[P1]*r[P2]
78591: **
78592: **
78593: ** Multiply the value in register P1 by the value in register P2
78594: ** and store the result in register P3.
78595: ** If either input is NULL, the result is NULL.
78596: */
78597: /* Opcode: Subtract P1 P2 P3 * *
78598: ** Synopsis:  r[P3]=r[P2]-r[P1]
78599: **
78600: ** Subtract the value in register P1 from the value in register P2
78601: ** and store the result in register P3.
78602: ** If either input is NULL, the result is NULL.
78603: */
78604: /* Opcode: Divide P1 P2 P3 * *
78605: ** Synopsis:  r[P3]=r[P2]/r[P1]
78606: **
78607: ** Divide the value in register P1 by the value in register P2
78608: ** and store the result in register P3 (P3=P2/P1). If the value in 
78609: ** register P1 is zero, then the result is NULL. If either input is 
78610: ** NULL, the result is NULL.
78611: */
78612: /* Opcode: Remainder P1 P2 P3 * *
78613: ** Synopsis:  r[P3]=r[P2]%r[P1]
78614: **
78615: ** Compute the remainder after integer register P2 is divided by 
78616: ** register P1 and store the result in register P3. 
78617: ** If the value in register P1 is zero the result is NULL.
78618: ** If either operand is NULL, the result is NULL.
78619: */
78620: case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
78621: case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
78622: case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
78623: case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
78624: case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
78625:   char bIntint;   /* Started out as two integer operands */
78626:   u16 flags;      /* Combined MEM_* flags from both inputs */
78627:   u16 type1;      /* Numeric type of left operand */
78628:   u16 type2;      /* Numeric type of right operand */
78629:   i64 iA;         /* Integer value of left operand */
78630:   i64 iB;         /* Integer value of right operand */
78631:   double rA;      /* Real value of left operand */
78632:   double rB;      /* Real value of right operand */
78633: 
78634:   pIn1 = &aMem[pOp->p1];
78635:   type1 = numericType(pIn1);
78636:   pIn2 = &aMem[pOp->p2];
78637:   type2 = numericType(pIn2);
78638:   pOut = &aMem[pOp->p3];
78639:   flags = pIn1->flags | pIn2->flags;
78640:   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
78641:   if( (type1 & type2 & MEM_Int)!=0 ){
78642:     iA = pIn1->u.i;
78643:     iB = pIn2->u.i;
78644:     bIntint = 1;
78645:     switch( pOp->opcode ){
78646:       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
78647:       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
78648:       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
78649:       case OP_Divide: {
78650:         if( iA==0 ) goto arithmetic_result_is_null;
78651:         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
78652:         iB /= iA;
78653:         break;
78654:       }
78655:       default: {
78656:         if( iA==0 ) goto arithmetic_result_is_null;
78657:         if( iA==-1 ) iA = 1;
78658:         iB %= iA;
78659:         break;
78660:       }
78661:     }
78662:     pOut->u.i = iB;
78663:     MemSetTypeFlag(pOut, MEM_Int);
78664:   }else{
78665:     bIntint = 0;
78666: fp_math:
78667:     rA = sqlite3VdbeRealValue(pIn1);
78668:     rB = sqlite3VdbeRealValue(pIn2);
78669:     switch( pOp->opcode ){
78670:       case OP_Add:         rB += rA;       break;
78671:       case OP_Subtract:    rB -= rA;       break;
78672:       case OP_Multiply:    rB *= rA;       break;
78673:       case OP_Divide: {
78674:         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78675:         if( rA==(double)0 ) goto arithmetic_result_is_null;
78676:         rB /= rA;
78677:         break;
78678:       }
78679:       default: {
78680:         iA = (i64)rA;
78681:         iB = (i64)rB;
78682:         if( iA==0 ) goto arithmetic_result_is_null;
78683:         if( iA==-1 ) iA = 1;
78684:         rB = (double)(iB % iA);
78685:         break;
78686:       }
78687:     }
78688: #ifdef SQLITE_OMIT_FLOATING_POINT
78689:     pOut->u.i = rB;
78690:     MemSetTypeFlag(pOut, MEM_Int);
78691: #else
78692:     if( sqlite3IsNaN(rB) ){
78693:       goto arithmetic_result_is_null;
78694:     }
78695:     pOut->u.r = rB;
78696:     MemSetTypeFlag(pOut, MEM_Real);
78697:     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
78698:       sqlite3VdbeIntegerAffinity(pOut);
78699:     }
78700: #endif
78701:   }
78702:   break;
78703: 
78704: arithmetic_result_is_null:
78705:   sqlite3VdbeMemSetNull(pOut);
78706:   break;
78707: }
78708: 
78709: /* Opcode: CollSeq P1 * * P4
78710: **
78711: ** P4 is a pointer to a CollSeq struct. If the next call to a user function
78712: ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
78713: ** be returned. This is used by the built-in min(), max() and nullif()
78714: ** functions.
78715: **
78716: ** If P1 is not zero, then it is a register that a subsequent min() or
78717: ** max() aggregate will set to 1 if the current row is not the minimum or
78718: ** maximum.  The P1 register is initialized to 0 by this instruction.
78719: **
78720: ** The interface used by the implementation of the aforementioned functions
78721: ** to retrieve the collation sequence set by this opcode is not available
78722: ** publicly.  Only built-in functions have access to this feature.
78723: */
78724: case OP_CollSeq: {
78725:   assert( pOp->p4type==P4_COLLSEQ );
78726:   if( pOp->p1 ){
78727:     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
78728:   }
78729:   break;
78730: }
78731: 
78732: /* Opcode: Function0 P1 P2 P3 P4 P5
78733: ** Synopsis: r[P3]=func(r[P2@P5])
78734: **
78735: ** Invoke a user function (P4 is a pointer to a FuncDef object that
78736: ** defines the function) with P5 arguments taken from register P2 and
78737: ** successors.  The result of the function is stored in register P3.
78738: ** Register P3 must not be one of the function inputs.
78739: **
78740: ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
78741: ** function was determined to be constant at compile time. If the first
78742: ** argument was constant then bit 0 of P1 is set. This is used to determine
78743: ** whether meta data associated with a user function argument using the
78744: ** sqlite3_set_auxdata() API may be safely retained until the next
78745: ** invocation of this opcode.
78746: **
78747: ** See also: Function, AggStep, AggFinal
78748: */
78749: /* Opcode: Function P1 P2 P3 P4 P5
78750: ** Synopsis: r[P3]=func(r[P2@P5])
78751: **
78752: ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
78753: ** contains a pointer to the function to be run) with P5 arguments taken
78754: ** from register P2 and successors.  The result of the function is stored
78755: ** in register P3.  Register P3 must not be one of the function inputs.
78756: **
78757: ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
78758: ** function was determined to be constant at compile time. If the first
78759: ** argument was constant then bit 0 of P1 is set. This is used to determine
78760: ** whether meta data associated with a user function argument using the
78761: ** sqlite3_set_auxdata() API may be safely retained until the next
78762: ** invocation of this opcode.
78763: **
78764: ** SQL functions are initially coded as OP_Function0 with P4 pointing
78765: ** to a FuncDef object.  But on first evaluation, the P4 operand is
78766: ** automatically converted into an sqlite3_context object and the operation
78767: ** changed to this OP_Function opcode.  In this way, the initialization of
78768: ** the sqlite3_context object occurs only once, rather than once for each
78769: ** evaluation of the function.
78770: **
78771: ** See also: Function0, AggStep, AggFinal
78772: */
78773: case OP_Function0: {
78774:   int n;
78775:   sqlite3_context *pCtx;
78776: 
78777:   assert( pOp->p4type==P4_FUNCDEF );
78778:   n = pOp->p5;
78779:   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
78780:   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
78781:   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78782:   pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78783:   if( pCtx==0 ) goto no_mem;
78784:   pCtx->pOut = 0;
78785:   pCtx->pFunc = pOp->p4.pFunc;
78786:   pCtx->iOp = (int)(pOp - aOp);
78787:   pCtx->pVdbe = p;
78788:   pCtx->argc = n;
78789:   pOp->p4type = P4_FUNCCTX;
78790:   pOp->p4.pCtx = pCtx;
78791:   pOp->opcode = OP_Function;
78792:   /* Fall through into OP_Function */
78793: }
78794: case OP_Function: {
78795:   int i;
78796:   sqlite3_context *pCtx;
78797: 
78798:   assert( pOp->p4type==P4_FUNCCTX );
78799:   pCtx = pOp->p4.pCtx;
78800: 
78801:   /* If this function is inside of a trigger, the register array in aMem[]
78802:   ** might change from one evaluation to the next.  The next block of code
78803:   ** checks to see if the register array has changed, and if so it
78804:   ** reinitializes the relavant parts of the sqlite3_context object */
78805:   pOut = &aMem[pOp->p3];
78806:   if( pCtx->pOut != pOut ){
78807:     pCtx->pOut = pOut;
78808:     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
78809:   }
78810: 
78811:   memAboutToChange(p, pCtx->pOut);
78812: #ifdef SQLITE_DEBUG
78813:   for(i=0; i<pCtx->argc; i++){
78814:     assert( memIsValid(pCtx->argv[i]) );
78815:     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
78816:   }
78817: #endif
78818:   MemSetTypeFlag(pCtx->pOut, MEM_Null);
78819:   pCtx->fErrorOrAux = 0;
78820:   db->lastRowid = lastRowid;
78821:   (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
78822:   lastRowid = db->lastRowid;  /* Remember rowid changes made by xSFunc */
78823: 
78824:   /* If the function returned an error, throw an exception */
78825:   if( pCtx->fErrorOrAux ){
78826:     if( pCtx->isError ){
78827:       sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
78828:       rc = pCtx->isError;
78829:     }
78830:     sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
78831:     if( rc ) goto abort_due_to_error;
78832:   }
78833: 
78834:   /* Copy the result of the function into register P3 */
78835:   if( pOut->flags & (MEM_Str|MEM_Blob) ){
78836:     sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
78837:     if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
78838:   }
78839: 
78840:   REGISTER_TRACE(pOp->p3, pCtx->pOut);
78841:   UPDATE_MAX_BLOBSIZE(pCtx->pOut);
78842:   break;
78843: }
78844: 
78845: /* Opcode: BitAnd P1 P2 P3 * *
78846: ** Synopsis:  r[P3]=r[P1]&r[P2]
78847: **
78848: ** Take the bit-wise AND of the values in register P1 and P2 and
78849: ** store the result in register P3.
78850: ** If either input is NULL, the result is NULL.
78851: */
78852: /* Opcode: BitOr P1 P2 P3 * *
78853: ** Synopsis:  r[P3]=r[P1]|r[P2]
78854: **
78855: ** Take the bit-wise OR of the values in register P1 and P2 and
78856: ** store the result in register P3.
78857: ** If either input is NULL, the result is NULL.
78858: */
78859: /* Opcode: ShiftLeft P1 P2 P3 * *
78860: ** Synopsis:  r[P3]=r[P2]<<r[P1]
78861: **
78862: ** Shift the integer value in register P2 to the left by the
78863: ** number of bits specified by the integer in register P1.
78864: ** Store the result in register P3.
78865: ** If either input is NULL, the result is NULL.
78866: */
78867: /* Opcode: ShiftRight P1 P2 P3 * *
78868: ** Synopsis:  r[P3]=r[P2]>>r[P1]
78869: **
78870: ** Shift the integer value in register P2 to the right by the
78871: ** number of bits specified by the integer in register P1.
78872: ** Store the result in register P3.
78873: ** If either input is NULL, the result is NULL.
78874: */
78875: case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
78876: case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
78877: case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
78878: case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
78879:   i64 iA;
78880:   u64 uA;
78881:   i64 iB;
78882:   u8 op;
78883: 
78884:   pIn1 = &aMem[pOp->p1];
78885:   pIn2 = &aMem[pOp->p2];
78886:   pOut = &aMem[pOp->p3];
78887:   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78888:     sqlite3VdbeMemSetNull(pOut);
78889:     break;
78890:   }
78891:   iA = sqlite3VdbeIntValue(pIn2);
78892:   iB = sqlite3VdbeIntValue(pIn1);
78893:   op = pOp->opcode;
78894:   if( op==OP_BitAnd ){
78895:     iA &= iB;
78896:   }else if( op==OP_BitOr ){
78897:     iA |= iB;
78898:   }else if( iB!=0 ){
78899:     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
78900: 
78901:     /* If shifting by a negative amount, shift in the other direction */
78902:     if( iB<0 ){
78903:       assert( OP_ShiftRight==OP_ShiftLeft+1 );
78904:       op = 2*OP_ShiftLeft + 1 - op;
78905:       iB = iB>(-64) ? -iB : 64;
78906:     }
78907: 
78908:     if( iB>=64 ){
78909:       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
78910:     }else{
78911:       memcpy(&uA, &iA, sizeof(uA));
78912:       if( op==OP_ShiftLeft ){
78913:         uA <<= iB;
78914:       }else{
78915:         uA >>= iB;
78916:         /* Sign-extend on a right shift of a negative number */
78917:         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
78918:       }
78919:       memcpy(&iA, &uA, sizeof(iA));
78920:     }
78921:   }
78922:   pOut->u.i = iA;
78923:   MemSetTypeFlag(pOut, MEM_Int);
78924:   break;
78925: }
78926: 
78927: /* Opcode: AddImm  P1 P2 * * *
78928: ** Synopsis:  r[P1]=r[P1]+P2
78929: ** 
78930: ** Add the constant P2 to the value in register P1.
78931: ** The result is always an integer.
78932: **
78933: ** To force any register to be an integer, just add 0.
78934: */
78935: case OP_AddImm: {            /* in1 */
78936:   pIn1 = &aMem[pOp->p1];
78937:   memAboutToChange(p, pIn1);
78938:   sqlite3VdbeMemIntegerify(pIn1);
78939:   pIn1->u.i += pOp->p2;
78940:   break;
78941: }
78942: 
78943: /* Opcode: MustBeInt P1 P2 * * *
78944: ** 
78945: ** Force the value in register P1 to be an integer.  If the value
78946: ** in P1 is not an integer and cannot be converted into an integer
78947: ** without data loss, then jump immediately to P2, or if P2==0
78948: ** raise an SQLITE_MISMATCH exception.
78949: */
78950: case OP_MustBeInt: {            /* jump, in1 */
78951:   pIn1 = &aMem[pOp->p1];
78952:   if( (pIn1->flags & MEM_Int)==0 ){
78953:     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
78954:     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
78955:     if( (pIn1->flags & MEM_Int)==0 ){
78956:       if( pOp->p2==0 ){
78957:         rc = SQLITE_MISMATCH;
78958:         goto abort_due_to_error;
78959:       }else{
78960:         goto jump_to_p2;
78961:       }
78962:     }
78963:   }
78964:   MemSetTypeFlag(pIn1, MEM_Int);
78965:   break;
78966: }
78967: 
78968: #ifndef SQLITE_OMIT_FLOATING_POINT
78969: /* Opcode: RealAffinity P1 * * * *
78970: **
78971: ** If register P1 holds an integer convert it to a real value.
78972: **
78973: ** This opcode is used when extracting information from a column that
78974: ** has REAL affinity.  Such column values may still be stored as
78975: ** integers, for space efficiency, but after extraction we want them
78976: ** to have only a real value.
78977: */
78978: case OP_RealAffinity: {                  /* in1 */
78979:   pIn1 = &aMem[pOp->p1];
78980:   if( pIn1->flags & MEM_Int ){
78981:     sqlite3VdbeMemRealify(pIn1);
78982:   }
78983:   break;
78984: }
78985: #endif
78986: 
78987: #ifndef SQLITE_OMIT_CAST
78988: /* Opcode: Cast P1 P2 * * *
78989: ** Synopsis: affinity(r[P1])
78990: **
78991: ** Force the value in register P1 to be the type defined by P2.
78992: ** 
78993: ** <ul>
78994: ** <li value="97"> TEXT
78995: ** <li value="98"> BLOB
78996: ** <li value="99"> NUMERIC
78997: ** <li value="100"> INTEGER
78998: ** <li value="101"> REAL
78999: ** </ul>
79000: **
79001: ** A NULL value is not changed by this routine.  It remains NULL.
79002: */
79003: case OP_Cast: {                  /* in1 */
79004:   assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
79005:   testcase( pOp->p2==SQLITE_AFF_TEXT );
79006:   testcase( pOp->p2==SQLITE_AFF_BLOB );
79007:   testcase( pOp->p2==SQLITE_AFF_NUMERIC );
79008:   testcase( pOp->p2==SQLITE_AFF_INTEGER );
79009:   testcase( pOp->p2==SQLITE_AFF_REAL );
79010:   pIn1 = &aMem[pOp->p1];
79011:   memAboutToChange(p, pIn1);
79012:   rc = ExpandBlob(pIn1);
79013:   sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
79014:   UPDATE_MAX_BLOBSIZE(pIn1);
79015:   if( rc ) goto abort_due_to_error;
79016:   break;
79017: }
79018: #endif /* SQLITE_OMIT_CAST */
79019: 
79020: /* Opcode: Lt P1 P2 P3 P4 P5
79021: ** Synopsis: IF r[P3]<r[P1]
79022: **
79023: ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
79024: ** jump to address P2.  
79025: **
79026: ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
79027: ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
79028: ** bit is clear then fall through if either operand is NULL.
79029: **
79030: ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
79031: ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
79032: ** to coerce both inputs according to this affinity before the
79033: ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
79034: ** affinity is used. Note that the affinity conversions are stored
79035: ** back into the input registers P1 and P3.  So this opcode can cause
79036: ** persistent changes to registers P1 and P3.
79037: **
79038: ** Once any conversions have taken place, and neither value is NULL, 
79039: ** the values are compared. If both values are blobs then memcmp() is
79040: ** used to determine the results of the comparison.  If both values
79041: ** are text, then the appropriate collating function specified in
79042: ** P4 is  used to do the comparison.  If P4 is not specified then
79043: ** memcmp() is used to compare text string.  If both values are
79044: ** numeric, then a numeric comparison is used. If the two values
79045: ** are of different types, then numbers are considered less than
79046: ** strings and strings are considered less than blobs.
79047: **
79048: ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
79049: ** store a boolean result (either 0, or 1, or NULL) in register P2.
79050: **
79051: ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
79052: ** equal to one another, provided that they do not have their MEM_Cleared
79053: ** bit set.
79054: */
79055: /* Opcode: Ne P1 P2 P3 P4 P5
79056: ** Synopsis: IF r[P3]!=r[P1]
79057: **
79058: ** This works just like the Lt opcode except that the jump is taken if
79059: ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
79060: ** additional information.
79061: **
79062: ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79063: ** true or false and is never NULL.  If both operands are NULL then the result
79064: ** of comparison is false.  If either operand is NULL then the result is true.
79065: ** If neither operand is NULL the result is the same as it would be if
79066: ** the SQLITE_NULLEQ flag were omitted from P5.
79067: */
79068: /* Opcode: Eq P1 P2 P3 P4 P5
79069: ** Synopsis: IF r[P3]==r[P1]
79070: **
79071: ** This works just like the Lt opcode except that the jump is taken if
79072: ** the operands in registers P1 and P3 are equal.
79073: ** See the Lt opcode for additional information.
79074: **
79075: ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
79076: ** true or false and is never NULL.  If both operands are NULL then the result
79077: ** of comparison is true.  If either operand is NULL then the result is false.
79078: ** If neither operand is NULL the result is the same as it would be if
79079: ** the SQLITE_NULLEQ flag were omitted from P5.
79080: */
79081: /* Opcode: Le P1 P2 P3 P4 P5
79082: ** Synopsis: IF r[P3]<=r[P1]
79083: **
79084: ** This works just like the Lt opcode except that the jump is taken if
79085: ** the content of register P3 is less than or equal to the content of
79086: ** register P1.  See the Lt opcode for additional information.
79087: */
79088: /* Opcode: Gt P1 P2 P3 P4 P5
79089: ** Synopsis: IF r[P3]>r[P1]
79090: **
79091: ** This works just like the Lt opcode except that the jump is taken if
79092: ** the content of register P3 is greater than the content of
79093: ** register P1.  See the Lt opcode for additional information.
79094: */
79095: /* Opcode: Ge P1 P2 P3 P4 P5
79096: ** Synopsis: IF r[P3]>=r[P1]
79097: **
79098: ** This works just like the Lt opcode except that the jump is taken if
79099: ** the content of register P3 is greater than or equal to the content of
79100: ** register P1.  See the Lt opcode for additional information.
79101: */
79102: case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
79103: case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
79104: case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
79105: case OP_Le:               /* same as TK_LE, jump, in1, in3 */
79106: case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
79107: case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
79108:   int res;            /* Result of the comparison of pIn1 against pIn3 */
79109:   char affinity;      /* Affinity to use for comparison */
79110:   u16 flags1;         /* Copy of initial value of pIn1->flags */
79111:   u16 flags3;         /* Copy of initial value of pIn3->flags */
79112: 
79113:   pIn1 = &aMem[pOp->p1];
79114:   pIn3 = &aMem[pOp->p3];
79115:   flags1 = pIn1->flags;
79116:   flags3 = pIn3->flags;
79117:   if( (flags1 | flags3)&MEM_Null ){
79118:     /* One or both operands are NULL */
79119:     if( pOp->p5 & SQLITE_NULLEQ ){
79120:       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
79121:       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
79122:       ** or not both operands are null.
79123:       */
79124:       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
79125:       assert( (flags1 & MEM_Cleared)==0 );
79126:       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
79127:       if( (flags1&MEM_Null)!=0
79128:        && (flags3&MEM_Null)!=0
79129:        && (flags3&MEM_Cleared)==0
79130:       ){
79131:         res = 0;  /* Results are equal */
79132:       }else{
79133:         res = 1;  /* Results are not equal */
79134:       }
79135:     }else{
79136:       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
79137:       ** then the result is always NULL.
79138:       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
79139:       */
79140:       if( pOp->p5 & SQLITE_STOREP2 ){
79141:         pOut = &aMem[pOp->p2];
79142:         memAboutToChange(p, pOut);
79143:         MemSetTypeFlag(pOut, MEM_Null);
79144:         REGISTER_TRACE(pOp->p2, pOut);
79145:       }else{
79146:         VdbeBranchTaken(2,3);
79147:         if( pOp->p5 & SQLITE_JUMPIFNULL ){
79148:           goto jump_to_p2;
79149:         }
79150:       }
79151:       break;
79152:     }
79153:   }else{
79154:     /* Neither operand is NULL.  Do a comparison. */
79155:     affinity = pOp->p5 & SQLITE_AFF_MASK;
79156:     if( affinity>=SQLITE_AFF_NUMERIC ){
79157:       if( (flags1 | flags3)&MEM_Str ){
79158:         if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79159:           applyNumericAffinity(pIn1,0);
79160:           flags3 = pIn3->flags;
79161:         }
79162:         if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
79163:           applyNumericAffinity(pIn3,0);
79164:         }
79165:       }
79166:     }else if( affinity==SQLITE_AFF_TEXT ){
79167:       if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
79168:         testcase( pIn1->flags & MEM_Int );
79169:         testcase( pIn1->flags & MEM_Real );
79170:         sqlite3VdbeMemStringify(pIn1, encoding, 1);
79171:         testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
79172:         flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
79173:         flags3 = pIn3->flags;
79174:       }
79175:       if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
79176:         testcase( pIn3->flags & MEM_Int );
79177:         testcase( pIn3->flags & MEM_Real );
79178:         sqlite3VdbeMemStringify(pIn3, encoding, 1);
79179:         testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
79180:         flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
79181:       }
79182:     }
79183:     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
79184:     if( flags1 & MEM_Zero ){
79185:       sqlite3VdbeMemExpandBlob(pIn1);
79186:       flags1 &= ~MEM_Zero;
79187:     }
79188:     if( flags3 & MEM_Zero ){
79189:       sqlite3VdbeMemExpandBlob(pIn3);
79190:       flags3 &= ~MEM_Zero;
79191:     }
79192:     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
79193:   }
79194:   switch( pOp->opcode ){
79195:     case OP_Eq:    res = res==0;     break;
79196:     case OP_Ne:    res = res!=0;     break;
79197:     case OP_Lt:    res = res<0;      break;
79198:     case OP_Le:    res = res<=0;     break;
79199:     case OP_Gt:    res = res>0;      break;
79200:     default:       res = res>=0;     break;
79201:   }
79202: 
79203:   /* Undo any changes made by applyAffinity() to the input registers. */
79204:   assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
79205:   pIn1->flags = flags1;
79206:   assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
79207:   pIn3->flags = flags3;
79208: 
79209:   if( pOp->p5 & SQLITE_STOREP2 ){
79210:     pOut = &aMem[pOp->p2];
79211:     memAboutToChange(p, pOut);
79212:     MemSetTypeFlag(pOut, MEM_Int);
79213:     pOut->u.i = res;
79214:     REGISTER_TRACE(pOp->p2, pOut);
79215:   }else{
79216:     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
79217:     if( res ){
79218:       goto jump_to_p2;
79219:     }
79220:   }
79221:   break;
79222: }
79223: 
79224: /* Opcode: Permutation * * * P4 *
79225: **
79226: ** Set the permutation used by the OP_Compare operator to be the array
79227: ** of integers in P4.
79228: **
79229: ** The permutation is only valid until the next OP_Compare that has
79230: ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
79231: ** occur immediately prior to the OP_Compare.
79232: **
79233: ** The first integer in the P4 integer array is the length of the array
79234: ** and does not become part of the permutation.
79235: */
79236: case OP_Permutation: {
79237:   assert( pOp->p4type==P4_INTARRAY );
79238:   assert( pOp->p4.ai );
79239:   aPermute = pOp->p4.ai + 1;
79240:   break;
79241: }
79242: 
79243: /* Opcode: Compare P1 P2 P3 P4 P5
79244: ** Synopsis: r[P1@P3] <-> r[P2@P3]
79245: **
79246: ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
79247: ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
79248: ** the comparison for use by the next OP_Jump instruct.
79249: **
79250: ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
79251: ** determined by the most recent OP_Permutation operator.  If the
79252: ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
79253: ** order.
79254: **
79255: ** P4 is a KeyInfo structure that defines collating sequences and sort
79256: ** orders for the comparison.  The permutation applies to registers
79257: ** only.  The KeyInfo elements are used sequentially.
79258: **
79259: ** The comparison is a sort comparison, so NULLs compare equal,
79260: ** NULLs are less than numbers, numbers are less than strings,
79261: ** and strings are less than blobs.
79262: */
79263: case OP_Compare: {
79264:   int n;
79265:   int i;
79266:   int p1;
79267:   int p2;
79268:   const KeyInfo *pKeyInfo;
79269:   int idx;
79270:   CollSeq *pColl;    /* Collating sequence to use on this term */
79271:   int bRev;          /* True for DESCENDING sort order */
79272: 
79273:   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
79274:   n = pOp->p3;
79275:   pKeyInfo = pOp->p4.pKeyInfo;
79276:   assert( n>0 );
79277:   assert( pKeyInfo!=0 );
79278:   p1 = pOp->p1;
79279:   p2 = pOp->p2;
79280: #if SQLITE_DEBUG
79281:   if( aPermute ){
79282:     int k, mx = 0;
79283:     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
79284:     assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
79285:     assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
79286:   }else{
79287:     assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
79288:     assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
79289:   }
79290: #endif /* SQLITE_DEBUG */
79291:   for(i=0; i<n; i++){
79292:     idx = aPermute ? aPermute[i] : i;
79293:     assert( memIsValid(&aMem[p1+idx]) );
79294:     assert( memIsValid(&aMem[p2+idx]) );
79295:     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
79296:     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
79297:     assert( i<pKeyInfo->nField );
79298:     pColl = pKeyInfo->aColl[i];
79299:     bRev = pKeyInfo->aSortOrder[i];
79300:     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
79301:     if( iCompare ){
79302:       if( bRev ) iCompare = -iCompare;
79303:       break;
79304:     }
79305:   }
79306:   aPermute = 0;
79307:   break;
79308: }
79309: 
79310: /* Opcode: Jump P1 P2 P3 * *
79311: **
79312: ** Jump to the instruction at address P1, P2, or P3 depending on whether
79313: ** in the most recent OP_Compare instruction the P1 vector was less than
79314: ** equal to, or greater than the P2 vector, respectively.
79315: */
79316: case OP_Jump: {             /* jump */
79317:   if( iCompare<0 ){
79318:     VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
79319:   }else if( iCompare==0 ){
79320:     VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
79321:   }else{
79322:     VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
79323:   }
79324:   break;
79325: }
79326: 
79327: /* Opcode: And P1 P2 P3 * *
79328: ** Synopsis: r[P3]=(r[P1] && r[P2])
79329: **
79330: ** Take the logical AND of the values in registers P1 and P2 and
79331: ** write the result into register P3.
79332: **
79333: ** If either P1 or P2 is 0 (false) then the result is 0 even if
79334: ** the other input is NULL.  A NULL and true or two NULLs give
79335: ** a NULL output.
79336: */
79337: /* Opcode: Or P1 P2 P3 * *
79338: ** Synopsis: r[P3]=(r[P1] || r[P2])
79339: **
79340: ** Take the logical OR of the values in register P1 and P2 and
79341: ** store the answer in register P3.
79342: **
79343: ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
79344: ** even if the other input is NULL.  A NULL and false or two NULLs
79345: ** give a NULL output.
79346: */
79347: case OP_And:              /* same as TK_AND, in1, in2, out3 */
79348: case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
79349:   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79350:   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
79351: 
79352:   pIn1 = &aMem[pOp->p1];
79353:   if( pIn1->flags & MEM_Null ){
79354:     v1 = 2;
79355:   }else{
79356:     v1 = sqlite3VdbeIntValue(pIn1)!=0;
79357:   }
79358:   pIn2 = &aMem[pOp->p2];
79359:   if( pIn2->flags & MEM_Null ){
79360:     v2 = 2;
79361:   }else{
79362:     v2 = sqlite3VdbeIntValue(pIn2)!=0;
79363:   }
79364:   if( pOp->opcode==OP_And ){
79365:     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
79366:     v1 = and_logic[v1*3+v2];
79367:   }else{
79368:     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
79369:     v1 = or_logic[v1*3+v2];
79370:   }
79371:   pOut = &aMem[pOp->p3];
79372:   if( v1==2 ){
79373:     MemSetTypeFlag(pOut, MEM_Null);
79374:   }else{
79375:     pOut->u.i = v1;
79376:     MemSetTypeFlag(pOut, MEM_Int);
79377:   }
79378:   break;
79379: }
79380: 
79381: /* Opcode: Not P1 P2 * * *
79382: ** Synopsis: r[P2]= !r[P1]
79383: **
79384: ** Interpret the value in register P1 as a boolean value.  Store the
79385: ** boolean complement in register P2.  If the value in register P1 is 
79386: ** NULL, then a NULL is stored in P2.
79387: */
79388: case OP_Not: {                /* same as TK_NOT, in1, out2 */
79389:   pIn1 = &aMem[pOp->p1];
79390:   pOut = &aMem[pOp->p2];
79391:   sqlite3VdbeMemSetNull(pOut);
79392:   if( (pIn1->flags & MEM_Null)==0 ){
79393:     pOut->flags = MEM_Int;
79394:     pOut->u.i = !sqlite3VdbeIntValue(pIn1);
79395:   }
79396:   break;
79397: }
79398: 
79399: /* Opcode: BitNot P1 P2 * * *
79400: ** Synopsis: r[P1]= ~r[P1]
79401: **
79402: ** Interpret the content of register P1 as an integer.  Store the
79403: ** ones-complement of the P1 value into register P2.  If P1 holds
79404: ** a NULL then store a NULL in P2.
79405: */
79406: case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
79407:   pIn1 = &aMem[pOp->p1];
79408:   pOut = &aMem[pOp->p2];
79409:   sqlite3VdbeMemSetNull(pOut);
79410:   if( (pIn1->flags & MEM_Null)==0 ){
79411:     pOut->flags = MEM_Int;
79412:     pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
79413:   }
79414:   break;
79415: }
79416: 
79417: /* Opcode: Once P1 P2 * * *
79418: **
79419: ** Check the "once" flag number P1. If it is set, jump to instruction P2. 
79420: ** Otherwise, set the flag and fall through to the next instruction.
79421: ** In other words, this opcode causes all following opcodes up through P2
79422: ** (but not including P2) to run just once and to be skipped on subsequent
79423: ** times through the loop.
79424: **
79425: ** All "once" flags are initially cleared whenever a prepared statement
79426: ** first begins to run.
79427: */
79428: case OP_Once: {             /* jump */
79429:   assert( pOp->p1<p->nOnceFlag );
79430:   VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
79431:   if( p->aOnceFlag[pOp->p1] ){
79432:     goto jump_to_p2;
79433:   }else{
79434:     p->aOnceFlag[pOp->p1] = 1;
79435:   }
79436:   break;
79437: }
79438: 
79439: /* Opcode: If P1 P2 P3 * *
79440: **
79441: ** Jump to P2 if the value in register P1 is true.  The value
79442: ** is considered true if it is numeric and non-zero.  If the value
79443: ** in P1 is NULL then take the jump if and only if P3 is non-zero.
79444: */
79445: /* Opcode: IfNot P1 P2 P3 * *
79446: **
79447: ** Jump to P2 if the value in register P1 is False.  The value
79448: ** is considered false if it has a numeric value of zero.  If the value
79449: ** in P1 is NULL then take the jump if and only if P3 is non-zero.
79450: */
79451: case OP_If:                 /* jump, in1 */
79452: case OP_IfNot: {            /* jump, in1 */
79453:   int c;
79454:   pIn1 = &aMem[pOp->p1];
79455:   if( pIn1->flags & MEM_Null ){
79456:     c = pOp->p3;
79457:   }else{
79458: #ifdef SQLITE_OMIT_FLOATING_POINT
79459:     c = sqlite3VdbeIntValue(pIn1)!=0;
79460: #else
79461:     c = sqlite3VdbeRealValue(pIn1)!=0.0;
79462: #endif
79463:     if( pOp->opcode==OP_IfNot ) c = !c;
79464:   }
79465:   VdbeBranchTaken(c!=0, 2);
79466:   if( c ){
79467:     goto jump_to_p2;
79468:   }
79469:   break;
79470: }
79471: 
79472: /* Opcode: IsNull P1 P2 * * *
79473: ** Synopsis:  if r[P1]==NULL goto P2
79474: **
79475: ** Jump to P2 if the value in register P1 is NULL.
79476: */
79477: case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
79478:   pIn1 = &aMem[pOp->p1];
79479:   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
79480:   if( (pIn1->flags & MEM_Null)!=0 ){
79481:     goto jump_to_p2;
79482:   }
79483:   break;
79484: }
79485: 
79486: /* Opcode: NotNull P1 P2 * * *
79487: ** Synopsis: if r[P1]!=NULL goto P2
79488: **
79489: ** Jump to P2 if the value in register P1 is not NULL.  
79490: */
79491: case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
79492:   pIn1 = &aMem[pOp->p1];
79493:   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
79494:   if( (pIn1->flags & MEM_Null)==0 ){
79495:     goto jump_to_p2;
79496:   }
79497:   break;
79498: }
79499: 
79500: /* Opcode: Column P1 P2 P3 P4 P5
79501: ** Synopsis:  r[P3]=PX
79502: **
79503: ** Interpret the data that cursor P1 points to as a structure built using
79504: ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
79505: ** information about the format of the data.)  Extract the P2-th column
79506: ** from this record.  If there are less that (P2+1) 
79507: ** values in the record, extract a NULL.
79508: **
79509: ** The value extracted is stored in register P3.
79510: **
79511: ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
79512: ** if the P4 argument is a P4_MEM use the value of the P4 argument as
79513: ** the result.
79514: **
79515: ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
79516: ** then the cache of the cursor is reset prior to extracting the column.
79517: ** The first OP_Column against a pseudo-table after the value of the content
79518: ** register has changed should have this bit set.
79519: **
79520: ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
79521: ** the result is guaranteed to only be used as the argument of a length()
79522: ** or typeof() function, respectively.  The loading of large blobs can be
79523: ** skipped for length() and all content loading can be skipped for typeof().
79524: */
79525: case OP_Column: {
79526:   int p2;            /* column number to retrieve */
79527:   VdbeCursor *pC;    /* The VDBE cursor */
79528:   BtCursor *pCrsr;   /* The BTree cursor */
79529:   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
79530:   int len;           /* The length of the serialized data for the column */
79531:   int i;             /* Loop counter */
79532:   Mem *pDest;        /* Where to write the extracted value */
79533:   Mem sMem;          /* For storing the record being decoded */
79534:   const u8 *zData;   /* Part of the record being decoded */
79535:   const u8 *zHdr;    /* Next unparsed byte of the header */
79536:   const u8 *zEndHdr; /* Pointer to first byte after the header */
79537:   u32 offset;        /* Offset into the data */
79538:   u64 offset64;      /* 64-bit offset */
79539:   u32 avail;         /* Number of bytes of available data */
79540:   u32 t;             /* A type code from the record header */
79541:   Mem *pReg;         /* PseudoTable input register */
79542: 
79543:   pC = p->apCsr[pOp->p1];
79544:   p2 = pOp->p2;
79545: 
79546:   /* If the cursor cache is stale, bring it up-to-date */
79547:   rc = sqlite3VdbeCursorMoveto(&pC, &p2);
79548:   if( rc ) goto abort_due_to_error;
79549: 
79550:   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79551:   pDest = &aMem[pOp->p3];
79552:   memAboutToChange(p, pDest);
79553:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
79554:   assert( pC!=0 );
79555:   assert( p2<pC->nField );
79556:   aOffset = pC->aOffset;
79557:   assert( pC->eCurType!=CURTYPE_VTAB );
79558:   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
79559:   assert( pC->eCurType!=CURTYPE_SORTER );
79560:   pCrsr = pC->uc.pCursor;
79561: 
79562:   if( pC->cacheStatus!=p->cacheCtr ){                /*OPTIMIZATION-IF-FALSE*/
79563:     if( pC->nullRow ){
79564:       if( pC->eCurType==CURTYPE_PSEUDO ){
79565:         assert( pC->uc.pseudoTableReg>0 );
79566:         pReg = &aMem[pC->uc.pseudoTableReg];
79567:         assert( pReg->flags & MEM_Blob );
79568:         assert( memIsValid(pReg) );
79569:         pC->payloadSize = pC->szRow = avail = pReg->n;
79570:         pC->aRow = (u8*)pReg->z;
79571:       }else{
79572:         sqlite3VdbeMemSetNull(pDest);
79573:         goto op_column_out;
79574:       }
79575:     }else{
79576:       assert( pC->eCurType==CURTYPE_BTREE );
79577:       assert( pCrsr );
79578:       assert( sqlite3BtreeCursorIsValid(pCrsr) );
79579:       pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
79580:       pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
79581:       assert( avail<=65536 );  /* Maximum page size is 64KiB */
79582:       if( pC->payloadSize <= (u32)avail ){
79583:         pC->szRow = pC->payloadSize;
79584:       }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
79585:         goto too_big;
79586:       }else{
79587:         pC->szRow = avail;
79588:       }
79589:     }
79590:     pC->cacheStatus = p->cacheCtr;
79591:     pC->iHdrOffset = getVarint32(pC->aRow, offset);
79592:     pC->nHdrParsed = 0;
79593:     aOffset[0] = offset;
79594: 
79595: 
79596:     if( avail<offset ){      /*OPTIMIZATION-IF-FALSE*/
79597:       /* pC->aRow does not have to hold the entire row, but it does at least
79598:       ** need to cover the header of the record.  If pC->aRow does not contain
79599:       ** the complete header, then set it to zero, forcing the header to be
79600:       ** dynamically allocated. */
79601:       pC->aRow = 0;
79602:       pC->szRow = 0;
79603: 
79604:       /* Make sure a corrupt database has not given us an oversize header.
79605:       ** Do this now to avoid an oversize memory allocation.
79606:       **
79607:       ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
79608:       ** types use so much data space that there can only be 4096 and 32 of
79609:       ** them, respectively.  So the maximum header length results from a
79610:       ** 3-byte type for each of the maximum of 32768 columns plus three
79611:       ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
79612:       */
79613:       if( offset > 98307 || offset > pC->payloadSize ){
79614:         rc = SQLITE_CORRUPT_BKPT;
79615:         goto abort_due_to_error;
79616:       }
79617:     }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
79618:       /* The following goto is an optimization.  It can be omitted and
79619:       ** everything will still work.  But OP_Column is measurably faster
79620:       ** by skipping the subsequent conditional, which is always true.
79621:       */
79622:       zData = pC->aRow;
79623:       assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
79624:       goto op_column_read_header;
79625:     }
79626:   }
79627: 
79628:   /* Make sure at least the first p2+1 entries of the header have been
79629:   ** parsed and valid information is in aOffset[] and pC->aType[].
79630:   */
79631:   if( pC->nHdrParsed<=p2 ){
79632:     /* If there is more header available for parsing in the record, try
79633:     ** to extract additional fields up through the p2+1-th field 
79634:     */
79635:     if( pC->iHdrOffset<aOffset[0] ){
79636:       /* Make sure zData points to enough of the record to cover the header. */
79637:       if( pC->aRow==0 ){
79638:         memset(&sMem, 0, sizeof(sMem));
79639:         rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
79640:         if( rc!=SQLITE_OK ) goto abort_due_to_error;
79641:         zData = (u8*)sMem.z;
79642:       }else{
79643:         zData = pC->aRow;
79644:       }
79645:   
79646:       /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
79647:     op_column_read_header:
79648:       i = pC->nHdrParsed;
79649:       offset64 = aOffset[i];
79650:       zHdr = zData + pC->iHdrOffset;
79651:       zEndHdr = zData + aOffset[0];
79652:       do{
79653:         if( (t = zHdr[0])<0x80 ){
79654:           zHdr++;
79655:           offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
79656:         }else{
79657:           zHdr += sqlite3GetVarint32(zHdr, &t);
79658:           offset64 += sqlite3VdbeSerialTypeLen(t);
79659:         }
79660:         pC->aType[i++] = t;
79661:         aOffset[i] = (u32)(offset64 & 0xffffffff);
79662:       }while( i<=p2 && zHdr<zEndHdr );
79663: 
79664:       /* The record is corrupt if any of the following are true:
79665:       ** (1) the bytes of the header extend past the declared header size
79666:       ** (2) the entire header was used but not all data was used
79667:       ** (3) the end of the data extends beyond the end of the record.
79668:       */
79669:       if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
79670:        || (offset64 > pC->payloadSize)
79671:       ){
79672:         if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79673:         rc = SQLITE_CORRUPT_BKPT;
79674:         goto abort_due_to_error;
79675:       }
79676: 
79677:       pC->nHdrParsed = i;
79678:       pC->iHdrOffset = (u32)(zHdr - zData);
79679:       if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79680:     }else{
79681:       t = 0;
79682:     }
79683: 
79684:     /* If after trying to extract new entries from the header, nHdrParsed is
79685:     ** still not up to p2, that means that the record has fewer than p2
79686:     ** columns.  So the result will be either the default value or a NULL.
79687:     */
79688:     if( pC->nHdrParsed<=p2 ){
79689:       if( pOp->p4type==P4_MEM ){
79690:         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
79691:       }else{
79692:         sqlite3VdbeMemSetNull(pDest);
79693:       }
79694:       goto op_column_out;
79695:     }
79696:   }else{
79697:     t = pC->aType[p2];
79698:   }
79699: 
79700:   /* Extract the content for the p2+1-th column.  Control can only
79701:   ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
79702:   ** all valid.
79703:   */
79704:   assert( p2<pC->nHdrParsed );
79705:   assert( rc==SQLITE_OK );
79706:   assert( sqlite3VdbeCheckMemInvariants(pDest) );
79707:   if( VdbeMemDynamic(pDest) ){
79708:     sqlite3VdbeMemSetNull(pDest);
79709:   }
79710:   assert( t==pC->aType[p2] );
79711:   if( pC->szRow>=aOffset[p2+1] ){
79712:     /* This is the common case where the desired content fits on the original
79713:     ** page - where the content is not on an overflow page */
79714:     zData = pC->aRow + aOffset[p2];
79715:     if( t<12 ){
79716:       sqlite3VdbeSerialGet(zData, t, pDest);
79717:     }else{
79718:       /* If the column value is a string, we need a persistent value, not
79719:       ** a MEM_Ephem value.  This branch is a fast short-cut that is equivalent
79720:       ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
79721:       */
79722:       static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
79723:       pDest->n = len = (t-12)/2;
79724:       pDest->enc = encoding;
79725:       if( pDest->szMalloc < len+2 ){
79726:         pDest->flags = MEM_Null;
79727:         if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
79728:       }else{
79729:         pDest->z = pDest->zMalloc;
79730:       }
79731:       memcpy(pDest->z, zData, len);
79732:       pDest->z[len] = 0;
79733:       pDest->z[len+1] = 0;
79734:       pDest->flags = aFlag[t&1];
79735:     }
79736:   }else{
79737:     pDest->enc = encoding;
79738:     /* This branch happens only when content is on overflow pages */
79739:     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
79740:           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
79741:      || (len = sqlite3VdbeSerialTypeLen(t))==0
79742:     ){
79743:       /* Content is irrelevant for
79744:       **    1. the typeof() function,
79745:       **    2. the length(X) function if X is a blob, and
79746:       **    3. if the content length is zero.
79747:       ** So we might as well use bogus content rather than reading
79748:       ** content from disk. */
79749:       static u8 aZero[8];  /* This is the bogus content */
79750:       sqlite3VdbeSerialGet(aZero, t, pDest);
79751:     }else{
79752:       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
79753:                                    pDest);
79754:       if( rc!=SQLITE_OK ) goto abort_due_to_error;
79755:       sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
79756:       pDest->flags &= ~MEM_Ephem;
79757:     }
79758:   }
79759: 
79760: op_column_out:
79761:   UPDATE_MAX_BLOBSIZE(pDest);
79762:   REGISTER_TRACE(pOp->p3, pDest);
79763:   break;
79764: }
79765: 
79766: /* Opcode: Affinity P1 P2 * P4 *
79767: ** Synopsis: affinity(r[P1@P2])
79768: **
79769: ** Apply affinities to a range of P2 registers starting with P1.
79770: **
79771: ** P4 is a string that is P2 characters long. The nth character of the
79772: ** string indicates the column affinity that should be used for the nth
79773: ** memory cell in the range.
79774: */
79775: case OP_Affinity: {
79776:   const char *zAffinity;   /* The affinity to be applied */
79777:   char cAff;               /* A single character of affinity */
79778: 
79779:   zAffinity = pOp->p4.z;
79780:   assert( zAffinity!=0 );
79781:   assert( zAffinity[pOp->p2]==0 );
79782:   pIn1 = &aMem[pOp->p1];
79783:   while( (cAff = *(zAffinity++))!=0 ){
79784:     assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
79785:     assert( memIsValid(pIn1) );
79786:     applyAffinity(pIn1, cAff, encoding);
79787:     pIn1++;
79788:   }
79789:   break;
79790: }
79791: 
79792: /* Opcode: MakeRecord P1 P2 P3 P4 *
79793: ** Synopsis: r[P3]=mkrec(r[P1@P2])
79794: **
79795: ** Convert P2 registers beginning with P1 into the [record format]
79796: ** use as a data record in a database table or as a key
79797: ** in an index.  The OP_Column opcode can decode the record later.
79798: **
79799: ** P4 may be a string that is P2 characters long.  The nth character of the
79800: ** string indicates the column affinity that should be used for the nth
79801: ** field of the index key.
79802: **
79803: ** The mapping from character to affinity is given by the SQLITE_AFF_
79804: ** macros defined in sqliteInt.h.
79805: **
79806: ** If P4 is NULL then all index fields have the affinity BLOB.
79807: */
79808: case OP_MakeRecord: {
79809:   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
79810:   Mem *pRec;             /* The new record */
79811:   u64 nData;             /* Number of bytes of data space */
79812:   int nHdr;              /* Number of bytes of header space */
79813:   i64 nByte;             /* Data space required for this record */
79814:   i64 nZero;             /* Number of zero bytes at the end of the record */
79815:   int nVarint;           /* Number of bytes in a varint */
79816:   u32 serial_type;       /* Type field */
79817:   Mem *pData0;           /* First field to be combined into the record */
79818:   Mem *pLast;            /* Last field of the record */
79819:   int nField;            /* Number of fields in the record */
79820:   char *zAffinity;       /* The affinity string for the record */
79821:   int file_format;       /* File format to use for encoding */
79822:   int i;                 /* Space used in zNewRecord[] header */
79823:   int j;                 /* Space used in zNewRecord[] content */
79824:   u32 len;               /* Length of a field */
79825: 
79826:   /* Assuming the record contains N fields, the record format looks
79827:   ** like this:
79828:   **
79829:   ** ------------------------------------------------------------------------
79830:   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
79831:   ** ------------------------------------------------------------------------
79832:   **
79833:   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
79834:   ** and so forth.
79835:   **
79836:   ** Each type field is a varint representing the serial type of the 
79837:   ** corresponding data element (see sqlite3VdbeSerialType()). The
79838:   ** hdr-size field is also a varint which is the offset from the beginning
79839:   ** of the record to data0.
79840:   */
79841:   nData = 0;         /* Number of bytes of data space */
79842:   nHdr = 0;          /* Number of bytes of header space */
79843:   nZero = 0;         /* Number of zero bytes at the end of the record */
79844:   nField = pOp->p1;
79845:   zAffinity = pOp->p4.z;
79846:   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
79847:   pData0 = &aMem[nField];
79848:   nField = pOp->p2;
79849:   pLast = &pData0[nField-1];
79850:   file_format = p->minWriteFileFormat;
79851: 
79852:   /* Identify the output register */
79853:   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
79854:   pOut = &aMem[pOp->p3];
79855:   memAboutToChange(p, pOut);
79856: 
79857:   /* Apply the requested affinity to all inputs
79858:   */
79859:   assert( pData0<=pLast );
79860:   if( zAffinity ){
79861:     pRec = pData0;
79862:     do{
79863:       applyAffinity(pRec++, *(zAffinity++), encoding);
79864:       assert( zAffinity[0]==0 || pRec<=pLast );
79865:     }while( zAffinity[0] );
79866:   }
79867: 
79868:   /* Loop through the elements that will make up the record to figure
79869:   ** out how much space is required for the new record.
79870:   */
79871:   pRec = pLast;
79872:   do{
79873:     assert( memIsValid(pRec) );
79874:     pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
79875:     if( pRec->flags & MEM_Zero ){
79876:       if( nData ){
79877:         if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
79878:       }else{
79879:         nZero += pRec->u.nZero;
79880:         len -= pRec->u.nZero;
79881:       }
79882:     }
79883:     nData += len;
79884:     testcase( serial_type==127 );
79885:     testcase( serial_type==128 );
79886:     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
79887:     if( pRec==pData0 ) break;
79888:     pRec--;
79889:   }while(1);
79890: 
79891:   /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
79892:   ** which determines the total number of bytes in the header. The varint
79893:   ** value is the size of the header in bytes including the size varint
79894:   ** itself. */
79895:   testcase( nHdr==126 );
79896:   testcase( nHdr==127 );
79897:   if( nHdr<=126 ){
79898:     /* The common case */
79899:     nHdr += 1;
79900:   }else{
79901:     /* Rare case of a really large header */
79902:     nVarint = sqlite3VarintLen(nHdr);
79903:     nHdr += nVarint;
79904:     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
79905:   }
79906:   nByte = nHdr+nData;
79907:   if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79908:     goto too_big;
79909:   }
79910: 
79911:   /* Make sure the output register has a buffer large enough to store 
79912:   ** the new record. The output register (pOp->p3) is not allowed to
79913:   ** be one of the input registers (because the following call to
79914:   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
79915:   */
79916:   if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
79917:     goto no_mem;
79918:   }
79919:   zNewRecord = (u8 *)pOut->z;
79920: 
79921:   /* Write the record */
79922:   i = putVarint32(zNewRecord, nHdr);
79923:   j = nHdr;
79924:   assert( pData0<=pLast );
79925:   pRec = pData0;
79926:   do{
79927:     serial_type = pRec->uTemp;
79928:     /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
79929:     ** additional varints, one per column. */
79930:     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
79931:     /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
79932:     ** immediately follow the header. */
79933:     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
79934:   }while( (++pRec)<=pLast );
79935:   assert( i==nHdr );
79936:   assert( j==nByte );
79937: 
79938:   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79939:   pOut->n = (int)nByte;
79940:   pOut->flags = MEM_Blob;
79941:   if( nZero ){
79942:     pOut->u.nZero = nZero;
79943:     pOut->flags |= MEM_Zero;
79944:   }
79945:   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
79946:   REGISTER_TRACE(pOp->p3, pOut);
79947:   UPDATE_MAX_BLOBSIZE(pOut);
79948:   break;
79949: }
79950: 
79951: /* Opcode: Count P1 P2 * * *
79952: ** Synopsis: r[P2]=count()
79953: **
79954: ** Store the number of entries (an integer value) in the table or index 
79955: ** opened by cursor P1 in register P2
79956: */
79957: #ifndef SQLITE_OMIT_BTREECOUNT
79958: case OP_Count: {         /* out2 */
79959:   i64 nEntry;
79960:   BtCursor *pCrsr;
79961: 
79962:   assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
79963:   pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
79964:   assert( pCrsr );
79965:   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
79966:   rc = sqlite3BtreeCount(pCrsr, &nEntry);
79967:   if( rc ) goto abort_due_to_error;
79968:   pOut = out2Prerelease(p, pOp);
79969:   pOut->u.i = nEntry;
79970:   break;
79971: }
79972: #endif
79973: 
79974: /* Opcode: Savepoint P1 * * P4 *
79975: **
79976: ** Open, release or rollback the savepoint named by parameter P4, depending
79977: ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
79978: ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
79979: */
79980: case OP_Savepoint: {
79981:   int p1;                         /* Value of P1 operand */
79982:   char *zName;                    /* Name of savepoint */
79983:   int nName;
79984:   Savepoint *pNew;
79985:   Savepoint *pSavepoint;
79986:   Savepoint *pTmp;
79987:   int iSavepoint;
79988:   int ii;
79989: 
79990:   p1 = pOp->p1;
79991:   zName = pOp->p4.z;
79992: 
79993:   /* Assert that the p1 parameter is valid. Also that if there is no open
79994:   ** transaction, then there cannot be any savepoints. 
79995:   */
79996:   assert( db->pSavepoint==0 || db->autoCommit==0 );
79997:   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
79998:   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
79999:   assert( checkSavepointCount(db) );
80000:   assert( p->bIsReader );
80001: 
80002:   if( p1==SAVEPOINT_BEGIN ){
80003:     if( db->nVdbeWrite>0 ){
80004:       /* A new savepoint cannot be created if there are active write 
80005:       ** statements (i.e. open read/write incremental blob handles).
80006:       */
80007:       sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
80008:       rc = SQLITE_BUSY;
80009:     }else{
80010:       nName = sqlite3Strlen30(zName);
80011: 
80012: #ifndef SQLITE_OMIT_VIRTUALTABLE
80013:       /* This call is Ok even if this savepoint is actually a transaction
80014:       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
80015:       ** If this is a transaction savepoint being opened, it is guaranteed
80016:       ** that the db->aVTrans[] array is empty.  */
80017:       assert( db->autoCommit==0 || db->nVTrans==0 );
80018:       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
80019:                                 db->nStatement+db->nSavepoint);
80020:       if( rc!=SQLITE_OK ) goto abort_due_to_error;
80021: #endif
80022: 
80023:       /* Create a new savepoint structure. */
80024:       pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
80025:       if( pNew ){
80026:         pNew->zName = (char *)&pNew[1];
80027:         memcpy(pNew->zName, zName, nName+1);
80028:     
80029:         /* If there is no open transaction, then mark this as a special
80030:         ** "transaction savepoint". */
80031:         if( db->autoCommit ){
80032:           db->autoCommit = 0;
80033:           db->isTransactionSavepoint = 1;
80034:         }else{
80035:           db->nSavepoint++;
80036:         }
80037: 
80038:         /* Link the new savepoint into the database handle's list. */
80039:         pNew->pNext = db->pSavepoint;
80040:         db->pSavepoint = pNew;
80041:         pNew->nDeferredCons = db->nDeferredCons;
80042:         pNew->nDeferredImmCons = db->nDeferredImmCons;
80043:       }
80044:     }
80045:   }else{
80046:     iSavepoint = 0;
80047: 
80048:     /* Find the named savepoint. If there is no such savepoint, then an
80049:     ** an error is returned to the user.  */
80050:     for(
80051:       pSavepoint = db->pSavepoint; 
80052:       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
80053:       pSavepoint = pSavepoint->pNext
80054:     ){
80055:       iSavepoint++;
80056:     }
80057:     if( !pSavepoint ){
80058:       sqlite3VdbeError(p, "no such savepoint: %s", zName);
80059:       rc = SQLITE_ERROR;
80060:     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
80061:       /* It is not possible to release (commit) a savepoint if there are 
80062:       ** active write statements.
80063:       */
80064:       sqlite3VdbeError(p, "cannot release savepoint - "
80065:                           "SQL statements in progress");
80066:       rc = SQLITE_BUSY;
80067:     }else{
80068: 
80069:       /* Determine whether or not this is a transaction savepoint. If so,
80070:       ** and this is a RELEASE command, then the current transaction 
80071:       ** is committed. 
80072:       */
80073:       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
80074:       if( isTransaction && p1==SAVEPOINT_RELEASE ){
80075:         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80076:           goto vdbe_return;
80077:         }
80078:         db->autoCommit = 1;
80079:         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80080:           p->pc = (int)(pOp - aOp);
80081:           db->autoCommit = 0;
80082:           p->rc = rc = SQLITE_BUSY;
80083:           goto vdbe_return;
80084:         }
80085:         db->isTransactionSavepoint = 0;
80086:         rc = p->rc;
80087:       }else{
80088:         int isSchemaChange;
80089:         iSavepoint = db->nSavepoint - iSavepoint - 1;
80090:         if( p1==SAVEPOINT_ROLLBACK ){
80091:           isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
80092:           for(ii=0; ii<db->nDb; ii++){
80093:             rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
80094:                                        SQLITE_ABORT_ROLLBACK,
80095:                                        isSchemaChange==0);
80096:             if( rc!=SQLITE_OK ) goto abort_due_to_error;
80097:           }
80098:         }else{
80099:           isSchemaChange = 0;
80100:         }
80101:         for(ii=0; ii<db->nDb; ii++){
80102:           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
80103:           if( rc!=SQLITE_OK ){
80104:             goto abort_due_to_error;
80105:           }
80106:         }
80107:         if( isSchemaChange ){
80108:           sqlite3ExpirePreparedStatements(db);
80109:           sqlite3ResetAllSchemasOfConnection(db);
80110:           db->flags = (db->flags | SQLITE_InternChanges);
80111:         }
80112:       }
80113:   
80114:       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
80115:       ** savepoints nested inside of the savepoint being operated on. */
80116:       while( db->pSavepoint!=pSavepoint ){
80117:         pTmp = db->pSavepoint;
80118:         db->pSavepoint = pTmp->pNext;
80119:         sqlite3DbFree(db, pTmp);
80120:         db->nSavepoint--;
80121:       }
80122: 
80123:       /* If it is a RELEASE, then destroy the savepoint being operated on 
80124:       ** too. If it is a ROLLBACK TO, then set the number of deferred 
80125:       ** constraint violations present in the database to the value stored
80126:       ** when the savepoint was created.  */
80127:       if( p1==SAVEPOINT_RELEASE ){
80128:         assert( pSavepoint==db->pSavepoint );
80129:         db->pSavepoint = pSavepoint->pNext;
80130:         sqlite3DbFree(db, pSavepoint);
80131:         if( !isTransaction ){
80132:           db->nSavepoint--;
80133:         }
80134:       }else{
80135:         db->nDeferredCons = pSavepoint->nDeferredCons;
80136:         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
80137:       }
80138: 
80139:       if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
80140:         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
80141:         if( rc!=SQLITE_OK ) goto abort_due_to_error;
80142:       }
80143:     }
80144:   }
80145:   if( rc ) goto abort_due_to_error;
80146: 
80147:   break;
80148: }
80149: 
80150: /* Opcode: AutoCommit P1 P2 * * *
80151: **
80152: ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
80153: ** back any currently active btree transactions. If there are any active
80154: ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
80155: ** there are active writing VMs or active VMs that use shared cache.
80156: **
80157: ** This instruction causes the VM to halt.
80158: */
80159: case OP_AutoCommit: {
80160:   int desiredAutoCommit;
80161:   int iRollback;
80162: 
80163:   desiredAutoCommit = pOp->p1;
80164:   iRollback = pOp->p2;
80165:   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
80166:   assert( desiredAutoCommit==1 || iRollback==0 );
80167:   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
80168:   assert( p->bIsReader );
80169: 
80170:   if( desiredAutoCommit!=db->autoCommit ){
80171:     if( iRollback ){
80172:       assert( desiredAutoCommit==1 );
80173:       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
80174:       db->autoCommit = 1;
80175:     }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
80176:       /* If this instruction implements a COMMIT and other VMs are writing
80177:       ** return an error indicating that the other VMs must complete first. 
80178:       */
80179:       sqlite3VdbeError(p, "cannot commit transaction - "
80180:                           "SQL statements in progress");
80181:       rc = SQLITE_BUSY;
80182:       goto abort_due_to_error;
80183:     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
80184:       goto vdbe_return;
80185:     }else{
80186:       db->autoCommit = (u8)desiredAutoCommit;
80187:     }
80188:     if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
80189:       p->pc = (int)(pOp - aOp);
80190:       db->autoCommit = (u8)(1-desiredAutoCommit);
80191:       p->rc = rc = SQLITE_BUSY;
80192:       goto vdbe_return;
80193:     }
80194:     assert( db->nStatement==0 );
80195:     sqlite3CloseSavepoints(db);
80196:     if( p->rc==SQLITE_OK ){
80197:       rc = SQLITE_DONE;
80198:     }else{
80199:       rc = SQLITE_ERROR;
80200:     }
80201:     goto vdbe_return;
80202:   }else{
80203:     sqlite3VdbeError(p,
80204:         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
80205:         (iRollback)?"cannot rollback - no transaction is active":
80206:                    "cannot commit - no transaction is active"));
80207:          
80208:     rc = SQLITE_ERROR;
80209:     goto abort_due_to_error;
80210:   }
80211:   break;
80212: }
80213: 
80214: /* Opcode: Transaction P1 P2 P3 P4 P5
80215: **
80216: ** Begin a transaction on database P1 if a transaction is not already
80217: ** active.
80218: ** If P2 is non-zero, then a write-transaction is started, or if a 
80219: ** read-transaction is already active, it is upgraded to a write-transaction.
80220: ** If P2 is zero, then a read-transaction is started.
80221: **
80222: ** P1 is the index of the database file on which the transaction is
80223: ** started.  Index 0 is the main database file and index 1 is the
80224: ** file used for temporary tables.  Indices of 2 or more are used for
80225: ** attached databases.
80226: **
80227: ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
80228: ** true (this flag is set if the Vdbe may modify more than one row and may
80229: ** throw an ABORT exception), a statement transaction may also be opened.
80230: ** More specifically, a statement transaction is opened iff the database
80231: ** connection is currently not in autocommit mode, or if there are other
80232: ** active statements. A statement transaction allows the changes made by this
80233: ** VDBE to be rolled back after an error without having to roll back the
80234: ** entire transaction. If no error is encountered, the statement transaction
80235: ** will automatically commit when the VDBE halts.
80236: **
80237: ** If P5!=0 then this opcode also checks the schema cookie against P3
80238: ** and the schema generation counter against P4.
80239: ** The cookie changes its value whenever the database schema changes.
80240: ** This operation is used to detect when that the cookie has changed
80241: ** and that the current process needs to reread the schema.  If the schema
80242: ** cookie in P3 differs from the schema cookie in the database header or
80243: ** if the schema generation counter in P4 differs from the current
80244: ** generation counter, then an SQLITE_SCHEMA error is raised and execution
80245: ** halts.  The sqlite3_step() wrapper function might then reprepare the
80246: ** statement and rerun it from the beginning.
80247: */
80248: case OP_Transaction: {
80249:   Btree *pBt;
80250:   int iMeta;
80251:   int iGen;
80252: 
80253:   assert( p->bIsReader );
80254:   assert( p->readOnly==0 || pOp->p2==0 );
80255:   assert( pOp->p1>=0 && pOp->p1<db->nDb );
80256:   assert( DbMaskTest(p->btreeMask, pOp->p1) );
80257:   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
80258:     rc = SQLITE_READONLY;
80259:     goto abort_due_to_error;
80260:   }
80261:   pBt = db->aDb[pOp->p1].pBt;
80262: 
80263:   if( pBt ){
80264:     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
80265:     testcase( rc==SQLITE_BUSY_SNAPSHOT );
80266:     testcase( rc==SQLITE_BUSY_RECOVERY );
80267:     if( (rc&0xff)==SQLITE_BUSY ){
80268:       p->pc = (int)(pOp - aOp);
80269:       p->rc = rc;
80270:       goto vdbe_return;
80271:     }
80272:     if( rc!=SQLITE_OK ){
80273:       goto abort_due_to_error;
80274:     }
80275: 
80276:     if( pOp->p2 && p->usesStmtJournal 
80277:      && (db->autoCommit==0 || db->nVdbeRead>1) 
80278:     ){
80279:       assert( sqlite3BtreeIsInTrans(pBt) );
80280:       if( p->iStatement==0 ){
80281:         assert( db->nStatement>=0 && db->nSavepoint>=0 );
80282:         db->nStatement++; 
80283:         p->iStatement = db->nSavepoint + db->nStatement;
80284:       }
80285: 
80286:       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
80287:       if( rc==SQLITE_OK ){
80288:         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
80289:       }
80290: 
80291:       /* Store the current value of the database handles deferred constraint
80292:       ** counter. If the statement transaction needs to be rolled back,
80293:       ** the value of this counter needs to be restored too.  */
80294:       p->nStmtDefCons = db->nDeferredCons;
80295:       p->nStmtDefImmCons = db->nDeferredImmCons;
80296:     }
80297: 
80298:     /* Gather the schema version number for checking:
80299:     ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
80300:     ** each time a query is executed to ensure that the internal cache of the
80301:     ** schema used when compiling the SQL query matches the schema of the
80302:     ** database against which the compiled query is actually executed.
80303:     */
80304:     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
80305:     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
80306:   }else{
80307:     iGen = iMeta = 0;
80308:   }
80309:   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
80310:   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
80311:     sqlite3DbFree(db, p->zErrMsg);
80312:     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
80313:     /* If the schema-cookie from the database file matches the cookie 
80314:     ** stored with the in-memory representation of the schema, do
80315:     ** not reload the schema from the database file.
80316:     **
80317:     ** If virtual-tables are in use, this is not just an optimization.
80318:     ** Often, v-tables store their data in other SQLite tables, which
80319:     ** are queried from within xNext() and other v-table methods using
80320:     ** prepared queries. If such a query is out-of-date, we do not want to
80321:     ** discard the database schema, as the user code implementing the
80322:     ** v-table would have to be ready for the sqlite3_vtab structure itself
80323:     ** to be invalidated whenever sqlite3_step() is called from within 
80324:     ** a v-table method.
80325:     */
80326:     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
80327:       sqlite3ResetOneSchema(db, pOp->p1);
80328:     }
80329:     p->expired = 1;
80330:     rc = SQLITE_SCHEMA;
80331:   }
80332:   if( rc ) goto abort_due_to_error;
80333:   break;
80334: }
80335: 
80336: /* Opcode: ReadCookie P1 P2 P3 * *
80337: **
80338: ** Read cookie number P3 from database P1 and write it into register P2.
80339: ** P3==1 is the schema version.  P3==2 is the database format.
80340: ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
80341: ** the main database file and P1==1 is the database file used to store
80342: ** temporary tables.
80343: **
80344: ** There must be a read-lock on the database (either a transaction
80345: ** must be started or there must be an open cursor) before
80346: ** executing this instruction.
80347: */
80348: case OP_ReadCookie: {               /* out2 */
80349:   int iMeta;
80350:   int iDb;
80351:   int iCookie;
80352: 
80353:   assert( p->bIsReader );
80354:   iDb = pOp->p1;
80355:   iCookie = pOp->p3;
80356:   assert( pOp->p3<SQLITE_N_BTREE_META );
80357:   assert( iDb>=0 && iDb<db->nDb );
80358:   assert( db->aDb[iDb].pBt!=0 );
80359:   assert( DbMaskTest(p->btreeMask, iDb) );
80360: 
80361:   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
80362:   pOut = out2Prerelease(p, pOp);
80363:   pOut->u.i = iMeta;
80364:   break;
80365: }
80366: 
80367: /* Opcode: SetCookie P1 P2 P3 * *
80368: **
80369: ** Write the integer value P3 into cookie number P2 of database P1.
80370: ** P2==1 is the schema version.  P2==2 is the database format.
80371: ** P2==3 is the recommended pager cache 
80372: ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
80373: ** database file used to store temporary tables.
80374: **
80375: ** A transaction must be started before executing this opcode.
80376: */
80377: case OP_SetCookie: {
80378:   Db *pDb;
80379:   assert( pOp->p2<SQLITE_N_BTREE_META );
80380:   assert( pOp->p1>=0 && pOp->p1<db->nDb );
80381:   assert( DbMaskTest(p->btreeMask, pOp->p1) );
80382:   assert( p->readOnly==0 );
80383:   pDb = &db->aDb[pOp->p1];
80384:   assert( pDb->pBt!=0 );
80385:   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
80386:   /* See note about index shifting on OP_ReadCookie */
80387:   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
80388:   if( pOp->p2==BTREE_SCHEMA_VERSION ){
80389:     /* When the schema cookie changes, record the new cookie internally */
80390:     pDb->pSchema->schema_cookie = pOp->p3;
80391:     db->flags |= SQLITE_InternChanges;
80392:   }else if( pOp->p2==BTREE_FILE_FORMAT ){
80393:     /* Record changes in the file format */
80394:     pDb->pSchema->file_format = pOp->p3;
80395:   }
80396:   if( pOp->p1==1 ){
80397:     /* Invalidate all prepared statements whenever the TEMP database
80398:     ** schema is changed.  Ticket #1644 */
80399:     sqlite3ExpirePreparedStatements(db);
80400:     p->expired = 0;
80401:   }
80402:   if( rc ) goto abort_due_to_error;
80403:   break;
80404: }
80405: 
80406: /* Opcode: OpenRead P1 P2 P3 P4 P5
80407: ** Synopsis: root=P2 iDb=P3
80408: **
80409: ** Open a read-only cursor for the database table whose root page is
80410: ** P2 in a database file.  The database file is determined by P3. 
80411: ** P3==0 means the main database, P3==1 means the database used for 
80412: ** temporary tables, and P3>1 means used the corresponding attached
80413: ** database.  Give the new cursor an identifier of P1.  The P1
80414: ** values need not be contiguous but all P1 values should be small integers.
80415: ** It is an error for P1 to be negative.
80416: **
80417: ** If P5!=0 then use the content of register P2 as the root page, not
80418: ** the value of P2 itself.
80419: **
80420: ** There will be a read lock on the database whenever there is an
80421: ** open cursor.  If the database was unlocked prior to this instruction
80422: ** then a read lock is acquired as part of this instruction.  A read
80423: ** lock allows other processes to read the database but prohibits
80424: ** any other process from modifying the database.  The read lock is
80425: ** released when all cursors are closed.  If this instruction attempts
80426: ** to get a read lock but fails, the script terminates with an
80427: ** SQLITE_BUSY error code.
80428: **
80429: ** The P4 value may be either an integer (P4_INT32) or a pointer to
80430: ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
80431: ** structure, then said structure defines the content and collating 
80432: ** sequence of the index being opened. Otherwise, if P4 is an integer 
80433: ** value, it is set to the number of columns in the table.
80434: **
80435: ** See also: OpenWrite, ReopenIdx
80436: */
80437: /* Opcode: ReopenIdx P1 P2 P3 P4 P5
80438: ** Synopsis: root=P2 iDb=P3
80439: **
80440: ** The ReopenIdx opcode works exactly like ReadOpen except that it first
80441: ** checks to see if the cursor on P1 is already open with a root page
80442: ** number of P2 and if it is this opcode becomes a no-op.  In other words,
80443: ** if the cursor is already open, do not reopen it.
80444: **
80445: ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
80446: ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
80447: ** every other ReopenIdx or OpenRead for the same cursor number.
80448: **
80449: ** See the OpenRead opcode documentation for additional information.
80450: */
80451: /* Opcode: OpenWrite P1 P2 P3 P4 P5
80452: ** Synopsis: root=P2 iDb=P3
80453: **
80454: ** Open a read/write cursor named P1 on the table or index whose root
80455: ** page is P2.  Or if P5!=0 use the content of register P2 to find the
80456: ** root page.
80457: **
80458: ** The P4 value may be either an integer (P4_INT32) or a pointer to
80459: ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
80460: ** structure, then said structure defines the content and collating 
80461: ** sequence of the index being opened. Otherwise, if P4 is an integer 
80462: ** value, it is set to the number of columns in the table, or to the
80463: ** largest index of any column of the table that is actually used.
80464: **
80465: ** This instruction works just like OpenRead except that it opens the cursor
80466: ** in read/write mode.  For a given table, there can be one or more read-only
80467: ** cursors or a single read/write cursor but not both.
80468: **
80469: ** See also OpenRead.
80470: */
80471: case OP_ReopenIdx: {
80472:   int nField;
80473:   KeyInfo *pKeyInfo;
80474:   int p2;
80475:   int iDb;
80476:   int wrFlag;
80477:   Btree *pX;
80478:   VdbeCursor *pCur;
80479:   Db *pDb;
80480: 
80481:   assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80482:   assert( pOp->p4type==P4_KEYINFO );
80483:   pCur = p->apCsr[pOp->p1];
80484:   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
80485:     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
80486:     goto open_cursor_set_hints;
80487:   }
80488:   /* If the cursor is not currently open or is open on a different
80489:   ** index, then fall through into OP_OpenRead to force a reopen */
80490: case OP_OpenRead:
80491: case OP_OpenWrite:
80492: 
80493:   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
80494:   assert( p->bIsReader );
80495:   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
80496:           || p->readOnly==0 );
80497: 
80498:   if( p->expired ){
80499:     rc = SQLITE_ABORT_ROLLBACK;
80500:     goto abort_due_to_error;
80501:   }
80502: 
80503:   nField = 0;
80504:   pKeyInfo = 0;
80505:   p2 = pOp->p2;
80506:   iDb = pOp->p3;
80507:   assert( iDb>=0 && iDb<db->nDb );
80508:   assert( DbMaskTest(p->btreeMask, iDb) );
80509:   pDb = &db->aDb[iDb];
80510:   pX = pDb->pBt;
80511:   assert( pX!=0 );
80512:   if( pOp->opcode==OP_OpenWrite ){
80513:     assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
80514:     wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
80515:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80516:     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
80517:       p->minWriteFileFormat = pDb->pSchema->file_format;
80518:     }
80519:   }else{
80520:     wrFlag = 0;
80521:   }
80522:   if( pOp->p5 & OPFLAG_P2ISREG ){
80523:     assert( p2>0 );
80524:     assert( p2<=(p->nMem+1 - p->nCursor) );
80525:     pIn2 = &aMem[p2];
80526:     assert( memIsValid(pIn2) );
80527:     assert( (pIn2->flags & MEM_Int)!=0 );
80528:     sqlite3VdbeMemIntegerify(pIn2);
80529:     p2 = (int)pIn2->u.i;
80530:     /* The p2 value always comes from a prior OP_CreateTable opcode and
80531:     ** that opcode will always set the p2 value to 2 or more or else fail.
80532:     ** If there were a failure, the prepared statement would have halted
80533:     ** before reaching this instruction. */
80534:     assert( p2>=2 );
80535:   }
80536:   if( pOp->p4type==P4_KEYINFO ){
80537:     pKeyInfo = pOp->p4.pKeyInfo;
80538:     assert( pKeyInfo->enc==ENC(db) );
80539:     assert( pKeyInfo->db==db );
80540:     nField = pKeyInfo->nField+pKeyInfo->nXField;
80541:   }else if( pOp->p4type==P4_INT32 ){
80542:     nField = pOp->p4.i;
80543:   }
80544:   assert( pOp->p1>=0 );
80545:   assert( nField>=0 );
80546:   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
80547:   pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
80548:   if( pCur==0 ) goto no_mem;
80549:   pCur->nullRow = 1;
80550:   pCur->isOrdered = 1;
80551:   pCur->pgnoRoot = p2;
80552: #ifdef SQLITE_DEBUG
80553:   pCur->wrFlag = wrFlag;
80554: #endif
80555:   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
80556:   pCur->pKeyInfo = pKeyInfo;
80557:   /* Set the VdbeCursor.isTable variable. Previous versions of
80558:   ** SQLite used to check if the root-page flags were sane at this point
80559:   ** and report database corruption if they were not, but this check has
80560:   ** since moved into the btree layer.  */  
80561:   pCur->isTable = pOp->p4type!=P4_KEYINFO;
80562: 
80563: open_cursor_set_hints:
80564:   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
80565:   assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
80566:   testcase( pOp->p5 & OPFLAG_BULKCSR );
80567: #ifdef SQLITE_ENABLE_CURSOR_HINTS
80568:   testcase( pOp->p2 & OPFLAG_SEEKEQ );
80569: #endif
80570:   sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
80571:                                (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
80572:   if( rc ) goto abort_due_to_error;
80573:   break;
80574: }
80575: 
80576: /* Opcode: OpenEphemeral P1 P2 * P4 P5
80577: ** Synopsis: nColumn=P2
80578: **
80579: ** Open a new cursor P1 to a transient table.
80580: ** The cursor is always opened read/write even if 
80581: ** the main database is read-only.  The ephemeral
80582: ** table is deleted automatically when the cursor is closed.
80583: **
80584: ** P2 is the number of columns in the ephemeral table.
80585: ** The cursor points to a BTree table if P4==0 and to a BTree index
80586: ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
80587: ** that defines the format of keys in the index.
80588: **
80589: ** The P5 parameter can be a mask of the BTREE_* flags defined
80590: ** in btree.h.  These flags control aspects of the operation of
80591: ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
80592: ** added automatically.
80593: */
80594: /* Opcode: OpenAutoindex P1 P2 * P4 *
80595: ** Synopsis: nColumn=P2
80596: **
80597: ** This opcode works the same as OP_OpenEphemeral.  It has a
80598: ** different name to distinguish its use.  Tables created using
80599: ** by this opcode will be used for automatically created transient
80600: ** indices in joins.
80601: */
80602: case OP_OpenAutoindex: 
80603: case OP_OpenEphemeral: {
80604:   VdbeCursor *pCx;
80605:   KeyInfo *pKeyInfo;
80606: 
80607:   static const int vfsFlags = 
80608:       SQLITE_OPEN_READWRITE |
80609:       SQLITE_OPEN_CREATE |
80610:       SQLITE_OPEN_EXCLUSIVE |
80611:       SQLITE_OPEN_DELETEONCLOSE |
80612:       SQLITE_OPEN_TRANSIENT_DB;
80613:   assert( pOp->p1>=0 );
80614:   assert( pOp->p2>=0 );
80615:   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
80616:   if( pCx==0 ) goto no_mem;
80617:   pCx->nullRow = 1;
80618:   pCx->isEphemeral = 1;
80619:   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt, 
80620:                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
80621:   if( rc==SQLITE_OK ){
80622:     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
80623:   }
80624:   if( rc==SQLITE_OK ){
80625:     /* If a transient index is required, create it by calling
80626:     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
80627:     ** opening it. If a transient table is required, just use the
80628:     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
80629:     */
80630:     if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
80631:       int pgno;
80632:       assert( pOp->p4type==P4_KEYINFO );
80633:       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); 
80634:       if( rc==SQLITE_OK ){
80635:         assert( pgno==MASTER_ROOT+1 );
80636:         assert( pKeyInfo->db==db );
80637:         assert( pKeyInfo->enc==ENC(db) );
80638:         pCx->pKeyInfo = pKeyInfo;
80639:         rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
80640:                                 pKeyInfo, pCx->uc.pCursor);
80641:       }
80642:       pCx->isTable = 0;
80643:     }else{
80644:       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, BTREE_WRCSR,
80645:                               0, pCx->uc.pCursor);
80646:       pCx->isTable = 1;
80647:     }
80648:   }
80649:   if( rc ) goto abort_due_to_error;
80650:   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
80651:   break;
80652: }
80653: 
80654: /* Opcode: SorterOpen P1 P2 P3 P4 *
80655: **
80656: ** This opcode works like OP_OpenEphemeral except that it opens
80657: ** a transient index that is specifically designed to sort large
80658: ** tables using an external merge-sort algorithm.
80659: **
80660: ** If argument P3 is non-zero, then it indicates that the sorter may
80661: ** assume that a stable sort considering the first P3 fields of each
80662: ** key is sufficient to produce the required results.
80663: */
80664: case OP_SorterOpen: {
80665:   VdbeCursor *pCx;
80666: 
80667:   assert( pOp->p1>=0 );
80668:   assert( pOp->p2>=0 );
80669:   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
80670:   if( pCx==0 ) goto no_mem;
80671:   pCx->pKeyInfo = pOp->p4.pKeyInfo;
80672:   assert( pCx->pKeyInfo->db==db );
80673:   assert( pCx->pKeyInfo->enc==ENC(db) );
80674:   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
80675:   if( rc ) goto abort_due_to_error;
80676:   break;
80677: }
80678: 
80679: /* Opcode: SequenceTest P1 P2 * * *
80680: ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
80681: **
80682: ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
80683: ** to P2. Regardless of whether or not the jump is taken, increment the
80684: ** the sequence value.
80685: */
80686: case OP_SequenceTest: {
80687:   VdbeCursor *pC;
80688:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80689:   pC = p->apCsr[pOp->p1];
80690:   assert( isSorter(pC) );
80691:   if( (pC->seqCount++)==0 ){
80692:     goto jump_to_p2;
80693:   }
80694:   break;
80695: }
80696: 
80697: /* Opcode: OpenPseudo P1 P2 P3 * *
80698: ** Synopsis: P3 columns in r[P2]
80699: **
80700: ** Open a new cursor that points to a fake table that contains a single
80701: ** row of data.  The content of that one row is the content of memory
80702: ** register P2.  In other words, cursor P1 becomes an alias for the 
80703: ** MEM_Blob content contained in register P2.
80704: **
80705: ** A pseudo-table created by this opcode is used to hold a single
80706: ** row output from the sorter so that the row can be decomposed into
80707: ** individual columns using the OP_Column opcode.  The OP_Column opcode
80708: ** is the only cursor opcode that works with a pseudo-table.
80709: **
80710: ** P3 is the number of fields in the records that will be stored by
80711: ** the pseudo-table.
80712: */
80713: case OP_OpenPseudo: {
80714:   VdbeCursor *pCx;
80715: 
80716:   assert( pOp->p1>=0 );
80717:   assert( pOp->p3>=0 );
80718:   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
80719:   if( pCx==0 ) goto no_mem;
80720:   pCx->nullRow = 1;
80721:   pCx->uc.pseudoTableReg = pOp->p2;
80722:   pCx->isTable = 1;
80723:   assert( pOp->p5==0 );
80724:   break;
80725: }
80726: 
80727: /* Opcode: Close P1 * * * *
80728: **
80729: ** Close a cursor previously opened as P1.  If P1 is not
80730: ** currently open, this instruction is a no-op.
80731: */
80732: case OP_Close: {
80733:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80734:   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
80735:   p->apCsr[pOp->p1] = 0;
80736:   break;
80737: }
80738: 
80739: #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
80740: /* Opcode: ColumnsUsed P1 * * P4 *
80741: **
80742: ** This opcode (which only exists if SQLite was compiled with
80743: ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
80744: ** table or index for cursor P1 are used.  P4 is a 64-bit integer
80745: ** (P4_INT64) in which the first 63 bits are one for each of the
80746: ** first 63 columns of the table or index that are actually used
80747: ** by the cursor.  The high-order bit is set if any column after
80748: ** the 64th is used.
80749: */
80750: case OP_ColumnsUsed: {
80751:   VdbeCursor *pC;
80752:   pC = p->apCsr[pOp->p1];
80753:   assert( pC->eCurType==CURTYPE_BTREE );
80754:   pC->maskUsed = *(u64*)pOp->p4.pI64;
80755:   break;
80756: }
80757: #endif
80758: 
80759: /* Opcode: SeekGE P1 P2 P3 P4 *
80760: ** Synopsis: key=r[P3@P4]
80761: **
80762: ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
80763: ** use the value in register P3 as the key.  If cursor P1 refers 
80764: ** to an SQL index, then P3 is the first in an array of P4 registers 
80765: ** that are used as an unpacked index key. 
80766: **
80767: ** Reposition cursor P1 so that  it points to the smallest entry that 
80768: ** is greater than or equal to the key value. If there are no records 
80769: ** greater than or equal to the key and P2 is not zero, then jump to P2.
80770: **
80771: ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80772: ** opcode will always land on a record that equally equals the key, or
80773: ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
80774: ** opcode must be followed by an IdxLE opcode with the same arguments.
80775: ** The IdxLE opcode will be skipped if this opcode succeeds, but the
80776: ** IdxLE opcode will be used on subsequent loop iterations.
80777: **
80778: ** This opcode leaves the cursor configured to move in forward order,
80779: ** from the beginning toward the end.  In other words, the cursor is
80780: ** configured to use Next, not Prev.
80781: **
80782: ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
80783: */
80784: /* Opcode: SeekGT P1 P2 P3 P4 *
80785: ** Synopsis: key=r[P3@P4]
80786: **
80787: ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
80788: ** use the value in register P3 as a key. If cursor P1 refers 
80789: ** to an SQL index, then P3 is the first in an array of P4 registers 
80790: ** that are used as an unpacked index key. 
80791: **
80792: ** Reposition cursor P1 so that  it points to the smallest entry that 
80793: ** is greater than the key value. If there are no records greater than 
80794: ** the key and P2 is not zero, then jump to P2.
80795: **
80796: ** This opcode leaves the cursor configured to move in forward order,
80797: ** from the beginning toward the end.  In other words, the cursor is
80798: ** configured to use Next, not Prev.
80799: **
80800: ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
80801: */
80802: /* Opcode: SeekLT P1 P2 P3 P4 * 
80803: ** Synopsis: key=r[P3@P4]
80804: **
80805: ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
80806: ** use the value in register P3 as a key. If cursor P1 refers 
80807: ** to an SQL index, then P3 is the first in an array of P4 registers 
80808: ** that are used as an unpacked index key. 
80809: **
80810: ** Reposition cursor P1 so that  it points to the largest entry that 
80811: ** is less than the key value. If there are no records less than 
80812: ** the key and P2 is not zero, then jump to P2.
80813: **
80814: ** This opcode leaves the cursor configured to move in reverse order,
80815: ** from the end toward the beginning.  In other words, the cursor is
80816: ** configured to use Prev, not Next.
80817: **
80818: ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
80819: */
80820: /* Opcode: SeekLE P1 P2 P3 P4 *
80821: ** Synopsis: key=r[P3@P4]
80822: **
80823: ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
80824: ** use the value in register P3 as a key. If cursor P1 refers 
80825: ** to an SQL index, then P3 is the first in an array of P4 registers 
80826: ** that are used as an unpacked index key. 
80827: **
80828: ** Reposition cursor P1 so that it points to the largest entry that 
80829: ** is less than or equal to the key value. If there are no records 
80830: ** less than or equal to the key and P2 is not zero, then jump to P2.
80831: **
80832: ** This opcode leaves the cursor configured to move in reverse order,
80833: ** from the end toward the beginning.  In other words, the cursor is
80834: ** configured to use Prev, not Next.
80835: **
80836: ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80837: ** opcode will always land on a record that equally equals the key, or
80838: ** else jump immediately to P2.  When the cursor is OPFLAG_SEEKEQ, this
80839: ** opcode must be followed by an IdxGE opcode with the same arguments.
80840: ** The IdxGE opcode will be skipped if this opcode succeeds, but the
80841: ** IdxGE opcode will be used on subsequent loop iterations.
80842: **
80843: ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
80844: */
80845: case OP_SeekLT:         /* jump, in3 */
80846: case OP_SeekLE:         /* jump, in3 */
80847: case OP_SeekGE:         /* jump, in3 */
80848: case OP_SeekGT: {       /* jump, in3 */
80849:   int res;           /* Comparison result */
80850:   int oc;            /* Opcode */
80851:   VdbeCursor *pC;    /* The cursor to seek */
80852:   UnpackedRecord r;  /* The key to seek for */
80853:   int nField;        /* Number of columns or fields in the key */
80854:   i64 iKey;          /* The rowid we are to seek to */
80855:   int eqOnly;        /* Only interested in == results */
80856: 
80857:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80858:   assert( pOp->p2!=0 );
80859:   pC = p->apCsr[pOp->p1];
80860:   assert( pC!=0 );
80861:   assert( pC->eCurType==CURTYPE_BTREE );
80862:   assert( OP_SeekLE == OP_SeekLT+1 );
80863:   assert( OP_SeekGE == OP_SeekLT+2 );
80864:   assert( OP_SeekGT == OP_SeekLT+3 );
80865:   assert( pC->isOrdered );
80866:   assert( pC->uc.pCursor!=0 );
80867:   oc = pOp->opcode;
80868:   eqOnly = 0;
80869:   pC->nullRow = 0;
80870: #ifdef SQLITE_DEBUG
80871:   pC->seekOp = pOp->opcode;
80872: #endif
80873: 
80874:   if( pC->isTable ){
80875:     /* The BTREE_SEEK_EQ flag is only set on index cursors */
80876:     assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0 );
80877: 
80878:     /* The input value in P3 might be of any type: integer, real, string,
80879:     ** blob, or NULL.  But it needs to be an integer before we can do
80880:     ** the seek, so convert it. */
80881:     pIn3 = &aMem[pOp->p3];
80882:     if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80883:       applyNumericAffinity(pIn3, 0);
80884:     }
80885:     iKey = sqlite3VdbeIntValue(pIn3);
80886: 
80887:     /* If the P3 value could not be converted into an integer without
80888:     ** loss of information, then special processing is required... */
80889:     if( (pIn3->flags & MEM_Int)==0 ){
80890:       if( (pIn3->flags & MEM_Real)==0 ){
80891:         /* If the P3 value cannot be converted into any kind of a number,
80892:         ** then the seek is not possible, so jump to P2 */
80893:         VdbeBranchTaken(1,2); goto jump_to_p2;
80894:         break;
80895:       }
80896: 
80897:       /* If the approximation iKey is larger than the actual real search
80898:       ** term, substitute >= for > and < for <=. e.g. if the search term
80899:       ** is 4.9 and the integer approximation 5:
80900:       **
80901:       **        (x >  4.9)    ->     (x >= 5)
80902:       **        (x <= 4.9)    ->     (x <  5)
80903:       */
80904:       if( pIn3->u.r<(double)iKey ){
80905:         assert( OP_SeekGE==(OP_SeekGT-1) );
80906:         assert( OP_SeekLT==(OP_SeekLE-1) );
80907:         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
80908:         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
80909:       }
80910: 
80911:       /* If the approximation iKey is smaller than the actual real search
80912:       ** term, substitute <= for < and > for >=.  */
80913:       else if( pIn3->u.r>(double)iKey ){
80914:         assert( OP_SeekLE==(OP_SeekLT+1) );
80915:         assert( OP_SeekGT==(OP_SeekGE+1) );
80916:         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
80917:         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
80918:       }
80919:     } 
80920:     rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
80921:     pC->movetoTarget = iKey;  /* Used by OP_Delete */
80922:     if( rc!=SQLITE_OK ){
80923:       goto abort_due_to_error;
80924:     }
80925:   }else{
80926:     /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
80927:     ** OP_SeekLE opcodes are allowed, and these must be immediately followed
80928:     ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
80929:     */
80930:     if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
80931:       eqOnly = 1;
80932:       assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
80933:       assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
80934:       assert( pOp[1].p1==pOp[0].p1 );
80935:       assert( pOp[1].p2==pOp[0].p2 );
80936:       assert( pOp[1].p3==pOp[0].p3 );
80937:       assert( pOp[1].p4.i==pOp[0].p4.i );
80938:     }
80939: 
80940:     nField = pOp->p4.i;
80941:     assert( pOp->p4type==P4_INT32 );
80942:     assert( nField>0 );
80943:     r.pKeyInfo = pC->pKeyInfo;
80944:     r.nField = (u16)nField;
80945: 
80946:     /* The next line of code computes as follows, only faster:
80947:     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
80948:     **     r.default_rc = -1;
80949:     **   }else{
80950:     **     r.default_rc = +1;
80951:     **   }
80952:     */
80953:     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
80954:     assert( oc!=OP_SeekGT || r.default_rc==-1 );
80955:     assert( oc!=OP_SeekLE || r.default_rc==-1 );
80956:     assert( oc!=OP_SeekGE || r.default_rc==+1 );
80957:     assert( oc!=OP_SeekLT || r.default_rc==+1 );
80958: 
80959:     r.aMem = &aMem[pOp->p3];
80960: #ifdef SQLITE_DEBUG
80961:     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
80962: #endif
80963:     ExpandBlob(r.aMem);
80964:     r.eqSeen = 0;
80965:     rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
80966:     if( rc!=SQLITE_OK ){
80967:       goto abort_due_to_error;
80968:     }
80969:     if( eqOnly && r.eqSeen==0 ){
80970:       assert( res!=0 );
80971:       goto seek_not_found;
80972:     }
80973:   }
80974:   pC->deferredMoveto = 0;
80975:   pC->cacheStatus = CACHE_STALE;
80976: #ifdef SQLITE_TEST
80977:   sqlite3_search_count++;
80978: #endif
80979:   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
80980:     if( res<0 || (res==0 && oc==OP_SeekGT) ){
80981:       res = 0;
80982:       rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
80983:       if( rc!=SQLITE_OK ) goto abort_due_to_error;
80984:     }else{
80985:       res = 0;
80986:     }
80987:   }else{
80988:     assert( oc==OP_SeekLT || oc==OP_SeekLE );
80989:     if( res>0 || (res==0 && oc==OP_SeekLT) ){
80990:       res = 0;
80991:       rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
80992:       if( rc!=SQLITE_OK ) goto abort_due_to_error;
80993:     }else{
80994:       /* res might be negative because the table is empty.  Check to
80995:       ** see if this is the case.
80996:       */
80997:       res = sqlite3BtreeEof(pC->uc.pCursor);
80998:     }
80999:   }
81000: seek_not_found:
81001:   assert( pOp->p2>0 );
81002:   VdbeBranchTaken(res!=0,2);
81003:   if( res ){
81004:     goto jump_to_p2;
81005:   }else if( eqOnly ){
81006:     assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
81007:     pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
81008:   }
81009:   break;
81010: }
81011:   
81012: 
81013: /* Opcode: Found P1 P2 P3 P4 *
81014: ** Synopsis: key=r[P3@P4]
81015: **
81016: ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81017: ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81018: ** record.
81019: **
81020: ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81021: ** is a prefix of any entry in P1 then a jump is made to P2 and
81022: ** P1 is left pointing at the matching entry.
81023: **
81024: ** This operation leaves the cursor in a state where it can be
81025: ** advanced in the forward direction.  The Next instruction will work,
81026: ** but not the Prev instruction.
81027: **
81028: ** See also: NotFound, NoConflict, NotExists. SeekGe
81029: */
81030: /* Opcode: NotFound P1 P2 P3 P4 *
81031: ** Synopsis: key=r[P3@P4]
81032: **
81033: ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81034: ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81035: ** record.
81036: ** 
81037: ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81038: ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
81039: ** does contain an entry whose prefix matches the P3/P4 record then control
81040: ** falls through to the next instruction and P1 is left pointing at the
81041: ** matching entry.
81042: **
81043: ** This operation leaves the cursor in a state where it cannot be
81044: ** advanced in either direction.  In other words, the Next and Prev
81045: ** opcodes do not work after this operation.
81046: **
81047: ** See also: Found, NotExists, NoConflict
81048: */
81049: /* Opcode: NoConflict P1 P2 P3 P4 *
81050: ** Synopsis: key=r[P3@P4]
81051: **
81052: ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
81053: ** P4>0 then register P3 is the first of P4 registers that form an unpacked
81054: ** record.
81055: ** 
81056: ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
81057: ** contains any NULL value, jump immediately to P2.  If all terms of the
81058: ** record are not-NULL then a check is done to determine if any row in the
81059: ** P1 index btree has a matching key prefix.  If there are no matches, jump
81060: ** immediately to P2.  If there is a match, fall through and leave the P1
81061: ** cursor pointing to the matching row.
81062: **
81063: ** This opcode is similar to OP_NotFound with the exceptions that the
81064: ** branch is always taken if any part of the search key input is NULL.
81065: **
81066: ** This operation leaves the cursor in a state where it cannot be
81067: ** advanced in either direction.  In other words, the Next and Prev
81068: ** opcodes do not work after this operation.
81069: **
81070: ** See also: NotFound, Found, NotExists
81071: */
81072: case OP_NoConflict:     /* jump, in3 */
81073: case OP_NotFound:       /* jump, in3 */
81074: case OP_Found: {        /* jump, in3 */
81075:   int alreadyExists;
81076:   int takeJump;
81077:   int ii;
81078:   VdbeCursor *pC;
81079:   int res;
81080:   char *pFree;
81081:   UnpackedRecord *pIdxKey;
81082:   UnpackedRecord r;
81083:   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
81084: 
81085: #ifdef SQLITE_TEST
81086:   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
81087: #endif
81088: 
81089:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81090:   assert( pOp->p4type==P4_INT32 );
81091:   pC = p->apCsr[pOp->p1];
81092:   assert( pC!=0 );
81093: #ifdef SQLITE_DEBUG
81094:   pC->seekOp = pOp->opcode;
81095: #endif
81096:   pIn3 = &aMem[pOp->p3];
81097:   assert( pC->eCurType==CURTYPE_BTREE );
81098:   assert( pC->uc.pCursor!=0 );
81099:   assert( pC->isTable==0 );
81100:   pFree = 0;
81101:   if( pOp->p4.i>0 ){
81102:     r.pKeyInfo = pC->pKeyInfo;
81103:     r.nField = (u16)pOp->p4.i;
81104:     r.aMem = pIn3;
81105:     for(ii=0; ii<r.nField; ii++){
81106:       assert( memIsValid(&r.aMem[ii]) );
81107:       ExpandBlob(&r.aMem[ii]);
81108: #ifdef SQLITE_DEBUG
81109:       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
81110: #endif
81111:     }
81112:     pIdxKey = &r;
81113:   }else{
81114:     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
81115:         pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
81116:     );
81117:     if( pIdxKey==0 ) goto no_mem;
81118:     assert( pIn3->flags & MEM_Blob );
81119:     ExpandBlob(pIn3);
81120:     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
81121:   }
81122:   pIdxKey->default_rc = 0;
81123:   takeJump = 0;
81124:   if( pOp->opcode==OP_NoConflict ){
81125:     /* For the OP_NoConflict opcode, take the jump if any of the
81126:     ** input fields are NULL, since any key with a NULL will not
81127:     ** conflict */
81128:     for(ii=0; ii<pIdxKey->nField; ii++){
81129:       if( pIdxKey->aMem[ii].flags & MEM_Null ){
81130:         takeJump = 1;
81131:         break;
81132:       }
81133:     }
81134:   }
81135:   rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
81136:   sqlite3DbFree(db, pFree);
81137:   if( rc!=SQLITE_OK ){
81138:     goto abort_due_to_error;
81139:   }
81140:   pC->seekResult = res;
81141:   alreadyExists = (res==0);
81142:   pC->nullRow = 1-alreadyExists;
81143:   pC->deferredMoveto = 0;
81144:   pC->cacheStatus = CACHE_STALE;
81145:   if( pOp->opcode==OP_Found ){
81146:     VdbeBranchTaken(alreadyExists!=0,2);
81147:     if( alreadyExists ) goto jump_to_p2;
81148:   }else{
81149:     VdbeBranchTaken(takeJump||alreadyExists==0,2);
81150:     if( takeJump || !alreadyExists ) goto jump_to_p2;
81151:   }
81152:   break;
81153: }
81154: 
81155: /* Opcode: SeekRowid P1 P2 P3 * *
81156: ** Synopsis: intkey=r[P3]
81157: **
81158: ** P1 is the index of a cursor open on an SQL table btree (with integer
81159: ** keys).  If register P3 does not contain an integer or if P1 does not
81160: ** contain a record with rowid P3 then jump immediately to P2.  
81161: ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
81162: ** a record with rowid P3 then 
81163: ** leave the cursor pointing at that record and fall through to the next
81164: ** instruction.
81165: **
81166: ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
81167: ** the P3 register must be guaranteed to contain an integer value.  With this
81168: ** opcode, register P3 might not contain an integer.
81169: **
81170: ** The OP_NotFound opcode performs the same operation on index btrees
81171: ** (with arbitrary multi-value keys).
81172: **
81173: ** This opcode leaves the cursor in a state where it cannot be advanced
81174: ** in either direction.  In other words, the Next and Prev opcodes will
81175: ** not work following this opcode.
81176: **
81177: ** See also: Found, NotFound, NoConflict, SeekRowid
81178: */
81179: /* Opcode: NotExists P1 P2 P3 * *
81180: ** Synopsis: intkey=r[P3]
81181: **
81182: ** P1 is the index of a cursor open on an SQL table btree (with integer
81183: ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
81184: ** rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
81185: ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then 
81186: ** leave the cursor pointing at that record and fall through to the next
81187: ** instruction.
81188: **
81189: ** The OP_SeekRowid opcode performs the same operation but also allows the
81190: ** P3 register to contain a non-integer value, in which case the jump is
81191: ** always taken.  This opcode requires that P3 always contain an integer.
81192: **
81193: ** The OP_NotFound opcode performs the same operation on index btrees
81194: ** (with arbitrary multi-value keys).
81195: **
81196: ** This opcode leaves the cursor in a state where it cannot be advanced
81197: ** in either direction.  In other words, the Next and Prev opcodes will
81198: ** not work following this opcode.
81199: **
81200: ** See also: Found, NotFound, NoConflict, SeekRowid
81201: */
81202: case OP_SeekRowid: {        /* jump, in3 */
81203:   VdbeCursor *pC;
81204:   BtCursor *pCrsr;
81205:   int res;
81206:   u64 iKey;
81207: 
81208:   pIn3 = &aMem[pOp->p3];
81209:   if( (pIn3->flags & MEM_Int)==0 ){
81210:     applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
81211:     if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
81212:   }
81213:   /* Fall through into OP_NotExists */
81214: case OP_NotExists:          /* jump, in3 */
81215:   pIn3 = &aMem[pOp->p3];
81216:   assert( pIn3->flags & MEM_Int );
81217:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81218:   pC = p->apCsr[pOp->p1];
81219:   assert( pC!=0 );
81220: #ifdef SQLITE_DEBUG
81221:   pC->seekOp = 0;
81222: #endif
81223:   assert( pC->isTable );
81224:   assert( pC->eCurType==CURTYPE_BTREE );
81225:   pCrsr = pC->uc.pCursor;
81226:   assert( pCrsr!=0 );
81227:   res = 0;
81228:   iKey = pIn3->u.i;
81229:   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
81230:   assert( rc==SQLITE_OK || res==0 );
81231:   pC->movetoTarget = iKey;  /* Used by OP_Delete */
81232:   pC->nullRow = 0;
81233:   pC->cacheStatus = CACHE_STALE;
81234:   pC->deferredMoveto = 0;
81235:   VdbeBranchTaken(res!=0,2);
81236:   pC->seekResult = res;
81237:   if( res!=0 ){
81238:     assert( rc==SQLITE_OK );
81239:     if( pOp->p2==0 ){
81240:       rc = SQLITE_CORRUPT_BKPT;
81241:     }else{
81242:       goto jump_to_p2;
81243:     }
81244:   }
81245:   if( rc ) goto abort_due_to_error;
81246:   break;
81247: }
81248: 
81249: /* Opcode: Sequence P1 P2 * * *
81250: ** Synopsis: r[P2]=cursor[P1].ctr++
81251: **
81252: ** Find the next available sequence number for cursor P1.
81253: ** Write the sequence number into register P2.
81254: ** The sequence number on the cursor is incremented after this
81255: ** instruction.  
81256: */
81257: case OP_Sequence: {           /* out2 */
81258:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81259:   assert( p->apCsr[pOp->p1]!=0 );
81260:   assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
81261:   pOut = out2Prerelease(p, pOp);
81262:   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
81263:   break;
81264: }
81265: 
81266: 
81267: /* Opcode: NewRowid P1 P2 P3 * *
81268: ** Synopsis: r[P2]=rowid
81269: **
81270: ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
81271: ** The record number is not previously used as a key in the database
81272: ** table that cursor P1 points to.  The new record number is written
81273: ** written to register P2.
81274: **
81275: ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
81276: ** the largest previously generated record number. No new record numbers are
81277: ** allowed to be less than this value. When this value reaches its maximum, 
81278: ** an SQLITE_FULL error is generated. The P3 register is updated with the '
81279: ** generated record number. This P3 mechanism is used to help implement the
81280: ** AUTOINCREMENT feature.
81281: */
81282: case OP_NewRowid: {           /* out2 */
81283:   i64 v;                 /* The new rowid */
81284:   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
81285:   int res;               /* Result of an sqlite3BtreeLast() */
81286:   int cnt;               /* Counter to limit the number of searches */
81287:   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
81288:   VdbeFrame *pFrame;     /* Root frame of VDBE */
81289: 
81290:   v = 0;
81291:   res = 0;
81292:   pOut = out2Prerelease(p, pOp);
81293:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81294:   pC = p->apCsr[pOp->p1];
81295:   assert( pC!=0 );
81296:   assert( pC->eCurType==CURTYPE_BTREE );
81297:   assert( pC->uc.pCursor!=0 );
81298:   {
81299:     /* The next rowid or record number (different terms for the same
81300:     ** thing) is obtained in a two-step algorithm.
81301:     **
81302:     ** First we attempt to find the largest existing rowid and add one
81303:     ** to that.  But if the largest existing rowid is already the maximum
81304:     ** positive integer, we have to fall through to the second
81305:     ** probabilistic algorithm
81306:     **
81307:     ** The second algorithm is to select a rowid at random and see if
81308:     ** it already exists in the table.  If it does not exist, we have
81309:     ** succeeded.  If the random rowid does exist, we select a new one
81310:     ** and try again, up to 100 times.
81311:     */
81312:     assert( pC->isTable );
81313: 
81314: #ifdef SQLITE_32BIT_ROWID
81315: #   define MAX_ROWID 0x7fffffff
81316: #else
81317:     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
81318:     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
81319:     ** to provide the constant while making all compilers happy.
81320:     */
81321: #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
81322: #endif
81323: 
81324:     if( !pC->useRandomRowid ){
81325:       rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
81326:       if( rc!=SQLITE_OK ){
81327:         goto abort_due_to_error;
81328:       }
81329:       if( res ){
81330:         v = 1;   /* IMP: R-61914-48074 */
81331:       }else{
81332:         assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
81333:         v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81334:         if( v>=MAX_ROWID ){
81335:           pC->useRandomRowid = 1;
81336:         }else{
81337:           v++;   /* IMP: R-29538-34987 */
81338:         }
81339:       }
81340:     }
81341: 
81342: #ifndef SQLITE_OMIT_AUTOINCREMENT
81343:     if( pOp->p3 ){
81344:       /* Assert that P3 is a valid memory cell. */
81345:       assert( pOp->p3>0 );
81346:       if( p->pFrame ){
81347:         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
81348:         /* Assert that P3 is a valid memory cell. */
81349:         assert( pOp->p3<=pFrame->nMem );
81350:         pMem = &pFrame->aMem[pOp->p3];
81351:       }else{
81352:         /* Assert that P3 is a valid memory cell. */
81353:         assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
81354:         pMem = &aMem[pOp->p3];
81355:         memAboutToChange(p, pMem);
81356:       }
81357:       assert( memIsValid(pMem) );
81358: 
81359:       REGISTER_TRACE(pOp->p3, pMem);
81360:       sqlite3VdbeMemIntegerify(pMem);
81361:       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
81362:       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
81363:         rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
81364:         goto abort_due_to_error;
81365:       }
81366:       if( v<pMem->u.i+1 ){
81367:         v = pMem->u.i + 1;
81368:       }
81369:       pMem->u.i = v;
81370:     }
81371: #endif
81372:     if( pC->useRandomRowid ){
81373:       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
81374:       ** largest possible integer (9223372036854775807) then the database
81375:       ** engine starts picking positive candidate ROWIDs at random until
81376:       ** it finds one that is not previously used. */
81377:       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
81378:                              ** an AUTOINCREMENT table. */
81379:       cnt = 0;
81380:       do{
81381:         sqlite3_randomness(sizeof(v), &v);
81382:         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
81383:       }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
81384:                                                  0, &res))==SQLITE_OK)
81385:             && (res==0)
81386:             && (++cnt<100));
81387:       if( rc ) goto abort_due_to_error;
81388:       if( res==0 ){
81389:         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
81390:         goto abort_due_to_error;
81391:       }
81392:       assert( v>0 );  /* EV: R-40812-03570 */
81393:     }
81394:     pC->deferredMoveto = 0;
81395:     pC->cacheStatus = CACHE_STALE;
81396:   }
81397:   pOut->u.i = v;
81398:   break;
81399: }
81400: 
81401: /* Opcode: Insert P1 P2 P3 P4 P5
81402: ** Synopsis: intkey=r[P3] data=r[P2]
81403: **
81404: ** Write an entry into the table of cursor P1.  A new entry is
81405: ** created if it doesn't already exist or the data for an existing
81406: ** entry is overwritten.  The data is the value MEM_Blob stored in register
81407: ** number P2. The key is stored in register P3. The key must
81408: ** be a MEM_Int.
81409: **
81410: ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
81411: ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
81412: ** then rowid is stored for subsequent return by the
81413: ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
81414: **
81415: ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
81416: ** the last seek operation (OP_NotExists or OP_SeekRowid) was a success,
81417: ** then this
81418: ** operation will not attempt to find the appropriate row before doing
81419: ** the insert but will instead overwrite the row that the cursor is
81420: ** currently pointing to.  Presumably, the prior OP_NotExists or
81421: ** OP_SeekRowid opcode
81422: ** has already positioned the cursor correctly.  This is an optimization
81423: ** that boosts performance by avoiding redundant seeks.
81424: **
81425: ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
81426: ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
81427: ** is part of an INSERT operation.  The difference is only important to
81428: ** the update hook.
81429: **
81430: ** Parameter P4 may point to a Table structure, or may be NULL. If it is 
81431: ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked 
81432: ** following a successful insert.
81433: **
81434: ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
81435: ** allocated, then ownership of P2 is transferred to the pseudo-cursor
81436: ** and register P2 becomes ephemeral.  If the cursor is changed, the
81437: ** value of register P2 will then change.  Make sure this does not
81438: ** cause any problems.)
81439: **
81440: ** This instruction only works on tables.  The equivalent instruction
81441: ** for indices is OP_IdxInsert.
81442: */
81443: /* Opcode: InsertInt P1 P2 P3 P4 P5
81444: ** Synopsis:  intkey=P3 data=r[P2]
81445: **
81446: ** This works exactly like OP_Insert except that the key is the
81447: ** integer value P3, not the value of the integer stored in register P3.
81448: */
81449: case OP_Insert: 
81450: case OP_InsertInt: {
81451:   Mem *pData;       /* MEM cell holding data for the record to be inserted */
81452:   Mem *pKey;        /* MEM cell holding key  for the record */
81453:   VdbeCursor *pC;   /* Cursor to table into which insert is written */
81454:   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
81455:   const char *zDb;  /* database name - used by the update hook */
81456:   Table *pTab;      /* Table structure - used by update and pre-update hooks */
81457:   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
81458:   BtreePayload x;   /* Payload to be inserted */
81459: 
81460:   op = 0;
81461:   pData = &aMem[pOp->p2];
81462:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81463:   assert( memIsValid(pData) );
81464:   pC = p->apCsr[pOp->p1];
81465:   assert( pC!=0 );
81466:   assert( pC->eCurType==CURTYPE_BTREE );
81467:   assert( pC->uc.pCursor!=0 );
81468:   assert( pC->isTable );
81469:   assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
81470:   REGISTER_TRACE(pOp->p2, pData);
81471: 
81472:   if( pOp->opcode==OP_Insert ){
81473:     pKey = &aMem[pOp->p3];
81474:     assert( pKey->flags & MEM_Int );
81475:     assert( memIsValid(pKey) );
81476:     REGISTER_TRACE(pOp->p3, pKey);
81477:     x.nKey = pKey->u.i;
81478:   }else{
81479:     assert( pOp->opcode==OP_InsertInt );
81480:     x.nKey = pOp->p3;
81481:   }
81482: 
81483:   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81484:     assert( pC->isTable );
81485:     assert( pC->iDb>=0 );
81486:     zDb = db->aDb[pC->iDb].zName;
81487:     pTab = pOp->p4.pTab;
81488:     assert( HasRowid(pTab) );
81489:     op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
81490:   }else{
81491:     pTab = 0; /* Not needed.  Silence a comiler warning. */
81492:     zDb = 0;  /* Not needed.  Silence a compiler warning. */
81493:   }
81494: 
81495: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81496:   /* Invoke the pre-update hook, if any */
81497:   if( db->xPreUpdateCallback 
81498:    && pOp->p4type==P4_TABLE
81499:    && !(pOp->p5 & OPFLAG_ISUPDATE)
81500:   ){
81501:     sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
81502:   }
81503: #endif
81504: 
81505:   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
81506:   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = x.nKey;
81507:   if( pData->flags & MEM_Null ){
81508:     x.pData = 0;
81509:     x.nData = 0;
81510:   }else{
81511:     assert( pData->flags & (MEM_Blob|MEM_Str) );
81512:     x.pData = pData->z;
81513:     x.nData = pData->n;
81514:   }
81515:   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
81516:   if( pData->flags & MEM_Zero ){
81517:     x.nZero = pData->u.nZero;
81518:   }else{
81519:     x.nZero = 0;
81520:   }
81521:   x.pKey = 0;
81522:   rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
81523:                           (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
81524:   );
81525:   pC->deferredMoveto = 0;
81526:   pC->cacheStatus = CACHE_STALE;
81527: 
81528:   /* Invoke the update-hook if required. */
81529:   if( rc ) goto abort_due_to_error;
81530:   if( db->xUpdateCallback && op ){
81531:     db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
81532:   }
81533:   break;
81534: }
81535: 
81536: /* Opcode: Delete P1 P2 P3 P4 P5
81537: **
81538: ** Delete the record at which the P1 cursor is currently pointing.
81539: **
81540: ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
81541: ** the cursor will be left pointing at  either the next or the previous
81542: ** record in the table. If it is left pointing at the next record, then
81543: ** the next Next instruction will be a no-op. As a result, in this case
81544: ** it is ok to delete a record from within a Next loop. If 
81545: ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
81546: ** left in an undefined state.
81547: **
81548: ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
81549: ** delete one of several associated with deleting a table row and all its
81550: ** associated index entries.  Exactly one of those deletes is the "primary"
81551: ** delete.  The others are all on OPFLAG_FORDELETE cursors or else are
81552: ** marked with the AUXDELETE flag.
81553: **
81554: ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
81555: ** change count is incremented (otherwise not).
81556: **
81557: ** P1 must not be pseudo-table.  It has to be a real table with
81558: ** multiple rows.
81559: **
81560: ** If P4 is not NULL then it points to a Table struture. In this case either 
81561: ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81562: ** have been positioned using OP_NotFound prior to invoking this opcode in 
81563: ** this case. Specifically, if one is configured, the pre-update hook is 
81564: ** invoked if P4 is not NULL. The update-hook is invoked if one is configured, 
81565: ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81566: **
81567: ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81568: ** of the memory cell that contains the value that the rowid of the row will
81569: ** be set to by the update.
81570: */
81571: case OP_Delete: {
81572:   VdbeCursor *pC;
81573:   const char *zDb;
81574:   Table *pTab;
81575:   int opflags;
81576: 
81577:   opflags = pOp->p2;
81578:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81579:   pC = p->apCsr[pOp->p1];
81580:   assert( pC!=0 );
81581:   assert( pC->eCurType==CURTYPE_BTREE );
81582:   assert( pC->uc.pCursor!=0 );
81583:   assert( pC->deferredMoveto==0 );
81584: 
81585: #ifdef SQLITE_DEBUG
81586:   if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81587:     /* If p5 is zero, the seek operation that positioned the cursor prior to
81588:     ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81589:     ** the row that is being deleted */
81590:     i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81591:     assert( pC->movetoTarget==iKey );
81592:   }
81593: #endif
81594: 
81595:   /* If the update-hook or pre-update-hook will be invoked, set zDb to
81596:   ** the name of the db to pass as to it. Also set local pTab to a copy
81597:   ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81598:   ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set 
81599:   ** VdbeCursor.movetoTarget to the current rowid.  */
81600:   if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81601:     assert( pC->iDb>=0 );
81602:     assert( pOp->p4.pTab!=0 );
81603:     zDb = db->aDb[pC->iDb].zName;
81604:     pTab = pOp->p4.pTab;
81605:     if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81606:       pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81607:     }
81608:   }else{
81609:     zDb = 0;   /* Not needed.  Silence a compiler warning. */
81610:     pTab = 0;  /* Not needed.  Silence a compiler warning. */
81611:   }
81612: 
81613: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81614:   /* Invoke the pre-update-hook if required. */
81615:   if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81616:     assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81617:     sqlite3VdbePreUpdateHook(p, pC,
81618:         (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE, 
81619:         zDb, pTab, pC->movetoTarget,
81620:         pOp->p3
81621:     );
81622:   }
81623:   if( opflags & OPFLAG_ISNOOP ) break;
81624: #endif
81625:  
81626:   /* Only flags that can be set are SAVEPOISTION and AUXDELETE */ 
81627:   assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
81628:   assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
81629:   assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
81630: 
81631: #ifdef SQLITE_DEBUG
81632:   if( p->pFrame==0 ){
81633:     if( pC->isEphemeral==0
81634:         && (pOp->p5 & OPFLAG_AUXDELETE)==0
81635:         && (pC->wrFlag & OPFLAG_FORDELETE)==0
81636:       ){
81637:       nExtraDelete++;
81638:     }
81639:     if( pOp->p2 & OPFLAG_NCHANGE ){
81640:       nExtraDelete--;
81641:     }
81642:   }
81643: #endif
81644: 
81645:   rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
81646:   pC->cacheStatus = CACHE_STALE;
81647:   if( rc ) goto abort_due_to_error;
81648: 
81649:   /* Invoke the update-hook if required. */
81650:   if( opflags & OPFLAG_NCHANGE ){
81651:     p->nChange++;
81652:     if( db->xUpdateCallback && HasRowid(pTab) ){
81653:       db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81654:           pC->movetoTarget);
81655:       assert( pC->iDb>=0 );
81656:     }
81657:   }
81658: 
81659:   break;
81660: }
81661: /* Opcode: ResetCount * * * * *
81662: **
81663: ** The value of the change counter is copied to the database handle
81664: ** change counter (returned by subsequent calls to sqlite3_changes()).
81665: ** Then the VMs internal change counter resets to 0.
81666: ** This is used by trigger programs.
81667: */
81668: case OP_ResetCount: {
81669:   sqlite3VdbeSetChanges(db, p->nChange);
81670:   p->nChange = 0;
81671:   break;
81672: }
81673: 
81674: /* Opcode: SorterCompare P1 P2 P3 P4
81675: ** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
81676: **
81677: ** P1 is a sorter cursor. This instruction compares a prefix of the
81678: ** record blob in register P3 against a prefix of the entry that 
81679: ** the sorter cursor currently points to.  Only the first P4 fields
81680: ** of r[P3] and the sorter record are compared.
81681: **
81682: ** If either P3 or the sorter contains a NULL in one of their significant
81683: ** fields (not counting the P4 fields at the end which are ignored) then
81684: ** the comparison is assumed to be equal.
81685: **
81686: ** Fall through to next instruction if the two records compare equal to
81687: ** each other.  Jump to P2 if they are different.
81688: */
81689: case OP_SorterCompare: {
81690:   VdbeCursor *pC;
81691:   int res;
81692:   int nKeyCol;
81693: 
81694:   pC = p->apCsr[pOp->p1];
81695:   assert( isSorter(pC) );
81696:   assert( pOp->p4type==P4_INT32 );
81697:   pIn3 = &aMem[pOp->p3];
81698:   nKeyCol = pOp->p4.i;
81699:   res = 0;
81700:   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
81701:   VdbeBranchTaken(res!=0,2);
81702:   if( rc ) goto abort_due_to_error;
81703:   if( res ) goto jump_to_p2;
81704:   break;
81705: };
81706: 
81707: /* Opcode: SorterData P1 P2 P3 * *
81708: ** Synopsis: r[P2]=data
81709: **
81710: ** Write into register P2 the current sorter data for sorter cursor P1.
81711: ** Then clear the column header cache on cursor P3.
81712: **
81713: ** This opcode is normally use to move a record out of the sorter and into
81714: ** a register that is the source for a pseudo-table cursor created using
81715: ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
81716: ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
81717: ** us from having to issue a separate NullRow instruction to clear that cache.
81718: */
81719: case OP_SorterData: {
81720:   VdbeCursor *pC;
81721: 
81722:   pOut = &aMem[pOp->p2];
81723:   pC = p->apCsr[pOp->p1];
81724:   assert( isSorter(pC) );
81725:   rc = sqlite3VdbeSorterRowkey(pC, pOut);
81726:   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
81727:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81728:   if( rc ) goto abort_due_to_error;
81729:   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
81730:   break;
81731: }
81732: 
81733: /* Opcode: RowData P1 P2 * * *
81734: ** Synopsis: r[P2]=data
81735: **
81736: ** Write into register P2 the complete row data for cursor P1.
81737: ** There is no interpretation of the data.  
81738: ** It is just copied onto the P2 register exactly as 
81739: ** it is found in the database file.
81740: **
81741: ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81742: ** of a real table, not a pseudo-table.
81743: */
81744: /* Opcode: RowKey P1 P2 * * *
81745: ** Synopsis: r[P2]=key
81746: **
81747: ** Write into register P2 the complete row key for cursor P1.
81748: ** There is no interpretation of the data.  
81749: ** The key is copied onto the P2 register exactly as 
81750: ** it is found in the database file.
81751: **
81752: ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81753: ** of a real table, not a pseudo-table.
81754: */
81755: case OP_RowKey:
81756: case OP_RowData: {
81757:   VdbeCursor *pC;
81758:   BtCursor *pCrsr;
81759:   u32 n;
81760: 
81761:   pOut = &aMem[pOp->p2];
81762:   memAboutToChange(p, pOut);
81763: 
81764:   /* Note that RowKey and RowData are really exactly the same instruction */
81765:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81766:   pC = p->apCsr[pOp->p1];
81767:   assert( pC!=0 );
81768:   assert( pC->eCurType==CURTYPE_BTREE );
81769:   assert( isSorter(pC)==0 );
81770:   assert( pC->isTable || pOp->opcode!=OP_RowData );
81771:   assert( pC->isTable==0 || pOp->opcode==OP_RowData );
81772:   assert( pC->nullRow==0 );
81773:   assert( pC->uc.pCursor!=0 );
81774:   pCrsr = pC->uc.pCursor;
81775: 
81776:   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
81777:   ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
81778:   ** that might invalidate the cursor.
81779:   ** If this where not the case, on of the following assert()s
81780:   ** would fail.  Should this ever change (because of changes in the code
81781:   ** generator) then the fix would be to insert a call to
81782:   ** sqlite3VdbeCursorMoveto().
81783:   */
81784:   assert( pC->deferredMoveto==0 );
81785:   assert( sqlite3BtreeCursorIsValid(pCrsr) );
81786: #if 0  /* Not required due to the previous to assert() statements */
81787:   rc = sqlite3VdbeCursorMoveto(pC);
81788:   if( rc!=SQLITE_OK ) goto abort_due_to_error;
81789: #endif
81790: 
81791:   n = sqlite3BtreePayloadSize(pCrsr);
81792:   if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
81793:     goto too_big;
81794:   }
81795:   testcase( n==0 );
81796:   if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
81797:     goto no_mem;
81798:   }
81799:   pOut->n = n;
81800:   MemSetTypeFlag(pOut, MEM_Blob);
81801:   if( pC->isTable==0 ){
81802:     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
81803:   }else{
81804:     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
81805:   }
81806:   if( rc ) goto abort_due_to_error;
81807:   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
81808:   UPDATE_MAX_BLOBSIZE(pOut);
81809:   REGISTER_TRACE(pOp->p2, pOut);
81810:   break;
81811: }
81812: 
81813: /* Opcode: Rowid P1 P2 * * *
81814: ** Synopsis: r[P2]=rowid
81815: **
81816: ** Store in register P2 an integer which is the key of the table entry that
81817: ** P1 is currently point to.
81818: **
81819: ** P1 can be either an ordinary table or a virtual table.  There used to
81820: ** be a separate OP_VRowid opcode for use with virtual tables, but this
81821: ** one opcode now works for both table types.
81822: */
81823: case OP_Rowid: {                 /* out2 */
81824:   VdbeCursor *pC;
81825:   i64 v;
81826:   sqlite3_vtab *pVtab;
81827:   const sqlite3_module *pModule;
81828: 
81829:   pOut = out2Prerelease(p, pOp);
81830:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81831:   pC = p->apCsr[pOp->p1];
81832:   assert( pC!=0 );
81833:   assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
81834:   if( pC->nullRow ){
81835:     pOut->flags = MEM_Null;
81836:     break;
81837:   }else if( pC->deferredMoveto ){
81838:     v = pC->movetoTarget;
81839: #ifndef SQLITE_OMIT_VIRTUALTABLE
81840:   }else if( pC->eCurType==CURTYPE_VTAB ){
81841:     assert( pC->uc.pVCur!=0 );
81842:     pVtab = pC->uc.pVCur->pVtab;
81843:     pModule = pVtab->pModule;
81844:     assert( pModule->xRowid );
81845:     rc = pModule->xRowid(pC->uc.pVCur, &v);
81846:     sqlite3VtabImportErrmsg(p, pVtab);
81847:     if( rc ) goto abort_due_to_error;
81848: #endif /* SQLITE_OMIT_VIRTUALTABLE */
81849:   }else{
81850:     assert( pC->eCurType==CURTYPE_BTREE );
81851:     assert( pC->uc.pCursor!=0 );
81852:     rc = sqlite3VdbeCursorRestore(pC);
81853:     if( rc ) goto abort_due_to_error;
81854:     if( pC->nullRow ){
81855:       pOut->flags = MEM_Null;
81856:       break;
81857:     }
81858:     v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
81859:   }
81860:   pOut->u.i = v;
81861:   break;
81862: }
81863: 
81864: /* Opcode: NullRow P1 * * * *
81865: **
81866: ** Move the cursor P1 to a null row.  Any OP_Column operations
81867: ** that occur while the cursor is on the null row will always
81868: ** write a NULL.
81869: */
81870: case OP_NullRow: {
81871:   VdbeCursor *pC;
81872: 
81873:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81874:   pC = p->apCsr[pOp->p1];
81875:   assert( pC!=0 );
81876:   pC->nullRow = 1;
81877:   pC->cacheStatus = CACHE_STALE;
81878:   if( pC->eCurType==CURTYPE_BTREE ){
81879:     assert( pC->uc.pCursor!=0 );
81880:     sqlite3BtreeClearCursor(pC->uc.pCursor);
81881:   }
81882:   break;
81883: }
81884: 
81885: /* Opcode: Last P1 P2 P3 * *
81886: **
81887: ** The next use of the Rowid or Column or Prev instruction for P1 
81888: ** will refer to the last entry in the database table or index.
81889: ** If the table or index is empty and P2>0, then jump immediately to P2.
81890: ** If P2 is 0 or if the table or index is not empty, fall through
81891: ** to the following instruction.
81892: **
81893: ** This opcode leaves the cursor configured to move in reverse order,
81894: ** from the end toward the beginning.  In other words, the cursor is
81895: ** configured to use Prev, not Next.
81896: */
81897: case OP_Last: {        /* jump */
81898:   VdbeCursor *pC;
81899:   BtCursor *pCrsr;
81900:   int res;
81901: 
81902:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81903:   pC = p->apCsr[pOp->p1];
81904:   assert( pC!=0 );
81905:   assert( pC->eCurType==CURTYPE_BTREE );
81906:   pCrsr = pC->uc.pCursor;
81907:   res = 0;
81908:   assert( pCrsr!=0 );
81909:   rc = sqlite3BtreeLast(pCrsr, &res);
81910:   pC->nullRow = (u8)res;
81911:   pC->deferredMoveto = 0;
81912:   pC->cacheStatus = CACHE_STALE;
81913:   pC->seekResult = pOp->p3;
81914: #ifdef SQLITE_DEBUG
81915:   pC->seekOp = OP_Last;
81916: #endif
81917:   if( rc ) goto abort_due_to_error;
81918:   if( pOp->p2>0 ){
81919:     VdbeBranchTaken(res!=0,2);
81920:     if( res ) goto jump_to_p2;
81921:   }
81922:   break;
81923: }
81924: 
81925: 
81926: /* Opcode: Sort P1 P2 * * *
81927: **
81928: ** This opcode does exactly the same thing as OP_Rewind except that
81929: ** it increments an undocumented global variable used for testing.
81930: **
81931: ** Sorting is accomplished by writing records into a sorting index,
81932: ** then rewinding that index and playing it back from beginning to
81933: ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
81934: ** rewinding so that the global variable will be incremented and
81935: ** regression tests can determine whether or not the optimizer is
81936: ** correctly optimizing out sorts.
81937: */
81938: case OP_SorterSort:    /* jump */
81939: case OP_Sort: {        /* jump */
81940: #ifdef SQLITE_TEST
81941:   sqlite3_sort_count++;
81942:   sqlite3_search_count--;
81943: #endif
81944:   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
81945:   /* Fall through into OP_Rewind */
81946: }
81947: /* Opcode: Rewind P1 P2 * * *
81948: **
81949: ** The next use of the Rowid or Column or Next instruction for P1 
81950: ** will refer to the first entry in the database table or index.
81951: ** If the table or index is empty, jump immediately to P2.
81952: ** If the table or index is not empty, fall through to the following 
81953: ** instruction.
81954: **
81955: ** This opcode leaves the cursor configured to move in forward order,
81956: ** from the beginning toward the end.  In other words, the cursor is
81957: ** configured to use Next, not Prev.
81958: */
81959: case OP_Rewind: {        /* jump */
81960:   VdbeCursor *pC;
81961:   BtCursor *pCrsr;
81962:   int res;
81963: 
81964:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81965:   pC = p->apCsr[pOp->p1];
81966:   assert( pC!=0 );
81967:   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
81968:   res = 1;
81969: #ifdef SQLITE_DEBUG
81970:   pC->seekOp = OP_Rewind;
81971: #endif
81972:   if( isSorter(pC) ){
81973:     rc = sqlite3VdbeSorterRewind(pC, &res);
81974:   }else{
81975:     assert( pC->eCurType==CURTYPE_BTREE );
81976:     pCrsr = pC->uc.pCursor;
81977:     assert( pCrsr );
81978:     rc = sqlite3BtreeFirst(pCrsr, &res);
81979:     pC->deferredMoveto = 0;
81980:     pC->cacheStatus = CACHE_STALE;
81981:   }
81982:   if( rc ) goto abort_due_to_error;
81983:   pC->nullRow = (u8)res;
81984:   assert( pOp->p2>0 && pOp->p2<p->nOp );
81985:   VdbeBranchTaken(res!=0,2);
81986:   if( res ) goto jump_to_p2;
81987:   break;
81988: }
81989: 
81990: /* Opcode: Next P1 P2 P3 P4 P5
81991: **
81992: ** Advance cursor P1 so that it points to the next key/data pair in its
81993: ** table or index.  If there are no more key/value pairs then fall through
81994: ** to the following instruction.  But if the cursor advance was successful,
81995: ** jump immediately to P2.
81996: **
81997: ** The Next opcode is only valid following an SeekGT, SeekGE, or
81998: ** OP_Rewind opcode used to position the cursor.  Next is not allowed
81999: ** to follow SeekLT, SeekLE, or OP_Last.
82000: **
82001: ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
82002: ** been opened prior to this opcode or the program will segfault.
82003: **
82004: ** The P3 value is a hint to the btree implementation. If P3==1, that
82005: ** means P1 is an SQL index and that this instruction could have been
82006: ** omitted if that index had been unique.  P3 is usually 0.  P3 is
82007: ** always either 0 or 1.
82008: **
82009: ** P4 is always of type P4_ADVANCE. The function pointer points to
82010: ** sqlite3BtreeNext().
82011: **
82012: ** If P5 is positive and the jump is taken, then event counter
82013: ** number P5-1 in the prepared statement is incremented.
82014: **
82015: ** See also: Prev, NextIfOpen
82016: */
82017: /* Opcode: NextIfOpen P1 P2 P3 P4 P5
82018: **
82019: ** This opcode works just like Next except that if cursor P1 is not
82020: ** open it behaves a no-op.
82021: */
82022: /* Opcode: Prev P1 P2 P3 P4 P5
82023: **
82024: ** Back up cursor P1 so that it points to the previous key/data pair in its
82025: ** table or index.  If there is no previous key/value pairs then fall through
82026: ** to the following instruction.  But if the cursor backup was successful,
82027: ** jump immediately to P2.
82028: **
82029: **
82030: ** The Prev opcode is only valid following an SeekLT, SeekLE, or
82031: ** OP_Last opcode used to position the cursor.  Prev is not allowed
82032: ** to follow SeekGT, SeekGE, or OP_Rewind.
82033: **
82034: ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
82035: ** not open then the behavior is undefined.
82036: **
82037: ** The P3 value is a hint to the btree implementation. If P3==1, that
82038: ** means P1 is an SQL index and that this instruction could have been
82039: ** omitted if that index had been unique.  P3 is usually 0.  P3 is
82040: ** always either 0 or 1.
82041: **
82042: ** P4 is always of type P4_ADVANCE. The function pointer points to
82043: ** sqlite3BtreePrevious().
82044: **
82045: ** If P5 is positive and the jump is taken, then event counter
82046: ** number P5-1 in the prepared statement is incremented.
82047: */
82048: /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
82049: **
82050: ** This opcode works just like Prev except that if cursor P1 is not
82051: ** open it behaves a no-op.
82052: */
82053: case OP_SorterNext: {  /* jump */
82054:   VdbeCursor *pC;
82055:   int res;
82056: 
82057:   pC = p->apCsr[pOp->p1];
82058:   assert( isSorter(pC) );
82059:   res = 0;
82060:   rc = sqlite3VdbeSorterNext(db, pC, &res);
82061:   goto next_tail;
82062: case OP_PrevIfOpen:    /* jump */
82063: case OP_NextIfOpen:    /* jump */
82064:   if( p->apCsr[pOp->p1]==0 ) break;
82065:   /* Fall through */
82066: case OP_Prev:          /* jump */
82067: case OP_Next:          /* jump */
82068:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82069:   assert( pOp->p5<ArraySize(p->aCounter) );
82070:   pC = p->apCsr[pOp->p1];
82071:   res = pOp->p3;
82072:   assert( pC!=0 );
82073:   assert( pC->deferredMoveto==0 );
82074:   assert( pC->eCurType==CURTYPE_BTREE );
82075:   assert( res==0 || (res==1 && pC->isTable==0) );
82076:   testcase( res==1 );
82077:   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
82078:   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
82079:   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
82080:   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
82081: 
82082:   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
82083:   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
82084:   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
82085:        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
82086:        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
82087:   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
82088:        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
82089:        || pC->seekOp==OP_Last );
82090: 
82091:   rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
82092: next_tail:
82093:   pC->cacheStatus = CACHE_STALE;
82094:   VdbeBranchTaken(res==0,2);
82095:   if( rc ) goto abort_due_to_error;
82096:   if( res==0 ){
82097:     pC->nullRow = 0;
82098:     p->aCounter[pOp->p5]++;
82099: #ifdef SQLITE_TEST
82100:     sqlite3_search_count++;
82101: #endif
82102:     goto jump_to_p2_and_check_for_interrupt;
82103:   }else{
82104:     pC->nullRow = 1;
82105:   }
82106:   goto check_for_interrupt;
82107: }
82108: 
82109: /* Opcode: IdxInsert P1 P2 P3 * P5
82110: ** Synopsis: key=r[P2]
82111: **
82112: ** Register P2 holds an SQL index key made using the
82113: ** MakeRecord instructions.  This opcode writes that key
82114: ** into the index P1.  Data for the entry is nil.
82115: **
82116: ** P3 is a flag that provides a hint to the b-tree layer that this
82117: ** insert is likely to be an append.
82118: **
82119: ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
82120: ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
82121: ** then the change counter is unchanged.
82122: **
82123: ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
82124: ** just done a seek to the spot where the new entry is to be inserted.
82125: ** This flag avoids doing an extra seek.
82126: **
82127: ** This instruction only works for indices.  The equivalent instruction
82128: ** for tables is OP_Insert.
82129: */
82130: case OP_SorterInsert:       /* in2 */
82131: case OP_IdxInsert: {        /* in2 */
82132:   VdbeCursor *pC;
82133:   BtreePayload x;
82134: 
82135:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82136:   pC = p->apCsr[pOp->p1];
82137:   assert( pC!=0 );
82138:   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
82139:   pIn2 = &aMem[pOp->p2];
82140:   assert( pIn2->flags & MEM_Blob );
82141:   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
82142:   assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
82143:   assert( pC->isTable==0 );
82144:   rc = ExpandBlob(pIn2);
82145:   if( rc ) goto abort_due_to_error;
82146:   if( pOp->opcode==OP_SorterInsert ){
82147:     rc = sqlite3VdbeSorterWrite(pC, pIn2);
82148:   }else{
82149:     x.nKey = pIn2->n;
82150:     x.pKey = pIn2->z;
82151:     x.nData = 0;
82152:     x.nZero = 0;
82153:     x.pData = 0;
82154:     rc = sqlite3BtreeInsert(pC->uc.pCursor, &x, pOp->p3, 
82155:         ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
82156:         );
82157:     assert( pC->deferredMoveto==0 );
82158:     pC->cacheStatus = CACHE_STALE;
82159:   }
82160:   if( rc) goto abort_due_to_error;
82161:   break;
82162: }
82163: 
82164: /* Opcode: IdxDelete P1 P2 P3 * *
82165: ** Synopsis: key=r[P2@P3]
82166: **
82167: ** The content of P3 registers starting at register P2 form
82168: ** an unpacked index key. This opcode removes that entry from the 
82169: ** index opened by cursor P1.
82170: */
82171: case OP_IdxDelete: {
82172:   VdbeCursor *pC;
82173:   BtCursor *pCrsr;
82174:   int res;
82175:   UnpackedRecord r;
82176: 
82177:   assert( pOp->p3>0 );
82178:   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
82179:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82180:   pC = p->apCsr[pOp->p1];
82181:   assert( pC!=0 );
82182:   assert( pC->eCurType==CURTYPE_BTREE );
82183:   pCrsr = pC->uc.pCursor;
82184:   assert( pCrsr!=0 );
82185:   assert( pOp->p5==0 );
82186:   r.pKeyInfo = pC->pKeyInfo;
82187:   r.nField = (u16)pOp->p3;
82188:   r.default_rc = 0;
82189:   r.aMem = &aMem[pOp->p2];
82190:   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
82191:   if( rc ) goto abort_due_to_error;
82192:   if( res==0 ){
82193:     rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
82194:     if( rc ) goto abort_due_to_error;
82195:   }
82196:   assert( pC->deferredMoveto==0 );
82197:   pC->cacheStatus = CACHE_STALE;
82198:   break;
82199: }
82200: 
82201: /* Opcode: Seek P1 * P3 P4 *
82202: ** Synopsis:  Move P3 to P1.rowid
82203: **
82204: ** P1 is an open index cursor and P3 is a cursor on the corresponding
82205: ** table.  This opcode does a deferred seek of the P3 table cursor
82206: ** to the row that corresponds to the current row of P1.
82207: **
82208: ** This is a deferred seek.  Nothing actually happens until
82209: ** the cursor is used to read a record.  That way, if no reads
82210: ** occur, no unnecessary I/O happens.
82211: **
82212: ** P4 may be an array of integers (type P4_INTARRAY) containing
82213: ** one entry for each column in the P3 table.  If array entry a(i)
82214: ** is non-zero, then reading column a(i)-1 from cursor P3 is 
82215: ** equivalent to performing the deferred seek and then reading column i 
82216: ** from P1.  This information is stored in P3 and used to redirect
82217: ** reads against P3 over to P1, thus possibly avoiding the need to
82218: ** seek and read cursor P3.
82219: */
82220: /* Opcode: IdxRowid P1 P2 * * *
82221: ** Synopsis: r[P2]=rowid
82222: **
82223: ** Write into register P2 an integer which is the last entry in the record at
82224: ** the end of the index key pointed to by cursor P1.  This integer should be
82225: ** the rowid of the table entry to which this index entry points.
82226: **
82227: ** See also: Rowid, MakeRecord.
82228: */
82229: case OP_Seek:
82230: case OP_IdxRowid: {              /* out2 */
82231:   VdbeCursor *pC;                /* The P1 index cursor */
82232:   VdbeCursor *pTabCur;           /* The P2 table cursor (OP_Seek only) */
82233:   i64 rowid;                     /* Rowid that P1 current points to */
82234: 
82235:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82236:   pC = p->apCsr[pOp->p1];
82237:   assert( pC!=0 );
82238:   assert( pC->eCurType==CURTYPE_BTREE );
82239:   assert( pC->uc.pCursor!=0 );
82240:   assert( pC->isTable==0 );
82241:   assert( pC->deferredMoveto==0 );
82242:   assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
82243: 
82244:   /* The IdxRowid and Seek opcodes are combined because of the commonality
82245:   ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
82246:   rc = sqlite3VdbeCursorRestore(pC);
82247: 
82248:   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
82249:   ** out from under the cursor.  That will never happens for an IdxRowid
82250:   ** or Seek opcode */
82251:   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
82252: 
82253:   if( !pC->nullRow ){
82254:     rowid = 0;  /* Not needed.  Only used to silence a warning. */
82255:     rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
82256:     if( rc!=SQLITE_OK ){
82257:       goto abort_due_to_error;
82258:     }
82259:     if( pOp->opcode==OP_Seek ){
82260:       assert( pOp->p3>=0 && pOp->p3<p->nCursor );
82261:       pTabCur = p->apCsr[pOp->p3];
82262:       assert( pTabCur!=0 );
82263:       assert( pTabCur->eCurType==CURTYPE_BTREE );
82264:       assert( pTabCur->uc.pCursor!=0 );
82265:       assert( pTabCur->isTable );
82266:       pTabCur->nullRow = 0;
82267:       pTabCur->movetoTarget = rowid;
82268:       pTabCur->deferredMoveto = 1;
82269:       assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
82270:       pTabCur->aAltMap = pOp->p4.ai;
82271:       pTabCur->pAltCursor = pC;
82272:     }else{
82273:       pOut = out2Prerelease(p, pOp);
82274:       pOut->u.i = rowid;
82275:       pOut->flags = MEM_Int;
82276:     }
82277:   }else{
82278:     assert( pOp->opcode==OP_IdxRowid );
82279:     sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
82280:   }
82281:   break;
82282: }
82283: 
82284: /* Opcode: IdxGE P1 P2 P3 P4 P5
82285: ** Synopsis: key=r[P3@P4]
82286: **
82287: ** The P4 register values beginning with P3 form an unpacked index 
82288: ** key that omits the PRIMARY KEY.  Compare this key value against the index 
82289: ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
82290: ** fields at the end.
82291: **
82292: ** If the P1 index entry is greater than or equal to the key value
82293: ** then jump to P2.  Otherwise fall through to the next instruction.
82294: */
82295: /* Opcode: IdxGT P1 P2 P3 P4 P5
82296: ** Synopsis: key=r[P3@P4]
82297: **
82298: ** The P4 register values beginning with P3 form an unpacked index 
82299: ** key that omits the PRIMARY KEY.  Compare this key value against the index 
82300: ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
82301: ** fields at the end.
82302: **
82303: ** If the P1 index entry is greater than the key value
82304: ** then jump to P2.  Otherwise fall through to the next instruction.
82305: */
82306: /* Opcode: IdxLT P1 P2 P3 P4 P5
82307: ** Synopsis: key=r[P3@P4]
82308: **
82309: ** The P4 register values beginning with P3 form an unpacked index 
82310: ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
82311: ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82312: ** ROWID on the P1 index.
82313: **
82314: ** If the P1 index entry is less than the key value then jump to P2.
82315: ** Otherwise fall through to the next instruction.
82316: */
82317: /* Opcode: IdxLE P1 P2 P3 P4 P5
82318: ** Synopsis: key=r[P3@P4]
82319: **
82320: ** The P4 register values beginning with P3 form an unpacked index 
82321: ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
82322: ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
82323: ** ROWID on the P1 index.
82324: **
82325: ** If the P1 index entry is less than or equal to the key value then jump
82326: ** to P2. Otherwise fall through to the next instruction.
82327: */
82328: case OP_IdxLE:          /* jump */
82329: case OP_IdxGT:          /* jump */
82330: case OP_IdxLT:          /* jump */
82331: case OP_IdxGE:  {       /* jump */
82332:   VdbeCursor *pC;
82333:   int res;
82334:   UnpackedRecord r;
82335: 
82336:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82337:   pC = p->apCsr[pOp->p1];
82338:   assert( pC!=0 );
82339:   assert( pC->isOrdered );
82340:   assert( pC->eCurType==CURTYPE_BTREE );
82341:   assert( pC->uc.pCursor!=0);
82342:   assert( pC->deferredMoveto==0 );
82343:   assert( pOp->p5==0 || pOp->p5==1 );
82344:   assert( pOp->p4type==P4_INT32 );
82345:   r.pKeyInfo = pC->pKeyInfo;
82346:   r.nField = (u16)pOp->p4.i;
82347:   if( pOp->opcode<OP_IdxLT ){
82348:     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
82349:     r.default_rc = -1;
82350:   }else{
82351:     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
82352:     r.default_rc = 0;
82353:   }
82354:   r.aMem = &aMem[pOp->p3];
82355: #ifdef SQLITE_DEBUG
82356:   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
82357: #endif
82358:   res = 0;  /* Not needed.  Only used to silence a warning. */
82359:   rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
82360:   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
82361:   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
82362:     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
82363:     res = -res;
82364:   }else{
82365:     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
82366:     res++;
82367:   }
82368:   VdbeBranchTaken(res>0,2);
82369:   if( rc ) goto abort_due_to_error;
82370:   if( res>0 ) goto jump_to_p2;
82371:   break;
82372: }
82373: 
82374: /* Opcode: Destroy P1 P2 P3 * *
82375: **
82376: ** Delete an entire database table or index whose root page in the database
82377: ** file is given by P1.
82378: **
82379: ** The table being destroyed is in the main database file if P3==0.  If
82380: ** P3==1 then the table to be clear is in the auxiliary database file
82381: ** that is used to store tables create using CREATE TEMPORARY TABLE.
82382: **
82383: ** If AUTOVACUUM is enabled then it is possible that another root page
82384: ** might be moved into the newly deleted root page in order to keep all
82385: ** root pages contiguous at the beginning of the database.  The former
82386: ** value of the root page that moved - its value before the move occurred -
82387: ** is stored in register P2.  If no page 
82388: ** movement was required (because the table being dropped was already 
82389: ** the last one in the database) then a zero is stored in register P2.
82390: ** If AUTOVACUUM is disabled then a zero is stored in register P2.
82391: **
82392: ** See also: Clear
82393: */
82394: case OP_Destroy: {     /* out2 */
82395:   int iMoved;
82396:   int iDb;
82397: 
82398:   assert( p->readOnly==0 );
82399:   assert( pOp->p1>1 );
82400:   pOut = out2Prerelease(p, pOp);
82401:   pOut->flags = MEM_Null;
82402:   if( db->nVdbeRead > db->nVDestroy+1 ){
82403:     rc = SQLITE_LOCKED;
82404:     p->errorAction = OE_Abort;
82405:     goto abort_due_to_error;
82406:   }else{
82407:     iDb = pOp->p3;
82408:     assert( DbMaskTest(p->btreeMask, iDb) );
82409:     iMoved = 0;  /* Not needed.  Only to silence a warning. */
82410:     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
82411:     pOut->flags = MEM_Int;
82412:     pOut->u.i = iMoved;
82413:     if( rc ) goto abort_due_to_error;
82414: #ifndef SQLITE_OMIT_AUTOVACUUM
82415:     if( iMoved!=0 ){
82416:       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
82417:       /* All OP_Destroy operations occur on the same btree */
82418:       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
82419:       resetSchemaOnFault = iDb+1;
82420:     }
82421: #endif
82422:   }
82423:   break;
82424: }
82425: 
82426: /* Opcode: Clear P1 P2 P3
82427: **
82428: ** Delete all contents of the database table or index whose root page
82429: ** in the database file is given by P1.  But, unlike Destroy, do not
82430: ** remove the table or index from the database file.
82431: **
82432: ** The table being clear is in the main database file if P2==0.  If
82433: ** P2==1 then the table to be clear is in the auxiliary database file
82434: ** that is used to store tables create using CREATE TEMPORARY TABLE.
82435: **
82436: ** If the P3 value is non-zero, then the table referred to must be an
82437: ** intkey table (an SQL table, not an index). In this case the row change 
82438: ** count is incremented by the number of rows in the table being cleared. 
82439: ** If P3 is greater than zero, then the value stored in register P3 is
82440: ** also incremented by the number of rows in the table being cleared.
82441: **
82442: ** See also: Destroy
82443: */
82444: case OP_Clear: {
82445:   int nChange;
82446:  
82447:   nChange = 0;
82448:   assert( p->readOnly==0 );
82449:   assert( DbMaskTest(p->btreeMask, pOp->p2) );
82450:   rc = sqlite3BtreeClearTable(
82451:       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
82452:   );
82453:   if( pOp->p3 ){
82454:     p->nChange += nChange;
82455:     if( pOp->p3>0 ){
82456:       assert( memIsValid(&aMem[pOp->p3]) );
82457:       memAboutToChange(p, &aMem[pOp->p3]);
82458:       aMem[pOp->p3].u.i += nChange;
82459:     }
82460:   }
82461:   if( rc ) goto abort_due_to_error;
82462:   break;
82463: }
82464: 
82465: /* Opcode: ResetSorter P1 * * * *
82466: **
82467: ** Delete all contents from the ephemeral table or sorter
82468: ** that is open on cursor P1.
82469: **
82470: ** This opcode only works for cursors used for sorting and
82471: ** opened with OP_OpenEphemeral or OP_SorterOpen.
82472: */
82473: case OP_ResetSorter: {
82474:   VdbeCursor *pC;
82475:  
82476:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
82477:   pC = p->apCsr[pOp->p1];
82478:   assert( pC!=0 );
82479:   if( isSorter(pC) ){
82480:     sqlite3VdbeSorterReset(db, pC->uc.pSorter);
82481:   }else{
82482:     assert( pC->eCurType==CURTYPE_BTREE );
82483:     assert( pC->isEphemeral );
82484:     rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
82485:     if( rc ) goto abort_due_to_error;
82486:   }
82487:   break;
82488: }
82489: 
82490: /* Opcode: CreateTable P1 P2 * * *
82491: ** Synopsis: r[P2]=root iDb=P1
82492: **
82493: ** Allocate a new table in the main database file if P1==0 or in the
82494: ** auxiliary database file if P1==1 or in an attached database if
82495: ** P1>1.  Write the root page number of the new table into
82496: ** register P2
82497: **
82498: ** The difference between a table and an index is this:  A table must
82499: ** have a 4-byte integer key and can have arbitrary data.  An index
82500: ** has an arbitrary key but no data.
82501: **
82502: ** See also: CreateIndex
82503: */
82504: /* Opcode: CreateIndex P1 P2 * * *
82505: ** Synopsis: r[P2]=root iDb=P1
82506: **
82507: ** Allocate a new index in the main database file if P1==0 or in the
82508: ** auxiliary database file if P1==1 or in an attached database if
82509: ** P1>1.  Write the root page number of the new table into
82510: ** register P2.
82511: **
82512: ** See documentation on OP_CreateTable for additional information.
82513: */
82514: case OP_CreateIndex:            /* out2 */
82515: case OP_CreateTable: {          /* out2 */
82516:   int pgno;
82517:   int flags;
82518:   Db *pDb;
82519: 
82520:   pOut = out2Prerelease(p, pOp);
82521:   pgno = 0;
82522:   assert( pOp->p1>=0 && pOp->p1<db->nDb );
82523:   assert( DbMaskTest(p->btreeMask, pOp->p1) );
82524:   assert( p->readOnly==0 );
82525:   pDb = &db->aDb[pOp->p1];
82526:   assert( pDb->pBt!=0 );
82527:   if( pOp->opcode==OP_CreateTable ){
82528:     /* flags = BTREE_INTKEY; */
82529:     flags = BTREE_INTKEY;
82530:   }else{
82531:     flags = BTREE_BLOBKEY;
82532:   }
82533:   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
82534:   if( rc ) goto abort_due_to_error;
82535:   pOut->u.i = pgno;
82536:   break;
82537: }
82538: 
82539: /* Opcode: ParseSchema P1 * * P4 *
82540: **
82541: ** Read and parse all entries from the SQLITE_MASTER table of database P1
82542: ** that match the WHERE clause P4. 
82543: **
82544: ** This opcode invokes the parser to create a new virtual machine,
82545: ** then runs the new virtual machine.  It is thus a re-entrant opcode.
82546: */
82547: case OP_ParseSchema: {
82548:   int iDb;
82549:   const char *zMaster;
82550:   char *zSql;
82551:   InitData initData;
82552: 
82553:   /* Any prepared statement that invokes this opcode will hold mutexes
82554:   ** on every btree.  This is a prerequisite for invoking 
82555:   ** sqlite3InitCallback().
82556:   */
82557: #ifdef SQLITE_DEBUG
82558:   for(iDb=0; iDb<db->nDb; iDb++){
82559:     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
82560:   }
82561: #endif
82562: 
82563:   iDb = pOp->p1;
82564:   assert( iDb>=0 && iDb<db->nDb );
82565:   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
82566:   /* Used to be a conditional */ {
82567:     zMaster = SCHEMA_TABLE(iDb);
82568:     initData.db = db;
82569:     initData.iDb = pOp->p1;
82570:     initData.pzErrMsg = &p->zErrMsg;
82571:     zSql = sqlite3MPrintf(db,
82572:        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
82573:        db->aDb[iDb].zName, zMaster, pOp->p4.z);
82574:     if( zSql==0 ){
82575:       rc = SQLITE_NOMEM_BKPT;
82576:     }else{
82577:       assert( db->init.busy==0 );
82578:       db->init.busy = 1;
82579:       initData.rc = SQLITE_OK;
82580:       assert( !db->mallocFailed );
82581:       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
82582:       if( rc==SQLITE_OK ) rc = initData.rc;
82583:       sqlite3DbFree(db, zSql);
82584:       db->init.busy = 0;
82585:     }
82586:   }
82587:   if( rc ){
82588:     sqlite3ResetAllSchemasOfConnection(db);
82589:     if( rc==SQLITE_NOMEM ){
82590:       goto no_mem;
82591:     }
82592:     goto abort_due_to_error;
82593:   }
82594:   break;  
82595: }
82596: 
82597: #if !defined(SQLITE_OMIT_ANALYZE)
82598: /* Opcode: LoadAnalysis P1 * * * *
82599: **
82600: ** Read the sqlite_stat1 table for database P1 and load the content
82601: ** of that table into the internal index hash table.  This will cause
82602: ** the analysis to be used when preparing all subsequent queries.
82603: */
82604: case OP_LoadAnalysis: {
82605:   assert( pOp->p1>=0 && pOp->p1<db->nDb );
82606:   rc = sqlite3AnalysisLoad(db, pOp->p1);
82607:   if( rc ) goto abort_due_to_error;
82608:   break;  
82609: }
82610: #endif /* !defined(SQLITE_OMIT_ANALYZE) */
82611: 
82612: /* Opcode: DropTable P1 * * P4 *
82613: **
82614: ** Remove the internal (in-memory) data structures that describe
82615: ** the table named P4 in database P1.  This is called after a table
82616: ** is dropped from disk (using the Destroy opcode) in order to keep 
82617: ** the internal representation of the
82618: ** schema consistent with what is on disk.
82619: */
82620: case OP_DropTable: {
82621:   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
82622:   break;
82623: }
82624: 
82625: /* Opcode: DropIndex P1 * * P4 *
82626: **
82627: ** Remove the internal (in-memory) data structures that describe
82628: ** the index named P4 in database P1.  This is called after an index
82629: ** is dropped from disk (using the Destroy opcode)
82630: ** in order to keep the internal representation of the
82631: ** schema consistent with what is on disk.
82632: */
82633: case OP_DropIndex: {
82634:   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
82635:   break;
82636: }
82637: 
82638: /* Opcode: DropTrigger P1 * * P4 *
82639: **
82640: ** Remove the internal (in-memory) data structures that describe
82641: ** the trigger named P4 in database P1.  This is called after a trigger
82642: ** is dropped from disk (using the Destroy opcode) in order to keep 
82643: ** the internal representation of the
82644: ** schema consistent with what is on disk.
82645: */
82646: case OP_DropTrigger: {
82647:   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
82648:   break;
82649: }
82650: 
82651: 
82652: #ifndef SQLITE_OMIT_INTEGRITY_CHECK
82653: /* Opcode: IntegrityCk P1 P2 P3 P4 P5
82654: **
82655: ** Do an analysis of the currently open database.  Store in
82656: ** register P1 the text of an error message describing any problems.
82657: ** If no problems are found, store a NULL in register P1.
82658: **
82659: ** The register P3 contains the maximum number of allowed errors.
82660: ** At most reg(P3) errors will be reported.
82661: ** In other words, the analysis stops as soon as reg(P1) errors are 
82662: ** seen.  Reg(P1) is updated with the number of errors remaining.
82663: **
82664: ** The root page numbers of all tables in the database are integers
82665: ** stored in P4_INTARRAY argument.
82666: **
82667: ** If P5 is not zero, the check is done on the auxiliary database
82668: ** file, not the main database file.
82669: **
82670: ** This opcode is used to implement the integrity_check pragma.
82671: */
82672: case OP_IntegrityCk: {
82673:   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
82674:   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
82675:   int nErr;       /* Number of errors reported */
82676:   char *z;        /* Text of the error report */
82677:   Mem *pnErr;     /* Register keeping track of errors remaining */
82678: 
82679:   assert( p->bIsReader );
82680:   nRoot = pOp->p2;
82681:   aRoot = pOp->p4.ai;
82682:   assert( nRoot>0 );
82683:   assert( aRoot[nRoot]==0 );
82684:   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
82685:   pnErr = &aMem[pOp->p3];
82686:   assert( (pnErr->flags & MEM_Int)!=0 );
82687:   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
82688:   pIn1 = &aMem[pOp->p1];
82689:   assert( pOp->p5<db->nDb );
82690:   assert( DbMaskTest(p->btreeMask, pOp->p5) );
82691:   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
82692:                                  (int)pnErr->u.i, &nErr);
82693:   pnErr->u.i -= nErr;
82694:   sqlite3VdbeMemSetNull(pIn1);
82695:   if( nErr==0 ){
82696:     assert( z==0 );
82697:   }else if( z==0 ){
82698:     goto no_mem;
82699:   }else{
82700:     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
82701:   }
82702:   UPDATE_MAX_BLOBSIZE(pIn1);
82703:   sqlite3VdbeChangeEncoding(pIn1, encoding);
82704:   break;
82705: }
82706: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
82707: 
82708: /* Opcode: RowSetAdd P1 P2 * * *
82709: ** Synopsis:  rowset(P1)=r[P2]
82710: **
82711: ** Insert the integer value held by register P2 into a boolean index
82712: ** held in register P1.
82713: **
82714: ** An assertion fails if P2 is not an integer.
82715: */
82716: case OP_RowSetAdd: {       /* in1, in2 */
82717:   pIn1 = &aMem[pOp->p1];
82718:   pIn2 = &aMem[pOp->p2];
82719:   assert( (pIn2->flags & MEM_Int)!=0 );
82720:   if( (pIn1->flags & MEM_RowSet)==0 ){
82721:     sqlite3VdbeMemSetRowSet(pIn1);
82722:     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82723:   }
82724:   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
82725:   break;
82726: }
82727: 
82728: /* Opcode: RowSetRead P1 P2 P3 * *
82729: ** Synopsis:  r[P3]=rowset(P1)
82730: **
82731: ** Extract the smallest value from boolean index P1 and put that value into
82732: ** register P3.  Or, if boolean index P1 is initially empty, leave P3
82733: ** unchanged and jump to instruction P2.
82734: */
82735: case OP_RowSetRead: {       /* jump, in1, out3 */
82736:   i64 val;
82737: 
82738:   pIn1 = &aMem[pOp->p1];
82739:   if( (pIn1->flags & MEM_RowSet)==0 
82740:    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
82741:   ){
82742:     /* The boolean index is empty */
82743:     sqlite3VdbeMemSetNull(pIn1);
82744:     VdbeBranchTaken(1,2);
82745:     goto jump_to_p2_and_check_for_interrupt;
82746:   }else{
82747:     /* A value was pulled from the index */
82748:     VdbeBranchTaken(0,2);
82749:     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
82750:   }
82751:   goto check_for_interrupt;
82752: }
82753: 
82754: /* Opcode: RowSetTest P1 P2 P3 P4
82755: ** Synopsis: if r[P3] in rowset(P1) goto P2
82756: **
82757: ** Register P3 is assumed to hold a 64-bit integer value. If register P1
82758: ** contains a RowSet object and that RowSet object contains
82759: ** the value held in P3, jump to register P2. Otherwise, insert the
82760: ** integer in P3 into the RowSet and continue on to the
82761: ** next opcode.
82762: **
82763: ** The RowSet object is optimized for the case where successive sets
82764: ** of integers, where each set contains no duplicates. Each set
82765: ** of values is identified by a unique P4 value. The first set
82766: ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
82767: ** non-negative.  For non-negative values of P4 only the lower 4
82768: ** bits are significant.
82769: **
82770: ** This allows optimizations: (a) when P4==0 there is no need to test
82771: ** the rowset object for P3, as it is guaranteed not to contain it,
82772: ** (b) when P4==-1 there is no need to insert the value, as it will
82773: ** never be tested for, and (c) when a value that is part of set X is
82774: ** inserted, there is no need to search to see if the same value was
82775: ** previously inserted as part of set X (only if it was previously
82776: ** inserted as part of some other set).
82777: */
82778: case OP_RowSetTest: {                     /* jump, in1, in3 */
82779:   int iSet;
82780:   int exists;
82781: 
82782:   pIn1 = &aMem[pOp->p1];
82783:   pIn3 = &aMem[pOp->p3];
82784:   iSet = pOp->p4.i;
82785:   assert( pIn3->flags&MEM_Int );
82786: 
82787:   /* If there is anything other than a rowset object in memory cell P1,
82788:   ** delete it now and initialize P1 with an empty rowset
82789:   */
82790:   if( (pIn1->flags & MEM_RowSet)==0 ){
82791:     sqlite3VdbeMemSetRowSet(pIn1);
82792:     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82793:   }
82794: 
82795:   assert( pOp->p4type==P4_INT32 );
82796:   assert( iSet==-1 || iSet>=0 );
82797:   if( iSet ){
82798:     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
82799:     VdbeBranchTaken(exists!=0,2);
82800:     if( exists ) goto jump_to_p2;
82801:   }
82802:   if( iSet>=0 ){
82803:     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
82804:   }
82805:   break;
82806: }
82807: 
82808: 
82809: #ifndef SQLITE_OMIT_TRIGGER
82810: 
82811: /* Opcode: Program P1 P2 P3 P4 P5
82812: **
82813: ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
82814: **
82815: ** P1 contains the address of the memory cell that contains the first memory 
82816: ** cell in an array of values used as arguments to the sub-program. P2 
82817: ** contains the address to jump to if the sub-program throws an IGNORE 
82818: ** exception using the RAISE() function. Register P3 contains the address 
82819: ** of a memory cell in this (the parent) VM that is used to allocate the 
82820: ** memory required by the sub-vdbe at runtime.
82821: **
82822: ** P4 is a pointer to the VM containing the trigger program.
82823: **
82824: ** If P5 is non-zero, then recursive program invocation is enabled.
82825: */
82826: case OP_Program: {        /* jump */
82827:   int nMem;               /* Number of memory registers for sub-program */
82828:   int nByte;              /* Bytes of runtime space required for sub-program */
82829:   Mem *pRt;               /* Register to allocate runtime space */
82830:   Mem *pMem;              /* Used to iterate through memory cells */
82831:   Mem *pEnd;              /* Last memory cell in new array */
82832:   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
82833:   SubProgram *pProgram;   /* Sub-program to execute */
82834:   void *t;                /* Token identifying trigger */
82835: 
82836:   pProgram = pOp->p4.pProgram;
82837:   pRt = &aMem[pOp->p3];
82838:   assert( pProgram->nOp>0 );
82839:   
82840:   /* If the p5 flag is clear, then recursive invocation of triggers is 
82841:   ** disabled for backwards compatibility (p5 is set if this sub-program
82842:   ** is really a trigger, not a foreign key action, and the flag set
82843:   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
82844:   ** 
82845:   ** It is recursive invocation of triggers, at the SQL level, that is 
82846:   ** disabled. In some cases a single trigger may generate more than one 
82847:   ** SubProgram (if the trigger may be executed with more than one different 
82848:   ** ON CONFLICT algorithm). SubProgram structures associated with a
82849:   ** single trigger all have the same value for the SubProgram.token 
82850:   ** variable.  */
82851:   if( pOp->p5 ){
82852:     t = pProgram->token;
82853:     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
82854:     if( pFrame ) break;
82855:   }
82856: 
82857:   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
82858:     rc = SQLITE_ERROR;
82859:     sqlite3VdbeError(p, "too many levels of trigger recursion");
82860:     goto abort_due_to_error;
82861:   }
82862: 
82863:   /* Register pRt is used to store the memory required to save the state
82864:   ** of the current program, and the memory required at runtime to execute
82865:   ** the trigger program. If this trigger has been fired before, then pRt 
82866:   ** is already allocated. Otherwise, it must be initialized.  */
82867:   if( (pRt->flags&MEM_Frame)==0 ){
82868:     /* SubProgram.nMem is set to the number of memory cells used by the 
82869:     ** program stored in SubProgram.aOp. As well as these, one memory
82870:     ** cell is required for each cursor used by the program. Set local
82871:     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
82872:     */
82873:     nMem = pProgram->nMem + pProgram->nCsr;
82874:     assert( nMem>0 );
82875:     if( pProgram->nCsr==0 ) nMem++;
82876:     nByte = ROUND8(sizeof(VdbeFrame))
82877:               + nMem * sizeof(Mem)
82878:               + pProgram->nCsr * sizeof(VdbeCursor *)
82879:               + pProgram->nOnce * sizeof(u8);
82880:     pFrame = sqlite3DbMallocZero(db, nByte);
82881:     if( !pFrame ){
82882:       goto no_mem;
82883:     }
82884:     sqlite3VdbeMemRelease(pRt);
82885:     pRt->flags = MEM_Frame;
82886:     pRt->u.pFrame = pFrame;
82887: 
82888:     pFrame->v = p;
82889:     pFrame->nChildMem = nMem;
82890:     pFrame->nChildCsr = pProgram->nCsr;
82891:     pFrame->pc = (int)(pOp - aOp);
82892:     pFrame->aMem = p->aMem;
82893:     pFrame->nMem = p->nMem;
82894:     pFrame->apCsr = p->apCsr;
82895:     pFrame->nCursor = p->nCursor;
82896:     pFrame->aOp = p->aOp;
82897:     pFrame->nOp = p->nOp;
82898:     pFrame->token = pProgram->token;
82899:     pFrame->aOnceFlag = p->aOnceFlag;
82900:     pFrame->nOnceFlag = p->nOnceFlag;
82901: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82902:     pFrame->anExec = p->anExec;
82903: #endif
82904: 
82905:     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
82906:     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
82907:       pMem->flags = MEM_Undefined;
82908:       pMem->db = db;
82909:     }
82910:   }else{
82911:     pFrame = pRt->u.pFrame;
82912:     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem 
82913:         || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
82914:     assert( pProgram->nCsr==pFrame->nChildCsr );
82915:     assert( (int)(pOp - aOp)==pFrame->pc );
82916:   }
82917: 
82918:   p->nFrame++;
82919:   pFrame->pParent = p->pFrame;
82920:   pFrame->lastRowid = lastRowid;
82921:   pFrame->nChange = p->nChange;
82922:   pFrame->nDbChange = p->db->nChange;
82923:   assert( pFrame->pAuxData==0 );
82924:   pFrame->pAuxData = p->pAuxData;
82925:   p->pAuxData = 0;
82926:   p->nChange = 0;
82927:   p->pFrame = pFrame;
82928:   p->aMem = aMem = VdbeFrameMem(pFrame);
82929:   p->nMem = pFrame->nChildMem;
82930:   p->nCursor = (u16)pFrame->nChildCsr;
82931:   p->apCsr = (VdbeCursor **)&aMem[p->nMem];
82932:   p->aOp = aOp = pProgram->aOp;
82933:   p->nOp = pProgram->nOp;
82934:   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
82935:   p->nOnceFlag = pProgram->nOnce;
82936: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82937:   p->anExec = 0;
82938: #endif
82939:   pOp = &aOp[-1];
82940:   memset(p->aOnceFlag, 0, p->nOnceFlag);
82941: 
82942:   break;
82943: }
82944: 
82945: /* Opcode: Param P1 P2 * * *
82946: **
82947: ** This opcode is only ever present in sub-programs called via the 
82948: ** OP_Program instruction. Copy a value currently stored in a memory 
82949: ** cell of the calling (parent) frame to cell P2 in the current frames 
82950: ** address space. This is used by trigger programs to access the new.* 
82951: ** and old.* values.
82952: **
82953: ** The address of the cell in the parent frame is determined by adding
82954: ** the value of the P1 argument to the value of the P1 argument to the
82955: ** calling OP_Program instruction.
82956: */
82957: case OP_Param: {           /* out2 */
82958:   VdbeFrame *pFrame;
82959:   Mem *pIn;
82960:   pOut = out2Prerelease(p, pOp);
82961:   pFrame = p->pFrame;
82962:   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
82963:   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
82964:   break;
82965: }
82966: 
82967: #endif /* #ifndef SQLITE_OMIT_TRIGGER */
82968: 
82969: #ifndef SQLITE_OMIT_FOREIGN_KEY
82970: /* Opcode: FkCounter P1 P2 * * *
82971: ** Synopsis: fkctr[P1]+=P2
82972: **
82973: ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
82974: ** If P1 is non-zero, the database constraint counter is incremented 
82975: ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
82976: ** statement counter is incremented (immediate foreign key constraints).
82977: */
82978: case OP_FkCounter: {
82979:   if( db->flags & SQLITE_DeferFKs ){
82980:     db->nDeferredImmCons += pOp->p2;
82981:   }else if( pOp->p1 ){
82982:     db->nDeferredCons += pOp->p2;
82983:   }else{
82984:     p->nFkConstraint += pOp->p2;
82985:   }
82986:   break;
82987: }
82988: 
82989: /* Opcode: FkIfZero P1 P2 * * *
82990: ** Synopsis: if fkctr[P1]==0 goto P2
82991: **
82992: ** This opcode tests if a foreign key constraint-counter is currently zero.
82993: ** If so, jump to instruction P2. Otherwise, fall through to the next 
82994: ** instruction.
82995: **
82996: ** If P1 is non-zero, then the jump is taken if the database constraint-counter
82997: ** is zero (the one that counts deferred constraint violations). If P1 is
82998: ** zero, the jump is taken if the statement constraint-counter is zero
82999: ** (immediate foreign key constraint violations).
83000: */
83001: case OP_FkIfZero: {         /* jump */
83002:   if( pOp->p1 ){
83003:     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
83004:     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
83005:   }else{
83006:     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
83007:     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
83008:   }
83009:   break;
83010: }
83011: #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
83012: 
83013: #ifndef SQLITE_OMIT_AUTOINCREMENT
83014: /* Opcode: MemMax P1 P2 * * *
83015: ** Synopsis: r[P1]=max(r[P1],r[P2])
83016: **
83017: ** P1 is a register in the root frame of this VM (the root frame is
83018: ** different from the current frame if this instruction is being executed
83019: ** within a sub-program). Set the value of register P1 to the maximum of 
83020: ** its current value and the value in register P2.
83021: **
83022: ** This instruction throws an error if the memory cell is not initially
83023: ** an integer.
83024: */
83025: case OP_MemMax: {        /* in2 */
83026:   VdbeFrame *pFrame;
83027:   if( p->pFrame ){
83028:     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
83029:     pIn1 = &pFrame->aMem[pOp->p1];
83030:   }else{
83031:     pIn1 = &aMem[pOp->p1];
83032:   }
83033:   assert( memIsValid(pIn1) );
83034:   sqlite3VdbeMemIntegerify(pIn1);
83035:   pIn2 = &aMem[pOp->p2];
83036:   sqlite3VdbeMemIntegerify(pIn2);
83037:   if( pIn1->u.i<pIn2->u.i){
83038:     pIn1->u.i = pIn2->u.i;
83039:   }
83040:   break;
83041: }
83042: #endif /* SQLITE_OMIT_AUTOINCREMENT */
83043: 
83044: /* Opcode: IfPos P1 P2 P3 * *
83045: ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
83046: **
83047: ** Register P1 must contain an integer.
83048: ** If the value of register P1 is 1 or greater, subtract P3 from the
83049: ** value in P1 and jump to P2.
83050: **
83051: ** If the initial value of register P1 is less than 1, then the
83052: ** value is unchanged and control passes through to the next instruction.
83053: */
83054: case OP_IfPos: {        /* jump, in1 */
83055:   pIn1 = &aMem[pOp->p1];
83056:   assert( pIn1->flags&MEM_Int );
83057:   VdbeBranchTaken( pIn1->u.i>0, 2);
83058:   if( pIn1->u.i>0 ){
83059:     pIn1->u.i -= pOp->p3;
83060:     goto jump_to_p2;
83061:   }
83062:   break;
83063: }
83064: 
83065: /* Opcode: OffsetLimit P1 P2 P3 * *
83066: ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
83067: **
83068: ** This opcode performs a commonly used computation associated with
83069: ** LIMIT and OFFSET process.  r[P1] holds the limit counter.  r[P3]
83070: ** holds the offset counter.  The opcode computes the combined value
83071: ** of the LIMIT and OFFSET and stores that value in r[P2].  The r[P2]
83072: ** value computed is the total number of rows that will need to be
83073: ** visited in order to complete the query.
83074: **
83075: ** If r[P3] is zero or negative, that means there is no OFFSET
83076: ** and r[P2] is set to be the value of the LIMIT, r[P1].
83077: **
83078: ** if r[P1] is zero or negative, that means there is no LIMIT
83079: ** and r[P2] is set to -1. 
83080: **
83081: ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
83082: */
83083: case OP_OffsetLimit: {    /* in1, out2, in3 */
83084:   pIn1 = &aMem[pOp->p1];
83085:   pIn3 = &aMem[pOp->p3];
83086:   pOut = out2Prerelease(p, pOp);
83087:   assert( pIn1->flags & MEM_Int );
83088:   assert( pIn3->flags & MEM_Int );
83089:   pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0);
83090:   break;
83091: }
83092: 
83093: /* Opcode: IfNotZero P1 P2 P3 * *
83094: ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
83095: **
83096: ** Register P1 must contain an integer.  If the content of register P1 is
83097: ** initially nonzero, then subtract P3 from the value in register P1 and
83098: ** jump to P2.  If register P1 is initially zero, leave it unchanged
83099: ** and fall through.
83100: */
83101: case OP_IfNotZero: {        /* jump, in1 */
83102:   pIn1 = &aMem[pOp->p1];
83103:   assert( pIn1->flags&MEM_Int );
83104:   VdbeBranchTaken(pIn1->u.i<0, 2);
83105:   if( pIn1->u.i ){
83106:      pIn1->u.i -= pOp->p3;
83107:      goto jump_to_p2;
83108:   }
83109:   break;
83110: }
83111: 
83112: /* Opcode: DecrJumpZero P1 P2 * * *
83113: ** Synopsis: if (--r[P1])==0 goto P2
83114: **
83115: ** Register P1 must hold an integer.  Decrement the value in register P1
83116: ** then jump to P2 if the new value is exactly zero.
83117: */
83118: case OP_DecrJumpZero: {      /* jump, in1 */
83119:   pIn1 = &aMem[pOp->p1];
83120:   assert( pIn1->flags&MEM_Int );
83121:   pIn1->u.i--;
83122:   VdbeBranchTaken(pIn1->u.i==0, 2);
83123:   if( pIn1->u.i==0 ) goto jump_to_p2;
83124:   break;
83125: }
83126: 
83127: 
83128: /* Opcode: AggStep0 * P2 P3 P4 P5
83129: ** Synopsis: accum=r[P3] step(r[P2@P5])
83130: **
83131: ** Execute the step function for an aggregate.  The
83132: ** function has P5 arguments.   P4 is a pointer to the FuncDef
83133: ** structure that specifies the function.  Register P3 is the
83134: ** accumulator.
83135: **
83136: ** The P5 arguments are taken from register P2 and its
83137: ** successors.
83138: */
83139: /* Opcode: AggStep * P2 P3 P4 P5
83140: ** Synopsis: accum=r[P3] step(r[P2@P5])
83141: **
83142: ** Execute the step function for an aggregate.  The
83143: ** function has P5 arguments.   P4 is a pointer to an sqlite3_context
83144: ** object that is used to run the function.  Register P3 is
83145: ** as the accumulator.
83146: **
83147: ** The P5 arguments are taken from register P2 and its
83148: ** successors.
83149: **
83150: ** This opcode is initially coded as OP_AggStep0.  On first evaluation,
83151: ** the FuncDef stored in P4 is converted into an sqlite3_context and
83152: ** the opcode is changed.  In this way, the initialization of the
83153: ** sqlite3_context only happens once, instead of on each call to the
83154: ** step function.
83155: */
83156: case OP_AggStep0: {
83157:   int n;
83158:   sqlite3_context *pCtx;
83159: 
83160:   assert( pOp->p4type==P4_FUNCDEF );
83161:   n = pOp->p5;
83162:   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83163:   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
83164:   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
83165:   pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
83166:   if( pCtx==0 ) goto no_mem;
83167:   pCtx->pMem = 0;
83168:   pCtx->pFunc = pOp->p4.pFunc;
83169:   pCtx->iOp = (int)(pOp - aOp);
83170:   pCtx->pVdbe = p;
83171:   pCtx->argc = n;
83172:   pOp->p4type = P4_FUNCCTX;
83173:   pOp->p4.pCtx = pCtx;
83174:   pOp->opcode = OP_AggStep;
83175:   /* Fall through into OP_AggStep */
83176: }
83177: case OP_AggStep: {
83178:   int i;
83179:   sqlite3_context *pCtx;
83180:   Mem *pMem;
83181:   Mem t;
83182: 
83183:   assert( pOp->p4type==P4_FUNCCTX );
83184:   pCtx = pOp->p4.pCtx;
83185:   pMem = &aMem[pOp->p3];
83186: 
83187:   /* If this function is inside of a trigger, the register array in aMem[]
83188:   ** might change from one evaluation to the next.  The next block of code
83189:   ** checks to see if the register array has changed, and if so it
83190:   ** reinitializes the relavant parts of the sqlite3_context object */
83191:   if( pCtx->pMem != pMem ){
83192:     pCtx->pMem = pMem;
83193:     for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
83194:   }
83195: 
83196: #ifdef SQLITE_DEBUG
83197:   for(i=0; i<pCtx->argc; i++){
83198:     assert( memIsValid(pCtx->argv[i]) );
83199:     REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
83200:   }
83201: #endif
83202: 
83203:   pMem->n++;
83204:   sqlite3VdbeMemInit(&t, db, MEM_Null);
83205:   pCtx->pOut = &t;
83206:   pCtx->fErrorOrAux = 0;
83207:   pCtx->skipFlag = 0;
83208:   (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
83209:   if( pCtx->fErrorOrAux ){
83210:     if( pCtx->isError ){
83211:       sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
83212:       rc = pCtx->isError;
83213:     }
83214:     sqlite3VdbeMemRelease(&t);
83215:     if( rc ) goto abort_due_to_error;
83216:   }else{
83217:     assert( t.flags==MEM_Null );
83218:   }
83219:   if( pCtx->skipFlag ){
83220:     assert( pOp[-1].opcode==OP_CollSeq );
83221:     i = pOp[-1].p1;
83222:     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
83223:   }
83224:   break;
83225: }
83226: 
83227: /* Opcode: AggFinal P1 P2 * P4 *
83228: ** Synopsis: accum=r[P1] N=P2
83229: **
83230: ** Execute the finalizer function for an aggregate.  P1 is
83231: ** the memory location that is the accumulator for the aggregate.
83232: **
83233: ** P2 is the number of arguments that the step function takes and
83234: ** P4 is a pointer to the FuncDef for this function.  The P2
83235: ** argument is not used by this opcode.  It is only there to disambiguate
83236: ** functions that can take varying numbers of arguments.  The
83237: ** P4 argument is only needed for the degenerate case where
83238: ** the step function was not previously called.
83239: */
83240: case OP_AggFinal: {
83241:   Mem *pMem;
83242:   assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
83243:   pMem = &aMem[pOp->p1];
83244:   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
83245:   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
83246:   if( rc ){
83247:     sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
83248:     goto abort_due_to_error;
83249:   }
83250:   sqlite3VdbeChangeEncoding(pMem, encoding);
83251:   UPDATE_MAX_BLOBSIZE(pMem);
83252:   if( sqlite3VdbeMemTooBig(pMem) ){
83253:     goto too_big;
83254:   }
83255:   break;
83256: }
83257: 
83258: #ifndef SQLITE_OMIT_WAL
83259: /* Opcode: Checkpoint P1 P2 P3 * *
83260: **
83261: ** Checkpoint database P1. This is a no-op if P1 is not currently in
83262: ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
83263: ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
83264: ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
83265: ** WAL after the checkpoint into mem[P3+1] and the number of pages
83266: ** in the WAL that have been checkpointed after the checkpoint
83267: ** completes into mem[P3+2].  However on an error, mem[P3+1] and
83268: ** mem[P3+2] are initialized to -1.
83269: */
83270: case OP_Checkpoint: {
83271:   int i;                          /* Loop counter */
83272:   int aRes[3];                    /* Results */
83273:   Mem *pMem;                      /* Write results here */
83274: 
83275:   assert( p->readOnly==0 );
83276:   aRes[0] = 0;
83277:   aRes[1] = aRes[2] = -1;
83278:   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
83279:        || pOp->p2==SQLITE_CHECKPOINT_FULL
83280:        || pOp->p2==SQLITE_CHECKPOINT_RESTART
83281:        || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
83282:   );
83283:   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
83284:   if( rc ){
83285:     if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
83286:     rc = SQLITE_OK;
83287:     aRes[0] = 1;
83288:   }
83289:   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
83290:     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
83291:   }    
83292:   break;
83293: };  
83294: #endif
83295: 
83296: #ifndef SQLITE_OMIT_PRAGMA
83297: /* Opcode: JournalMode P1 P2 P3 * *
83298: **
83299: ** Change the journal mode of database P1 to P3. P3 must be one of the
83300: ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
83301: ** modes (delete, truncate, persist, off and memory), this is a simple
83302: ** operation. No IO is required.
83303: **
83304: ** If changing into or out of WAL mode the procedure is more complicated.
83305: **
83306: ** Write a string containing the final journal-mode to register P2.
83307: */
83308: case OP_JournalMode: {    /* out2 */
83309:   Btree *pBt;                     /* Btree to change journal mode of */
83310:   Pager *pPager;                  /* Pager associated with pBt */
83311:   int eNew;                       /* New journal mode */
83312:   int eOld;                       /* The old journal mode */
83313: #ifndef SQLITE_OMIT_WAL
83314:   const char *zFilename;          /* Name of database file for pPager */
83315: #endif
83316: 
83317:   pOut = out2Prerelease(p, pOp);
83318:   eNew = pOp->p3;
83319:   assert( eNew==PAGER_JOURNALMODE_DELETE 
83320:        || eNew==PAGER_JOURNALMODE_TRUNCATE 
83321:        || eNew==PAGER_JOURNALMODE_PERSIST 
83322:        || eNew==PAGER_JOURNALMODE_OFF
83323:        || eNew==PAGER_JOURNALMODE_MEMORY
83324:        || eNew==PAGER_JOURNALMODE_WAL
83325:        || eNew==PAGER_JOURNALMODE_QUERY
83326:   );
83327:   assert( pOp->p1>=0 && pOp->p1<db->nDb );
83328:   assert( p->readOnly==0 );
83329: 
83330:   pBt = db->aDb[pOp->p1].pBt;
83331:   pPager = sqlite3BtreePager(pBt);
83332:   eOld = sqlite3PagerGetJournalMode(pPager);
83333:   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
83334:   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
83335: 
83336: #ifndef SQLITE_OMIT_WAL
83337:   zFilename = sqlite3PagerFilename(pPager, 1);
83338: 
83339:   /* Do not allow a transition to journal_mode=WAL for a database
83340:   ** in temporary storage or if the VFS does not support shared memory 
83341:   */
83342:   if( eNew==PAGER_JOURNALMODE_WAL
83343:    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
83344:        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
83345:   ){
83346:     eNew = eOld;
83347:   }
83348: 
83349:   if( (eNew!=eOld)
83350:    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
83351:   ){
83352:     if( !db->autoCommit || db->nVdbeRead>1 ){
83353:       rc = SQLITE_ERROR;
83354:       sqlite3VdbeError(p,
83355:           "cannot change %s wal mode from within a transaction",
83356:           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
83357:       );
83358:       goto abort_due_to_error;
83359:     }else{
83360:  
83361:       if( eOld==PAGER_JOURNALMODE_WAL ){
83362:         /* If leaving WAL mode, close the log file. If successful, the call
83363:         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
83364:         ** file. An EXCLUSIVE lock may still be held on the database file 
83365:         ** after a successful return. 
83366:         */
83367:         rc = sqlite3PagerCloseWal(pPager);
83368:         if( rc==SQLITE_OK ){
83369:           sqlite3PagerSetJournalMode(pPager, eNew);
83370:         }
83371:       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
83372:         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
83373:         ** as an intermediate */
83374:         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
83375:       }
83376:   
83377:       /* Open a transaction on the database file. Regardless of the journal
83378:       ** mode, this transaction always uses a rollback journal.
83379:       */
83380:       assert( sqlite3BtreeIsInTrans(pBt)==0 );
83381:       if( rc==SQLITE_OK ){
83382:         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
83383:       }
83384:     }
83385:   }
83386: #endif /* ifndef SQLITE_OMIT_WAL */
83387: 
83388:   if( rc ) eNew = eOld;
83389:   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
83390: 
83391:   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
83392:   pOut->z = (char *)sqlite3JournalModename(eNew);
83393:   pOut->n = sqlite3Strlen30(pOut->z);
83394:   pOut->enc = SQLITE_UTF8;
83395:   sqlite3VdbeChangeEncoding(pOut, encoding);
83396:   if( rc ) goto abort_due_to_error;
83397:   break;
83398: };
83399: #endif /* SQLITE_OMIT_PRAGMA */
83400: 
83401: #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
83402: /* Opcode: Vacuum * * * * *
83403: **
83404: ** Vacuum the entire database.  This opcode will cause other virtual
83405: ** machines to be created and run.  It may not be called from within
83406: ** a transaction.
83407: */
83408: case OP_Vacuum: {
83409:   assert( p->readOnly==0 );
83410:   rc = sqlite3RunVacuum(&p->zErrMsg, db);
83411:   if( rc ) goto abort_due_to_error;
83412:   break;
83413: }
83414: #endif
83415: 
83416: #if !defined(SQLITE_OMIT_AUTOVACUUM)
83417: /* Opcode: IncrVacuum P1 P2 * * *
83418: **
83419: ** Perform a single step of the incremental vacuum procedure on
83420: ** the P1 database. If the vacuum has finished, jump to instruction
83421: ** P2. Otherwise, fall through to the next instruction.
83422: */
83423: case OP_IncrVacuum: {        /* jump */
83424:   Btree *pBt;
83425: 
83426:   assert( pOp->p1>=0 && pOp->p1<db->nDb );
83427:   assert( DbMaskTest(p->btreeMask, pOp->p1) );
83428:   assert( p->readOnly==0 );
83429:   pBt = db->aDb[pOp->p1].pBt;
83430:   rc = sqlite3BtreeIncrVacuum(pBt);
83431:   VdbeBranchTaken(rc==SQLITE_DONE,2);
83432:   if( rc ){
83433:     if( rc!=SQLITE_DONE ) goto abort_due_to_error;
83434:     rc = SQLITE_OK;
83435:     goto jump_to_p2;
83436:   }
83437:   break;
83438: }
83439: #endif
83440: 
83441: /* Opcode: Expire P1 * * * *
83442: **
83443: ** Cause precompiled statements to expire.  When an expired statement
83444: ** is executed using sqlite3_step() it will either automatically
83445: ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
83446: ** or it will fail with SQLITE_SCHEMA.
83447: ** 
83448: ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
83449: ** then only the currently executing statement is expired.
83450: */
83451: case OP_Expire: {
83452:   if( !pOp->p1 ){
83453:     sqlite3ExpirePreparedStatements(db);
83454:   }else{
83455:     p->expired = 1;
83456:   }
83457:   break;
83458: }
83459: 
83460: #ifndef SQLITE_OMIT_SHARED_CACHE
83461: /* Opcode: TableLock P1 P2 P3 P4 *
83462: ** Synopsis: iDb=P1 root=P2 write=P3
83463: **
83464: ** Obtain a lock on a particular table. This instruction is only used when
83465: ** the shared-cache feature is enabled. 
83466: **
83467: ** P1 is the index of the database in sqlite3.aDb[] of the database
83468: ** on which the lock is acquired.  A readlock is obtained if P3==0 or
83469: ** a write lock if P3==1.
83470: **
83471: ** P2 contains the root-page of the table to lock.
83472: **
83473: ** P4 contains a pointer to the name of the table being locked. This is only
83474: ** used to generate an error message if the lock cannot be obtained.
83475: */
83476: case OP_TableLock: {
83477:   u8 isWriteLock = (u8)pOp->p3;
83478:   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
83479:     int p1 = pOp->p1; 
83480:     assert( p1>=0 && p1<db->nDb );
83481:     assert( DbMaskTest(p->btreeMask, p1) );
83482:     assert( isWriteLock==0 || isWriteLock==1 );
83483:     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
83484:     if( rc ){
83485:       if( (rc&0xFF)==SQLITE_LOCKED ){
83486:         const char *z = pOp->p4.z;
83487:         sqlite3VdbeError(p, "database table is locked: %s", z);
83488:       }
83489:       goto abort_due_to_error;
83490:     }
83491:   }
83492:   break;
83493: }
83494: #endif /* SQLITE_OMIT_SHARED_CACHE */
83495: 
83496: #ifndef SQLITE_OMIT_VIRTUALTABLE
83497: /* Opcode: VBegin * * * P4 *
83498: **
83499: ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
83500: ** xBegin method for that table.
83501: **
83502: ** Also, whether or not P4 is set, check that this is not being called from
83503: ** within a callback to a virtual table xSync() method. If it is, the error
83504: ** code will be set to SQLITE_LOCKED.
83505: */
83506: case OP_VBegin: {
83507:   VTable *pVTab;
83508:   pVTab = pOp->p4.pVtab;
83509:   rc = sqlite3VtabBegin(db, pVTab);
83510:   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
83511:   if( rc ) goto abort_due_to_error;
83512:   break;
83513: }
83514: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83515: 
83516: #ifndef SQLITE_OMIT_VIRTUALTABLE
83517: /* Opcode: VCreate P1 P2 * * *
83518: **
83519: ** P2 is a register that holds the name of a virtual table in database 
83520: ** P1. Call the xCreate method for that table.
83521: */
83522: case OP_VCreate: {
83523:   Mem sMem;          /* For storing the record being decoded */
83524:   const char *zTab;  /* Name of the virtual table */
83525: 
83526:   memset(&sMem, 0, sizeof(sMem));
83527:   sMem.db = db;
83528:   /* Because P2 is always a static string, it is impossible for the
83529:   ** sqlite3VdbeMemCopy() to fail */
83530:   assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
83531:   assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
83532:   rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
83533:   assert( rc==SQLITE_OK );
83534:   zTab = (const char*)sqlite3_value_text(&sMem);
83535:   assert( zTab || db->mallocFailed );
83536:   if( zTab ){
83537:     rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
83538:   }
83539:   sqlite3VdbeMemRelease(&sMem);
83540:   if( rc ) goto abort_due_to_error;
83541:   break;
83542: }
83543: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83544: 
83545: #ifndef SQLITE_OMIT_VIRTUALTABLE
83546: /* Opcode: VDestroy P1 * * P4 *
83547: **
83548: ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
83549: ** of that table.
83550: */
83551: case OP_VDestroy: {
83552:   db->nVDestroy++;
83553:   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
83554:   db->nVDestroy--;
83555:   if( rc ) goto abort_due_to_error;
83556:   break;
83557: }
83558: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83559: 
83560: #ifndef SQLITE_OMIT_VIRTUALTABLE
83561: /* Opcode: VOpen P1 * * P4 *
83562: **
83563: ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83564: ** P1 is a cursor number.  This opcode opens a cursor to the virtual
83565: ** table and stores that cursor in P1.
83566: */
83567: case OP_VOpen: {
83568:   VdbeCursor *pCur;
83569:   sqlite3_vtab_cursor *pVCur;
83570:   sqlite3_vtab *pVtab;
83571:   const sqlite3_module *pModule;
83572: 
83573:   assert( p->bIsReader );
83574:   pCur = 0;
83575:   pVCur = 0;
83576:   pVtab = pOp->p4.pVtab->pVtab;
83577:   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83578:     rc = SQLITE_LOCKED;
83579:     goto abort_due_to_error;
83580:   }
83581:   pModule = pVtab->pModule;
83582:   rc = pModule->xOpen(pVtab, &pVCur);
83583:   sqlite3VtabImportErrmsg(p, pVtab);
83584:   if( rc ) goto abort_due_to_error;
83585: 
83586:   /* Initialize sqlite3_vtab_cursor base class */
83587:   pVCur->pVtab = pVtab;
83588: 
83589:   /* Initialize vdbe cursor object */
83590:   pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
83591:   if( pCur ){
83592:     pCur->uc.pVCur = pVCur;
83593:     pVtab->nRef++;
83594:   }else{
83595:     assert( db->mallocFailed );
83596:     pModule->xClose(pVCur);
83597:     goto no_mem;
83598:   }
83599:   break;
83600: }
83601: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83602: 
83603: #ifndef SQLITE_OMIT_VIRTUALTABLE
83604: /* Opcode: VFilter P1 P2 P3 P4 *
83605: ** Synopsis: iplan=r[P3] zplan='P4'
83606: **
83607: ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
83608: ** the filtered result set is empty.
83609: **
83610: ** P4 is either NULL or a string that was generated by the xBestIndex
83611: ** method of the module.  The interpretation of the P4 string is left
83612: ** to the module implementation.
83613: **
83614: ** This opcode invokes the xFilter method on the virtual table specified
83615: ** by P1.  The integer query plan parameter to xFilter is stored in register
83616: ** P3. Register P3+1 stores the argc parameter to be passed to the
83617: ** xFilter method. Registers P3+2..P3+1+argc are the argc
83618: ** additional parameters which are passed to
83619: ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
83620: **
83621: ** A jump is made to P2 if the result set after filtering would be empty.
83622: */
83623: case OP_VFilter: {   /* jump */
83624:   int nArg;
83625:   int iQuery;
83626:   const sqlite3_module *pModule;
83627:   Mem *pQuery;
83628:   Mem *pArgc;
83629:   sqlite3_vtab_cursor *pVCur;
83630:   sqlite3_vtab *pVtab;
83631:   VdbeCursor *pCur;
83632:   int res;
83633:   int i;
83634:   Mem **apArg;
83635: 
83636:   pQuery = &aMem[pOp->p3];
83637:   pArgc = &pQuery[1];
83638:   pCur = p->apCsr[pOp->p1];
83639:   assert( memIsValid(pQuery) );
83640:   REGISTER_TRACE(pOp->p3, pQuery);
83641:   assert( pCur->eCurType==CURTYPE_VTAB );
83642:   pVCur = pCur->uc.pVCur;
83643:   pVtab = pVCur->pVtab;
83644:   pModule = pVtab->pModule;
83645: 
83646:   /* Grab the index number and argc parameters */
83647:   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
83648:   nArg = (int)pArgc->u.i;
83649:   iQuery = (int)pQuery->u.i;
83650: 
83651:   /* Invoke the xFilter method */
83652:   res = 0;
83653:   apArg = p->apArg;
83654:   for(i = 0; i<nArg; i++){
83655:     apArg[i] = &pArgc[i+1];
83656:   }
83657:   rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
83658:   sqlite3VtabImportErrmsg(p, pVtab);
83659:   if( rc ) goto abort_due_to_error;
83660:   res = pModule->xEof(pVCur);
83661:   pCur->nullRow = 0;
83662:   VdbeBranchTaken(res!=0,2);
83663:   if( res ) goto jump_to_p2;
83664:   break;
83665: }
83666: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83667: 
83668: #ifndef SQLITE_OMIT_VIRTUALTABLE
83669: /* Opcode: VColumn P1 P2 P3 * *
83670: ** Synopsis: r[P3]=vcolumn(P2)
83671: **
83672: ** Store the value of the P2-th column of
83673: ** the row of the virtual-table that the 
83674: ** P1 cursor is pointing to into register P3.
83675: */
83676: case OP_VColumn: {
83677:   sqlite3_vtab *pVtab;
83678:   const sqlite3_module *pModule;
83679:   Mem *pDest;
83680:   sqlite3_context sContext;
83681: 
83682:   VdbeCursor *pCur = p->apCsr[pOp->p1];
83683:   assert( pCur->eCurType==CURTYPE_VTAB );
83684:   assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83685:   pDest = &aMem[pOp->p3];
83686:   memAboutToChange(p, pDest);
83687:   if( pCur->nullRow ){
83688:     sqlite3VdbeMemSetNull(pDest);
83689:     break;
83690:   }
83691:   pVtab = pCur->uc.pVCur->pVtab;
83692:   pModule = pVtab->pModule;
83693:   assert( pModule->xColumn );
83694:   memset(&sContext, 0, sizeof(sContext));
83695:   sContext.pOut = pDest;
83696:   MemSetTypeFlag(pDest, MEM_Null);
83697:   rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
83698:   sqlite3VtabImportErrmsg(p, pVtab);
83699:   if( sContext.isError ){
83700:     rc = sContext.isError;
83701:   }
83702:   sqlite3VdbeChangeEncoding(pDest, encoding);
83703:   REGISTER_TRACE(pOp->p3, pDest);
83704:   UPDATE_MAX_BLOBSIZE(pDest);
83705: 
83706:   if( sqlite3VdbeMemTooBig(pDest) ){
83707:     goto too_big;
83708:   }
83709:   if( rc ) goto abort_due_to_error;
83710:   break;
83711: }
83712: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83713: 
83714: #ifndef SQLITE_OMIT_VIRTUALTABLE
83715: /* Opcode: VNext P1 P2 * * *
83716: **
83717: ** Advance virtual table P1 to the next row in its result set and
83718: ** jump to instruction P2.  Or, if the virtual table has reached
83719: ** the end of its result set, then fall through to the next instruction.
83720: */
83721: case OP_VNext: {   /* jump */
83722:   sqlite3_vtab *pVtab;
83723:   const sqlite3_module *pModule;
83724:   int res;
83725:   VdbeCursor *pCur;
83726: 
83727:   res = 0;
83728:   pCur = p->apCsr[pOp->p1];
83729:   assert( pCur->eCurType==CURTYPE_VTAB );
83730:   if( pCur->nullRow ){
83731:     break;
83732:   }
83733:   pVtab = pCur->uc.pVCur->pVtab;
83734:   pModule = pVtab->pModule;
83735:   assert( pModule->xNext );
83736: 
83737:   /* Invoke the xNext() method of the module. There is no way for the
83738:   ** underlying implementation to return an error if one occurs during
83739:   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
83740:   ** data is available) and the error code returned when xColumn or
83741:   ** some other method is next invoked on the save virtual table cursor.
83742:   */
83743:   rc = pModule->xNext(pCur->uc.pVCur);
83744:   sqlite3VtabImportErrmsg(p, pVtab);
83745:   if( rc ) goto abort_due_to_error;
83746:   res = pModule->xEof(pCur->uc.pVCur);
83747:   VdbeBranchTaken(!res,2);
83748:   if( !res ){
83749:     /* If there is data, jump to P2 */
83750:     goto jump_to_p2_and_check_for_interrupt;
83751:   }
83752:   goto check_for_interrupt;
83753: }
83754: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83755: 
83756: #ifndef SQLITE_OMIT_VIRTUALTABLE
83757: /* Opcode: VRename P1 * * P4 *
83758: **
83759: ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83760: ** This opcode invokes the corresponding xRename method. The value
83761: ** in register P1 is passed as the zName argument to the xRename method.
83762: */
83763: case OP_VRename: {
83764:   sqlite3_vtab *pVtab;
83765:   Mem *pName;
83766: 
83767:   pVtab = pOp->p4.pVtab->pVtab;
83768:   pName = &aMem[pOp->p1];
83769:   assert( pVtab->pModule->xRename );
83770:   assert( memIsValid(pName) );
83771:   assert( p->readOnly==0 );
83772:   REGISTER_TRACE(pOp->p1, pName);
83773:   assert( pName->flags & MEM_Str );
83774:   testcase( pName->enc==SQLITE_UTF8 );
83775:   testcase( pName->enc==SQLITE_UTF16BE );
83776:   testcase( pName->enc==SQLITE_UTF16LE );
83777:   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
83778:   if( rc ) goto abort_due_to_error;
83779:   rc = pVtab->pModule->xRename(pVtab, pName->z);
83780:   sqlite3VtabImportErrmsg(p, pVtab);
83781:   p->expired = 0;
83782:   if( rc ) goto abort_due_to_error;
83783:   break;
83784: }
83785: #endif
83786: 
83787: #ifndef SQLITE_OMIT_VIRTUALTABLE
83788: /* Opcode: VUpdate P1 P2 P3 P4 P5
83789: ** Synopsis: data=r[P3@P2]
83790: **
83791: ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83792: ** This opcode invokes the corresponding xUpdate method. P2 values
83793: ** are contiguous memory cells starting at P3 to pass to the xUpdate 
83794: ** invocation. The value in register (P3+P2-1) corresponds to the 
83795: ** p2th element of the argv array passed to xUpdate.
83796: **
83797: ** The xUpdate method will do a DELETE or an INSERT or both.
83798: ** The argv[0] element (which corresponds to memory cell P3)
83799: ** is the rowid of a row to delete.  If argv[0] is NULL then no 
83800: ** deletion occurs.  The argv[1] element is the rowid of the new 
83801: ** row.  This can be NULL to have the virtual table select the new 
83802: ** rowid for itself.  The subsequent elements in the array are 
83803: ** the values of columns in the new row.
83804: **
83805: ** If P2==1 then no insert is performed.  argv[0] is the rowid of
83806: ** a row to delete.
83807: **
83808: ** P1 is a boolean flag. If it is set to true and the xUpdate call
83809: ** is successful, then the value returned by sqlite3_last_insert_rowid() 
83810: ** is set to the value of the rowid for the row just inserted.
83811: **
83812: ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
83813: ** apply in the case of a constraint failure on an insert or update.
83814: */
83815: case OP_VUpdate: {
83816:   sqlite3_vtab *pVtab;
83817:   const sqlite3_module *pModule;
83818:   int nArg;
83819:   int i;
83820:   sqlite_int64 rowid;
83821:   Mem **apArg;
83822:   Mem *pX;
83823: 
83824:   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
83825:        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
83826:   );
83827:   assert( p->readOnly==0 );
83828:   pVtab = pOp->p4.pVtab->pVtab;
83829:   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83830:     rc = SQLITE_LOCKED;
83831:     goto abort_due_to_error;
83832:   }
83833:   pModule = pVtab->pModule;
83834:   nArg = pOp->p2;
83835:   assert( pOp->p4type==P4_VTAB );
83836:   if( ALWAYS(pModule->xUpdate) ){
83837:     u8 vtabOnConflict = db->vtabOnConflict;
83838:     apArg = p->apArg;
83839:     pX = &aMem[pOp->p3];
83840:     for(i=0; i<nArg; i++){
83841:       assert( memIsValid(pX) );
83842:       memAboutToChange(p, pX);
83843:       apArg[i] = pX;
83844:       pX++;
83845:     }
83846:     db->vtabOnConflict = pOp->p5;
83847:     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
83848:     db->vtabOnConflict = vtabOnConflict;
83849:     sqlite3VtabImportErrmsg(p, pVtab);
83850:     if( rc==SQLITE_OK && pOp->p1 ){
83851:       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
83852:       db->lastRowid = lastRowid = rowid;
83853:     }
83854:     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
83855:       if( pOp->p5==OE_Ignore ){
83856:         rc = SQLITE_OK;
83857:       }else{
83858:         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
83859:       }
83860:     }else{
83861:       p->nChange++;
83862:     }
83863:     if( rc ) goto abort_due_to_error;
83864:   }
83865:   break;
83866: }
83867: #endif /* SQLITE_OMIT_VIRTUALTABLE */
83868: 
83869: #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
83870: /* Opcode: Pagecount P1 P2 * * *
83871: **
83872: ** Write the current number of pages in database P1 to memory cell P2.
83873: */
83874: case OP_Pagecount: {            /* out2 */
83875:   pOut = out2Prerelease(p, pOp);
83876:   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
83877:   break;
83878: }
83879: #endif
83880: 
83881: 
83882: #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
83883: /* Opcode: MaxPgcnt P1 P2 P3 * *
83884: **
83885: ** Try to set the maximum page count for database P1 to the value in P3.
83886: ** Do not let the maximum page count fall below the current page count and
83887: ** do not change the maximum page count value if P3==0.
83888: **
83889: ** Store the maximum page count after the change in register P2.
83890: */
83891: case OP_MaxPgcnt: {            /* out2 */
83892:   unsigned int newMax;
83893:   Btree *pBt;
83894: 
83895:   pOut = out2Prerelease(p, pOp);
83896:   pBt = db->aDb[pOp->p1].pBt;
83897:   newMax = 0;
83898:   if( pOp->p3 ){
83899:     newMax = sqlite3BtreeLastPage(pBt);
83900:     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
83901:   }
83902:   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
83903:   break;
83904: }
83905: #endif
83906: 
83907: 
83908: /* Opcode: Init * P2 * P4 *
83909: ** Synopsis:  Start at P2
83910: **
83911: ** Programs contain a single instance of this opcode as the very first
83912: ** opcode.
83913: **
83914: ** If tracing is enabled (by the sqlite3_trace()) interface, then
83915: ** the UTF-8 string contained in P4 is emitted on the trace callback.
83916: ** Or if P4 is blank, use the string returned by sqlite3_sql().
83917: **
83918: ** If P2 is not zero, jump to instruction P2.
83919: */
83920: case OP_Init: {          /* jump */
83921:   char *zTrace;
83922: 
83923:   /* If the P4 argument is not NULL, then it must be an SQL comment string.
83924:   ** The "--" string is broken up to prevent false-positives with srcck1.c.
83925:   **
83926:   ** This assert() provides evidence for:
83927:   ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
83928:   ** would have been returned by the legacy sqlite3_trace() interface by
83929:   ** using the X argument when X begins with "--" and invoking
83930:   ** sqlite3_expanded_sql(P) otherwise.
83931:   */
83932:   assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
83933: 
83934: #ifndef SQLITE_OMIT_TRACE
83935:   if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
83936:    && !p->doingRerun
83937:    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83938:   ){
83939: #ifndef SQLITE_OMIT_DEPRECATED
83940:     if( db->mTrace & SQLITE_TRACE_LEGACY ){
83941:       void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
83942:       char *z = sqlite3VdbeExpandSql(p, zTrace);
83943:       x(db->pTraceArg, z);
83944:       sqlite3_free(z);
83945:     }else
83946: #endif
83947:     {
83948:       (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
83949:     }
83950:   }
83951: #ifdef SQLITE_USE_FCNTL_TRACE
83952:   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
83953:   if( zTrace ){
83954:     int i;
83955:     for(i=0; i<db->nDb; i++){
83956:       if( DbMaskTest(p->btreeMask, i)==0 ) continue;
83957:       sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
83958:     }
83959:   }
83960: #endif /* SQLITE_USE_FCNTL_TRACE */
83961: #ifdef SQLITE_DEBUG
83962:   if( (db->flags & SQLITE_SqlTrace)!=0
83963:    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83964:   ){
83965:     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
83966:   }
83967: #endif /* SQLITE_DEBUG */
83968: #endif /* SQLITE_OMIT_TRACE */
83969:   if( pOp->p2 ) goto jump_to_p2;
83970:   break;
83971: }
83972: 
83973: #ifdef SQLITE_ENABLE_CURSOR_HINTS
83974: /* Opcode: CursorHint P1 * * P4 *
83975: **
83976: ** Provide a hint to cursor P1 that it only needs to return rows that
83977: ** satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
83978: ** to values currently held in registers.  TK_COLUMN terms in the P4
83979: ** expression refer to columns in the b-tree to which cursor P1 is pointing.
83980: */
83981: case OP_CursorHint: {
83982:   VdbeCursor *pC;
83983: 
83984:   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83985:   assert( pOp->p4type==P4_EXPR );
83986:   pC = p->apCsr[pOp->p1];
83987:   if( pC ){
83988:     assert( pC->eCurType==CURTYPE_BTREE );
83989:     sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
83990:                            pOp->p4.pExpr, aMem);
83991:   }
83992:   break;
83993: }
83994: #endif /* SQLITE_ENABLE_CURSOR_HINTS */
83995: 
83996: /* Opcode: Noop * * * * *
83997: **
83998: ** Do nothing.  This instruction is often useful as a jump
83999: ** destination.
84000: */
84001: /*
84002: ** The magic Explain opcode are only inserted when explain==2 (which
84003: ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
84004: ** This opcode records information from the optimizer.  It is the
84005: ** the same as a no-op.  This opcodesnever appears in a real VM program.
84006: */
84007: default: {          /* This is really OP_Noop and OP_Explain */
84008:   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
84009:   break;
84010: }
84011: 
84012: /*****************************************************************************
84013: ** The cases of the switch statement above this line should all be indented
84014: ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
84015: ** readability.  From this point on down, the normal indentation rules are
84016: ** restored.
84017: *****************************************************************************/
84018:     }
84019: 
84020: #ifdef VDBE_PROFILE
84021:     {
84022:       u64 endTime = sqlite3Hwtime();
84023:       if( endTime>start ) pOrigOp->cycles += endTime - start;
84024:       pOrigOp->cnt++;
84025:     }
84026: #endif
84027: 
84028:     /* The following code adds nothing to the actual functionality
84029:     ** of the program.  It is only here for testing and debugging.
84030:     ** On the other hand, it does burn CPU cycles every time through
84031:     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
84032:     */
84033: #ifndef NDEBUG
84034:     assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
84035: 
84036: #ifdef SQLITE_DEBUG
84037:     if( db->flags & SQLITE_VdbeTrace ){
84038:       u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
84039:       if( rc!=0 ) printf("rc=%d\n",rc);
84040:       if( opProperty & (OPFLG_OUT2) ){
84041:         registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
84042:       }
84043:       if( opProperty & OPFLG_OUT3 ){
84044:         registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
84045:       }
84046:     }
84047: #endif  /* SQLITE_DEBUG */
84048: #endif  /* NDEBUG */
84049:   }  /* The end of the for(;;) loop the loops through opcodes */
84050: 
84051:   /* If we reach this point, it means that execution is finished with
84052:   ** an error of some kind.
84053:   */
84054: abort_due_to_error:
84055:   if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
84056:   assert( rc );
84057:   if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
84058:     sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84059:   }
84060:   p->rc = rc;
84061:   sqlite3SystemError(db, rc);
84062:   testcase( sqlite3GlobalConfig.xLog!=0 );
84063:   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
84064:                    (int)(pOp - aOp), p->zSql, p->zErrMsg);
84065:   sqlite3VdbeHalt(p);
84066:   if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
84067:   rc = SQLITE_ERROR;
84068:   if( resetSchemaOnFault>0 ){
84069:     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
84070:   }
84071: 
84072:   /* This is the only way out of this procedure.  We have to
84073:   ** release the mutexes on btrees that were acquired at the
84074:   ** top. */
84075: vdbe_return:
84076:   db->lastRowid = lastRowid;
84077:   testcase( nVmStep>0 );
84078:   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
84079:   sqlite3VdbeLeave(p);
84080:   assert( rc!=SQLITE_OK || nExtraDelete==0 
84081:        || sqlite3_strlike("DELETE%",p->zSql,0)!=0 
84082:   );
84083:   return rc;
84084: 
84085:   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
84086:   ** is encountered.
84087:   */
84088: too_big:
84089:   sqlite3VdbeError(p, "string or blob too big");
84090:   rc = SQLITE_TOOBIG;
84091:   goto abort_due_to_error;
84092: 
84093:   /* Jump to here if a malloc() fails.
84094:   */
84095: no_mem:
84096:   sqlite3OomFault(db);
84097:   sqlite3VdbeError(p, "out of memory");
84098:   rc = SQLITE_NOMEM_BKPT;
84099:   goto abort_due_to_error;
84100: 
84101:   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
84102:   ** flag.
84103:   */
84104: abort_due_to_interrupt:
84105:   assert( db->u1.isInterrupted );
84106:   rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
84107:   p->rc = rc;
84108:   sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
84109:   goto abort_due_to_error;
84110: }
84111: 
84112: 
84113: /************** End of vdbe.c ************************************************/
84114: /************** Begin file vdbeblob.c ****************************************/
84115: /*
84116: ** 2007 May 1
84117: **
84118: ** The author disclaims copyright to this source code.  In place of
84119: ** a legal notice, here is a blessing:
84120: **
84121: **    May you do good and not evil.
84122: **    May you find forgiveness for yourself and forgive others.
84123: **    May you share freely, never taking more than you give.
84124: **
84125: *************************************************************************
84126: **
84127: ** This file contains code used to implement incremental BLOB I/O.
84128: */
84129: 
84130: /* #include "sqliteInt.h" */
84131: /* #include "vdbeInt.h" */
84132: 
84133: #ifndef SQLITE_OMIT_INCRBLOB
84134: 
84135: /*
84136: ** Valid sqlite3_blob* handles point to Incrblob structures.
84137: */
84138: typedef struct Incrblob Incrblob;
84139: struct Incrblob {
84140:   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
84141:   int nByte;              /* Size of open blob, in bytes */
84142:   int iOffset;            /* Byte offset of blob in cursor data */
84143:   int iCol;               /* Table column this handle is open on */
84144:   BtCursor *pCsr;         /* Cursor pointing at blob row */
84145:   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
84146:   sqlite3 *db;            /* The associated database */
84147:   char *zDb;              /* Database name */
84148:   Table *pTab;            /* Table object */
84149: };
84150: 
84151: 
84152: /*
84153: ** This function is used by both blob_open() and blob_reopen(). It seeks
84154: ** the b-tree cursor associated with blob handle p to point to row iRow.
84155: ** If successful, SQLITE_OK is returned and subsequent calls to
84156: ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
84157: **
84158: ** If an error occurs, or if the specified row does not exist or does not
84159: ** contain a value of type TEXT or BLOB in the column nominated when the
84160: ** blob handle was opened, then an error code is returned and *pzErr may
84161: ** be set to point to a buffer containing an error message. It is the
84162: ** responsibility of the caller to free the error message buffer using
84163: ** sqlite3DbFree().
84164: **
84165: ** If an error does occur, then the b-tree cursor is closed. All subsequent
84166: ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
84167: ** immediately return SQLITE_ABORT.
84168: */
84169: static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
84170:   int rc;                         /* Error code */
84171:   char *zErr = 0;                 /* Error message */
84172:   Vdbe *v = (Vdbe *)p->pStmt;
84173: 
84174:   /* Set the value of the SQL statements only variable to integer iRow. 
84175:   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
84176:   ** triggering asserts related to mutexes.
84177:   */
84178:   assert( v->aVar[0].flags&MEM_Int );
84179:   v->aVar[0].u.i = iRow;
84180: 
84181:   rc = sqlite3_step(p->pStmt);
84182:   if( rc==SQLITE_ROW ){
84183:     VdbeCursor *pC = v->apCsr[0];
84184:     u32 type = pC->aType[p->iCol];
84185:     if( type<12 ){
84186:       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
84187:           type==0?"null": type==7?"real": "integer"
84188:       );
84189:       rc = SQLITE_ERROR;
84190:       sqlite3_finalize(p->pStmt);
84191:       p->pStmt = 0;
84192:     }else{
84193:       p->iOffset = pC->aType[p->iCol + pC->nField];
84194:       p->nByte = sqlite3VdbeSerialTypeLen(type);
84195:       p->pCsr =  pC->uc.pCursor;
84196:       sqlite3BtreeIncrblobCursor(p->pCsr);
84197:     }
84198:   }
84199: 
84200:   if( rc==SQLITE_ROW ){
84201:     rc = SQLITE_OK;
84202:   }else if( p->pStmt ){
84203:     rc = sqlite3_finalize(p->pStmt);
84204:     p->pStmt = 0;
84205:     if( rc==SQLITE_OK ){
84206:       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
84207:       rc = SQLITE_ERROR;
84208:     }else{
84209:       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
84210:     }
84211:   }
84212: 
84213:   assert( rc!=SQLITE_OK || zErr==0 );
84214:   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
84215: 
84216:   *pzErr = zErr;
84217:   return rc;
84218: }
84219: 
84220: /*
84221: ** Open a blob handle.
84222: */
84223: SQLITE_API int sqlite3_blob_open(
84224:   sqlite3* db,            /* The database connection */
84225:   const char *zDb,        /* The attached database containing the blob */
84226:   const char *zTable,     /* The table containing the blob */
84227:   const char *zColumn,    /* The column containing the blob */
84228:   sqlite_int64 iRow,      /* The row containing the glob */
84229:   int flags,              /* True -> read/write access, false -> read-only */
84230:   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
84231: ){
84232:   int nAttempt = 0;
84233:   int iCol;               /* Index of zColumn in row-record */
84234:   int rc = SQLITE_OK;
84235:   char *zErr = 0;
84236:   Table *pTab;
84237:   Parse *pParse = 0;
84238:   Incrblob *pBlob = 0;
84239: 
84240: #ifdef SQLITE_ENABLE_API_ARMOR
84241:   if( ppBlob==0 ){
84242:     return SQLITE_MISUSE_BKPT;
84243:   }
84244: #endif
84245:   *ppBlob = 0;
84246: #ifdef SQLITE_ENABLE_API_ARMOR
84247:   if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
84248:     return SQLITE_MISUSE_BKPT;
84249:   }
84250: #endif
84251:   flags = !!flags;                /* flags = (flags ? 1 : 0); */
84252: 
84253:   sqlite3_mutex_enter(db->mutex);
84254: 
84255:   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
84256:   if( !pBlob ) goto blob_open_out;
84257:   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
84258:   if( !pParse ) goto blob_open_out;
84259: 
84260:   do {
84261:     memset(pParse, 0, sizeof(Parse));
84262:     pParse->db = db;
84263:     sqlite3DbFree(db, zErr);
84264:     zErr = 0;
84265: 
84266:     sqlite3BtreeEnterAll(db);
84267:     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
84268:     if( pTab && IsVirtual(pTab) ){
84269:       pTab = 0;
84270:       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
84271:     }
84272:     if( pTab && !HasRowid(pTab) ){
84273:       pTab = 0;
84274:       sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
84275:     }
84276: #ifndef SQLITE_OMIT_VIEW
84277:     if( pTab && pTab->pSelect ){
84278:       pTab = 0;
84279:       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
84280:     }
84281: #endif
84282:     if( !pTab ){
84283:       if( pParse->zErrMsg ){
84284:         sqlite3DbFree(db, zErr);
84285:         zErr = pParse->zErrMsg;
84286:         pParse->zErrMsg = 0;
84287:       }
84288:       rc = SQLITE_ERROR;
84289:       sqlite3BtreeLeaveAll(db);
84290:       goto blob_open_out;
84291:     }
84292:     pBlob->pTab = pTab;
84293:     pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zName;
84294: 
84295:     /* Now search pTab for the exact column. */
84296:     for(iCol=0; iCol<pTab->nCol; iCol++) {
84297:       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
84298:         break;
84299:       }
84300:     }
84301:     if( iCol==pTab->nCol ){
84302:       sqlite3DbFree(db, zErr);
84303:       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
84304:       rc = SQLITE_ERROR;
84305:       sqlite3BtreeLeaveAll(db);
84306:       goto blob_open_out;
84307:     }
84308: 
84309:     /* If the value is being opened for writing, check that the
84310:     ** column is not indexed, and that it is not part of a foreign key. 
84311:     ** It is against the rules to open a column to which either of these
84312:     ** descriptions applies for writing.  */
84313:     if( flags ){
84314:       const char *zFault = 0;
84315:       Index *pIdx;
84316: #ifndef SQLITE_OMIT_FOREIGN_KEY
84317:       if( db->flags&SQLITE_ForeignKeys ){
84318:         /* Check that the column is not part of an FK child key definition. It
84319:         ** is not necessary to check if it is part of a parent key, as parent
84320:         ** key columns must be indexed. The check below will pick up this 
84321:         ** case.  */
84322:         FKey *pFKey;
84323:         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
84324:           int j;
84325:           for(j=0; j<pFKey->nCol; j++){
84326:             if( pFKey->aCol[j].iFrom==iCol ){
84327:               zFault = "foreign key";
84328:             }
84329:           }
84330:         }
84331:       }
84332: #endif
84333:       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84334:         int j;
84335:         for(j=0; j<pIdx->nKeyCol; j++){
84336:           /* FIXME: Be smarter about indexes that use expressions */
84337:           if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
84338:             zFault = "indexed";
84339:           }
84340:         }
84341:       }
84342:       if( zFault ){
84343:         sqlite3DbFree(db, zErr);
84344:         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
84345:         rc = SQLITE_ERROR;
84346:         sqlite3BtreeLeaveAll(db);
84347:         goto blob_open_out;
84348:       }
84349:     }
84350: 
84351:     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
84352:     assert( pBlob->pStmt || db->mallocFailed );
84353:     if( pBlob->pStmt ){
84354:       
84355:       /* This VDBE program seeks a btree cursor to the identified 
84356:       ** db/table/row entry. The reason for using a vdbe program instead
84357:       ** of writing code to use the b-tree layer directly is that the
84358:       ** vdbe program will take advantage of the various transaction,
84359:       ** locking and error handling infrastructure built into the vdbe.
84360:       **
84361:       ** After seeking the cursor, the vdbe executes an OP_ResultRow.
84362:       ** Code external to the Vdbe then "borrows" the b-tree cursor and
84363:       ** uses it to implement the blob_read(), blob_write() and 
84364:       ** blob_bytes() functions.
84365:       **
84366:       ** The sqlite3_blob_close() function finalizes the vdbe program,
84367:       ** which closes the b-tree cursor and (possibly) commits the 
84368:       ** transaction.
84369:       */
84370:       static const int iLn = VDBE_OFFSET_LINENO(2);
84371:       static const VdbeOpList openBlob[] = {
84372:         {OP_TableLock,      0, 0, 0},  /* 0: Acquire a read or write lock */
84373:         {OP_OpenRead,       0, 0, 0},  /* 1: Open a cursor */
84374:         {OP_Variable,       1, 1, 0},  /* 2: Move ?1 into reg[1] */
84375:         {OP_NotExists,      0, 7, 1},  /* 3: Seek the cursor */
84376:         {OP_Column,         0, 0, 1},  /* 4  */
84377:         {OP_ResultRow,      1, 0, 0},  /* 5  */
84378:         {OP_Goto,           0, 2, 0},  /* 6  */
84379:         {OP_Close,          0, 0, 0},  /* 7  */
84380:         {OP_Halt,           0, 0, 0},  /* 8  */
84381:       };
84382:       Vdbe *v = (Vdbe *)pBlob->pStmt;
84383:       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84384:       VdbeOp *aOp;
84385: 
84386:       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags, 
84387:                            pTab->pSchema->schema_cookie,
84388:                            pTab->pSchema->iGeneration);
84389:       sqlite3VdbeChangeP5(v, 1);     
84390:       aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
84391: 
84392:       /* Make sure a mutex is held on the table to be accessed */
84393:       sqlite3VdbeUsesBtree(v, iDb); 
84394: 
84395:       if( db->mallocFailed==0 ){
84396:         assert( aOp!=0 );
84397:         /* Configure the OP_TableLock instruction */
84398: #ifdef SQLITE_OMIT_SHARED_CACHE
84399:         aOp[0].opcode = OP_Noop;
84400: #else
84401:         aOp[0].p1 = iDb;
84402:         aOp[0].p2 = pTab->tnum;
84403:         aOp[0].p3 = flags;
84404:         sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
84405:       }
84406:       if( db->mallocFailed==0 ){
84407: #endif
84408: 
84409:         /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
84410:         ** parameter of the other to pTab->tnum.  */
84411:         if( flags ) aOp[1].opcode = OP_OpenWrite;
84412:         aOp[1].p2 = pTab->tnum;
84413:         aOp[1].p3 = iDb;   
84414: 
84415:         /* Configure the number of columns. Configure the cursor to
84416:         ** think that the table has one more column than it really
84417:         ** does. An OP_Column to retrieve this imaginary column will
84418:         ** always return an SQL NULL. This is useful because it means
84419:         ** we can invoke OP_Column to fill in the vdbe cursors type 
84420:         ** and offset cache without causing any IO.
84421:         */
84422:         aOp[1].p4type = P4_INT32;
84423:         aOp[1].p4.i = pTab->nCol+1;
84424:         aOp[4].p2 = pTab->nCol;
84425: 
84426:         pParse->nVar = 1;
84427:         pParse->nMem = 1;
84428:         pParse->nTab = 1;
84429:         sqlite3VdbeMakeReady(v, pParse);
84430:       }
84431:     }
84432:    
84433:     pBlob->flags = flags;
84434:     pBlob->iCol = iCol;
84435:     pBlob->db = db;
84436:     sqlite3BtreeLeaveAll(db);
84437:     if( db->mallocFailed ){
84438:       goto blob_open_out;
84439:     }
84440:     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
84441:     rc = blobSeekToRow(pBlob, iRow, &zErr);
84442:   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
84443: 
84444: blob_open_out:
84445:   if( rc==SQLITE_OK && db->mallocFailed==0 ){
84446:     *ppBlob = (sqlite3_blob *)pBlob;
84447:   }else{
84448:     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
84449:     sqlite3DbFree(db, pBlob);
84450:   }
84451:   sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84452:   sqlite3DbFree(db, zErr);
84453:   sqlite3ParserReset(pParse);
84454:   sqlite3StackFree(db, pParse);
84455:   rc = sqlite3ApiExit(db, rc);
84456:   sqlite3_mutex_leave(db->mutex);
84457:   return rc;
84458: }
84459: 
84460: /*
84461: ** Close a blob handle that was previously created using
84462: ** sqlite3_blob_open().
84463: */
84464: SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
84465:   Incrblob *p = (Incrblob *)pBlob;
84466:   int rc;
84467:   sqlite3 *db;
84468: 
84469:   if( p ){
84470:     db = p->db;
84471:     sqlite3_mutex_enter(db->mutex);
84472:     rc = sqlite3_finalize(p->pStmt);
84473:     sqlite3DbFree(db, p);
84474:     sqlite3_mutex_leave(db->mutex);
84475:   }else{
84476:     rc = SQLITE_OK;
84477:   }
84478:   return rc;
84479: }
84480: 
84481: /*
84482: ** Perform a read or write operation on a blob
84483: */
84484: static int blobReadWrite(
84485:   sqlite3_blob *pBlob, 
84486:   void *z, 
84487:   int n, 
84488:   int iOffset, 
84489:   int (*xCall)(BtCursor*, u32, u32, void*)
84490: ){
84491:   int rc;
84492:   Incrblob *p = (Incrblob *)pBlob;
84493:   Vdbe *v;
84494:   sqlite3 *db;
84495: 
84496:   if( p==0 ) return SQLITE_MISUSE_BKPT;
84497:   db = p->db;
84498:   sqlite3_mutex_enter(db->mutex);
84499:   v = (Vdbe*)p->pStmt;
84500: 
84501:   if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
84502:     /* Request is out of range. Return a transient error. */
84503:     rc = SQLITE_ERROR;
84504:   }else if( v==0 ){
84505:     /* If there is no statement handle, then the blob-handle has
84506:     ** already been invalidated. Return SQLITE_ABORT in this case.
84507:     */
84508:     rc = SQLITE_ABORT;
84509:   }else{
84510:     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
84511:     ** returned, clean-up the statement handle.
84512:     */
84513:     assert( db == v->db );
84514:     sqlite3BtreeEnterCursor(p->pCsr);
84515: 
84516: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
84517:     if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
84518:       /* If a pre-update hook is registered and this is a write cursor, 
84519:       ** invoke it here. 
84520:       ** 
84521:       ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
84522:       ** operation should really be an SQLITE_UPDATE. This is probably
84523:       ** incorrect, but is convenient because at this point the new.* values 
84524:       ** are not easily obtainable. And for the sessions module, an 
84525:       ** SQLITE_UPDATE where the PK columns do not change is handled in the 
84526:       ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
84527:       ** slightly more efficient). Since you cannot write to a PK column
84528:       ** using the incremental-blob API, this works. For the sessions module
84529:       ** anyhow.
84530:       */
84531:       sqlite3_int64 iKey;
84532:       iKey = sqlite3BtreeIntegerKey(p->pCsr);
84533:       sqlite3VdbePreUpdateHook(
84534:           v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
84535:       );
84536:     }
84537: #endif
84538: 
84539:     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
84540:     sqlite3BtreeLeaveCursor(p->pCsr);
84541:     if( rc==SQLITE_ABORT ){
84542:       sqlite3VdbeFinalize(v);
84543:       p->pStmt = 0;
84544:     }else{
84545:       v->rc = rc;
84546:     }
84547:   }
84548:   sqlite3Error(db, rc);
84549:   rc = sqlite3ApiExit(db, rc);
84550:   sqlite3_mutex_leave(db->mutex);
84551:   return rc;
84552: }
84553: 
84554: /*
84555: ** Read data from a blob handle.
84556: */
84557: SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
84558:   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
84559: }
84560: 
84561: /*
84562: ** Write data to a blob handle.
84563: */
84564: SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
84565:   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
84566: }
84567: 
84568: /*
84569: ** Query a blob handle for the size of the data.
84570: **
84571: ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
84572: ** so no mutex is required for access.
84573: */
84574: SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
84575:   Incrblob *p = (Incrblob *)pBlob;
84576:   return (p && p->pStmt) ? p->nByte : 0;
84577: }
84578: 
84579: /*
84580: ** Move an existing blob handle to point to a different row of the same
84581: ** database table.
84582: **
84583: ** If an error occurs, or if the specified row does not exist or does not
84584: ** contain a blob or text value, then an error code is returned and the
84585: ** database handle error code and message set. If this happens, then all 
84586: ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
84587: ** immediately return SQLITE_ABORT.
84588: */
84589: SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
84590:   int rc;
84591:   Incrblob *p = (Incrblob *)pBlob;
84592:   sqlite3 *db;
84593: 
84594:   if( p==0 ) return SQLITE_MISUSE_BKPT;
84595:   db = p->db;
84596:   sqlite3_mutex_enter(db->mutex);
84597: 
84598:   if( p->pStmt==0 ){
84599:     /* If there is no statement handle, then the blob-handle has
84600:     ** already been invalidated. Return SQLITE_ABORT in this case.
84601:     */
84602:     rc = SQLITE_ABORT;
84603:   }else{
84604:     char *zErr;
84605:     rc = blobSeekToRow(p, iRow, &zErr);
84606:     if( rc!=SQLITE_OK ){
84607:       sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84608:       sqlite3DbFree(db, zErr);
84609:     }
84610:     assert( rc!=SQLITE_SCHEMA );
84611:   }
84612: 
84613:   rc = sqlite3ApiExit(db, rc);
84614:   assert( rc==SQLITE_OK || p->pStmt==0 );
84615:   sqlite3_mutex_leave(db->mutex);
84616:   return rc;
84617: }
84618: 
84619: #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
84620: 
84621: /************** End of vdbeblob.c ********************************************/
84622: /************** Begin file vdbesort.c ****************************************/
84623: /*
84624: ** 2011-07-09
84625: **
84626: ** The author disclaims copyright to this source code.  In place of
84627: ** a legal notice, here is a blessing:
84628: **
84629: **    May you do good and not evil.
84630: **    May you find forgiveness for yourself and forgive others.
84631: **    May you share freely, never taking more than you give.
84632: **
84633: *************************************************************************
84634: ** This file contains code for the VdbeSorter object, used in concert with
84635: ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
84636: ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
84637: ** using indexes and without LIMIT clauses.
84638: **
84639: ** The VdbeSorter object implements a multi-threaded external merge sort
84640: ** algorithm that is efficient even if the number of elements being sorted
84641: ** exceeds the available memory.
84642: **
84643: ** Here is the (internal, non-API) interface between this module and the
84644: ** rest of the SQLite system:
84645: **
84646: **    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
84647: **
84648: **    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
84649: **                                  object.  The row is a binary blob in the
84650: **                                  OP_MakeRecord format that contains both
84651: **                                  the ORDER BY key columns and result columns
84652: **                                  in the case of a SELECT w/ ORDER BY, or
84653: **                                  the complete record for an index entry
84654: **                                  in the case of a CREATE INDEX.
84655: **
84656: **    sqlite3VdbeSorterRewind()     Sort all content previously added.
84657: **                                  Position the read cursor on the
84658: **                                  first sorted element.
84659: **
84660: **    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
84661: **                                  element.
84662: **
84663: **    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
84664: **                                  row currently under the read cursor.
84665: **
84666: **    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
84667: **                                  currently under the read cursor against
84668: **                                  another binary blob X and report if
84669: **                                  X is strictly less than the read cursor.
84670: **                                  Used to enforce uniqueness in a
84671: **                                  CREATE UNIQUE INDEX statement.
84672: **
84673: **    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
84674: **                                  all resources.
84675: **
84676: **    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
84677: **                                  is like Close() followed by Init() only
84678: **                                  much faster.
84679: **
84680: ** The interfaces above must be called in a particular order.  Write() can 
84681: ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
84682: ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
84683: **
84684: **   Init()
84685: **   for each record: Write()
84686: **   Rewind()
84687: **     Rowkey()/Compare()
84688: **   Next() 
84689: **   Close()
84690: **
84691: ** Algorithm:
84692: **
84693: ** Records passed to the sorter via calls to Write() are initially held 
84694: ** unsorted in main memory. Assuming the amount of memory used never exceeds
84695: ** a threshold, when Rewind() is called the set of records is sorted using
84696: ** an in-memory merge sort. In this case, no temporary files are required
84697: ** and subsequent calls to Rowkey(), Next() and Compare() read records 
84698: ** directly from main memory.
84699: **
84700: ** If the amount of space used to store records in main memory exceeds the
84701: ** threshold, then the set of records currently in memory are sorted and
84702: ** written to a temporary file in "Packed Memory Array" (PMA) format.
84703: ** A PMA created at this point is known as a "level-0 PMA". Higher levels
84704: ** of PMAs may be created by merging existing PMAs together - for example
84705: ** merging two or more level-0 PMAs together creates a level-1 PMA.
84706: **
84707: ** The threshold for the amount of main memory to use before flushing 
84708: ** records to a PMA is roughly the same as the limit configured for the
84709: ** page-cache of the main database. Specifically, the threshold is set to 
84710: ** the value returned by "PRAGMA main.page_size" multipled by 
84711: ** that returned by "PRAGMA main.cache_size", in bytes.
84712: **
84713: ** If the sorter is running in single-threaded mode, then all PMAs generated
84714: ** are appended to a single temporary file. Or, if the sorter is running in
84715: ** multi-threaded mode then up to (N+1) temporary files may be opened, where
84716: ** N is the configured number of worker threads. In this case, instead of
84717: ** sorting the records and writing the PMA to a temporary file itself, the
84718: ** calling thread usually launches a worker thread to do so. Except, if
84719: ** there are already N worker threads running, the main thread does the work
84720: ** itself.
84721: **
84722: ** The sorter is running in multi-threaded mode if (a) the library was built
84723: ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
84724: ** than zero, and (b) worker threads have been enabled at runtime by calling
84725: ** "PRAGMA threads=N" with some value of N greater than 0.
84726: **
84727: ** When Rewind() is called, any data remaining in memory is flushed to a 
84728: ** final PMA. So at this point the data is stored in some number of sorted
84729: ** PMAs within temporary files on disk.
84730: **
84731: ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
84732: ** sorter is running in single-threaded mode, then these PMAs are merged
84733: ** incrementally as keys are retreived from the sorter by the VDBE.  The
84734: ** MergeEngine object, described in further detail below, performs this
84735: ** merge.
84736: **
84737: ** Or, if running in multi-threaded mode, then a background thread is
84738: ** launched to merge the existing PMAs. Once the background thread has
84739: ** merged T bytes of data into a single sorted PMA, the main thread 
84740: ** begins reading keys from that PMA while the background thread proceeds
84741: ** with merging the next T bytes of data. And so on.
84742: **
84743: ** Parameter T is set to half the value of the memory threshold used 
84744: ** by Write() above to determine when to create a new PMA.
84745: **
84746: ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when 
84747: ** Rewind() is called, then a hierarchy of incremental-merges is used. 
84748: ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on 
84749: ** disk are merged together. Then T bytes of data from the second set, and
84750: ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
84751: ** PMAs at a time. This done is to improve locality.
84752: **
84753: ** If running in multi-threaded mode and there are more than
84754: ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
84755: ** than one background thread may be created. Specifically, there may be
84756: ** one background thread for each temporary file on disk, and one background
84757: ** thread to merge the output of each of the others to a single PMA for
84758: ** the main thread to read from.
84759: */
84760: /* #include "sqliteInt.h" */
84761: /* #include "vdbeInt.h" */
84762: 
84763: /* 
84764: ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
84765: ** messages to stderr that may be helpful in understanding the performance
84766: ** characteristics of the sorter in multi-threaded mode.
84767: */
84768: #if 0
84769: # define SQLITE_DEBUG_SORTER_THREADS 1
84770: #endif
84771: 
84772: /*
84773: ** Hard-coded maximum amount of data to accumulate in memory before flushing
84774: ** to a level 0 PMA. The purpose of this limit is to prevent various integer
84775: ** overflows. 512MiB.
84776: */
84777: #define SQLITE_MAX_PMASZ    (1<<29)
84778: 
84779: /*
84780: ** Private objects used by the sorter
84781: */
84782: typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
84783: typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
84784: typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
84785: typedef struct SorterRecord SorterRecord;   /* A record being sorted */
84786: typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
84787: typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
84788: typedef struct SorterList SorterList;       /* In-memory list of records */
84789: typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
84790: 
84791: /*
84792: ** A container for a temp file handle and the current amount of data 
84793: ** stored in the file.
84794: */
84795: struct SorterFile {
84796:   sqlite3_file *pFd;              /* File handle */
84797:   i64 iEof;                       /* Bytes of data stored in pFd */
84798: };
84799: 
84800: /*
84801: ** An in-memory list of objects to be sorted.
84802: **
84803: ** If aMemory==0 then each object is allocated separately and the objects
84804: ** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
84805: ** are stored in the aMemory[] bulk memory, one right after the other, and
84806: ** are connected using SorterRecord.u.iNext.
84807: */
84808: struct SorterList {
84809:   SorterRecord *pList;            /* Linked list of records */
84810:   u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
84811:   int szPMA;                      /* Size of pList as PMA in bytes */
84812: };
84813: 
84814: /*
84815: ** The MergeEngine object is used to combine two or more smaller PMAs into
84816: ** one big PMA using a merge operation.  Separate PMAs all need to be
84817: ** combined into one big PMA in order to be able to step through the sorted
84818: ** records in order.
84819: **
84820: ** The aReadr[] array contains a PmaReader object for each of the PMAs being
84821: ** merged.  An aReadr[] object either points to a valid key or else is at EOF.
84822: ** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
84823: ** For the purposes of the paragraphs below, we assume that the array is
84824: ** actually N elements in size, where N is the smallest power of 2 greater
84825: ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
84826: ** are treated as if they are empty (always at EOF).
84827: **
84828: ** The aTree[] array is also N elements in size. The value of N is stored in
84829: ** the MergeEngine.nTree variable.
84830: **
84831: ** The final (N/2) elements of aTree[] contain the results of comparing
84832: ** pairs of PMA keys together. Element i contains the result of 
84833: ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
84834: ** aTree element is set to the index of it. 
84835: **
84836: ** For the purposes of this comparison, EOF is considered greater than any
84837: ** other key value. If the keys are equal (only possible with two EOF
84838: ** values), it doesn't matter which index is stored.
84839: **
84840: ** The (N/4) elements of aTree[] that precede the final (N/2) described 
84841: ** above contains the index of the smallest of each block of 4 PmaReaders
84842: ** And so on. So that aTree[1] contains the index of the PmaReader that 
84843: ** currently points to the smallest key value. aTree[0] is unused.
84844: **
84845: ** Example:
84846: **
84847: **     aReadr[0] -> Banana
84848: **     aReadr[1] -> Feijoa
84849: **     aReadr[2] -> Elderberry
84850: **     aReadr[3] -> Currant
84851: **     aReadr[4] -> Grapefruit
84852: **     aReadr[5] -> Apple
84853: **     aReadr[6] -> Durian
84854: **     aReadr[7] -> EOF
84855: **
84856: **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
84857: **
84858: ** The current element is "Apple" (the value of the key indicated by 
84859: ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
84860: ** be advanced to the next key in its segment. Say the next key is
84861: ** "Eggplant":
84862: **
84863: **     aReadr[5] -> Eggplant
84864: **
84865: ** The contents of aTree[] are updated first by comparing the new PmaReader
84866: ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
84867: ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
84868: ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
84869: ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
84870: ** so the value written into element 1 of the array is 0. As follows:
84871: **
84872: **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
84873: **
84874: ** In other words, each time we advance to the next sorter element, log2(N)
84875: ** key comparison operations are required, where N is the number of segments
84876: ** being merged (rounded up to the next power of 2).
84877: */
84878: struct MergeEngine {
84879:   int nTree;                 /* Used size of aTree/aReadr (power of 2) */
84880:   SortSubtask *pTask;        /* Used by this thread only */
84881:   int *aTree;                /* Current state of incremental merge */
84882:   PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
84883: };
84884: 
84885: /*
84886: ** This object represents a single thread of control in a sort operation.
84887: ** Exactly VdbeSorter.nTask instances of this object are allocated
84888: ** as part of each VdbeSorter object. Instances are never allocated any
84889: ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
84890: ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
84891: ** single-threaded operation, there is exactly one instance of this object
84892: ** and for multi-threaded operation there are two or more instances.
84893: **
84894: ** Essentially, this structure contains all those fields of the VdbeSorter
84895: ** structure for which each thread requires a separate instance. For example,
84896: ** each thread requries its own UnpackedRecord object to unpack records in
84897: ** as part of comparison operations.
84898: **
84899: ** Before a background thread is launched, variable bDone is set to 0. Then, 
84900: ** right before it exits, the thread itself sets bDone to 1. This is used for 
84901: ** two purposes:
84902: **
84903: **   1. When flushing the contents of memory to a level-0 PMA on disk, to
84904: **      attempt to select a SortSubtask for which there is not already an
84905: **      active background thread (since doing so causes the main thread
84906: **      to block until it finishes).
84907: **
84908: **   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
84909: **      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
84910: **      block provoke debugging output.
84911: **
84912: ** In both cases, the effects of the main thread seeing (bDone==0) even
84913: ** after the thread has finished are not dire. So we don't worry about
84914: ** memory barriers and such here.
84915: */
84916: typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
84917: struct SortSubtask {
84918:   SQLiteThread *pThread;          /* Background thread, if any */
84919:   int bDone;                      /* Set if thread is finished but not joined */
84920:   VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
84921:   UnpackedRecord *pUnpacked;      /* Space to unpack a record */
84922:   SorterList list;                /* List for thread to write to a PMA */
84923:   int nPMA;                       /* Number of PMAs currently in file */
84924:   SorterCompare xCompare;         /* Compare function to use */
84925:   SorterFile file;                /* Temp file for level-0 PMAs */
84926:   SorterFile file2;               /* Space for other PMAs */
84927: };
84928: 
84929: 
84930: /*
84931: ** Main sorter structure. A single instance of this is allocated for each 
84932: ** sorter cursor created by the VDBE.
84933: **
84934: ** mxKeysize:
84935: **   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
84936: **   this variable is updated so as to be set to the size on disk of the
84937: **   largest record in the sorter.
84938: */
84939: struct VdbeSorter {
84940:   int mnPmaSize;                  /* Minimum PMA size, in bytes */
84941:   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
84942:   int mxKeysize;                  /* Largest serialized key seen so far */
84943:   int pgsz;                       /* Main database page size */
84944:   PmaReader *pReader;             /* Readr data from here after Rewind() */
84945:   MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
84946:   sqlite3 *db;                    /* Database connection */
84947:   KeyInfo *pKeyInfo;              /* How to compare records */
84948:   UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
84949:   SorterList list;                /* List of in-memory records */
84950:   int iMemory;                    /* Offset of free space in list.aMemory */
84951:   int nMemory;                    /* Size of list.aMemory allocation in bytes */
84952:   u8 bUsePMA;                     /* True if one or more PMAs created */
84953:   u8 bUseThreads;                 /* True to use background threads */
84954:   u8 iPrev;                       /* Previous thread used to flush PMA */
84955:   u8 nTask;                       /* Size of aTask[] array */
84956:   u8 typeMask;
84957:   SortSubtask aTask[1];           /* One or more subtasks */
84958: };
84959: 
84960: #define SORTER_TYPE_INTEGER 0x01
84961: #define SORTER_TYPE_TEXT    0x02
84962: 
84963: /*
84964: ** An instance of the following object is used to read records out of a
84965: ** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
84966: ** aKey might point into aMap or into aBuffer.  If neither of those locations
84967: ** contain a contiguous representation of the key, then aAlloc is allocated
84968: ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
84969: **
84970: ** pFd==0 at EOF.
84971: */
84972: struct PmaReader {
84973:   i64 iReadOff;               /* Current read offset */
84974:   i64 iEof;                   /* 1 byte past EOF for this PmaReader */
84975:   int nAlloc;                 /* Bytes of space at aAlloc */
84976:   int nKey;                   /* Number of bytes in key */
84977:   sqlite3_file *pFd;          /* File handle we are reading from */
84978:   u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
84979:   u8 *aKey;                   /* Pointer to current key */
84980:   u8 *aBuffer;                /* Current read buffer */
84981:   int nBuffer;                /* Size of read buffer in bytes */
84982:   u8 *aMap;                   /* Pointer to mapping of entire file */
84983:   IncrMerger *pIncr;          /* Incremental merger */
84984: };
84985: 
84986: /*
84987: ** Normally, a PmaReader object iterates through an existing PMA stored 
84988: ** within a temp file. However, if the PmaReader.pIncr variable points to
84989: ** an object of the following type, it may be used to iterate/merge through
84990: ** multiple PMAs simultaneously.
84991: **
84992: ** There are two types of IncrMerger object - single (bUseThread==0) and 
84993: ** multi-threaded (bUseThread==1). 
84994: **
84995: ** A multi-threaded IncrMerger object uses two temporary files - aFile[0] 
84996: ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in 
84997: ** size. When the IncrMerger is initialized, it reads enough data from 
84998: ** pMerger to populate aFile[0]. It then sets variables within the 
84999: ** corresponding PmaReader object to read from that file and kicks off 
85000: ** a background thread to populate aFile[1] with the next mxSz bytes of 
85001: ** sorted record data from pMerger. 
85002: **
85003: ** When the PmaReader reaches the end of aFile[0], it blocks until the
85004: ** background thread has finished populating aFile[1]. It then exchanges
85005: ** the contents of the aFile[0] and aFile[1] variables within this structure,
85006: ** sets the PmaReader fields to read from the new aFile[0] and kicks off
85007: ** another background thread to populate the new aFile[1]. And so on, until
85008: ** the contents of pMerger are exhausted.
85009: **
85010: ** A single-threaded IncrMerger does not open any temporary files of its
85011: ** own. Instead, it has exclusive access to mxSz bytes of space beginning
85012: ** at offset iStartOff of file pTask->file2. And instead of using a 
85013: ** background thread to prepare data for the PmaReader, with a single
85014: ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
85015: ** keys from pMerger by the calling thread whenever the PmaReader runs out
85016: ** of data.
85017: */
85018: struct IncrMerger {
85019:   SortSubtask *pTask;             /* Task that owns this merger */
85020:   MergeEngine *pMerger;           /* Merge engine thread reads data from */
85021:   i64 iStartOff;                  /* Offset to start writing file at */
85022:   int mxSz;                       /* Maximum bytes of data to store */
85023:   int bEof;                       /* Set to true when merge is finished */
85024:   int bUseThread;                 /* True to use a bg thread for this object */
85025:   SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
85026: };
85027: 
85028: /*
85029: ** An instance of this object is used for writing a PMA.
85030: **
85031: ** The PMA is written one record at a time.  Each record is of an arbitrary
85032: ** size.  But I/O is more efficient if it occurs in page-sized blocks where
85033: ** each block is aligned on a page boundary.  This object caches writes to
85034: ** the PMA so that aligned, page-size blocks are written.
85035: */
85036: struct PmaWriter {
85037:   int eFWErr;                     /* Non-zero if in an error state */
85038:   u8 *aBuffer;                    /* Pointer to write buffer */
85039:   int nBuffer;                    /* Size of write buffer in bytes */
85040:   int iBufStart;                  /* First byte of buffer to write */
85041:   int iBufEnd;                    /* Last byte of buffer to write */
85042:   i64 iWriteOff;                  /* Offset of start of buffer in file */
85043:   sqlite3_file *pFd;              /* File handle to write to */
85044: };
85045: 
85046: /*
85047: ** This object is the header on a single record while that record is being
85048: ** held in memory and prior to being written out as part of a PMA.
85049: **
85050: ** How the linked list is connected depends on how memory is being managed
85051: ** by this module. If using a separate allocation for each in-memory record
85052: ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
85053: ** SorterRecord.u.pNext pointers.
85054: **
85055: ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
85056: ** then while records are being accumulated the list is linked using the
85057: ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
85058: ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
85059: ** has finished passing records to the sorter, or when the in-memory buffer
85060: ** is full, the list is sorted. As part of the sorting process, it is
85061: ** converted to use the SorterRecord.u.pNext pointers. See function
85062: ** vdbeSorterSort() for details.
85063: */
85064: struct SorterRecord {
85065:   int nVal;                       /* Size of the record in bytes */
85066:   union {
85067:     SorterRecord *pNext;          /* Pointer to next record in list */
85068:     int iNext;                    /* Offset within aMemory of next record */
85069:   } u;
85070:   /* The data for the record immediately follows this header */
85071: };
85072: 
85073: /* Return a pointer to the buffer containing the record data for SorterRecord
85074: ** object p. Should be used as if:
85075: **
85076: **   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
85077: */
85078: #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
85079: 
85080: 
85081: /* Maximum number of PMAs that a single MergeEngine can merge */
85082: #define SORTER_MAX_MERGE_COUNT 16
85083: 
85084: static int vdbeIncrSwap(IncrMerger*);
85085: static void vdbeIncrFree(IncrMerger *);
85086: 
85087: /*
85088: ** Free all memory belonging to the PmaReader object passed as the
85089: ** argument. All structure fields are set to zero before returning.
85090: */
85091: static void vdbePmaReaderClear(PmaReader *pReadr){
85092:   sqlite3_free(pReadr->aAlloc);
85093:   sqlite3_free(pReadr->aBuffer);
85094:   if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85095:   vdbeIncrFree(pReadr->pIncr);
85096:   memset(pReadr, 0, sizeof(PmaReader));
85097: }
85098: 
85099: /*
85100: ** Read the next nByte bytes of data from the PMA p.
85101: ** If successful, set *ppOut to point to a buffer containing the data
85102: ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
85103: ** error code.
85104: **
85105: ** The buffer returned in *ppOut is only valid until the
85106: ** next call to this function.
85107: */
85108: static int vdbePmaReadBlob(
85109:   PmaReader *p,                   /* PmaReader from which to take the blob */
85110:   int nByte,                      /* Bytes of data to read */
85111:   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
85112: ){
85113:   int iBuf;                       /* Offset within buffer to read from */
85114:   int nAvail;                     /* Bytes of data available in buffer */
85115: 
85116:   if( p->aMap ){
85117:     *ppOut = &p->aMap[p->iReadOff];
85118:     p->iReadOff += nByte;
85119:     return SQLITE_OK;
85120:   }
85121: 
85122:   assert( p->aBuffer );
85123: 
85124:   /* If there is no more data to be read from the buffer, read the next 
85125:   ** p->nBuffer bytes of data from the file into it. Or, if there are less
85126:   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
85127:   iBuf = p->iReadOff % p->nBuffer;
85128:   if( iBuf==0 ){
85129:     int nRead;                    /* Bytes to read from disk */
85130:     int rc;                       /* sqlite3OsRead() return code */
85131: 
85132:     /* Determine how many bytes of data to read. */
85133:     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
85134:       nRead = p->nBuffer;
85135:     }else{
85136:       nRead = (int)(p->iEof - p->iReadOff);
85137:     }
85138:     assert( nRead>0 );
85139: 
85140:     /* Readr data from the file. Return early if an error occurs. */
85141:     rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
85142:     assert( rc!=SQLITE_IOERR_SHORT_READ );
85143:     if( rc!=SQLITE_OK ) return rc;
85144:   }
85145:   nAvail = p->nBuffer - iBuf; 
85146: 
85147:   if( nByte<=nAvail ){
85148:     /* The requested data is available in the in-memory buffer. In this
85149:     ** case there is no need to make a copy of the data, just return a 
85150:     ** pointer into the buffer to the caller.  */
85151:     *ppOut = &p->aBuffer[iBuf];
85152:     p->iReadOff += nByte;
85153:   }else{
85154:     /* The requested data is not all available in the in-memory buffer.
85155:     ** In this case, allocate space at p->aAlloc[] to copy the requested
85156:     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
85157:     int nRem;                     /* Bytes remaining to copy */
85158: 
85159:     /* Extend the p->aAlloc[] allocation if required. */
85160:     if( p->nAlloc<nByte ){
85161:       u8 *aNew;
85162:       int nNew = MAX(128, p->nAlloc*2);
85163:       while( nByte>nNew ) nNew = nNew*2;
85164:       aNew = sqlite3Realloc(p->aAlloc, nNew);
85165:       if( !aNew ) return SQLITE_NOMEM_BKPT;
85166:       p->nAlloc = nNew;
85167:       p->aAlloc = aNew;
85168:     }
85169: 
85170:     /* Copy as much data as is available in the buffer into the start of
85171:     ** p->aAlloc[].  */
85172:     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
85173:     p->iReadOff += nAvail;
85174:     nRem = nByte - nAvail;
85175: 
85176:     /* The following loop copies up to p->nBuffer bytes per iteration into
85177:     ** the p->aAlloc[] buffer.  */
85178:     while( nRem>0 ){
85179:       int rc;                     /* vdbePmaReadBlob() return code */
85180:       int nCopy;                  /* Number of bytes to copy */
85181:       u8 *aNext;                  /* Pointer to buffer to copy data from */
85182: 
85183:       nCopy = nRem;
85184:       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
85185:       rc = vdbePmaReadBlob(p, nCopy, &aNext);
85186:       if( rc!=SQLITE_OK ) return rc;
85187:       assert( aNext!=p->aAlloc );
85188:       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
85189:       nRem -= nCopy;
85190:     }
85191: 
85192:     *ppOut = p->aAlloc;
85193:   }
85194: 
85195:   return SQLITE_OK;
85196: }
85197: 
85198: /*
85199: ** Read a varint from the stream of data accessed by p. Set *pnOut to
85200: ** the value read.
85201: */
85202: static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
85203:   int iBuf;
85204: 
85205:   if( p->aMap ){
85206:     p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
85207:   }else{
85208:     iBuf = p->iReadOff % p->nBuffer;
85209:     if( iBuf && (p->nBuffer-iBuf)>=9 ){
85210:       p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
85211:     }else{
85212:       u8 aVarint[16], *a;
85213:       int i = 0, rc;
85214:       do{
85215:         rc = vdbePmaReadBlob(p, 1, &a);
85216:         if( rc ) return rc;
85217:         aVarint[(i++)&0xf] = a[0];
85218:       }while( (a[0]&0x80)!=0 );
85219:       sqlite3GetVarint(aVarint, pnOut);
85220:     }
85221:   }
85222: 
85223:   return SQLITE_OK;
85224: }
85225: 
85226: /*
85227: ** Attempt to memory map file pFile. If successful, set *pp to point to the
85228: ** new mapping and return SQLITE_OK. If the mapping is not attempted 
85229: ** (because the file is too large or the VFS layer is configured not to use
85230: ** mmap), return SQLITE_OK and set *pp to NULL.
85231: **
85232: ** Or, if an error occurs, return an SQLite error code. The final value of
85233: ** *pp is undefined in this case.
85234: */
85235: static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
85236:   int rc = SQLITE_OK;
85237:   if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
85238:     sqlite3_file *pFd = pFile->pFd;
85239:     if( pFd->pMethods->iVersion>=3 ){
85240:       rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
85241:       testcase( rc!=SQLITE_OK );
85242:     }
85243:   }
85244:   return rc;
85245: }
85246: 
85247: /*
85248: ** Attach PmaReader pReadr to file pFile (if it is not already attached to
85249: ** that file) and seek it to offset iOff within the file.  Return SQLITE_OK 
85250: ** if successful, or an SQLite error code if an error occurs.
85251: */
85252: static int vdbePmaReaderSeek(
85253:   SortSubtask *pTask,             /* Task context */
85254:   PmaReader *pReadr,              /* Reader whose cursor is to be moved */
85255:   SorterFile *pFile,              /* Sorter file to read from */
85256:   i64 iOff                        /* Offset in pFile */
85257: ){
85258:   int rc = SQLITE_OK;
85259: 
85260:   assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
85261: 
85262:   if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
85263:   if( pReadr->aMap ){
85264:     sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
85265:     pReadr->aMap = 0;
85266:   }
85267:   pReadr->iReadOff = iOff;
85268:   pReadr->iEof = pFile->iEof;
85269:   pReadr->pFd = pFile->pFd;
85270: 
85271:   rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
85272:   if( rc==SQLITE_OK && pReadr->aMap==0 ){
85273:     int pgsz = pTask->pSorter->pgsz;
85274:     int iBuf = pReadr->iReadOff % pgsz;
85275:     if( pReadr->aBuffer==0 ){
85276:       pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
85277:       if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
85278:       pReadr->nBuffer = pgsz;
85279:     }
85280:     if( rc==SQLITE_OK && iBuf ){
85281:       int nRead = pgsz - iBuf;
85282:       if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
85283:         nRead = (int)(pReadr->iEof - pReadr->iReadOff);
85284:       }
85285:       rc = sqlite3OsRead(
85286:           pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
85287:       );
85288:       testcase( rc!=SQLITE_OK );
85289:     }
85290:   }
85291: 
85292:   return rc;
85293: }
85294: 
85295: /*
85296: ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
85297: ** no error occurs, or an SQLite error code if one does.
85298: */
85299: static int vdbePmaReaderNext(PmaReader *pReadr){
85300:   int rc = SQLITE_OK;             /* Return Code */
85301:   u64 nRec = 0;                   /* Size of record in bytes */
85302: 
85303: 
85304:   if( pReadr->iReadOff>=pReadr->iEof ){
85305:     IncrMerger *pIncr = pReadr->pIncr;
85306:     int bEof = 1;
85307:     if( pIncr ){
85308:       rc = vdbeIncrSwap(pIncr);
85309:       if( rc==SQLITE_OK && pIncr->bEof==0 ){
85310:         rc = vdbePmaReaderSeek(
85311:             pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
85312:         );
85313:         bEof = 0;
85314:       }
85315:     }
85316: 
85317:     if( bEof ){
85318:       /* This is an EOF condition */
85319:       vdbePmaReaderClear(pReadr);
85320:       testcase( rc!=SQLITE_OK );
85321:       return rc;
85322:     }
85323:   }
85324: 
85325:   if( rc==SQLITE_OK ){
85326:     rc = vdbePmaReadVarint(pReadr, &nRec);
85327:   }
85328:   if( rc==SQLITE_OK ){
85329:     pReadr->nKey = (int)nRec;
85330:     rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
85331:     testcase( rc!=SQLITE_OK );
85332:   }
85333: 
85334:   return rc;
85335: }
85336: 
85337: /*
85338: ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
85339: ** starting at offset iStart and ending at offset iEof-1. This function 
85340: ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the 
85341: ** PMA is empty).
85342: **
85343: ** If the pnByte parameter is NULL, then it is assumed that the file 
85344: ** contains a single PMA, and that that PMA omits the initial length varint.
85345: */
85346: static int vdbePmaReaderInit(
85347:   SortSubtask *pTask,             /* Task context */
85348:   SorterFile *pFile,              /* Sorter file to read from */
85349:   i64 iStart,                     /* Start offset in pFile */
85350:   PmaReader *pReadr,              /* PmaReader to populate */
85351:   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
85352: ){
85353:   int rc;
85354: 
85355:   assert( pFile->iEof>iStart );
85356:   assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
85357:   assert( pReadr->aBuffer==0 );
85358:   assert( pReadr->aMap==0 );
85359: 
85360:   rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
85361:   if( rc==SQLITE_OK ){
85362:     u64 nByte = 0;                 /* Size of PMA in bytes */
85363:     rc = vdbePmaReadVarint(pReadr, &nByte);
85364:     pReadr->iEof = pReadr->iReadOff + nByte;
85365:     *pnByte += nByte;
85366:   }
85367: 
85368:   if( rc==SQLITE_OK ){
85369:     rc = vdbePmaReaderNext(pReadr);
85370:   }
85371:   return rc;
85372: }
85373: 
85374: /*
85375: ** A version of vdbeSorterCompare() that assumes that it has already been
85376: ** determined that the first field of key1 is equal to the first field of 
85377: ** key2.
85378: */
85379: static int vdbeSorterCompareTail(
85380:   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85381:   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85382:   const void *pKey1, int nKey1,   /* Left side of comparison */
85383:   const void *pKey2, int nKey2    /* Right side of comparison */
85384: ){
85385:   UnpackedRecord *r2 = pTask->pUnpacked;
85386:   if( *pbKey2Cached==0 ){
85387:     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85388:     *pbKey2Cached = 1;
85389:   }
85390:   return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
85391: }
85392: 
85393: /*
85394: ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
85395: ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
85396: ** used by the comparison. Return the result of the comparison.
85397: **
85398: ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
85399: ** it is assumed that (pTask->pUnpacked) contains the unpacked version
85400: ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
85401: ** version of key2 and *pbKey2Cached set to true before returning.
85402: **
85403: ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
85404: ** to SQLITE_NOMEM.
85405: */
85406: static int vdbeSorterCompare(
85407:   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85408:   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85409:   const void *pKey1, int nKey1,   /* Left side of comparison */
85410:   const void *pKey2, int nKey2    /* Right side of comparison */
85411: ){
85412:   UnpackedRecord *r2 = pTask->pUnpacked;
85413:   if( !*pbKey2Cached ){
85414:     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
85415:     *pbKey2Cached = 1;
85416:   }
85417:   return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
85418: }
85419: 
85420: /*
85421: ** A specially optimized version of vdbeSorterCompare() that assumes that
85422: ** the first field of each key is a TEXT value and that the collation
85423: ** sequence to compare them with is BINARY.
85424: */
85425: static int vdbeSorterCompareText(
85426:   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85427:   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85428:   const void *pKey1, int nKey1,   /* Left side of comparison */
85429:   const void *pKey2, int nKey2    /* Right side of comparison */
85430: ){
85431:   const u8 * const p1 = (const u8 * const)pKey1;
85432:   const u8 * const p2 = (const u8 * const)pKey2;
85433:   const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
85434:   const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
85435: 
85436:   int n1;
85437:   int n2;
85438:   int res;
85439: 
85440:   getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
85441:   getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
85442:   res = memcmp(v1, v2, MIN(n1, n2));
85443:   if( res==0 ){
85444:     res = n1 - n2;
85445:   }
85446: 
85447:   if( res==0 ){
85448:     if( pTask->pSorter->pKeyInfo->nField>1 ){
85449:       res = vdbeSorterCompareTail(
85450:           pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85451:       );
85452:     }
85453:   }else{
85454:     if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85455:       res = res * -1;
85456:     }
85457:   }
85458: 
85459:   return res;
85460: }
85461: 
85462: /*
85463: ** A specially optimized version of vdbeSorterCompare() that assumes that
85464: ** the first field of each key is an INTEGER value.
85465: */
85466: static int vdbeSorterCompareInt(
85467:   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
85468:   int *pbKey2Cached,              /* True if pTask->pUnpacked is pKey2 */
85469:   const void *pKey1, int nKey1,   /* Left side of comparison */
85470:   const void *pKey2, int nKey2    /* Right side of comparison */
85471: ){
85472:   const u8 * const p1 = (const u8 * const)pKey1;
85473:   const u8 * const p2 = (const u8 * const)pKey2;
85474:   const int s1 = p1[1];                 /* Left hand serial type */
85475:   const int s2 = p2[1];                 /* Right hand serial type */
85476:   const u8 * const v1 = &p1[ p1[0] ];   /* Pointer to value 1 */
85477:   const u8 * const v2 = &p2[ p2[0] ];   /* Pointer to value 2 */
85478:   int res;                              /* Return value */
85479: 
85480:   assert( (s1>0 && s1<7) || s1==8 || s1==9 );
85481:   assert( (s2>0 && s2<7) || s2==8 || s2==9 );
85482: 
85483:   if( s1>7 && s2>7 ){
85484:     res = s1 - s2;
85485:   }else{
85486:     if( s1==s2 ){
85487:       if( (*v1 ^ *v2) & 0x80 ){
85488:         /* The two values have different signs */
85489:         res = (*v1 & 0x80) ? -1 : +1;
85490:       }else{
85491:         /* The two values have the same sign. Compare using memcmp(). */
85492:         static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
85493:         int i;
85494:         res = 0;
85495:         for(i=0; i<aLen[s1]; i++){
85496:           if( (res = v1[i] - v2[i]) ) break;
85497:         }
85498:       }
85499:     }else{
85500:       if( s2>7 ){
85501:         res = +1;
85502:       }else if( s1>7 ){
85503:         res = -1;
85504:       }else{
85505:         res = s1 - s2;
85506:       }
85507:       assert( res!=0 );
85508: 
85509:       if( res>0 ){
85510:         if( *v1 & 0x80 ) res = -1;
85511:       }else{
85512:         if( *v2 & 0x80 ) res = +1;
85513:       }
85514:     }
85515:   }
85516: 
85517:   if( res==0 ){
85518:     if( pTask->pSorter->pKeyInfo->nField>1 ){
85519:       res = vdbeSorterCompareTail(
85520:           pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
85521:       );
85522:     }
85523:   }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
85524:     res = res * -1;
85525:   }
85526: 
85527:   return res;
85528: }
85529: 
85530: /*
85531: ** Initialize the temporary index cursor just opened as a sorter cursor.
85532: **
85533: ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
85534: ** to determine the number of fields that should be compared from the
85535: ** records being sorted. However, if the value passed as argument nField
85536: ** is non-zero and the sorter is able to guarantee a stable sort, nField
85537: ** is used instead. This is used when sorting records for a CREATE INDEX
85538: ** statement. In this case, keys are always delivered to the sorter in
85539: ** order of the primary key, which happens to be make up the final part 
85540: ** of the records being sorted. So if the sort is stable, there is never
85541: ** any reason to compare PK fields and they can be ignored for a small
85542: ** performance boost.
85543: **
85544: ** The sorter can guarantee a stable sort when running in single-threaded
85545: ** mode, but not in multi-threaded mode.
85546: **
85547: ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
85548: */
85549: SQLITE_PRIVATE int sqlite3VdbeSorterInit(
85550:   sqlite3 *db,                    /* Database connection (for malloc()) */
85551:   int nField,                     /* Number of key fields in each record */
85552:   VdbeCursor *pCsr                /* Cursor that holds the new sorter */
85553: ){
85554:   int pgsz;                       /* Page size of main database */
85555:   int i;                          /* Used to iterate through aTask[] */
85556:   VdbeSorter *pSorter;            /* The new sorter */
85557:   KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
85558:   int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
85559:   int sz;                         /* Size of pSorter in bytes */
85560:   int rc = SQLITE_OK;
85561: #if SQLITE_MAX_WORKER_THREADS==0
85562: # define nWorker 0
85563: #else
85564:   int nWorker;
85565: #endif
85566: 
85567:   /* Initialize the upper limit on the number of worker threads */
85568: #if SQLITE_MAX_WORKER_THREADS>0
85569:   if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
85570:     nWorker = 0;
85571:   }else{
85572:     nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
85573:   }
85574: #endif
85575: 
85576:   /* Do not allow the total number of threads (main thread + all workers)
85577:   ** to exceed the maximum merge count */
85578: #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
85579:   if( nWorker>=SORTER_MAX_MERGE_COUNT ){
85580:     nWorker = SORTER_MAX_MERGE_COUNT-1;
85581:   }
85582: #endif
85583: 
85584:   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
85585:   assert( pCsr->eCurType==CURTYPE_SORTER );
85586:   szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
85587:   sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
85588: 
85589:   pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
85590:   pCsr->uc.pSorter = pSorter;
85591:   if( pSorter==0 ){
85592:     rc = SQLITE_NOMEM_BKPT;
85593:   }else{
85594:     pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
85595:     memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
85596:     pKeyInfo->db = 0;
85597:     if( nField && nWorker==0 ){
85598:       pKeyInfo->nXField += (pKeyInfo->nField - nField);
85599:       pKeyInfo->nField = nField;
85600:     }
85601:     pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
85602:     pSorter->nTask = nWorker + 1;
85603:     pSorter->iPrev = (u8)(nWorker - 1);
85604:     pSorter->bUseThreads = (pSorter->nTask>1);
85605:     pSorter->db = db;
85606:     for(i=0; i<pSorter->nTask; i++){
85607:       SortSubtask *pTask = &pSorter->aTask[i];
85608:       pTask->pSorter = pSorter;
85609:     }
85610: 
85611:     if( !sqlite3TempInMemory(db) ){
85612:       i64 mxCache;                /* Cache size in bytes*/
85613:       u32 szPma = sqlite3GlobalConfig.szPma;
85614:       pSorter->mnPmaSize = szPma * pgsz;
85615: 
85616:       mxCache = db->aDb[0].pSchema->cache_size;
85617:       if( mxCache<0 ){
85618:         /* A negative cache-size value C indicates that the cache is abs(C)
85619:         ** KiB in size.  */
85620:         mxCache = mxCache * -1024;
85621:       }else{
85622:         mxCache = mxCache * pgsz;
85623:       }
85624:       mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85625:       pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
85626: 
85627:       /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
85628:       ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
85629:       ** large heap allocations.
85630:       */
85631:       if( sqlite3GlobalConfig.pScratch==0 ){
85632:         assert( pSorter->iMemory==0 );
85633:         pSorter->nMemory = pgsz;
85634:         pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
85635:         if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
85636:       }
85637:     }
85638: 
85639:     if( (pKeyInfo->nField+pKeyInfo->nXField)<13 
85640:      && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
85641:     ){
85642:       pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
85643:     }
85644:   }
85645: 
85646:   return rc;
85647: }
85648: #undef nWorker   /* Defined at the top of this function */
85649: 
85650: /*
85651: ** Free the list of sorted records starting at pRecord.
85652: */
85653: static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
85654:   SorterRecord *p;
85655:   SorterRecord *pNext;
85656:   for(p=pRecord; p; p=pNext){
85657:     pNext = p->u.pNext;
85658:     sqlite3DbFree(db, p);
85659:   }
85660: }
85661: 
85662: /*
85663: ** Free all resources owned by the object indicated by argument pTask. All 
85664: ** fields of *pTask are zeroed before returning.
85665: */
85666: static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
85667:   sqlite3DbFree(db, pTask->pUnpacked);
85668: #if SQLITE_MAX_WORKER_THREADS>0
85669:   /* pTask->list.aMemory can only be non-zero if it was handed memory
85670:   ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
85671:   if( pTask->list.aMemory ){
85672:     sqlite3_free(pTask->list.aMemory);
85673:   }else
85674: #endif
85675:   {
85676:     assert( pTask->list.aMemory==0 );
85677:     vdbeSorterRecordFree(0, pTask->list.pList);
85678:   }
85679:   if( pTask->file.pFd ){
85680:     sqlite3OsCloseFree(pTask->file.pFd);
85681:   }
85682:   if( pTask->file2.pFd ){
85683:     sqlite3OsCloseFree(pTask->file2.pFd);
85684:   }
85685:   memset(pTask, 0, sizeof(SortSubtask));
85686: }
85687: 
85688: #ifdef SQLITE_DEBUG_SORTER_THREADS
85689: static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
85690:   i64 t;
85691:   int iTask = (pTask - pTask->pSorter->aTask);
85692:   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85693:   fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
85694: }
85695: static void vdbeSorterRewindDebug(const char *zEvent){
85696:   i64 t;
85697:   sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
85698:   fprintf(stderr, "%lld:X %s\n", t, zEvent);
85699: }
85700: static void vdbeSorterPopulateDebug(
85701:   SortSubtask *pTask,
85702:   const char *zEvent
85703: ){
85704:   i64 t;
85705:   int iTask = (pTask - pTask->pSorter->aTask);
85706:   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85707:   fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
85708: }
85709: static void vdbeSorterBlockDebug(
85710:   SortSubtask *pTask,
85711:   int bBlocked,
85712:   const char *zEvent
85713: ){
85714:   if( bBlocked ){
85715:     i64 t;
85716:     sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85717:     fprintf(stderr, "%lld:main %s\n", t, zEvent);
85718:   }
85719: }
85720: #else
85721: # define vdbeSorterWorkDebug(x,y)
85722: # define vdbeSorterRewindDebug(y)
85723: # define vdbeSorterPopulateDebug(x,y)
85724: # define vdbeSorterBlockDebug(x,y,z)
85725: #endif
85726: 
85727: #if SQLITE_MAX_WORKER_THREADS>0
85728: /*
85729: ** Join thread pTask->thread.
85730: */
85731: static int vdbeSorterJoinThread(SortSubtask *pTask){
85732:   int rc = SQLITE_OK;
85733:   if( pTask->pThread ){
85734: #ifdef SQLITE_DEBUG_SORTER_THREADS
85735:     int bDone = pTask->bDone;
85736: #endif
85737:     void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
85738:     vdbeSorterBlockDebug(pTask, !bDone, "enter");
85739:     (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
85740:     vdbeSorterBlockDebug(pTask, !bDone, "exit");
85741:     rc = SQLITE_PTR_TO_INT(pRet);
85742:     assert( pTask->bDone==1 );
85743:     pTask->bDone = 0;
85744:     pTask->pThread = 0;
85745:   }
85746:   return rc;
85747: }
85748: 
85749: /*
85750: ** Launch a background thread to run xTask(pIn).
85751: */
85752: static int vdbeSorterCreateThread(
85753:   SortSubtask *pTask,             /* Thread will use this task object */
85754:   void *(*xTask)(void*),          /* Routine to run in a separate thread */
85755:   void *pIn                       /* Argument passed into xTask() */
85756: ){
85757:   assert( pTask->pThread==0 && pTask->bDone==0 );
85758:   return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
85759: }
85760: 
85761: /*
85762: ** Join all outstanding threads launched by SorterWrite() to create 
85763: ** level-0 PMAs.
85764: */
85765: static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
85766:   int rc = rcin;
85767:   int i;
85768: 
85769:   /* This function is always called by the main user thread.
85770:   **
85771:   ** If this function is being called after SorterRewind() has been called, 
85772:   ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
85773:   ** is currently attempt to join one of the other threads. To avoid a race
85774:   ** condition where this thread also attempts to join the same object, join 
85775:   ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
85776:   for(i=pSorter->nTask-1; i>=0; i--){
85777:     SortSubtask *pTask = &pSorter->aTask[i];
85778:     int rc2 = vdbeSorterJoinThread(pTask);
85779:     if( rc==SQLITE_OK ) rc = rc2;
85780:   }
85781:   return rc;
85782: }
85783: #else
85784: # define vdbeSorterJoinAll(x,rcin) (rcin)
85785: # define vdbeSorterJoinThread(pTask) SQLITE_OK
85786: #endif
85787: 
85788: /*
85789: ** Allocate a new MergeEngine object capable of handling up to
85790: ** nReader PmaReader inputs.
85791: **
85792: ** nReader is automatically rounded up to the next power of two.
85793: ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
85794: */
85795: static MergeEngine *vdbeMergeEngineNew(int nReader){
85796:   int N = 2;                      /* Smallest power of two >= nReader */
85797:   int nByte;                      /* Total bytes of space to allocate */
85798:   MergeEngine *pNew;              /* Pointer to allocated object to return */
85799: 
85800:   assert( nReader<=SORTER_MAX_MERGE_COUNT );
85801: 
85802:   while( N<nReader ) N += N;
85803:   nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
85804: 
85805:   pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
85806:   if( pNew ){
85807:     pNew->nTree = N;
85808:     pNew->pTask = 0;
85809:     pNew->aReadr = (PmaReader*)&pNew[1];
85810:     pNew->aTree = (int*)&pNew->aReadr[N];
85811:   }
85812:   return pNew;
85813: }
85814: 
85815: /*
85816: ** Free the MergeEngine object passed as the only argument.
85817: */
85818: static void vdbeMergeEngineFree(MergeEngine *pMerger){
85819:   int i;
85820:   if( pMerger ){
85821:     for(i=0; i<pMerger->nTree; i++){
85822:       vdbePmaReaderClear(&pMerger->aReadr[i]);
85823:     }
85824:   }
85825:   sqlite3_free(pMerger);
85826: }
85827: 
85828: /*
85829: ** Free all resources associated with the IncrMerger object indicated by
85830: ** the first argument.
85831: */
85832: static void vdbeIncrFree(IncrMerger *pIncr){
85833:   if( pIncr ){
85834: #if SQLITE_MAX_WORKER_THREADS>0
85835:     if( pIncr->bUseThread ){
85836:       vdbeSorterJoinThread(pIncr->pTask);
85837:       if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
85838:       if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
85839:     }
85840: #endif
85841:     vdbeMergeEngineFree(pIncr->pMerger);
85842:     sqlite3_free(pIncr);
85843:   }
85844: }
85845: 
85846: /*
85847: ** Reset a sorting cursor back to its original empty state.
85848: */
85849: SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
85850:   int i;
85851:   (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
85852:   assert( pSorter->bUseThreads || pSorter->pReader==0 );
85853: #if SQLITE_MAX_WORKER_THREADS>0
85854:   if( pSorter->pReader ){
85855:     vdbePmaReaderClear(pSorter->pReader);
85856:     sqlite3DbFree(db, pSorter->pReader);
85857:     pSorter->pReader = 0;
85858:   }
85859: #endif
85860:   vdbeMergeEngineFree(pSorter->pMerger);
85861:   pSorter->pMerger = 0;
85862:   for(i=0; i<pSorter->nTask; i++){
85863:     SortSubtask *pTask = &pSorter->aTask[i];
85864:     vdbeSortSubtaskCleanup(db, pTask);
85865:     pTask->pSorter = pSorter;
85866:   }
85867:   if( pSorter->list.aMemory==0 ){
85868:     vdbeSorterRecordFree(0, pSorter->list.pList);
85869:   }
85870:   pSorter->list.pList = 0;
85871:   pSorter->list.szPMA = 0;
85872:   pSorter->bUsePMA = 0;
85873:   pSorter->iMemory = 0;
85874:   pSorter->mxKeysize = 0;
85875:   sqlite3DbFree(db, pSorter->pUnpacked);
85876:   pSorter->pUnpacked = 0;
85877: }
85878: 
85879: /*
85880: ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
85881: */
85882: SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
85883:   VdbeSorter *pSorter;
85884:   assert( pCsr->eCurType==CURTYPE_SORTER );
85885:   pSorter = pCsr->uc.pSorter;
85886:   if( pSorter ){
85887:     sqlite3VdbeSorterReset(db, pSorter);
85888:     sqlite3_free(pSorter->list.aMemory);
85889:     sqlite3DbFree(db, pSorter);
85890:     pCsr->uc.pSorter = 0;
85891:   }
85892: }
85893: 
85894: #if SQLITE_MAX_MMAP_SIZE>0
85895: /*
85896: ** The first argument is a file-handle open on a temporary file. The file
85897: ** is guaranteed to be nByte bytes or smaller in size. This function
85898: ** attempts to extend the file to nByte bytes in size and to ensure that
85899: ** the VFS has memory mapped it.
85900: **
85901: ** Whether or not the file does end up memory mapped of course depends on
85902: ** the specific VFS implementation.
85903: */
85904: static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
85905:   if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
85906:     void *p = 0;
85907:     int chunksize = 4*1024;
85908:     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
85909:     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
85910:     sqlite3OsFetch(pFd, 0, (int)nByte, &p);
85911:     sqlite3OsUnfetch(pFd, 0, p);
85912:   }
85913: }
85914: #else
85915: # define vdbeSorterExtendFile(x,y,z)
85916: #endif
85917: 
85918: /*
85919: ** Allocate space for a file-handle and open a temporary file. If successful,
85920: ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
85921: ** Otherwise, set *ppFd to 0 and return an SQLite error code.
85922: */
85923: static int vdbeSorterOpenTempFile(
85924:   sqlite3 *db,                    /* Database handle doing sort */
85925:   i64 nExtend,                    /* Attempt to extend file to this size */
85926:   sqlite3_file **ppFd
85927: ){
85928:   int rc;
85929:   if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
85930:   rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
85931:       SQLITE_OPEN_TEMP_JOURNAL |
85932:       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
85933:       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
85934:   );
85935:   if( rc==SQLITE_OK ){
85936:     i64 max = SQLITE_MAX_MMAP_SIZE;
85937:     sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
85938:     if( nExtend>0 ){
85939:       vdbeSorterExtendFile(db, *ppFd, nExtend);
85940:     }
85941:   }
85942:   return rc;
85943: }
85944: 
85945: /*
85946: ** If it has not already been allocated, allocate the UnpackedRecord 
85947: ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or 
85948: ** if no allocation was required), or SQLITE_NOMEM otherwise.
85949: */
85950: static int vdbeSortAllocUnpacked(SortSubtask *pTask){
85951:   if( pTask->pUnpacked==0 ){
85952:     char *pFree;
85953:     pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
85954:         pTask->pSorter->pKeyInfo, 0, 0, &pFree
85955:     );
85956:     assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
85957:     if( pFree==0 ) return SQLITE_NOMEM_BKPT;
85958:     pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
85959:     pTask->pUnpacked->errCode = 0;
85960:   }
85961:   return SQLITE_OK;
85962: }
85963: 
85964: 
85965: /*
85966: ** Merge the two sorted lists p1 and p2 into a single list.
85967: */
85968: static SorterRecord *vdbeSorterMerge(
85969:   SortSubtask *pTask,             /* Calling thread context */
85970:   SorterRecord *p1,               /* First list to merge */
85971:   SorterRecord *p2                /* Second list to merge */
85972: ){
85973:   SorterRecord *pFinal = 0;
85974:   SorterRecord **pp = &pFinal;
85975:   int bCached = 0;
85976: 
85977:   assert( p1!=0 && p2!=0 );
85978:   for(;;){
85979:     int res;
85980:     res = pTask->xCompare(
85981:         pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
85982:     );
85983: 
85984:     if( res<=0 ){
85985:       *pp = p1;
85986:       pp = &p1->u.pNext;
85987:       p1 = p1->u.pNext;
85988:       if( p1==0 ){
85989:         *pp = p2;
85990:         break;
85991:       }
85992:     }else{
85993:       *pp = p2;
85994:       pp = &p2->u.pNext;
85995:       p2 = p2->u.pNext;
85996:       bCached = 0;
85997:       if( p2==0 ){
85998:         *pp = p1;
85999:         break;
86000:       }
86001:     }
86002:   }
86003:   return pFinal;
86004: }
86005: 
86006: /*
86007: ** Return the SorterCompare function to compare values collected by the
86008: ** sorter object passed as the only argument.
86009: */
86010: static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
86011:   if( p->typeMask==SORTER_TYPE_INTEGER ){
86012:     return vdbeSorterCompareInt;
86013:   }else if( p->typeMask==SORTER_TYPE_TEXT ){
86014:     return vdbeSorterCompareText; 
86015:   }
86016:   return vdbeSorterCompare;
86017: }
86018: 
86019: /*
86020: ** Sort the linked list of records headed at pTask->pList. Return 
86021: ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if 
86022: ** an error occurs.
86023: */
86024: static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
86025:   int i;
86026:   SorterRecord **aSlot;
86027:   SorterRecord *p;
86028:   int rc;
86029: 
86030:   rc = vdbeSortAllocUnpacked(pTask);
86031:   if( rc!=SQLITE_OK ) return rc;
86032: 
86033:   p = pList->pList;
86034:   pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
86035: 
86036:   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
86037:   if( !aSlot ){
86038:     return SQLITE_NOMEM_BKPT;
86039:   }
86040: 
86041:   while( p ){
86042:     SorterRecord *pNext;
86043:     if( pList->aMemory ){
86044:       if( (u8*)p==pList->aMemory ){
86045:         pNext = 0;
86046:       }else{
86047:         assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
86048:         pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
86049:       }
86050:     }else{
86051:       pNext = p->u.pNext;
86052:     }
86053: 
86054:     p->u.pNext = 0;
86055:     for(i=0; aSlot[i]; i++){
86056:       p = vdbeSorterMerge(pTask, p, aSlot[i]);
86057:       aSlot[i] = 0;
86058:     }
86059:     aSlot[i] = p;
86060:     p = pNext;
86061:   }
86062: 
86063:   p = 0;
86064:   for(i=0; i<64; i++){
86065:     if( aSlot[i]==0 ) continue;
86066:     p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
86067:   }
86068:   pList->pList = p;
86069: 
86070:   sqlite3_free(aSlot);
86071:   assert( pTask->pUnpacked->errCode==SQLITE_OK 
86072:        || pTask->pUnpacked->errCode==SQLITE_NOMEM 
86073:   );
86074:   return pTask->pUnpacked->errCode;
86075: }
86076: 
86077: /*
86078: ** Initialize a PMA-writer object.
86079: */
86080: static void vdbePmaWriterInit(
86081:   sqlite3_file *pFd,              /* File handle to write to */
86082:   PmaWriter *p,                   /* Object to populate */
86083:   int nBuf,                       /* Buffer size */
86084:   i64 iStart                      /* Offset of pFd to begin writing at */
86085: ){
86086:   memset(p, 0, sizeof(PmaWriter));
86087:   p->aBuffer = (u8*)sqlite3Malloc(nBuf);
86088:   if( !p->aBuffer ){
86089:     p->eFWErr = SQLITE_NOMEM_BKPT;
86090:   }else{
86091:     p->iBufEnd = p->iBufStart = (iStart % nBuf);
86092:     p->iWriteOff = iStart - p->iBufStart;
86093:     p->nBuffer = nBuf;
86094:     p->pFd = pFd;
86095:   }
86096: }
86097: 
86098: /*
86099: ** Write nData bytes of data to the PMA. Return SQLITE_OK
86100: ** if successful, or an SQLite error code if an error occurs.
86101: */
86102: static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
86103:   int nRem = nData;
86104:   while( nRem>0 && p->eFWErr==0 ){
86105:     int nCopy = nRem;
86106:     if( nCopy>(p->nBuffer - p->iBufEnd) ){
86107:       nCopy = p->nBuffer - p->iBufEnd;
86108:     }
86109: 
86110:     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
86111:     p->iBufEnd += nCopy;
86112:     if( p->iBufEnd==p->nBuffer ){
86113:       p->eFWErr = sqlite3OsWrite(p->pFd, 
86114:           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
86115:           p->iWriteOff + p->iBufStart
86116:       );
86117:       p->iBufStart = p->iBufEnd = 0;
86118:       p->iWriteOff += p->nBuffer;
86119:     }
86120:     assert( p->iBufEnd<p->nBuffer );
86121: 
86122:     nRem -= nCopy;
86123:   }
86124: }
86125: 
86126: /*
86127: ** Flush any buffered data to disk and clean up the PMA-writer object.
86128: ** The results of using the PMA-writer after this call are undefined.
86129: ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
86130: ** required. Otherwise, return an SQLite error code.
86131: **
86132: ** Before returning, set *piEof to the offset immediately following the
86133: ** last byte written to the file.
86134: */
86135: static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
86136:   int rc;
86137:   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
86138:     p->eFWErr = sqlite3OsWrite(p->pFd, 
86139:         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
86140:         p->iWriteOff + p->iBufStart
86141:     );
86142:   }
86143:   *piEof = (p->iWriteOff + p->iBufEnd);
86144:   sqlite3_free(p->aBuffer);
86145:   rc = p->eFWErr;
86146:   memset(p, 0, sizeof(PmaWriter));
86147:   return rc;
86148: }
86149: 
86150: /*
86151: ** Write value iVal encoded as a varint to the PMA. Return 
86152: ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
86153: */
86154: static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
86155:   int nByte; 
86156:   u8 aByte[10];
86157:   nByte = sqlite3PutVarint(aByte, iVal);
86158:   vdbePmaWriteBlob(p, aByte, nByte);
86159: }
86160: 
86161: /*
86162: ** Write the current contents of in-memory linked-list pList to a level-0
86163: ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if 
86164: ** successful, or an SQLite error code otherwise.
86165: **
86166: ** The format of a PMA is:
86167: **
86168: **     * A varint. This varint contains the total number of bytes of content
86169: **       in the PMA (not including the varint itself).
86170: **
86171: **     * One or more records packed end-to-end in order of ascending keys. 
86172: **       Each record consists of a varint followed by a blob of data (the 
86173: **       key). The varint is the number of bytes in the blob of data.
86174: */
86175: static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
86176:   sqlite3 *db = pTask->pSorter->db;
86177:   int rc = SQLITE_OK;             /* Return code */
86178:   PmaWriter writer;               /* Object used to write to the file */
86179: 
86180: #ifdef SQLITE_DEBUG
86181:   /* Set iSz to the expected size of file pTask->file after writing the PMA. 
86182:   ** This is used by an assert() statement at the end of this function.  */
86183:   i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
86184: #endif
86185: 
86186:   vdbeSorterWorkDebug(pTask, "enter");
86187:   memset(&writer, 0, sizeof(PmaWriter));
86188:   assert( pList->szPMA>0 );
86189: 
86190:   /* If the first temporary PMA file has not been opened, open it now. */
86191:   if( pTask->file.pFd==0 ){
86192:     rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
86193:     assert( rc!=SQLITE_OK || pTask->file.pFd );
86194:     assert( pTask->file.iEof==0 );
86195:     assert( pTask->nPMA==0 );
86196:   }
86197: 
86198:   /* Try to get the file to memory map */
86199:   if( rc==SQLITE_OK ){
86200:     vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
86201:   }
86202: 
86203:   /* Sort the list */
86204:   if( rc==SQLITE_OK ){
86205:     rc = vdbeSorterSort(pTask, pList);
86206:   }
86207: 
86208:   if( rc==SQLITE_OK ){
86209:     SorterRecord *p;
86210:     SorterRecord *pNext = 0;
86211: 
86212:     vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
86213:                       pTask->file.iEof);
86214:     pTask->nPMA++;
86215:     vdbePmaWriteVarint(&writer, pList->szPMA);
86216:     for(p=pList->pList; p; p=pNext){
86217:       pNext = p->u.pNext;
86218:       vdbePmaWriteVarint(&writer, p->nVal);
86219:       vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
86220:       if( pList->aMemory==0 ) sqlite3_free(p);
86221:     }
86222:     pList->pList = p;
86223:     rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
86224:   }
86225: 
86226:   vdbeSorterWorkDebug(pTask, "exit");
86227:   assert( rc!=SQLITE_OK || pList->pList==0 );
86228:   assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
86229:   return rc;
86230: }
86231: 
86232: /*
86233: ** Advance the MergeEngine to its next entry.
86234: ** Set *pbEof to true there is no next entry because
86235: ** the MergeEngine has reached the end of all its inputs.
86236: **
86237: ** Return SQLITE_OK if successful or an error code if an error occurs.
86238: */
86239: static int vdbeMergeEngineStep(
86240:   MergeEngine *pMerger,      /* The merge engine to advance to the next row */
86241:   int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
86242: ){
86243:   int rc;
86244:   int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
86245:   SortSubtask *pTask = pMerger->pTask;
86246: 
86247:   /* Advance the current PmaReader */
86248:   rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
86249: 
86250:   /* Update contents of aTree[] */
86251:   if( rc==SQLITE_OK ){
86252:     int i;                      /* Index of aTree[] to recalculate */
86253:     PmaReader *pReadr1;         /* First PmaReader to compare */
86254:     PmaReader *pReadr2;         /* Second PmaReader to compare */
86255:     int bCached = 0;
86256: 
86257:     /* Find the first two PmaReaders to compare. The one that was just
86258:     ** advanced (iPrev) and the one next to it in the array.  */
86259:     pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
86260:     pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
86261: 
86262:     for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
86263:       /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
86264:       int iRes;
86265:       if( pReadr1->pFd==0 ){
86266:         iRes = +1;
86267:       }else if( pReadr2->pFd==0 ){
86268:         iRes = -1;
86269:       }else{
86270:         iRes = pTask->xCompare(pTask, &bCached,
86271:             pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
86272:         );
86273:       }
86274: 
86275:       /* If pReadr1 contained the smaller value, set aTree[i] to its index.
86276:       ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
86277:       ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
86278:       ** pKey2 to point to the record belonging to pReadr2.
86279:       **
86280:       ** Alternatively, if pReadr2 contains the smaller of the two values,
86281:       ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
86282:       ** was actually called above, then pTask->pUnpacked now contains
86283:       ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
86284:       ** vdbeSorterCompare() from decoding pReadr2 again.
86285:       **
86286:       ** If the two values were equal, then the value from the oldest
86287:       ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
86288:       ** is sorted from oldest to newest, so pReadr1 contains older values
86289:       ** than pReadr2 iff (pReadr1<pReadr2).  */
86290:       if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
86291:         pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
86292:         pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86293:         bCached = 0;
86294:       }else{
86295:         if( pReadr1->pFd ) bCached = 0;
86296:         pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
86297:         pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
86298:       }
86299:     }
86300:     *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
86301:   }
86302: 
86303:   return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
86304: }
86305: 
86306: #if SQLITE_MAX_WORKER_THREADS>0
86307: /*
86308: ** The main routine for background threads that write level-0 PMAs.
86309: */
86310: static void *vdbeSorterFlushThread(void *pCtx){
86311:   SortSubtask *pTask = (SortSubtask*)pCtx;
86312:   int rc;                         /* Return code */
86313:   assert( pTask->bDone==0 );
86314:   rc = vdbeSorterListToPMA(pTask, &pTask->list);
86315:   pTask->bDone = 1;
86316:   return SQLITE_INT_TO_PTR(rc);
86317: }
86318: #endif /* SQLITE_MAX_WORKER_THREADS>0 */
86319: 
86320: /*
86321: ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
86322: ** using a background thread.
86323: */
86324: static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
86325: #if SQLITE_MAX_WORKER_THREADS==0
86326:   pSorter->bUsePMA = 1;
86327:   return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
86328: #else
86329:   int rc = SQLITE_OK;
86330:   int i;
86331:   SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
86332:   int nWorker = (pSorter->nTask-1);
86333: 
86334:   /* Set the flag to indicate that at least one PMA has been written. 
86335:   ** Or will be, anyhow.  */
86336:   pSorter->bUsePMA = 1;
86337: 
86338:   /* Select a sub-task to sort and flush the current list of in-memory
86339:   ** records to disk. If the sorter is running in multi-threaded mode,
86340:   ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
86341:   ** the background thread from a sub-tasks previous turn is still running,
86342:   ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
86343:   ** fall back to using the final sub-task. The first (pSorter->nTask-1)
86344:   ** sub-tasks are prefered as they use background threads - the final 
86345:   ** sub-task uses the main thread. */
86346:   for(i=0; i<nWorker; i++){
86347:     int iTest = (pSorter->iPrev + i + 1) % nWorker;
86348:     pTask = &pSorter->aTask[iTest];
86349:     if( pTask->bDone ){
86350:       rc = vdbeSorterJoinThread(pTask);
86351:     }
86352:     if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
86353:   }
86354: 
86355:   if( rc==SQLITE_OK ){
86356:     if( i==nWorker ){
86357:       /* Use the foreground thread for this operation */
86358:       rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
86359:     }else{
86360:       /* Launch a background thread for this operation */
86361:       u8 *aMem = pTask->list.aMemory;
86362:       void *pCtx = (void*)pTask;
86363: 
86364:       assert( pTask->pThread==0 && pTask->bDone==0 );
86365:       assert( pTask->list.pList==0 );
86366:       assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
86367: 
86368:       pSorter->iPrev = (u8)(pTask - pSorter->aTask);
86369:       pTask->list = pSorter->list;
86370:       pSorter->list.pList = 0;
86371:       pSorter->list.szPMA = 0;
86372:       if( aMem ){
86373:         pSorter->list.aMemory = aMem;
86374:         pSorter->nMemory = sqlite3MallocSize(aMem);
86375:       }else if( pSorter->list.aMemory ){
86376:         pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
86377:         if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
86378:       }
86379: 
86380:       rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
86381:     }
86382:   }
86383: 
86384:   return rc;
86385: #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
86386: }
86387: 
86388: /*
86389: ** Add a record to the sorter.
86390: */
86391: SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
86392:   const VdbeCursor *pCsr,         /* Sorter cursor */
86393:   Mem *pVal                       /* Memory cell containing record */
86394: ){
86395:   VdbeSorter *pSorter;
86396:   int rc = SQLITE_OK;             /* Return Code */
86397:   SorterRecord *pNew;             /* New list element */
86398:   int bFlush;                     /* True to flush contents of memory to PMA */
86399:   int nReq;                       /* Bytes of memory required */
86400:   int nPMA;                       /* Bytes of PMA space required */
86401:   int t;                          /* serial type of first record field */
86402: 
86403:   assert( pCsr->eCurType==CURTYPE_SORTER );
86404:   pSorter = pCsr->uc.pSorter;
86405:   getVarint32((const u8*)&pVal->z[1], t);
86406:   if( t>0 && t<10 && t!=7 ){
86407:     pSorter->typeMask &= SORTER_TYPE_INTEGER;
86408:   }else if( t>10 && (t & 0x01) ){
86409:     pSorter->typeMask &= SORTER_TYPE_TEXT;
86410:   }else{
86411:     pSorter->typeMask = 0;
86412:   }
86413: 
86414:   assert( pSorter );
86415: 
86416:   /* Figure out whether or not the current contents of memory should be
86417:   ** flushed to a PMA before continuing. If so, do so.
86418:   **
86419:   ** If using the single large allocation mode (pSorter->aMemory!=0), then
86420:   ** flush the contents of memory to a new PMA if (a) at least one value is
86421:   ** already in memory and (b) the new value will not fit in memory.
86422:   ** 
86423:   ** Or, if using separate allocations for each record, flush the contents
86424:   ** of memory to a PMA if either of the following are true:
86425:   **
86426:   **   * The total memory allocated for the in-memory list is greater 
86427:   **     than (page-size * cache-size), or
86428:   **
86429:   **   * The total memory allocated for the in-memory list is greater 
86430:   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
86431:   */
86432:   nReq = pVal->n + sizeof(SorterRecord);
86433:   nPMA = pVal->n + sqlite3VarintLen(pVal->n);
86434:   if( pSorter->mxPmaSize ){
86435:     if( pSorter->list.aMemory ){
86436:       bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
86437:     }else{
86438:       bFlush = (
86439:           (pSorter->list.szPMA > pSorter->mxPmaSize)
86440:        || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
86441:       );
86442:     }
86443:     if( bFlush ){
86444:       rc = vdbeSorterFlushPMA(pSorter);
86445:       pSorter->list.szPMA = 0;
86446:       pSorter->iMemory = 0;
86447:       assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
86448:     }
86449:   }
86450: 
86451:   pSorter->list.szPMA += nPMA;
86452:   if( nPMA>pSorter->mxKeysize ){
86453:     pSorter->mxKeysize = nPMA;
86454:   }
86455: 
86456:   if( pSorter->list.aMemory ){
86457:     int nMin = pSorter->iMemory + nReq;
86458: 
86459:     if( nMin>pSorter->nMemory ){
86460:       u8 *aNew;
86461:       int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
86462:       int nNew = pSorter->nMemory * 2;
86463:       while( nNew < nMin ) nNew = nNew*2;
86464:       if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
86465:       if( nNew < nMin ) nNew = nMin;
86466: 
86467:       aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
86468:       if( !aNew ) return SQLITE_NOMEM_BKPT;
86469:       pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
86470:       pSorter->list.aMemory = aNew;
86471:       pSorter->nMemory = nNew;
86472:     }
86473: 
86474:     pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
86475:     pSorter->iMemory += ROUND8(nReq);
86476:     if( pSorter->list.pList ){
86477:       pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
86478:     }
86479:   }else{
86480:     pNew = (SorterRecord *)sqlite3Malloc(nReq);
86481:     if( pNew==0 ){
86482:       return SQLITE_NOMEM_BKPT;
86483:     }
86484:     pNew->u.pNext = pSorter->list.pList;
86485:   }
86486: 
86487:   memcpy(SRVAL(pNew), pVal->z, pVal->n);
86488:   pNew->nVal = pVal->n;
86489:   pSorter->list.pList = pNew;
86490: 
86491:   return rc;
86492: }
86493: 
86494: /*
86495: ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
86496: ** of the data stored in aFile[1] is the same as that used by regular PMAs,
86497: ** except that the number-of-bytes varint is omitted from the start.
86498: */
86499: static int vdbeIncrPopulate(IncrMerger *pIncr){
86500:   int rc = SQLITE_OK;
86501:   int rc2;
86502:   i64 iStart = pIncr->iStartOff;
86503:   SorterFile *pOut = &pIncr->aFile[1];
86504:   SortSubtask *pTask = pIncr->pTask;
86505:   MergeEngine *pMerger = pIncr->pMerger;
86506:   PmaWriter writer;
86507:   assert( pIncr->bEof==0 );
86508: 
86509:   vdbeSorterPopulateDebug(pTask, "enter");
86510: 
86511:   vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
86512:   while( rc==SQLITE_OK ){
86513:     int dummy;
86514:     PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
86515:     int nKey = pReader->nKey;
86516:     i64 iEof = writer.iWriteOff + writer.iBufEnd;
86517: 
86518:     /* Check if the output file is full or if the input has been exhausted.
86519:     ** In either case exit the loop. */
86520:     if( pReader->pFd==0 ) break;
86521:     if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
86522: 
86523:     /* Write the next key to the output. */
86524:     vdbePmaWriteVarint(&writer, nKey);
86525:     vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
86526:     assert( pIncr->pMerger->pTask==pTask );
86527:     rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
86528:   }
86529: 
86530:   rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
86531:   if( rc==SQLITE_OK ) rc = rc2;
86532:   vdbeSorterPopulateDebug(pTask, "exit");
86533:   return rc;
86534: }
86535: 
86536: #if SQLITE_MAX_WORKER_THREADS>0
86537: /*
86538: ** The main routine for background threads that populate aFile[1] of
86539: ** multi-threaded IncrMerger objects.
86540: */
86541: static void *vdbeIncrPopulateThread(void *pCtx){
86542:   IncrMerger *pIncr = (IncrMerger*)pCtx;
86543:   void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
86544:   pIncr->pTask->bDone = 1;
86545:   return pRet;
86546: }
86547: 
86548: /*
86549: ** Launch a background thread to populate aFile[1] of pIncr.
86550: */
86551: static int vdbeIncrBgPopulate(IncrMerger *pIncr){
86552:   void *p = (void*)pIncr;
86553:   assert( pIncr->bUseThread );
86554:   return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
86555: }
86556: #endif
86557: 
86558: /*
86559: ** This function is called when the PmaReader corresponding to pIncr has
86560: ** finished reading the contents of aFile[0]. Its purpose is to "refill"
86561: ** aFile[0] such that the PmaReader should start rereading it from the
86562: ** beginning.
86563: **
86564: ** For single-threaded objects, this is accomplished by literally reading 
86565: ** keys from pIncr->pMerger and repopulating aFile[0]. 
86566: **
86567: ** For multi-threaded objects, all that is required is to wait until the 
86568: ** background thread is finished (if it is not already) and then swap 
86569: ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
86570: ** been exhausted, this function also launches a new background thread
86571: ** to populate the new aFile[1].
86572: **
86573: ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
86574: */
86575: static int vdbeIncrSwap(IncrMerger *pIncr){
86576:   int rc = SQLITE_OK;
86577: 
86578: #if SQLITE_MAX_WORKER_THREADS>0
86579:   if( pIncr->bUseThread ){
86580:     rc = vdbeSorterJoinThread(pIncr->pTask);
86581: 
86582:     if( rc==SQLITE_OK ){
86583:       SorterFile f0 = pIncr->aFile[0];
86584:       pIncr->aFile[0] = pIncr->aFile[1];
86585:       pIncr->aFile[1] = f0;
86586:     }
86587: 
86588:     if( rc==SQLITE_OK ){
86589:       if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86590:         pIncr->bEof = 1;
86591:       }else{
86592:         rc = vdbeIncrBgPopulate(pIncr);
86593:       }
86594:     }
86595:   }else
86596: #endif
86597:   {
86598:     rc = vdbeIncrPopulate(pIncr);
86599:     pIncr->aFile[0] = pIncr->aFile[1];
86600:     if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86601:       pIncr->bEof = 1;
86602:     }
86603:   }
86604: 
86605:   return rc;
86606: }
86607: 
86608: /*
86609: ** Allocate and return a new IncrMerger object to read data from pMerger.
86610: **
86611: ** If an OOM condition is encountered, return NULL. In this case free the
86612: ** pMerger argument before returning.
86613: */
86614: static int vdbeIncrMergerNew(
86615:   SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
86616:   MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
86617:   IncrMerger **ppOut      /* Write the new IncrMerger here */
86618: ){
86619:   int rc = SQLITE_OK;
86620:   IncrMerger *pIncr = *ppOut = (IncrMerger*)
86621:        (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
86622:   if( pIncr ){
86623:     pIncr->pMerger = pMerger;
86624:     pIncr->pTask = pTask;
86625:     pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
86626:     pTask->file2.iEof += pIncr->mxSz;
86627:   }else{
86628:     vdbeMergeEngineFree(pMerger);
86629:     rc = SQLITE_NOMEM_BKPT;
86630:   }
86631:   return rc;
86632: }
86633: 
86634: #if SQLITE_MAX_WORKER_THREADS>0
86635: /*
86636: ** Set the "use-threads" flag on object pIncr.
86637: */
86638: static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
86639:   pIncr->bUseThread = 1;
86640:   pIncr->pTask->file2.iEof -= pIncr->mxSz;
86641: }
86642: #endif /* SQLITE_MAX_WORKER_THREADS>0 */
86643: 
86644: 
86645: 
86646: /*
86647: ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
86648: ** two PmaReaders that feed that entry.  Neither of the PmaReaders
86649: ** are advanced.  This routine merely does the comparison.
86650: */
86651: static void vdbeMergeEngineCompare(
86652:   MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
86653:   int iOut               /* Store the result in pMerger->aTree[iOut] */
86654: ){
86655:   int i1;
86656:   int i2;
86657:   int iRes;
86658:   PmaReader *p1;
86659:   PmaReader *p2;
86660: 
86661:   assert( iOut<pMerger->nTree && iOut>0 );
86662: 
86663:   if( iOut>=(pMerger->nTree/2) ){
86664:     i1 = (iOut - pMerger->nTree/2) * 2;
86665:     i2 = i1 + 1;
86666:   }else{
86667:     i1 = pMerger->aTree[iOut*2];
86668:     i2 = pMerger->aTree[iOut*2+1];
86669:   }
86670: 
86671:   p1 = &pMerger->aReadr[i1];
86672:   p2 = &pMerger->aReadr[i2];
86673: 
86674:   if( p1->pFd==0 ){
86675:     iRes = i2;
86676:   }else if( p2->pFd==0 ){
86677:     iRes = i1;
86678:   }else{
86679:     SortSubtask *pTask = pMerger->pTask;
86680:     int bCached = 0;
86681:     int res;
86682:     assert( pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
86683:     res = pTask->xCompare(
86684:         pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
86685:     );
86686:     if( res<=0 ){
86687:       iRes = i1;
86688:     }else{
86689:       iRes = i2;
86690:     }
86691:   }
86692: 
86693:   pMerger->aTree[iOut] = iRes;
86694: }
86695: 
86696: /*
86697: ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
86698: ** and vdbePmaReaderIncrMergeInit().
86699: **
86700: ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
86701: ** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
86702: ** when there exists one or more separate worker threads.
86703: */
86704: #define INCRINIT_NORMAL 0
86705: #define INCRINIT_TASK   1
86706: #define INCRINIT_ROOT   2
86707: 
86708: /* 
86709: ** Forward reference required as the vdbeIncrMergeInit() and
86710: ** vdbePmaReaderIncrInit() routines are called mutually recursively when
86711: ** building a merge tree.
86712: */
86713: static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
86714: 
86715: /*
86716: ** Initialize the MergeEngine object passed as the second argument. Once this
86717: ** function returns, the first key of merged data may be read from the 
86718: ** MergeEngine object in the usual fashion.
86719: **
86720: ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
86721: ** objects attached to the PmaReader objects that the merger reads from have
86722: ** already been populated, but that they have not yet populated aFile[0] and
86723: ** set the PmaReader objects up to read from it. In this case all that is
86724: ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
86725: ** its first key.
86726: **
86727: ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use 
86728: ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data 
86729: ** to pMerger.
86730: **
86731: ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86732: */
86733: static int vdbeMergeEngineInit(
86734:   SortSubtask *pTask,             /* Thread that will run pMerger */
86735:   MergeEngine *pMerger,           /* MergeEngine to initialize */
86736:   int eMode                       /* One of the INCRINIT_XXX constants */
86737: ){
86738:   int rc = SQLITE_OK;             /* Return code */
86739:   int i;                          /* For looping over PmaReader objects */
86740:   int nTree = pMerger->nTree;
86741: 
86742:   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86743:   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86744: 
86745:   /* Verify that the MergeEngine is assigned to a single thread */
86746:   assert( pMerger->pTask==0 );
86747:   pMerger->pTask = pTask;
86748: 
86749:   for(i=0; i<nTree; i++){
86750:     if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
86751:       /* PmaReaders should be normally initialized in order, as if they are
86752:       ** reading from the same temp file this makes for more linear file IO.
86753:       ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
86754:       ** in use it will block the vdbePmaReaderNext() call while it uses
86755:       ** the main thread to fill its buffer. So calling PmaReaderNext()
86756:       ** on this PmaReader before any of the multi-threaded PmaReaders takes
86757:       ** better advantage of multi-processor hardware. */
86758:       rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
86759:     }else{
86760:       rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
86761:     }
86762:     if( rc!=SQLITE_OK ) return rc;
86763:   }
86764: 
86765:   for(i=pMerger->nTree-1; i>0; i--){
86766:     vdbeMergeEngineCompare(pMerger, i);
86767:   }
86768:   return pTask->pUnpacked->errCode;
86769: }
86770: 
86771: /*
86772: ** The PmaReader passed as the first argument is guaranteed to be an
86773: ** incremental-reader (pReadr->pIncr!=0). This function serves to open
86774: ** and/or initialize the temp file related fields of the IncrMerge
86775: ** object at (pReadr->pIncr).
86776: **
86777: ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
86778: ** in the sub-tree headed by pReadr are also initialized. Data is then 
86779: ** loaded into the buffers belonging to pReadr and it is set to point to 
86780: ** the first key in its range.
86781: **
86782: ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
86783: ** to be a multi-threaded PmaReader and this function is being called in a
86784: ** background thread. In this case all PmaReaders in the sub-tree are 
86785: ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
86786: ** pReadr is populated. However, pReadr itself is not set up to point
86787: ** to its first key. A call to vdbePmaReaderNext() is still required to do
86788: ** that. 
86789: **
86790: ** The reason this function does not call vdbePmaReaderNext() immediately 
86791: ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
86792: ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
86793: ** this entire function is being run by thread (pTask->thread), that will
86794: ** lead to the current background thread attempting to join itself.
86795: **
86796: ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
86797: ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
86798: ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
86799: ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
86800: ** the current PmaReader set to point to the first key in its range.
86801: **
86802: ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86803: */
86804: static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
86805:   int rc = SQLITE_OK;
86806:   IncrMerger *pIncr = pReadr->pIncr;
86807:   SortSubtask *pTask = pIncr->pTask;
86808:   sqlite3 *db = pTask->pSorter->db;
86809: 
86810:   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86811:   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
86812: 
86813:   rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
86814: 
86815:   /* Set up the required files for pIncr. A multi-theaded IncrMerge object
86816:   ** requires two temp files to itself, whereas a single-threaded object
86817:   ** only requires a region of pTask->file2. */
86818:   if( rc==SQLITE_OK ){
86819:     int mxSz = pIncr->mxSz;
86820: #if SQLITE_MAX_WORKER_THREADS>0
86821:     if( pIncr->bUseThread ){
86822:       rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
86823:       if( rc==SQLITE_OK ){
86824:         rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
86825:       }
86826:     }else
86827: #endif
86828:     /*if( !pIncr->bUseThread )*/{
86829:       if( pTask->file2.pFd==0 ){
86830:         assert( pTask->file2.iEof>0 );
86831:         rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
86832:         pTask->file2.iEof = 0;
86833:       }
86834:       if( rc==SQLITE_OK ){
86835:         pIncr->aFile[1].pFd = pTask->file2.pFd;
86836:         pIncr->iStartOff = pTask->file2.iEof;
86837:         pTask->file2.iEof += mxSz;
86838:       }
86839:     }
86840:   }
86841: 
86842: #if SQLITE_MAX_WORKER_THREADS>0
86843:   if( rc==SQLITE_OK && pIncr->bUseThread ){
86844:     /* Use the current thread to populate aFile[1], even though this
86845:     ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
86846:     ** then this function is already running in background thread 
86847:     ** pIncr->pTask->thread. 
86848:     **
86849:     ** If this is the INCRINIT_ROOT object, then it is running in the 
86850:     ** main VDBE thread. But that is Ok, as that thread cannot return
86851:     ** control to the VDBE or proceed with anything useful until the 
86852:     ** first results are ready from this merger object anyway.
86853:     */
86854:     assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
86855:     rc = vdbeIncrPopulate(pIncr);
86856:   }
86857: #endif
86858: 
86859:   if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
86860:     rc = vdbePmaReaderNext(pReadr);
86861:   }
86862: 
86863:   return rc;
86864: }
86865: 
86866: #if SQLITE_MAX_WORKER_THREADS>0
86867: /*
86868: ** The main routine for vdbePmaReaderIncrMergeInit() operations run in 
86869: ** background threads.
86870: */
86871: static void *vdbePmaReaderBgIncrInit(void *pCtx){
86872:   PmaReader *pReader = (PmaReader*)pCtx;
86873:   void *pRet = SQLITE_INT_TO_PTR(
86874:                   vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
86875:                );
86876:   pReader->pIncr->pTask->bDone = 1;
86877:   return pRet;
86878: }
86879: #endif
86880: 
86881: /*
86882: ** If the PmaReader passed as the first argument is not an incremental-reader
86883: ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
86884: ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
86885: ** this routine to initialize the incremental merge.
86886: ** 
86887: ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1), 
86888: ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
86889: ** Or, if the IncrMerger is single threaded, the same function is called
86890: ** using the current thread.
86891: */
86892: static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
86893:   IncrMerger *pIncr = pReadr->pIncr;   /* Incremental merger */
86894:   int rc = SQLITE_OK;                  /* Return code */
86895:   if( pIncr ){
86896: #if SQLITE_MAX_WORKER_THREADS>0
86897:     assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
86898:     if( pIncr->bUseThread ){
86899:       void *pCtx = (void*)pReadr;
86900:       rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
86901:     }else
86902: #endif
86903:     {
86904:       rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
86905:     }
86906:   }
86907:   return rc;
86908: }
86909: 
86910: /*
86911: ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
86912: ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
86913: ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
86914: ** to NULL and return an SQLite error code.
86915: **
86916: ** When this function is called, *piOffset is set to the offset of the
86917: ** first PMA to read from pTask->file. Assuming no error occurs, it is 
86918: ** set to the offset immediately following the last byte of the last
86919: ** PMA before returning. If an error does occur, then the final value of
86920: ** *piOffset is undefined.
86921: */
86922: static int vdbeMergeEngineLevel0(
86923:   SortSubtask *pTask,             /* Sorter task to read from */
86924:   int nPMA,                       /* Number of PMAs to read */
86925:   i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
86926:   MergeEngine **ppOut             /* OUT: New merge-engine */
86927: ){
86928:   MergeEngine *pNew;              /* Merge engine to return */
86929:   i64 iOff = *piOffset;
86930:   int i;
86931:   int rc = SQLITE_OK;
86932: 
86933:   *ppOut = pNew = vdbeMergeEngineNew(nPMA);
86934:   if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
86935: 
86936:   for(i=0; i<nPMA && rc==SQLITE_OK; i++){
86937:     i64 nDummy = 0;
86938:     PmaReader *pReadr = &pNew->aReadr[i];
86939:     rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
86940:     iOff = pReadr->iEof;
86941:   }
86942: 
86943:   if( rc!=SQLITE_OK ){
86944:     vdbeMergeEngineFree(pNew);
86945:     *ppOut = 0;
86946:   }
86947:   *piOffset = iOff;
86948:   return rc;
86949: }
86950: 
86951: /*
86952: ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
86953: ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
86954: **
86955: ** i.e.
86956: **
86957: **   nPMA<=16    -> TreeDepth() == 0
86958: **   nPMA<=256   -> TreeDepth() == 1
86959: **   nPMA<=65536 -> TreeDepth() == 2
86960: */
86961: static int vdbeSorterTreeDepth(int nPMA){
86962:   int nDepth = 0;
86963:   i64 nDiv = SORTER_MAX_MERGE_COUNT;
86964:   while( nDiv < (i64)nPMA ){
86965:     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86966:     nDepth++;
86967:   }
86968:   return nDepth;
86969: }
86970: 
86971: /*
86972: ** pRoot is the root of an incremental merge-tree with depth nDepth (according
86973: ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
86974: ** tree, counting from zero. This function adds pLeaf to the tree.
86975: **
86976: ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
86977: ** code is returned and pLeaf is freed.
86978: */
86979: static int vdbeSorterAddToTree(
86980:   SortSubtask *pTask,             /* Task context */
86981:   int nDepth,                     /* Depth of tree according to TreeDepth() */
86982:   int iSeq,                       /* Sequence number of leaf within tree */
86983:   MergeEngine *pRoot,             /* Root of tree */
86984:   MergeEngine *pLeaf              /* Leaf to add to tree */
86985: ){
86986:   int rc = SQLITE_OK;
86987:   int nDiv = 1;
86988:   int i;
86989:   MergeEngine *p = pRoot;
86990:   IncrMerger *pIncr;
86991: 
86992:   rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
86993: 
86994:   for(i=1; i<nDepth; i++){
86995:     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86996:   }
86997: 
86998:   for(i=1; i<nDepth && rc==SQLITE_OK; i++){
86999:     int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
87000:     PmaReader *pReadr = &p->aReadr[iIter];
87001: 
87002:     if( pReadr->pIncr==0 ){
87003:       MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
87004:       if( pNew==0 ){
87005:         rc = SQLITE_NOMEM_BKPT;
87006:       }else{
87007:         rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
87008:       }
87009:     }
87010:     if( rc==SQLITE_OK ){
87011:       p = pReadr->pIncr->pMerger;
87012:       nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
87013:     }
87014:   }
87015: 
87016:   if( rc==SQLITE_OK ){
87017:     p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
87018:   }else{
87019:     vdbeIncrFree(pIncr);
87020:   }
87021:   return rc;
87022: }
87023: 
87024: /*
87025: ** This function is called as part of a SorterRewind() operation on a sorter
87026: ** that has already written two or more level-0 PMAs to one or more temp
87027: ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that 
87028: ** can be used to incrementally merge all PMAs on disk.
87029: **
87030: ** If successful, SQLITE_OK is returned and *ppOut set to point to the
87031: ** MergeEngine object at the root of the tree before returning. Or, if an
87032: ** error occurs, an SQLite error code is returned and the final value 
87033: ** of *ppOut is undefined.
87034: */
87035: static int vdbeSorterMergeTreeBuild(
87036:   VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
87037:   MergeEngine **ppOut        /* Write the MergeEngine here */
87038: ){
87039:   MergeEngine *pMain = 0;
87040:   int rc = SQLITE_OK;
87041:   int iTask;
87042: 
87043: #if SQLITE_MAX_WORKER_THREADS>0
87044:   /* If the sorter uses more than one task, then create the top-level 
87045:   ** MergeEngine here. This MergeEngine will read data from exactly 
87046:   ** one PmaReader per sub-task.  */
87047:   assert( pSorter->bUseThreads || pSorter->nTask==1 );
87048:   if( pSorter->nTask>1 ){
87049:     pMain = vdbeMergeEngineNew(pSorter->nTask);
87050:     if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
87051:   }
87052: #endif
87053: 
87054:   for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87055:     SortSubtask *pTask = &pSorter->aTask[iTask];
87056:     assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
87057:     if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
87058:       MergeEngine *pRoot = 0;     /* Root node of tree for this task */
87059:       int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
87060:       i64 iReadOff = 0;
87061: 
87062:       if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
87063:         rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
87064:       }else{
87065:         int i;
87066:         int iSeq = 0;
87067:         pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
87068:         if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
87069:         for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
87070:           MergeEngine *pMerger = 0; /* New level-0 PMA merger */
87071:           int nReader;              /* Number of level-0 PMAs to merge */
87072: 
87073:           nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
87074:           rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
87075:           if( rc==SQLITE_OK ){
87076:             rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
87077:           }
87078:         }
87079:       }
87080: 
87081:       if( rc==SQLITE_OK ){
87082: #if SQLITE_MAX_WORKER_THREADS>0
87083:         if( pMain!=0 ){
87084:           rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
87085:         }else
87086: #endif
87087:         {
87088:           assert( pMain==0 );
87089:           pMain = pRoot;
87090:         }
87091:       }else{
87092:         vdbeMergeEngineFree(pRoot);
87093:       }
87094:     }
87095:   }
87096: 
87097:   if( rc!=SQLITE_OK ){
87098:     vdbeMergeEngineFree(pMain);
87099:     pMain = 0;
87100:   }
87101:   *ppOut = pMain;
87102:   return rc;
87103: }
87104: 
87105: /*
87106: ** This function is called as part of an sqlite3VdbeSorterRewind() operation
87107: ** on a sorter that has written two or more PMAs to temporary files. It sets
87108: ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
87109: ** (for multi-threaded sorters) so that it can be used to iterate through
87110: ** all records stored in the sorter.
87111: **
87112: ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
87113: */
87114: static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
87115:   int rc;                         /* Return code */
87116:   SortSubtask *pTask0 = &pSorter->aTask[0];
87117:   MergeEngine *pMain = 0;
87118: #if SQLITE_MAX_WORKER_THREADS
87119:   sqlite3 *db = pTask0->pSorter->db;
87120:   int i;
87121:   SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
87122:   for(i=0; i<pSorter->nTask; i++){
87123:     pSorter->aTask[i].xCompare = xCompare;
87124:   }
87125: #endif
87126: 
87127:   rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
87128:   if( rc==SQLITE_OK ){
87129: #if SQLITE_MAX_WORKER_THREADS
87130:     assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
87131:     if( pSorter->bUseThreads ){
87132:       int iTask;
87133:       PmaReader *pReadr = 0;
87134:       SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
87135:       rc = vdbeSortAllocUnpacked(pLast);
87136:       if( rc==SQLITE_OK ){
87137:         pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
87138:         pSorter->pReader = pReadr;
87139:         if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
87140:       }
87141:       if( rc==SQLITE_OK ){
87142:         rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
87143:         if( rc==SQLITE_OK ){
87144:           vdbeIncrMergerSetThreads(pReadr->pIncr);
87145:           for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
87146:             IncrMerger *pIncr;
87147:             if( (pIncr = pMain->aReadr[iTask].pIncr) ){
87148:               vdbeIncrMergerSetThreads(pIncr);
87149:               assert( pIncr->pTask!=pLast );
87150:             }
87151:           }
87152:           for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
87153:             /* Check that:
87154:             **   
87155:             **   a) The incremental merge object is configured to use the
87156:             **      right task, and
87157:             **   b) If it is using task (nTask-1), it is configured to run
87158:             **      in single-threaded mode. This is important, as the
87159:             **      root merge (INCRINIT_ROOT) will be using the same task
87160:             **      object.
87161:             */
87162:             PmaReader *p = &pMain->aReadr[iTask];
87163:             assert( p->pIncr==0 || (
87164:                 (p->pIncr->pTask==&pSorter->aTask[iTask])             /* a */
87165:              && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0)  /* b */
87166:             ));
87167:             rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
87168:           }
87169:         }
87170:         pMain = 0;
87171:       }
87172:       if( rc==SQLITE_OK ){
87173:         rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
87174:       }
87175:     }else
87176: #endif
87177:     {
87178:       rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
87179:       pSorter->pMerger = pMain;
87180:       pMain = 0;
87181:     }
87182:   }
87183: 
87184:   if( rc!=SQLITE_OK ){
87185:     vdbeMergeEngineFree(pMain);
87186:   }
87187:   return rc;
87188: }
87189: 
87190: 
87191: /*
87192: ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
87193: ** this function is called to prepare for iterating through the records
87194: ** in sorted order.
87195: */
87196: SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
87197:   VdbeSorter *pSorter;
87198:   int rc = SQLITE_OK;             /* Return code */
87199: 
87200:   assert( pCsr->eCurType==CURTYPE_SORTER );
87201:   pSorter = pCsr->uc.pSorter;
87202:   assert( pSorter );
87203: 
87204:   /* If no data has been written to disk, then do not do so now. Instead,
87205:   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
87206:   ** from the in-memory list.  */
87207:   if( pSorter->bUsePMA==0 ){
87208:     if( pSorter->list.pList ){
87209:       *pbEof = 0;
87210:       rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
87211:     }else{
87212:       *pbEof = 1;
87213:     }
87214:     return rc;
87215:   }
87216: 
87217:   /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() 
87218:   ** function flushes the contents of memory to disk, it immediately always
87219:   ** creates a new list consisting of a single key immediately afterwards.
87220:   ** So the list is never empty at this point.  */
87221:   assert( pSorter->list.pList );
87222:   rc = vdbeSorterFlushPMA(pSorter);
87223: 
87224:   /* Join all threads */
87225:   rc = vdbeSorterJoinAll(pSorter, rc);
87226: 
87227:   vdbeSorterRewindDebug("rewind");
87228: 
87229:   /* Assuming no errors have occurred, set up a merger structure to 
87230:   ** incrementally read and merge all remaining PMAs.  */
87231:   assert( pSorter->pReader==0 );
87232:   if( rc==SQLITE_OK ){
87233:     rc = vdbeSorterSetupMerge(pSorter);
87234:     *pbEof = 0;
87235:   }
87236: 
87237:   vdbeSorterRewindDebug("rewinddone");
87238:   return rc;
87239: }
87240: 
87241: /*
87242: ** Advance to the next element in the sorter.
87243: */
87244: SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
87245:   VdbeSorter *pSorter;
87246:   int rc;                         /* Return code */
87247: 
87248:   assert( pCsr->eCurType==CURTYPE_SORTER );
87249:   pSorter = pCsr->uc.pSorter;
87250:   assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
87251:   if( pSorter->bUsePMA ){
87252:     assert( pSorter->pReader==0 || pSorter->pMerger==0 );
87253:     assert( pSorter->bUseThreads==0 || pSorter->pReader );
87254:     assert( pSorter->bUseThreads==1 || pSorter->pMerger );
87255: #if SQLITE_MAX_WORKER_THREADS>0
87256:     if( pSorter->bUseThreads ){
87257:       rc = vdbePmaReaderNext(pSorter->pReader);
87258:       *pbEof = (pSorter->pReader->pFd==0);
87259:     }else
87260: #endif
87261:     /*if( !pSorter->bUseThreads )*/ {
87262:       assert( pSorter->pMerger!=0 );
87263:       assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
87264:       rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
87265:     }
87266:   }else{
87267:     SorterRecord *pFree = pSorter->list.pList;
87268:     pSorter->list.pList = pFree->u.pNext;
87269:     pFree->u.pNext = 0;
87270:     if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
87271:     *pbEof = !pSorter->list.pList;
87272:     rc = SQLITE_OK;
87273:   }
87274:   return rc;
87275: }
87276: 
87277: /*
87278: ** Return a pointer to a buffer owned by the sorter that contains the 
87279: ** current key.
87280: */
87281: static void *vdbeSorterRowkey(
87282:   const VdbeSorter *pSorter,      /* Sorter object */
87283:   int *pnKey                      /* OUT: Size of current key in bytes */
87284: ){
87285:   void *pKey;
87286:   if( pSorter->bUsePMA ){
87287:     PmaReader *pReader;
87288: #if SQLITE_MAX_WORKER_THREADS>0
87289:     if( pSorter->bUseThreads ){
87290:       pReader = pSorter->pReader;
87291:     }else
87292: #endif
87293:     /*if( !pSorter->bUseThreads )*/{
87294:       pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
87295:     }
87296:     *pnKey = pReader->nKey;
87297:     pKey = pReader->aKey;
87298:   }else{
87299:     *pnKey = pSorter->list.pList->nVal;
87300:     pKey = SRVAL(pSorter->list.pList);
87301:   }
87302:   return pKey;
87303: }
87304: 
87305: /*
87306: ** Copy the current sorter key into the memory cell pOut.
87307: */
87308: SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
87309:   VdbeSorter *pSorter;
87310:   void *pKey; int nKey;           /* Sorter key to copy into pOut */
87311: 
87312:   assert( pCsr->eCurType==CURTYPE_SORTER );
87313:   pSorter = pCsr->uc.pSorter;
87314:   pKey = vdbeSorterRowkey(pSorter, &nKey);
87315:   if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
87316:     return SQLITE_NOMEM_BKPT;
87317:   }
87318:   pOut->n = nKey;
87319:   MemSetTypeFlag(pOut, MEM_Blob);
87320:   memcpy(pOut->z, pKey, nKey);
87321: 
87322:   return SQLITE_OK;
87323: }
87324: 
87325: /*
87326: ** Compare the key in memory cell pVal with the key that the sorter cursor
87327: ** passed as the first argument currently points to. For the purposes of
87328: ** the comparison, ignore the rowid field at the end of each record.
87329: **
87330: ** If the sorter cursor key contains any NULL values, consider it to be
87331: ** less than pVal. Even if pVal also contains NULL values.
87332: **
87333: ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
87334: ** Otherwise, set *pRes to a negative, zero or positive value if the
87335: ** key in pVal is smaller than, equal to or larger than the current sorter
87336: ** key.
87337: **
87338: ** This routine forms the core of the OP_SorterCompare opcode, which in
87339: ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
87340: */
87341: SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
87342:   const VdbeCursor *pCsr,         /* Sorter cursor */
87343:   Mem *pVal,                      /* Value to compare to current sorter key */
87344:   int nKeyCol,                    /* Compare this many columns */
87345:   int *pRes                       /* OUT: Result of comparison */
87346: ){
87347:   VdbeSorter *pSorter;
87348:   UnpackedRecord *r2;
87349:   KeyInfo *pKeyInfo;
87350:   int i;
87351:   void *pKey; int nKey;           /* Sorter key to compare pVal with */
87352: 
87353:   assert( pCsr->eCurType==CURTYPE_SORTER );
87354:   pSorter = pCsr->uc.pSorter;
87355:   r2 = pSorter->pUnpacked;
87356:   pKeyInfo = pCsr->pKeyInfo;
87357:   if( r2==0 ){
87358:     char *p;
87359:     r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
87360:     assert( pSorter->pUnpacked==(UnpackedRecord*)p );
87361:     if( r2==0 ) return SQLITE_NOMEM_BKPT;
87362:     r2->nField = nKeyCol;
87363:   }
87364:   assert( r2->nField==nKeyCol );
87365: 
87366:   pKey = vdbeSorterRowkey(pSorter, &nKey);
87367:   sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
87368:   for(i=0; i<nKeyCol; i++){
87369:     if( r2->aMem[i].flags & MEM_Null ){
87370:       *pRes = -1;
87371:       return SQLITE_OK;
87372:     }
87373:   }
87374: 
87375:   *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
87376:   return SQLITE_OK;
87377: }
87378: 
87379: /************** End of vdbesort.c ********************************************/
87380: /************** Begin file memjournal.c **************************************/
87381: /*
87382: ** 2008 October 7
87383: **
87384: ** The author disclaims copyright to this source code.  In place of
87385: ** a legal notice, here is a blessing:
87386: **
87387: **    May you do good and not evil.
87388: **    May you find forgiveness for yourself and forgive others.
87389: **    May you share freely, never taking more than you give.
87390: **
87391: *************************************************************************
87392: **
87393: ** This file contains code use to implement an in-memory rollback journal.
87394: ** The in-memory rollback journal is used to journal transactions for
87395: ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
87396: **
87397: ** Update:  The in-memory journal is also used to temporarily cache
87398: ** smaller journals that are not critical for power-loss recovery.
87399: ** For example, statement journals that are not too big will be held
87400: ** entirely in memory, thus reducing the number of file I/O calls, and
87401: ** more importantly, reducing temporary file creation events.  If these
87402: ** journals become too large for memory, they are spilled to disk.  But
87403: ** in the common case, they are usually small and no file I/O needs to
87404: ** occur.
87405: */
87406: /* #include "sqliteInt.h" */
87407: 
87408: /* Forward references to internal structures */
87409: typedef struct MemJournal MemJournal;
87410: typedef struct FilePoint FilePoint;
87411: typedef struct FileChunk FileChunk;
87412: 
87413: /*
87414: ** The rollback journal is composed of a linked list of these structures.
87415: **
87416: ** The zChunk array is always at least 8 bytes in size - usually much more.
87417: ** Its actual size is stored in the MemJournal.nChunkSize variable.
87418: */
87419: struct FileChunk {
87420:   FileChunk *pNext;               /* Next chunk in the journal */
87421:   u8 zChunk[8];                   /* Content of this chunk */
87422: };
87423: 
87424: /*
87425: ** By default, allocate this many bytes of memory for each FileChunk object.
87426: */
87427: #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
87428: 
87429: /*
87430: ** For chunk size nChunkSize, return the number of bytes that should
87431: ** be allocated for each FileChunk structure.
87432: */
87433: #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
87434: 
87435: /*
87436: ** An instance of this object serves as a cursor into the rollback journal.
87437: ** The cursor can be either for reading or writing.
87438: */
87439: struct FilePoint {
87440:   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
87441:   FileChunk *pChunk;              /* Specific chunk into which cursor points */
87442: };
87443: 
87444: /*
87445: ** This structure is a subclass of sqlite3_file. Each open memory-journal
87446: ** is an instance of this class.
87447: */
87448: struct MemJournal {
87449:   const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
87450:   int nChunkSize;                 /* In-memory chunk-size */
87451: 
87452:   int nSpill;                     /* Bytes of data before flushing */
87453:   int nSize;                      /* Bytes of data currently in memory */
87454:   FileChunk *pFirst;              /* Head of in-memory chunk-list */
87455:   FilePoint endpoint;             /* Pointer to the end of the file */
87456:   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
87457: 
87458:   int flags;                      /* xOpen flags */
87459:   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
87460:   const char *zJournal;           /* Name of the journal file */
87461: };
87462: 
87463: /*
87464: ** Read data from the in-memory journal file.  This is the implementation
87465: ** of the sqlite3_vfs.xRead method.
87466: */
87467: static int memjrnlRead(
87468:   sqlite3_file *pJfd,    /* The journal file from which to read */
87469:   void *zBuf,            /* Put the results here */
87470:   int iAmt,              /* Number of bytes to read */
87471:   sqlite_int64 iOfst     /* Begin reading at this offset */
87472: ){
87473:   MemJournal *p = (MemJournal *)pJfd;
87474:   u8 *zOut = zBuf;
87475:   int nRead = iAmt;
87476:   int iChunkOffset;
87477:   FileChunk *pChunk;
87478: 
87479: #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87480:   if( (iAmt+iOfst)>p->endpoint.iOffset ){
87481:     return SQLITE_IOERR_SHORT_READ;
87482:   }
87483: #endif
87484: 
87485:   assert( (iAmt+iOfst)<=p->endpoint.iOffset );
87486:   assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
87487:   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
87488:     sqlite3_int64 iOff = 0;
87489:     for(pChunk=p->pFirst; 
87490:         ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
87491:         pChunk=pChunk->pNext
87492:     ){
87493:       iOff += p->nChunkSize;
87494:     }
87495:   }else{
87496:     pChunk = p->readpoint.pChunk;
87497:     assert( pChunk!=0 );
87498:   }
87499: 
87500:   iChunkOffset = (int)(iOfst%p->nChunkSize);
87501:   do {
87502:     int iSpace = p->nChunkSize - iChunkOffset;
87503:     int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
87504:     memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
87505:     zOut += nCopy;
87506:     nRead -= iSpace;
87507:     iChunkOffset = 0;
87508:   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
87509:   p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
87510:   p->readpoint.pChunk = pChunk;
87511: 
87512:   return SQLITE_OK;
87513: }
87514: 
87515: /*
87516: ** Free the list of FileChunk structures headed at MemJournal.pFirst.
87517: */
87518: static void memjrnlFreeChunks(MemJournal *p){
87519:   FileChunk *pIter;
87520:   FileChunk *pNext;
87521:   for(pIter=p->pFirst; pIter; pIter=pNext){
87522:     pNext = pIter->pNext;
87523:     sqlite3_free(pIter);
87524:   } 
87525:   p->pFirst = 0;
87526: }
87527: 
87528: /*
87529: ** Flush the contents of memory to a real file on disk.
87530: */
87531: static int memjrnlCreateFile(MemJournal *p){
87532:   int rc;
87533:   sqlite3_file *pReal = (sqlite3_file*)p;
87534:   MemJournal copy = *p;
87535: 
87536:   memset(p, 0, sizeof(MemJournal));
87537:   rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
87538:   if( rc==SQLITE_OK ){
87539:     int nChunk = copy.nChunkSize;
87540:     i64 iOff = 0;
87541:     FileChunk *pIter;
87542:     for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
87543:       if( iOff + nChunk > copy.endpoint.iOffset ){
87544:         nChunk = copy.endpoint.iOffset - iOff;
87545:       }
87546:       rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
87547:       if( rc ) break;
87548:       iOff += nChunk;
87549:     }
87550:     if( rc==SQLITE_OK ){
87551:       /* No error has occurred. Free the in-memory buffers. */
87552:       memjrnlFreeChunks(&copy);
87553:     }
87554:   }
87555:   if( rc!=SQLITE_OK ){
87556:     /* If an error occurred while creating or writing to the file, restore
87557:     ** the original before returning. This way, SQLite uses the in-memory
87558:     ** journal data to roll back changes made to the internal page-cache
87559:     ** before this function was called.  */
87560:     sqlite3OsClose(pReal);
87561:     *p = copy;
87562:   }
87563:   return rc;
87564: }
87565: 
87566: 
87567: /*
87568: ** Write data to the file.
87569: */
87570: static int memjrnlWrite(
87571:   sqlite3_file *pJfd,    /* The journal file into which to write */
87572:   const void *zBuf,      /* Take data to be written from here */
87573:   int iAmt,              /* Number of bytes to write */
87574:   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
87575: ){
87576:   MemJournal *p = (MemJournal *)pJfd;
87577:   int nWrite = iAmt;
87578:   u8 *zWrite = (u8 *)zBuf;
87579: 
87580:   /* If the file should be created now, create it and write the new data
87581:   ** into the file on disk. */
87582:   if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
87583:     int rc = memjrnlCreateFile(p);
87584:     if( rc==SQLITE_OK ){
87585:       rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
87586:     }
87587:     return rc;
87588:   }
87589: 
87590:   /* If the contents of this write should be stored in memory */
87591:   else{
87592:     /* An in-memory journal file should only ever be appended to. Random
87593:     ** access writes are not required. The only exception to this is when
87594:     ** the in-memory journal is being used by a connection using the
87595:     ** atomic-write optimization. In this case the first 28 bytes of the
87596:     ** journal file may be written as part of committing the transaction. */ 
87597:     assert( iOfst==p->endpoint.iOffset || iOfst==0 );
87598: #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87599:     if( iOfst==0 && p->pFirst ){
87600:       assert( p->nChunkSize>iAmt );
87601:       memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
87602:     }else
87603: #else
87604:     assert( iOfst>0 || p->pFirst==0 );
87605: #endif
87606:     {
87607:       while( nWrite>0 ){
87608:         FileChunk *pChunk = p->endpoint.pChunk;
87609:         int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
87610:         int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
87611: 
87612:         if( iChunkOffset==0 ){
87613:           /* New chunk is required to extend the file. */
87614:           FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
87615:           if( !pNew ){
87616:             return SQLITE_IOERR_NOMEM_BKPT;
87617:           }
87618:           pNew->pNext = 0;
87619:           if( pChunk ){
87620:             assert( p->pFirst );
87621:             pChunk->pNext = pNew;
87622:           }else{
87623:             assert( !p->pFirst );
87624:             p->pFirst = pNew;
87625:           }
87626:           p->endpoint.pChunk = pNew;
87627:         }
87628: 
87629:         memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
87630:         zWrite += iSpace;
87631:         nWrite -= iSpace;
87632:         p->endpoint.iOffset += iSpace;
87633:       }
87634:       p->nSize = iAmt + iOfst;
87635:     }
87636:   }
87637: 
87638:   return SQLITE_OK;
87639: }
87640: 
87641: /*
87642: ** Truncate the file.
87643: **
87644: ** If the journal file is already on disk, truncate it there. Or, if it
87645: ** is still in main memory but is being truncated to zero bytes in size,
87646: ** ignore 
87647: */
87648: static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
87649:   MemJournal *p = (MemJournal *)pJfd;
87650:   if( ALWAYS(size==0) ){
87651:     memjrnlFreeChunks(p);
87652:     p->nSize = 0;
87653:     p->endpoint.pChunk = 0;
87654:     p->endpoint.iOffset = 0;
87655:     p->readpoint.pChunk = 0;
87656:     p->readpoint.iOffset = 0;
87657:   }
87658:   return SQLITE_OK;
87659: }
87660: 
87661: /*
87662: ** Close the file.
87663: */
87664: static int memjrnlClose(sqlite3_file *pJfd){
87665:   MemJournal *p = (MemJournal *)pJfd;
87666:   memjrnlFreeChunks(p);
87667:   return SQLITE_OK;
87668: }
87669: 
87670: /*
87671: ** Sync the file.
87672: **
87673: ** If the real file has been created, call its xSync method. Otherwise, 
87674: ** syncing an in-memory journal is a no-op. 
87675: */
87676: static int memjrnlSync(sqlite3_file *pJfd, int flags){
87677:   UNUSED_PARAMETER2(pJfd, flags);
87678:   return SQLITE_OK;
87679: }
87680: 
87681: /*
87682: ** Query the size of the file in bytes.
87683: */
87684: static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
87685:   MemJournal *p = (MemJournal *)pJfd;
87686:   *pSize = (sqlite_int64) p->endpoint.iOffset;
87687:   return SQLITE_OK;
87688: }
87689: 
87690: /*
87691: ** Table of methods for MemJournal sqlite3_file object.
87692: */
87693: static const struct sqlite3_io_methods MemJournalMethods = {
87694:   1,                /* iVersion */
87695:   memjrnlClose,     /* xClose */
87696:   memjrnlRead,      /* xRead */
87697:   memjrnlWrite,     /* xWrite */
87698:   memjrnlTruncate,  /* xTruncate */
87699:   memjrnlSync,      /* xSync */
87700:   memjrnlFileSize,  /* xFileSize */
87701:   0,                /* xLock */
87702:   0,                /* xUnlock */
87703:   0,                /* xCheckReservedLock */
87704:   0,                /* xFileControl */
87705:   0,                /* xSectorSize */
87706:   0,                /* xDeviceCharacteristics */
87707:   0,                /* xShmMap */
87708:   0,                /* xShmLock */
87709:   0,                /* xShmBarrier */
87710:   0,                /* xShmUnmap */
87711:   0,                /* xFetch */
87712:   0                 /* xUnfetch */
87713: };
87714: 
87715: /* 
87716: ** Open a journal file. 
87717: **
87718: ** The behaviour of the journal file depends on the value of parameter 
87719: ** nSpill. If nSpill is 0, then the journal file is always create and 
87720: ** accessed using the underlying VFS. If nSpill is less than zero, then
87721: ** all content is always stored in main-memory. Finally, if nSpill is a
87722: ** positive value, then the journal file is initially created in-memory
87723: ** but may be flushed to disk later on. In this case the journal file is
87724: ** flushed to disk either when it grows larger than nSpill bytes in size,
87725: ** or when sqlite3JournalCreate() is called.
87726: */
87727: SQLITE_PRIVATE int sqlite3JournalOpen(
87728:   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
87729:   const char *zName,         /* Name of the journal file */
87730:   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
87731:   int flags,                 /* Opening flags */
87732:   int nSpill                 /* Bytes buffered before opening the file */
87733: ){
87734:   MemJournal *p = (MemJournal*)pJfd;
87735: 
87736:   /* Zero the file-handle object. If nSpill was passed zero, initialize
87737:   ** it using the sqlite3OsOpen() function of the underlying VFS. In this
87738:   ** case none of the code in this module is executed as a result of calls
87739:   ** made on the journal file-handle.  */
87740:   memset(p, 0, sizeof(MemJournal));
87741:   if( nSpill==0 ){
87742:     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
87743:   }
87744: 
87745:   if( nSpill>0 ){
87746:     p->nChunkSize = nSpill;
87747:   }else{
87748:     p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
87749:     assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
87750:   }
87751: 
87752:   p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
87753:   p->nSpill = nSpill;
87754:   p->flags = flags;
87755:   p->zJournal = zName;
87756:   p->pVfs = pVfs;
87757:   return SQLITE_OK;
87758: }
87759: 
87760: /*
87761: ** Open an in-memory journal file.
87762: */
87763: SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
87764:   sqlite3JournalOpen(0, 0, pJfd, 0, -1);
87765: }
87766: 
87767: #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87768: /*
87769: ** If the argument p points to a MemJournal structure that is not an 
87770: ** in-memory-only journal file (i.e. is one that was opened with a +ve
87771: ** nSpill parameter), and the underlying file has not yet been created, 
87772: ** create it now.
87773: */
87774: SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
87775:   int rc = SQLITE_OK;
87776:   if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
87777:     rc = memjrnlCreateFile((MemJournal*)p);
87778:   }
87779:   return rc;
87780: }
87781: #endif
87782: 
87783: /*
87784: ** The file-handle passed as the only argument is open on a journal file.
87785: ** Return true if this "journal file" is currently stored in heap memory,
87786: ** or false otherwise.
87787: */
87788: SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
87789:   return p->pMethods==&MemJournalMethods;
87790: }
87791: 
87792: /* 
87793: ** Return the number of bytes required to store a JournalFile that uses vfs
87794: ** pVfs to create the underlying on-disk files.
87795: */
87796: SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
87797:   return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
87798: }
87799: 
87800: /************** End of memjournal.c ******************************************/
87801: /************** Begin file walker.c ******************************************/
87802: /*
87803: ** 2008 August 16
87804: **
87805: ** The author disclaims copyright to this source code.  In place of
87806: ** a legal notice, here is a blessing:
87807: **
87808: **    May you do good and not evil.
87809: **    May you find forgiveness for yourself and forgive others.
87810: **    May you share freely, never taking more than you give.
87811: **
87812: *************************************************************************
87813: ** This file contains routines used for walking the parser tree for
87814: ** an SQL statement.
87815: */
87816: /* #include "sqliteInt.h" */
87817: /* #include <stdlib.h> */
87818: /* #include <string.h> */
87819: 
87820: 
87821: /*
87822: ** Walk an expression tree.  Invoke the callback once for each node
87823: ** of the expression, while descending.  (In other words, the callback
87824: ** is invoked before visiting children.)
87825: **
87826: ** The return value from the callback should be one of the WRC_*
87827: ** constants to specify how to proceed with the walk.
87828: **
87829: **    WRC_Continue      Continue descending down the tree.
87830: **
87831: **    WRC_Prune         Do not descend into child nodes.  But allow
87832: **                      the walk to continue with sibling nodes.
87833: **
87834: **    WRC_Abort         Do no more callbacks.  Unwind the stack and
87835: **                      return the top-level walk call.
87836: **
87837: ** The return value from this routine is WRC_Abort to abandon the tree walk
87838: ** and WRC_Continue to continue.
87839: */
87840: static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
87841:   int rc;
87842:   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
87843:   testcase( ExprHasProperty(pExpr, EP_Reduced) );
87844:   rc = pWalker->xExprCallback(pWalker, pExpr);
87845:   if( rc==WRC_Continue
87846:               && !ExprHasProperty(pExpr,EP_TokenOnly) ){
87847:     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
87848:     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
87849:     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87850:       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
87851:     }else{
87852:       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
87853:     }
87854:   }
87855:   return rc & WRC_Abort;
87856: }
87857: SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
87858:   return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
87859: }
87860: 
87861: /*
87862: ** Call sqlite3WalkExpr() for every expression in list p or until
87863: ** an abort request is seen.
87864: */
87865: SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
87866:   int i;
87867:   struct ExprList_item *pItem;
87868:   if( p ){
87869:     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
87870:       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
87871:     }
87872:   }
87873:   return WRC_Continue;
87874: }
87875: 
87876: /*
87877: ** Walk all expressions associated with SELECT statement p.  Do
87878: ** not invoke the SELECT callback on p, but do (of course) invoke
87879: ** any expr callbacks and SELECT callbacks that come from subqueries.
87880: ** Return WRC_Abort or WRC_Continue.
87881: */
87882: SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
87883:   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
87884:   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
87885:   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
87886:   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
87887:   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
87888:   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
87889:   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
87890:   return WRC_Continue;
87891: }
87892: 
87893: /*
87894: ** Walk the parse trees associated with all subqueries in the
87895: ** FROM clause of SELECT statement p.  Do not invoke the select
87896: ** callback on p, but do invoke it on each FROM clause subquery
87897: ** and on any subqueries further down in the tree.  Return 
87898: ** WRC_Abort or WRC_Continue;
87899: */
87900: SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
87901:   SrcList *pSrc;
87902:   int i;
87903:   struct SrcList_item *pItem;
87904: 
87905:   pSrc = p->pSrc;
87906:   if( ALWAYS(pSrc) ){
87907:     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
87908:       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
87909:         return WRC_Abort;
87910:       }
87911:       if( pItem->fg.isTabFunc
87912:        && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
87913:       ){
87914:         return WRC_Abort;
87915:       }
87916:     }
87917:   }
87918:   return WRC_Continue;
87919: } 
87920: 
87921: /*
87922: ** Call sqlite3WalkExpr() for every expression in Select statement p.
87923: ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
87924: ** on the compound select chain, p->pPrior. 
87925: **
87926: ** If it is not NULL, the xSelectCallback() callback is invoked before
87927: ** the walk of the expressions and FROM clause. The xSelectCallback2()
87928: ** method, if it is not NULL, is invoked following the walk of the 
87929: ** expressions and FROM clause.
87930: **
87931: ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
87932: ** there is an abort request.
87933: **
87934: ** If the Walker does not have an xSelectCallback() then this routine
87935: ** is a no-op returning WRC_Continue.
87936: */
87937: SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
87938:   int rc;
87939:   if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
87940:     return WRC_Continue;
87941:   }
87942:   rc = WRC_Continue;
87943:   pWalker->walkerDepth++;
87944:   while( p ){
87945:     if( pWalker->xSelectCallback ){
87946:        rc = pWalker->xSelectCallback(pWalker, p);
87947:        if( rc ) break;
87948:     }
87949:     if( sqlite3WalkSelectExpr(pWalker, p)
87950:      || sqlite3WalkSelectFrom(pWalker, p)
87951:     ){
87952:       pWalker->walkerDepth--;
87953:       return WRC_Abort;
87954:     }
87955:     if( pWalker->xSelectCallback2 ){
87956:       pWalker->xSelectCallback2(pWalker, p);
87957:     }
87958:     p = p->pPrior;
87959:   }
87960:   pWalker->walkerDepth--;
87961:   return rc & WRC_Abort;
87962: }
87963: 
87964: /************** End of walker.c **********************************************/
87965: /************** Begin file resolve.c *****************************************/
87966: /*
87967: ** 2008 August 18
87968: **
87969: ** The author disclaims copyright to this source code.  In place of
87970: ** a legal notice, here is a blessing:
87971: **
87972: **    May you do good and not evil.
87973: **    May you find forgiveness for yourself and forgive others.
87974: **    May you share freely, never taking more than you give.
87975: **
87976: *************************************************************************
87977: **
87978: ** This file contains routines used for walking the parser tree and
87979: ** resolve all identifiers by associating them with a particular
87980: ** table and column.
87981: */
87982: /* #include "sqliteInt.h" */
87983: /* #include <stdlib.h> */
87984: /* #include <string.h> */
87985: 
87986: /*
87987: ** Walk the expression tree pExpr and increase the aggregate function
87988: ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
87989: ** This needs to occur when copying a TK_AGG_FUNCTION node from an
87990: ** outer query into an inner subquery.
87991: **
87992: ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
87993: ** is a helper function - a callback for the tree walker.
87994: */
87995: static int incrAggDepth(Walker *pWalker, Expr *pExpr){
87996:   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
87997:   return WRC_Continue;
87998: }
87999: static void incrAggFunctionDepth(Expr *pExpr, int N){
88000:   if( N>0 ){
88001:     Walker w;
88002:     memset(&w, 0, sizeof(w));
88003:     w.xExprCallback = incrAggDepth;
88004:     w.u.n = N;
88005:     sqlite3WalkExpr(&w, pExpr);
88006:   }
88007: }
88008: 
88009: /*
88010: ** Turn the pExpr expression into an alias for the iCol-th column of the
88011: ** result set in pEList.
88012: **
88013: ** If the reference is followed by a COLLATE operator, then make sure
88014: ** the COLLATE operator is preserved.  For example:
88015: **
88016: **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
88017: **
88018: ** Should be transformed into:
88019: **
88020: **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
88021: **
88022: ** The nSubquery parameter specifies how many levels of subquery the
88023: ** alias is removed from the original expression.  The usual value is
88024: ** zero but it might be more if the alias is contained within a subquery
88025: ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
88026: ** structures must be increased by the nSubquery amount.
88027: */
88028: static void resolveAlias(
88029:   Parse *pParse,         /* Parsing context */
88030:   ExprList *pEList,      /* A result set */
88031:   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
88032:   Expr *pExpr,           /* Transform this into an alias to the result set */
88033:   const char *zType,     /* "GROUP" or "ORDER" or "" */
88034:   int nSubquery          /* Number of subqueries that the label is moving */
88035: ){
88036:   Expr *pOrig;           /* The iCol-th column of the result set */
88037:   Expr *pDup;            /* Copy of pOrig */
88038:   sqlite3 *db;           /* The database connection */
88039: 
88040:   assert( iCol>=0 && iCol<pEList->nExpr );
88041:   pOrig = pEList->a[iCol].pExpr;
88042:   assert( pOrig!=0 );
88043:   db = pParse->db;
88044:   pDup = sqlite3ExprDup(db, pOrig, 0);
88045:   if( pDup==0 ) return;
88046:   if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
88047:   if( pExpr->op==TK_COLLATE ){
88048:     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
88049:   }
88050:   ExprSetProperty(pDup, EP_Alias);
88051: 
88052:   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
88053:   ** prevents ExprDelete() from deleting the Expr structure itself,
88054:   ** allowing it to be repopulated by the memcpy() on the following line.
88055:   ** The pExpr->u.zToken might point into memory that will be freed by the
88056:   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
88057:   ** make a copy of the token before doing the sqlite3DbFree().
88058:   */
88059:   ExprSetProperty(pExpr, EP_Static);
88060:   sqlite3ExprDelete(db, pExpr);
88061:   memcpy(pExpr, pDup, sizeof(*pExpr));
88062:   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
88063:     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
88064:     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
88065:     pExpr->flags |= EP_MemToken;
88066:   }
88067:   sqlite3DbFree(db, pDup);
88068: }
88069: 
88070: 
88071: /*
88072: ** Return TRUE if the name zCol occurs anywhere in the USING clause.
88073: **
88074: ** Return FALSE if the USING clause is NULL or if it does not contain
88075: ** zCol.
88076: */
88077: static int nameInUsingClause(IdList *pUsing, const char *zCol){
88078:   if( pUsing ){
88079:     int k;
88080:     for(k=0; k<pUsing->nId; k++){
88081:       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
88082:     }
88083:   }
88084:   return 0;
88085: }
88086: 
88087: /*
88088: ** Subqueries stores the original database, table and column names for their
88089: ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
88090: ** Check to see if the zSpan given to this routine matches the zDb, zTab,
88091: ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
88092: ** match anything.
88093: */
88094: SQLITE_PRIVATE int sqlite3MatchSpanName(
88095:   const char *zSpan,
88096:   const char *zCol,
88097:   const char *zTab,
88098:   const char *zDb
88099: ){
88100:   int n;
88101:   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88102:   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
88103:     return 0;
88104:   }
88105:   zSpan += n+1;
88106:   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
88107:   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
88108:     return 0;
88109:   }
88110:   zSpan += n+1;
88111:   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
88112:     return 0;
88113:   }
88114:   return 1;
88115: }
88116: 
88117: /*
88118: ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
88119: ** that name in the set of source tables in pSrcList and make the pExpr 
88120: ** expression node refer back to that source column.  The following changes
88121: ** are made to pExpr:
88122: **
88123: **    pExpr->iDb           Set the index in db->aDb[] of the database X
88124: **                         (even if X is implied).
88125: **    pExpr->iTable        Set to the cursor number for the table obtained
88126: **                         from pSrcList.
88127: **    pExpr->pTab          Points to the Table structure of X.Y (even if
88128: **                         X and/or Y are implied.)
88129: **    pExpr->iColumn       Set to the column number within the table.
88130: **    pExpr->op            Set to TK_COLUMN.
88131: **    pExpr->pLeft         Any expression this points to is deleted
88132: **    pExpr->pRight        Any expression this points to is deleted.
88133: **
88134: ** The zDb variable is the name of the database (the "X").  This value may be
88135: ** NULL meaning that name is of the form Y.Z or Z.  Any available database
88136: ** can be used.  The zTable variable is the name of the table (the "Y").  This
88137: ** value can be NULL if zDb is also NULL.  If zTable is NULL it
88138: ** means that the form of the name is Z and that columns from any table
88139: ** can be used.
88140: **
88141: ** If the name cannot be resolved unambiguously, leave an error message
88142: ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
88143: */
88144: static int lookupName(
88145:   Parse *pParse,       /* The parsing context */
88146:   const char *zDb,     /* Name of the database containing table, or NULL */
88147:   const char *zTab,    /* Name of table containing column, or NULL */
88148:   const char *zCol,    /* Name of the column. */
88149:   NameContext *pNC,    /* The name context used to resolve the name */
88150:   Expr *pExpr          /* Make this EXPR node point to the selected column */
88151: ){
88152:   int i, j;                         /* Loop counters */
88153:   int cnt = 0;                      /* Number of matching column names */
88154:   int cntTab = 0;                   /* Number of matching table names */
88155:   int nSubquery = 0;                /* How many levels of subquery */
88156:   sqlite3 *db = pParse->db;         /* The database connection */
88157:   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
88158:   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
88159:   NameContext *pTopNC = pNC;        /* First namecontext in the list */
88160:   Schema *pSchema = 0;              /* Schema of the expression */
88161:   int isTrigger = 0;                /* True if resolved to a trigger column */
88162:   Table *pTab = 0;                  /* Table hold the row */
88163:   Column *pCol;                     /* A column of pTab */
88164: 
88165:   assert( pNC );     /* the name context cannot be NULL. */
88166:   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
88167:   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
88168: 
88169:   /* Initialize the node to no-match */
88170:   pExpr->iTable = -1;
88171:   pExpr->pTab = 0;
88172:   ExprSetVVAProperty(pExpr, EP_NoReduce);
88173: 
88174:   /* Translate the schema name in zDb into a pointer to the corresponding
88175:   ** schema.  If not found, pSchema will remain NULL and nothing will match
88176:   ** resulting in an appropriate error message toward the end of this routine
88177:   */
88178:   if( zDb ){
88179:     testcase( pNC->ncFlags & NC_PartIdx );
88180:     testcase( pNC->ncFlags & NC_IsCheck );
88181:     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
88182:       /* Silently ignore database qualifiers inside CHECK constraints and
88183:       ** partial indices.  Do not raise errors because that might break
88184:       ** legacy and because it does not hurt anything to just ignore the
88185:       ** database name. */
88186:       zDb = 0;
88187:     }else{
88188:       for(i=0; i<db->nDb; i++){
88189:         assert( db->aDb[i].zName );
88190:         if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
88191:           pSchema = db->aDb[i].pSchema;
88192:           break;
88193:         }
88194:       }
88195:     }
88196:   }
88197: 
88198:   /* Start at the inner-most context and move outward until a match is found */
88199:   while( pNC && cnt==0 ){
88200:     ExprList *pEList;
88201:     SrcList *pSrcList = pNC->pSrcList;
88202: 
88203:     if( pSrcList ){
88204:       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
88205:         pTab = pItem->pTab;
88206:         assert( pTab!=0 && pTab->zName!=0 );
88207:         assert( pTab->nCol>0 );
88208:         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
88209:           int hit = 0;
88210:           pEList = pItem->pSelect->pEList;
88211:           for(j=0; j<pEList->nExpr; j++){
88212:             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
88213:               cnt++;
88214:               cntTab = 2;
88215:               pMatch = pItem;
88216:               pExpr->iColumn = j;
88217:               hit = 1;
88218:             }
88219:           }
88220:           if( hit || zTab==0 ) continue;
88221:         }
88222:         if( zDb && pTab->pSchema!=pSchema ){
88223:           continue;
88224:         }
88225:         if( zTab ){
88226:           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
88227:           assert( zTabName!=0 );
88228:           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
88229:             continue;
88230:           }
88231:         }
88232:         if( 0==(cntTab++) ){
88233:           pMatch = pItem;
88234:         }
88235:         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
88236:           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88237:             /* If there has been exactly one prior match and this match
88238:             ** is for the right-hand table of a NATURAL JOIN or is in a 
88239:             ** USING clause, then skip this match.
88240:             */
88241:             if( cnt==1 ){
88242:               if( pItem->fg.jointype & JT_NATURAL ) continue;
88243:               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
88244:             }
88245:             cnt++;
88246:             pMatch = pItem;
88247:             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
88248:             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
88249:             break;
88250:           }
88251:         }
88252:       }
88253:       if( pMatch ){
88254:         pExpr->iTable = pMatch->iCursor;
88255:         pExpr->pTab = pMatch->pTab;
88256:         /* RIGHT JOIN not (yet) supported */
88257:         assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
88258:         if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
88259:           ExprSetProperty(pExpr, EP_CanBeNull);
88260:         }
88261:         pSchema = pExpr->pTab->pSchema;
88262:       }
88263:     } /* if( pSrcList ) */
88264: 
88265: #ifndef SQLITE_OMIT_TRIGGER
88266:     /* If we have not already resolved the name, then maybe 
88267:     ** it is a new.* or old.* trigger argument reference
88268:     */
88269:     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
88270:       int op = pParse->eTriggerOp;
88271:       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
88272:       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
88273:         pExpr->iTable = 1;
88274:         pTab = pParse->pTriggerTab;
88275:       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
88276:         pExpr->iTable = 0;
88277:         pTab = pParse->pTriggerTab;
88278:       }else{
88279:         pTab = 0;
88280:       }
88281: 
88282:       if( pTab ){ 
88283:         int iCol;
88284:         pSchema = pTab->pSchema;
88285:         cntTab++;
88286:         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
88287:           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
88288:             if( iCol==pTab->iPKey ){
88289:               iCol = -1;
88290:             }
88291:             break;
88292:           }
88293:         }
88294:         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
88295:           /* IMP: R-51414-32910 */
88296:           iCol = -1;
88297:         }
88298:         if( iCol<pTab->nCol ){
88299:           cnt++;
88300:           if( iCol<0 ){
88301:             pExpr->affinity = SQLITE_AFF_INTEGER;
88302:           }else if( pExpr->iTable==0 ){
88303:             testcase( iCol==31 );
88304:             testcase( iCol==32 );
88305:             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88306:           }else{
88307:             testcase( iCol==31 );
88308:             testcase( iCol==32 );
88309:             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
88310:           }
88311:           pExpr->iColumn = (i16)iCol;
88312:           pExpr->pTab = pTab;
88313:           isTrigger = 1;
88314:         }
88315:       }
88316:     }
88317: #endif /* !defined(SQLITE_OMIT_TRIGGER) */
88318: 
88319:     /*
88320:     ** Perhaps the name is a reference to the ROWID
88321:     */
88322:     if( cnt==0
88323:      && cntTab==1
88324:      && pMatch
88325:      && (pNC->ncFlags & NC_IdxExpr)==0
88326:      && sqlite3IsRowid(zCol)
88327:      && VisibleRowid(pMatch->pTab)
88328:     ){
88329:       cnt = 1;
88330:       pExpr->iColumn = -1;
88331:       pExpr->affinity = SQLITE_AFF_INTEGER;
88332:     }
88333: 
88334:     /*
88335:     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
88336:     ** might refer to an result-set alias.  This happens, for example, when
88337:     ** we are resolving names in the WHERE clause of the following command:
88338:     **
88339:     **     SELECT a+b AS x FROM table WHERE x<10;
88340:     **
88341:     ** In cases like this, replace pExpr with a copy of the expression that
88342:     ** forms the result set entry ("a+b" in the example) and return immediately.
88343:     ** Note that the expression in the result set should have already been
88344:     ** resolved by the time the WHERE clause is resolved.
88345:     **
88346:     ** The ability to use an output result-set column in the WHERE, GROUP BY,
88347:     ** or HAVING clauses, or as part of a larger expression in the ORDER BY
88348:     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
88349:     ** is supported for backwards compatibility only. Hence, we issue a warning
88350:     ** on sqlite3_log() whenever the capability is used.
88351:     */
88352:     if( (pEList = pNC->pEList)!=0
88353:      && zTab==0
88354:      && cnt==0
88355:     ){
88356:       for(j=0; j<pEList->nExpr; j++){
88357:         char *zAs = pEList->a[j].zName;
88358:         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88359:           Expr *pOrig;
88360:           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
88361:           assert( pExpr->x.pList==0 );
88362:           assert( pExpr->x.pSelect==0 );
88363:           pOrig = pEList->a[j].pExpr;
88364:           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
88365:             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
88366:             return WRC_Abort;
88367:           }
88368:           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
88369:           cnt = 1;
88370:           pMatch = 0;
88371:           assert( zTab==0 && zDb==0 );
88372:           goto lookupname_end;
88373:         }
88374:       } 
88375:     }
88376: 
88377:     /* Advance to the next name context.  The loop will exit when either
88378:     ** we have a match (cnt>0) or when we run out of name contexts.
88379:     */
88380:     if( cnt==0 ){
88381:       pNC = pNC->pNext;
88382:       nSubquery++;
88383:     }
88384:   }
88385: 
88386:   /*
88387:   ** If X and Y are NULL (in other words if only the column name Z is
88388:   ** supplied) and the value of Z is enclosed in double-quotes, then
88389:   ** Z is a string literal if it doesn't match any column names.  In that
88390:   ** case, we need to return right away and not make any changes to
88391:   ** pExpr.
88392:   **
88393:   ** Because no reference was made to outer contexts, the pNC->nRef
88394:   ** fields are not changed in any context.
88395:   */
88396:   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
88397:     pExpr->op = TK_STRING;
88398:     pExpr->pTab = 0;
88399:     return WRC_Prune;
88400:   }
88401: 
88402:   /*
88403:   ** cnt==0 means there was not match.  cnt>1 means there were two or
88404:   ** more matches.  Either way, we have an error.
88405:   */
88406:   if( cnt!=1 ){
88407:     const char *zErr;
88408:     zErr = cnt==0 ? "no such column" : "ambiguous column name";
88409:     if( zDb ){
88410:       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
88411:     }else if( zTab ){
88412:       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
88413:     }else{
88414:       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
88415:     }
88416:     pParse->checkSchema = 1;
88417:     pTopNC->nErr++;
88418:   }
88419: 
88420:   /* If a column from a table in pSrcList is referenced, then record
88421:   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
88422:   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
88423:   ** column number is greater than the number of bits in the bitmask
88424:   ** then set the high-order bit of the bitmask.
88425:   */
88426:   if( pExpr->iColumn>=0 && pMatch!=0 ){
88427:     int n = pExpr->iColumn;
88428:     testcase( n==BMS-1 );
88429:     if( n>=BMS ){
88430:       n = BMS-1;
88431:     }
88432:     assert( pMatch->iCursor==pExpr->iTable );
88433:     pMatch->colUsed |= ((Bitmask)1)<<n;
88434:   }
88435: 
88436:   /* Clean up and return
88437:   */
88438:   sqlite3ExprDelete(db, pExpr->pLeft);
88439:   pExpr->pLeft = 0;
88440:   sqlite3ExprDelete(db, pExpr->pRight);
88441:   pExpr->pRight = 0;
88442:   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
88443: lookupname_end:
88444:   if( cnt==1 ){
88445:     assert( pNC!=0 );
88446:     if( !ExprHasProperty(pExpr, EP_Alias) ){
88447:       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
88448:     }
88449:     /* Increment the nRef value on all name contexts from TopNC up to
88450:     ** the point where the name matched. */
88451:     for(;;){
88452:       assert( pTopNC!=0 );
88453:       pTopNC->nRef++;
88454:       if( pTopNC==pNC ) break;
88455:       pTopNC = pTopNC->pNext;
88456:     }
88457:     return WRC_Prune;
88458:   } else {
88459:     return WRC_Abort;
88460:   }
88461: }
88462: 
88463: /*
88464: ** Allocate and return a pointer to an expression to load the column iCol
88465: ** from datasource iSrc in SrcList pSrc.
88466: */
88467: SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
88468:   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
88469:   if( p ){
88470:     struct SrcList_item *pItem = &pSrc->a[iSrc];
88471:     p->pTab = pItem->pTab;
88472:     p->iTable = pItem->iCursor;
88473:     if( p->pTab->iPKey==iCol ){
88474:       p->iColumn = -1;
88475:     }else{
88476:       p->iColumn = (ynVar)iCol;
88477:       testcase( iCol==BMS );
88478:       testcase( iCol==BMS-1 );
88479:       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
88480:     }
88481:     ExprSetProperty(p, EP_Resolved);
88482:   }
88483:   return p;
88484: }
88485: 
88486: /*
88487: ** Report an error that an expression is not valid for some set of
88488: ** pNC->ncFlags values determined by validMask.
88489: */
88490: static void notValid(
88491:   Parse *pParse,       /* Leave error message here */
88492:   NameContext *pNC,    /* The name context */
88493:   const char *zMsg,    /* Type of error */
88494:   int validMask        /* Set of contexts for which prohibited */
88495: ){
88496:   assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
88497:   if( (pNC->ncFlags & validMask)!=0 ){
88498:     const char *zIn = "partial index WHERE clauses";
88499:     if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
88500: #ifndef SQLITE_OMIT_CHECK
88501:     else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
88502: #endif
88503:     sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
88504:   }
88505: }
88506: 
88507: /*
88508: ** Expression p should encode a floating point value between 1.0 and 0.0.
88509: ** Return 1024 times this value.  Or return -1 if p is not a floating point
88510: ** value between 1.0 and 0.0.
88511: */
88512: static int exprProbability(Expr *p){
88513:   double r = -1.0;
88514:   if( p->op!=TK_FLOAT ) return -1;
88515:   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
88516:   assert( r>=0.0 );
88517:   if( r>1.0 ) return -1;
88518:   return (int)(r*134217728.0);
88519: }
88520: 
88521: /*
88522: ** This routine is callback for sqlite3WalkExpr().
88523: **
88524: ** Resolve symbolic names into TK_COLUMN operators for the current
88525: ** node in the expression tree.  Return 0 to continue the search down
88526: ** the tree or 2 to abort the tree walk.
88527: **
88528: ** This routine also does error checking and name resolution for
88529: ** function names.  The operator for aggregate functions is changed
88530: ** to TK_AGG_FUNCTION.
88531: */
88532: static int resolveExprStep(Walker *pWalker, Expr *pExpr){
88533:   NameContext *pNC;
88534:   Parse *pParse;
88535: 
88536:   pNC = pWalker->u.pNC;
88537:   assert( pNC!=0 );
88538:   pParse = pNC->pParse;
88539:   assert( pParse==pWalker->pParse );
88540: 
88541:   if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
88542:   ExprSetProperty(pExpr, EP_Resolved);
88543: #ifndef NDEBUG
88544:   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
88545:     SrcList *pSrcList = pNC->pSrcList;
88546:     int i;
88547:     for(i=0; i<pNC->pSrcList->nSrc; i++){
88548:       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
88549:     }
88550:   }
88551: #endif
88552:   switch( pExpr->op ){
88553: 
88554: #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
88555:     /* The special operator TK_ROW means use the rowid for the first
88556:     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
88557:     ** clause processing on UPDATE and DELETE statements.
88558:     */
88559:     case TK_ROW: {
88560:       SrcList *pSrcList = pNC->pSrcList;
88561:       struct SrcList_item *pItem;
88562:       assert( pSrcList && pSrcList->nSrc==1 );
88563:       pItem = pSrcList->a; 
88564:       pExpr->op = TK_COLUMN;
88565:       pExpr->pTab = pItem->pTab;
88566:       pExpr->iTable = pItem->iCursor;
88567:       pExpr->iColumn = -1;
88568:       pExpr->affinity = SQLITE_AFF_INTEGER;
88569:       break;
88570:     }
88571: #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
88572:           && !defined(SQLITE_OMIT_SUBQUERY) */
88573: 
88574:     /* A lone identifier is the name of a column.
88575:     */
88576:     case TK_ID: {
88577:       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
88578:     }
88579:   
88580:     /* A table name and column name:     ID.ID
88581:     ** Or a database, table and column:  ID.ID.ID
88582:     */
88583:     case TK_DOT: {
88584:       const char *zColumn;
88585:       const char *zTable;
88586:       const char *zDb;
88587:       Expr *pRight;
88588: 
88589:       /* if( pSrcList==0 ) break; */
88590:       notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
88591:       /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
88592:       pRight = pExpr->pRight;
88593:       if( pRight->op==TK_ID ){
88594:         zDb = 0;
88595:         zTable = pExpr->pLeft->u.zToken;
88596:         zColumn = pRight->u.zToken;
88597:       }else{
88598:         assert( pRight->op==TK_DOT );
88599:         zDb = pExpr->pLeft->u.zToken;
88600:         zTable = pRight->pLeft->u.zToken;
88601:         zColumn = pRight->pRight->u.zToken;
88602:       }
88603:       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
88604:     }
88605: 
88606:     /* Resolve function names
88607:     */
88608:     case TK_FUNCTION: {
88609:       ExprList *pList = pExpr->x.pList;    /* The argument list */
88610:       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
88611:       int no_such_func = 0;       /* True if no such function exists */
88612:       int wrong_num_args = 0;     /* True if wrong number of arguments */
88613:       int is_agg = 0;             /* True if is an aggregate function */
88614:       int auth;                   /* Authorization to use the function */
88615:       int nId;                    /* Number of characters in function name */
88616:       const char *zId;            /* The function name. */
88617:       FuncDef *pDef;              /* Information about the function */
88618:       u8 enc = ENC(pParse->db);   /* The database encoding */
88619: 
88620:       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88621:       notValid(pParse, pNC, "functions", NC_PartIdx);
88622:       zId = pExpr->u.zToken;
88623:       nId = sqlite3Strlen30(zId);
88624:       pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
88625:       if( pDef==0 ){
88626:         pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
88627:         if( pDef==0 ){
88628:           no_such_func = 1;
88629:         }else{
88630:           wrong_num_args = 1;
88631:         }
88632:       }else{
88633:         is_agg = pDef->xFinalize!=0;
88634:         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
88635:           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
88636:           if( n==2 ){
88637:             pExpr->iTable = exprProbability(pList->a[1].pExpr);
88638:             if( pExpr->iTable<0 ){
88639:               sqlite3ErrorMsg(pParse,
88640:                 "second argument to likelihood() must be a "
88641:                 "constant between 0.0 and 1.0");
88642:               pNC->nErr++;
88643:             }
88644:           }else{
88645:             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
88646:             ** equivalent to likelihood(X, 0.0625).
88647:             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
88648:             ** short-hand for likelihood(X,0.0625).
88649:             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
88650:             ** for likelihood(X,0.9375).
88651:             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
88652:             ** to likelihood(X,0.9375). */
88653:             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
88654:             pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
88655:           }             
88656:         }
88657: #ifndef SQLITE_OMIT_AUTHORIZATION
88658:         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
88659:         if( auth!=SQLITE_OK ){
88660:           if( auth==SQLITE_DENY ){
88661:             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
88662:                                     pDef->zName);
88663:             pNC->nErr++;
88664:           }
88665:           pExpr->op = TK_NULL;
88666:           return WRC_Prune;
88667:         }
88668: #endif
88669:         if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
88670:           /* For the purposes of the EP_ConstFunc flag, date and time
88671:           ** functions and other functions that change slowly are considered
88672:           ** constant because they are constant for the duration of one query */
88673:           ExprSetProperty(pExpr,EP_ConstFunc);
88674:         }
88675:         if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
88676:           /* Date/time functions that use 'now', and other functions like
88677:           ** sqlite_version() that might change over time cannot be used
88678:           ** in an index. */
88679:           notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
88680:         }
88681:       }
88682:       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
88683:         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
88684:         pNC->nErr++;
88685:         is_agg = 0;
88686:       }else if( no_such_func && pParse->db->init.busy==0
88687: #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
88688:                 && pParse->explain==0
88689: #endif
88690:       ){
88691:         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
88692:         pNC->nErr++;
88693:       }else if( wrong_num_args ){
88694:         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
88695:              nId, zId);
88696:         pNC->nErr++;
88697:       }
88698:       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
88699:       sqlite3WalkExprList(pWalker, pList);
88700:       if( is_agg ){
88701:         NameContext *pNC2 = pNC;
88702:         pExpr->op = TK_AGG_FUNCTION;
88703:         pExpr->op2 = 0;
88704:         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
88705:           pExpr->op2++;
88706:           pNC2 = pNC2->pNext;
88707:         }
88708:         assert( pDef!=0 );
88709:         if( pNC2 ){
88710:           assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
88711:           testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
88712:           pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
88713: 
88714:         }
88715:         pNC->ncFlags |= NC_AllowAgg;
88716:       }
88717:       /* FIX ME:  Compute pExpr->affinity based on the expected return
88718:       ** type of the function 
88719:       */
88720:       return WRC_Prune;
88721:     }
88722: #ifndef SQLITE_OMIT_SUBQUERY
88723:     case TK_SELECT:
88724:     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
88725: #endif
88726:     case TK_IN: {
88727:       testcase( pExpr->op==TK_IN );
88728:       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88729:         int nRef = pNC->nRef;
88730:         notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88731:         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
88732:         assert( pNC->nRef>=nRef );
88733:         if( nRef!=pNC->nRef ){
88734:           ExprSetProperty(pExpr, EP_VarSelect);
88735:           pNC->ncFlags |= NC_VarSelect;
88736:         }
88737:       }
88738:       break;
88739:     }
88740:     case TK_VARIABLE: {
88741:       notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88742:       break;
88743:     }
88744:   }
88745:   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
88746: }
88747: 
88748: /*
88749: ** pEList is a list of expressions which are really the result set of the
88750: ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
88751: ** This routine checks to see if pE is a simple identifier which corresponds
88752: ** to the AS-name of one of the terms of the expression list.  If it is,
88753: ** this routine return an integer between 1 and N where N is the number of
88754: ** elements in pEList, corresponding to the matching entry.  If there is
88755: ** no match, or if pE is not a simple identifier, then this routine
88756: ** return 0.
88757: **
88758: ** pEList has been resolved.  pE has not.
88759: */
88760: static int resolveAsName(
88761:   Parse *pParse,     /* Parsing context for error messages */
88762:   ExprList *pEList,  /* List of expressions to scan */
88763:   Expr *pE           /* Expression we are trying to match */
88764: ){
88765:   int i;             /* Loop counter */
88766: 
88767:   UNUSED_PARAMETER(pParse);
88768: 
88769:   if( pE->op==TK_ID ){
88770:     char *zCol = pE->u.zToken;
88771:     for(i=0; i<pEList->nExpr; i++){
88772:       char *zAs = pEList->a[i].zName;
88773:       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88774:         return i+1;
88775:       }
88776:     }
88777:   }
88778:   return 0;
88779: }
88780: 
88781: /*
88782: ** pE is a pointer to an expression which is a single term in the
88783: ** ORDER BY of a compound SELECT.  The expression has not been
88784: ** name resolved.
88785: **
88786: ** At the point this routine is called, we already know that the
88787: ** ORDER BY term is not an integer index into the result set.  That
88788: ** case is handled by the calling routine.
88789: **
88790: ** Attempt to match pE against result set columns in the left-most
88791: ** SELECT statement.  Return the index i of the matching column,
88792: ** as an indication to the caller that it should sort by the i-th column.
88793: ** The left-most column is 1.  In other words, the value returned is the
88794: ** same integer value that would be used in the SQL statement to indicate
88795: ** the column.
88796: **
88797: ** If there is no match, return 0.  Return -1 if an error occurs.
88798: */
88799: static int resolveOrderByTermToExprList(
88800:   Parse *pParse,     /* Parsing context for error messages */
88801:   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
88802:   Expr *pE           /* The specific ORDER BY term */
88803: ){
88804:   int i;             /* Loop counter */
88805:   ExprList *pEList;  /* The columns of the result set */
88806:   NameContext nc;    /* Name context for resolving pE */
88807:   sqlite3 *db;       /* Database connection */
88808:   int rc;            /* Return code from subprocedures */
88809:   u8 savedSuppErr;   /* Saved value of db->suppressErr */
88810: 
88811:   assert( sqlite3ExprIsInteger(pE, &i)==0 );
88812:   pEList = pSelect->pEList;
88813: 
88814:   /* Resolve all names in the ORDER BY term expression
88815:   */
88816:   memset(&nc, 0, sizeof(nc));
88817:   nc.pParse = pParse;
88818:   nc.pSrcList = pSelect->pSrc;
88819:   nc.pEList = pEList;
88820:   nc.ncFlags = NC_AllowAgg;
88821:   nc.nErr = 0;
88822:   db = pParse->db;
88823:   savedSuppErr = db->suppressErr;
88824:   db->suppressErr = 1;
88825:   rc = sqlite3ResolveExprNames(&nc, pE);
88826:   db->suppressErr = savedSuppErr;
88827:   if( rc ) return 0;
88828: 
88829:   /* Try to match the ORDER BY expression against an expression
88830:   ** in the result set.  Return an 1-based index of the matching
88831:   ** result-set entry.
88832:   */
88833:   for(i=0; i<pEList->nExpr; i++){
88834:     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
88835:       return i+1;
88836:     }
88837:   }
88838: 
88839:   /* If no match, return 0. */
88840:   return 0;
88841: }
88842: 
88843: /*
88844: ** Generate an ORDER BY or GROUP BY term out-of-range error.
88845: */
88846: static void resolveOutOfRangeError(
88847:   Parse *pParse,         /* The error context into which to write the error */
88848:   const char *zType,     /* "ORDER" or "GROUP" */
88849:   int i,                 /* The index (1-based) of the term out of range */
88850:   int mx                 /* Largest permissible value of i */
88851: ){
88852:   sqlite3ErrorMsg(pParse, 
88853:     "%r %s BY term out of range - should be "
88854:     "between 1 and %d", i, zType, mx);
88855: }
88856: 
88857: /*
88858: ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
88859: ** each term of the ORDER BY clause is a constant integer between 1
88860: ** and N where N is the number of columns in the compound SELECT.
88861: **
88862: ** ORDER BY terms that are already an integer between 1 and N are
88863: ** unmodified.  ORDER BY terms that are integers outside the range of
88864: ** 1 through N generate an error.  ORDER BY terms that are expressions
88865: ** are matched against result set expressions of compound SELECT
88866: ** beginning with the left-most SELECT and working toward the right.
88867: ** At the first match, the ORDER BY expression is transformed into
88868: ** the integer column number.
88869: **
88870: ** Return the number of errors seen.
88871: */
88872: static int resolveCompoundOrderBy(
88873:   Parse *pParse,        /* Parsing context.  Leave error messages here */
88874:   Select *pSelect       /* The SELECT statement containing the ORDER BY */
88875: ){
88876:   int i;
88877:   ExprList *pOrderBy;
88878:   ExprList *pEList;
88879:   sqlite3 *db;
88880:   int moreToDo = 1;
88881: 
88882:   pOrderBy = pSelect->pOrderBy;
88883:   if( pOrderBy==0 ) return 0;
88884:   db = pParse->db;
88885: #if SQLITE_MAX_COLUMN
88886:   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88887:     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
88888:     return 1;
88889:   }
88890: #endif
88891:   for(i=0; i<pOrderBy->nExpr; i++){
88892:     pOrderBy->a[i].done = 0;
88893:   }
88894:   pSelect->pNext = 0;
88895:   while( pSelect->pPrior ){
88896:     pSelect->pPrior->pNext = pSelect;
88897:     pSelect = pSelect->pPrior;
88898:   }
88899:   while( pSelect && moreToDo ){
88900:     struct ExprList_item *pItem;
88901:     moreToDo = 0;
88902:     pEList = pSelect->pEList;
88903:     assert( pEList!=0 );
88904:     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88905:       int iCol = -1;
88906:       Expr *pE, *pDup;
88907:       if( pItem->done ) continue;
88908:       pE = sqlite3ExprSkipCollate(pItem->pExpr);
88909:       if( sqlite3ExprIsInteger(pE, &iCol) ){
88910:         if( iCol<=0 || iCol>pEList->nExpr ){
88911:           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
88912:           return 1;
88913:         }
88914:       }else{
88915:         iCol = resolveAsName(pParse, pEList, pE);
88916:         if( iCol==0 ){
88917:           pDup = sqlite3ExprDup(db, pE, 0);
88918:           if( !db->mallocFailed ){
88919:             assert(pDup);
88920:             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
88921:           }
88922:           sqlite3ExprDelete(db, pDup);
88923:         }
88924:       }
88925:       if( iCol>0 ){
88926:         /* Convert the ORDER BY term into an integer column number iCol,
88927:         ** taking care to preserve the COLLATE clause if it exists */
88928:         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
88929:         if( pNew==0 ) return 1;
88930:         pNew->flags |= EP_IntValue;
88931:         pNew->u.iValue = iCol;
88932:         if( pItem->pExpr==pE ){
88933:           pItem->pExpr = pNew;
88934:         }else{
88935:           Expr *pParent = pItem->pExpr;
88936:           assert( pParent->op==TK_COLLATE );
88937:           while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
88938:           assert( pParent->pLeft==pE );
88939:           pParent->pLeft = pNew;
88940:         }
88941:         sqlite3ExprDelete(db, pE);
88942:         pItem->u.x.iOrderByCol = (u16)iCol;
88943:         pItem->done = 1;
88944:       }else{
88945:         moreToDo = 1;
88946:       }
88947:     }
88948:     pSelect = pSelect->pNext;
88949:   }
88950:   for(i=0; i<pOrderBy->nExpr; i++){
88951:     if( pOrderBy->a[i].done==0 ){
88952:       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
88953:             "column in the result set", i+1);
88954:       return 1;
88955:     }
88956:   }
88957:   return 0;
88958: }
88959: 
88960: /*
88961: ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
88962: ** the SELECT statement pSelect.  If any term is reference to a
88963: ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
88964: ** field) then convert that term into a copy of the corresponding result set
88965: ** column.
88966: **
88967: ** If any errors are detected, add an error message to pParse and
88968: ** return non-zero.  Return zero if no errors are seen.
88969: */
88970: SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
88971:   Parse *pParse,        /* Parsing context.  Leave error messages here */
88972:   Select *pSelect,      /* The SELECT statement containing the clause */
88973:   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
88974:   const char *zType     /* "ORDER" or "GROUP" */
88975: ){
88976:   int i;
88977:   sqlite3 *db = pParse->db;
88978:   ExprList *pEList;
88979:   struct ExprList_item *pItem;
88980: 
88981:   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
88982: #if SQLITE_MAX_COLUMN
88983:   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88984:     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
88985:     return 1;
88986:   }
88987: #endif
88988:   pEList = pSelect->pEList;
88989:   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
88990:   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88991:     if( pItem->u.x.iOrderByCol ){
88992:       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
88993:         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
88994:         return 1;
88995:       }
88996:       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
88997:                    zType,0);
88998:     }
88999:   }
89000:   return 0;
89001: }
89002: 
89003: /*
89004: ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
89005: ** The Name context of the SELECT statement is pNC.  zType is either
89006: ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
89007: **
89008: ** This routine resolves each term of the clause into an expression.
89009: ** If the order-by term is an integer I between 1 and N (where N is the
89010: ** number of columns in the result set of the SELECT) then the expression
89011: ** in the resolution is a copy of the I-th result-set expression.  If
89012: ** the order-by term is an identifier that corresponds to the AS-name of
89013: ** a result-set expression, then the term resolves to a copy of the
89014: ** result-set expression.  Otherwise, the expression is resolved in
89015: ** the usual way - using sqlite3ResolveExprNames().
89016: **
89017: ** This routine returns the number of errors.  If errors occur, then
89018: ** an appropriate error message might be left in pParse.  (OOM errors
89019: ** excepted.)
89020: */
89021: static int resolveOrderGroupBy(
89022:   NameContext *pNC,     /* The name context of the SELECT statement */
89023:   Select *pSelect,      /* The SELECT statement holding pOrderBy */
89024:   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
89025:   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
89026: ){
89027:   int i, j;                      /* Loop counters */
89028:   int iCol;                      /* Column number */
89029:   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
89030:   Parse *pParse;                 /* Parsing context */
89031:   int nResult;                   /* Number of terms in the result set */
89032: 
89033:   if( pOrderBy==0 ) return 0;
89034:   nResult = pSelect->pEList->nExpr;
89035:   pParse = pNC->pParse;
89036:   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
89037:     Expr *pE = pItem->pExpr;
89038:     Expr *pE2 = sqlite3ExprSkipCollate(pE);
89039:     if( zType[0]!='G' ){
89040:       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
89041:       if( iCol>0 ){
89042:         /* If an AS-name match is found, mark this ORDER BY column as being
89043:         ** a copy of the iCol-th result-set column.  The subsequent call to
89044:         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
89045:         ** copy of the iCol-th result-set expression. */
89046:         pItem->u.x.iOrderByCol = (u16)iCol;
89047:         continue;
89048:       }
89049:     }
89050:     if( sqlite3ExprIsInteger(pE2, &iCol) ){
89051:       /* The ORDER BY term is an integer constant.  Again, set the column
89052:       ** number so that sqlite3ResolveOrderGroupBy() will convert the
89053:       ** order-by term to a copy of the result-set expression */
89054:       if( iCol<1 || iCol>0xffff ){
89055:         resolveOutOfRangeError(pParse, zType, i+1, nResult);
89056:         return 1;
89057:       }
89058:       pItem->u.x.iOrderByCol = (u16)iCol;
89059:       continue;
89060:     }
89061: 
89062:     /* Otherwise, treat the ORDER BY term as an ordinary expression */
89063:     pItem->u.x.iOrderByCol = 0;
89064:     if( sqlite3ResolveExprNames(pNC, pE) ){
89065:       return 1;
89066:     }
89067:     for(j=0; j<pSelect->pEList->nExpr; j++){
89068:       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
89069:         pItem->u.x.iOrderByCol = j+1;
89070:       }
89071:     }
89072:   }
89073:   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
89074: }
89075: 
89076: /*
89077: ** Resolve names in the SELECT statement p and all of its descendants.
89078: */
89079: static int resolveSelectStep(Walker *pWalker, Select *p){
89080:   NameContext *pOuterNC;  /* Context that contains this SELECT */
89081:   NameContext sNC;        /* Name context of this SELECT */
89082:   int isCompound;         /* True if p is a compound select */
89083:   int nCompound;          /* Number of compound terms processed so far */
89084:   Parse *pParse;          /* Parsing context */
89085:   int i;                  /* Loop counter */
89086:   ExprList *pGroupBy;     /* The GROUP BY clause */
89087:   Select *pLeftmost;      /* Left-most of SELECT of a compound */
89088:   sqlite3 *db;            /* Database connection */
89089:   
89090: 
89091:   assert( p!=0 );
89092:   if( p->selFlags & SF_Resolved ){
89093:     return WRC_Prune;
89094:   }
89095:   pOuterNC = pWalker->u.pNC;
89096:   pParse = pWalker->pParse;
89097:   db = pParse->db;
89098: 
89099:   /* Normally sqlite3SelectExpand() will be called first and will have
89100:   ** already expanded this SELECT.  However, if this is a subquery within
89101:   ** an expression, sqlite3ResolveExprNames() will be called without a
89102:   ** prior call to sqlite3SelectExpand().  When that happens, let
89103:   ** sqlite3SelectPrep() do all of the processing for this SELECT.
89104:   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
89105:   ** this routine in the correct order.
89106:   */
89107:   if( (p->selFlags & SF_Expanded)==0 ){
89108:     sqlite3SelectPrep(pParse, p, pOuterNC);
89109:     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
89110:   }
89111: 
89112:   isCompound = p->pPrior!=0;
89113:   nCompound = 0;
89114:   pLeftmost = p;
89115:   while( p ){
89116:     assert( (p->selFlags & SF_Expanded)!=0 );
89117:     assert( (p->selFlags & SF_Resolved)==0 );
89118:     p->selFlags |= SF_Resolved;
89119: 
89120:     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
89121:     ** are not allowed to refer to any names, so pass an empty NameContext.
89122:     */
89123:     memset(&sNC, 0, sizeof(sNC));
89124:     sNC.pParse = pParse;
89125:     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
89126:         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
89127:       return WRC_Abort;
89128:     }
89129: 
89130:     /* If the SF_Converted flags is set, then this Select object was
89131:     ** was created by the convertCompoundSelectToSubquery() function.
89132:     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
89133:     ** as if it were part of the sub-query, not the parent. This block
89134:     ** moves the pOrderBy down to the sub-query. It will be moved back
89135:     ** after the names have been resolved.  */
89136:     if( p->selFlags & SF_Converted ){
89137:       Select *pSub = p->pSrc->a[0].pSelect;
89138:       assert( p->pSrc->nSrc==1 && p->pOrderBy );
89139:       assert( pSub->pPrior && pSub->pOrderBy==0 );
89140:       pSub->pOrderBy = p->pOrderBy;
89141:       p->pOrderBy = 0;
89142:     }
89143:   
89144:     /* Recursively resolve names in all subqueries
89145:     */
89146:     for(i=0; i<p->pSrc->nSrc; i++){
89147:       struct SrcList_item *pItem = &p->pSrc->a[i];
89148:       if( pItem->pSelect ){
89149:         NameContext *pNC;         /* Used to iterate name contexts */
89150:         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
89151:         const char *zSavedContext = pParse->zAuthContext;
89152: 
89153:         /* Count the total number of references to pOuterNC and all of its
89154:         ** parent contexts. After resolving references to expressions in
89155:         ** pItem->pSelect, check if this value has changed. If so, then
89156:         ** SELECT statement pItem->pSelect must be correlated. Set the
89157:         ** pItem->fg.isCorrelated flag if this is the case. */
89158:         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
89159: 
89160:         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
89161:         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
89162:         pParse->zAuthContext = zSavedContext;
89163:         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
89164: 
89165:         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
89166:         assert( pItem->fg.isCorrelated==0 && nRef<=0 );
89167:         pItem->fg.isCorrelated = (nRef!=0);
89168:       }
89169:     }
89170:   
89171:     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
89172:     ** resolve the result-set expression list.
89173:     */
89174:     sNC.ncFlags = NC_AllowAgg;
89175:     sNC.pSrcList = p->pSrc;
89176:     sNC.pNext = pOuterNC;
89177:   
89178:     /* Resolve names in the result set. */
89179:     if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
89180:   
89181:     /* If there are no aggregate functions in the result-set, and no GROUP BY 
89182:     ** expression, do not allow aggregates in any of the other expressions.
89183:     */
89184:     assert( (p->selFlags & SF_Aggregate)==0 );
89185:     pGroupBy = p->pGroupBy;
89186:     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
89187:       assert( NC_MinMaxAgg==SF_MinMaxAgg );
89188:       p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
89189:     }else{
89190:       sNC.ncFlags &= ~NC_AllowAgg;
89191:     }
89192:   
89193:     /* If a HAVING clause is present, then there must be a GROUP BY clause.
89194:     */
89195:     if( p->pHaving && !pGroupBy ){
89196:       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
89197:       return WRC_Abort;
89198:     }
89199:   
89200:     /* Add the output column list to the name-context before parsing the
89201:     ** other expressions in the SELECT statement. This is so that
89202:     ** expressions in the WHERE clause (etc.) can refer to expressions by
89203:     ** aliases in the result set.
89204:     **
89205:     ** Minor point: If this is the case, then the expression will be
89206:     ** re-evaluated for each reference to it.
89207:     */
89208:     sNC.pEList = p->pEList;
89209:     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
89210:     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
89211: 
89212:     /* Resolve names in table-valued-function arguments */
89213:     for(i=0; i<p->pSrc->nSrc; i++){
89214:       struct SrcList_item *pItem = &p->pSrc->a[i];
89215:       if( pItem->fg.isTabFunc
89216:        && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) 
89217:       ){
89218:         return WRC_Abort;
89219:       }
89220:     }
89221: 
89222:     /* The ORDER BY and GROUP BY clauses may not refer to terms in
89223:     ** outer queries 
89224:     */
89225:     sNC.pNext = 0;
89226:     sNC.ncFlags |= NC_AllowAgg;
89227: 
89228:     /* If this is a converted compound query, move the ORDER BY clause from 
89229:     ** the sub-query back to the parent query. At this point each term
89230:     ** within the ORDER BY clause has been transformed to an integer value.
89231:     ** These integers will be replaced by copies of the corresponding result
89232:     ** set expressions by the call to resolveOrderGroupBy() below.  */
89233:     if( p->selFlags & SF_Converted ){
89234:       Select *pSub = p->pSrc->a[0].pSelect;
89235:       p->pOrderBy = pSub->pOrderBy;
89236:       pSub->pOrderBy = 0;
89237:     }
89238: 
89239:     /* Process the ORDER BY clause for singleton SELECT statements.
89240:     ** The ORDER BY clause for compounds SELECT statements is handled
89241:     ** below, after all of the result-sets for all of the elements of
89242:     ** the compound have been resolved.
89243:     **
89244:     ** If there is an ORDER BY clause on a term of a compound-select other
89245:     ** than the right-most term, then that is a syntax error.  But the error
89246:     ** is not detected until much later, and so we need to go ahead and
89247:     ** resolve those symbols on the incorrect ORDER BY for consistency.
89248:     */
89249:     if( isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
89250:      && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
89251:     ){
89252:       return WRC_Abort;
89253:     }
89254:     if( db->mallocFailed ){
89255:       return WRC_Abort;
89256:     }
89257:   
89258:     /* Resolve the GROUP BY clause.  At the same time, make sure 
89259:     ** the GROUP BY clause does not contain aggregate functions.
89260:     */
89261:     if( pGroupBy ){
89262:       struct ExprList_item *pItem;
89263:     
89264:       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
89265:         return WRC_Abort;
89266:       }
89267:       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
89268:         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
89269:           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
89270:               "the GROUP BY clause");
89271:           return WRC_Abort;
89272:         }
89273:       }
89274:     }
89275: 
89276:     /* If this is part of a compound SELECT, check that it has the right
89277:     ** number of expressions in the select list. */
89278:     if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
89279:       sqlite3SelectWrongNumTermsError(pParse, p->pNext);
89280:       return WRC_Abort;
89281:     }
89282: 
89283:     /* Advance to the next term of the compound
89284:     */
89285:     p = p->pPrior;
89286:     nCompound++;
89287:   }
89288: 
89289:   /* Resolve the ORDER BY on a compound SELECT after all terms of
89290:   ** the compound have been resolved.
89291:   */
89292:   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
89293:     return WRC_Abort;
89294:   }
89295: 
89296:   return WRC_Prune;
89297: }
89298: 
89299: /*
89300: ** This routine walks an expression tree and resolves references to
89301: ** table columns and result-set columns.  At the same time, do error
89302: ** checking on function usage and set a flag if any aggregate functions
89303: ** are seen.
89304: **
89305: ** To resolve table columns references we look for nodes (or subtrees) of the 
89306: ** form X.Y.Z or Y.Z or just Z where
89307: **
89308: **      X:   The name of a database.  Ex:  "main" or "temp" or
89309: **           the symbolic name assigned to an ATTACH-ed database.
89310: **
89311: **      Y:   The name of a table in a FROM clause.  Or in a trigger
89312: **           one of the special names "old" or "new".
89313: **
89314: **      Z:   The name of a column in table Y.
89315: **
89316: ** The node at the root of the subtree is modified as follows:
89317: **
89318: **    Expr.op        Changed to TK_COLUMN
89319: **    Expr.pTab      Points to the Table object for X.Y
89320: **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
89321: **    Expr.iTable    The VDBE cursor number for X.Y
89322: **
89323: **
89324: ** To resolve result-set references, look for expression nodes of the
89325: ** form Z (with no X and Y prefix) where the Z matches the right-hand
89326: ** size of an AS clause in the result-set of a SELECT.  The Z expression
89327: ** is replaced by a copy of the left-hand side of the result-set expression.
89328: ** Table-name and function resolution occurs on the substituted expression
89329: ** tree.  For example, in:
89330: **
89331: **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
89332: **
89333: ** The "x" term of the order by is replaced by "a+b" to render:
89334: **
89335: **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
89336: **
89337: ** Function calls are checked to make sure that the function is 
89338: ** defined and that the correct number of arguments are specified.
89339: ** If the function is an aggregate function, then the NC_HasAgg flag is
89340: ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
89341: ** If an expression contains aggregate functions then the EP_Agg
89342: ** property on the expression is set.
89343: **
89344: ** An error message is left in pParse if anything is amiss.  The number
89345: ** if errors is returned.
89346: */
89347: SQLITE_PRIVATE int sqlite3ResolveExprNames( 
89348:   NameContext *pNC,       /* Namespace to resolve expressions in. */
89349:   Expr *pExpr             /* The expression to be analyzed. */
89350: ){
89351:   u16 savedHasAgg;
89352:   Walker w;
89353: 
89354:   if( pExpr==0 ) return 0;
89355: #if SQLITE_MAX_EXPR_DEPTH>0
89356:   {
89357:     Parse *pParse = pNC->pParse;
89358:     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
89359:       return 1;
89360:     }
89361:     pParse->nHeight += pExpr->nHeight;
89362:   }
89363: #endif
89364:   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
89365:   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
89366:   w.pParse = pNC->pParse;
89367:   w.xExprCallback = resolveExprStep;
89368:   w.xSelectCallback = resolveSelectStep;
89369:   w.xSelectCallback2 = 0;
89370:   w.walkerDepth = 0;
89371:   w.eCode = 0;
89372:   w.u.pNC = pNC;
89373:   sqlite3WalkExpr(&w, pExpr);
89374: #if SQLITE_MAX_EXPR_DEPTH>0
89375:   pNC->pParse->nHeight -= pExpr->nHeight;
89376: #endif
89377:   if( pNC->nErr>0 || w.pParse->nErr>0 ){
89378:     ExprSetProperty(pExpr, EP_Error);
89379:   }
89380:   if( pNC->ncFlags & NC_HasAgg ){
89381:     ExprSetProperty(pExpr, EP_Agg);
89382:   }
89383:   pNC->ncFlags |= savedHasAgg;
89384:   return ExprHasProperty(pExpr, EP_Error);
89385: }
89386: 
89387: /*
89388: ** Resolve all names for all expression in an expression list.  This is
89389: ** just like sqlite3ResolveExprNames() except that it works for an expression
89390: ** list rather than a single expression.
89391: */
89392: SQLITE_PRIVATE int sqlite3ResolveExprListNames( 
89393:   NameContext *pNC,       /* Namespace to resolve expressions in. */
89394:   ExprList *pList         /* The expression list to be analyzed. */
89395: ){
89396:   int i;
89397:   if( pList ){
89398:     for(i=0; i<pList->nExpr; i++){
89399:       if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
89400:     }
89401:   }
89402:   return WRC_Continue;
89403: }
89404: 
89405: /*
89406: ** Resolve all names in all expressions of a SELECT and in all
89407: ** decendents of the SELECT, including compounds off of p->pPrior,
89408: ** subqueries in expressions, and subqueries used as FROM clause
89409: ** terms.
89410: **
89411: ** See sqlite3ResolveExprNames() for a description of the kinds of
89412: ** transformations that occur.
89413: **
89414: ** All SELECT statements should have been expanded using
89415: ** sqlite3SelectExpand() prior to invoking this routine.
89416: */
89417: SQLITE_PRIVATE void sqlite3ResolveSelectNames(
89418:   Parse *pParse,         /* The parser context */
89419:   Select *p,             /* The SELECT statement being coded. */
89420:   NameContext *pOuterNC  /* Name context for parent SELECT statement */
89421: ){
89422:   Walker w;
89423: 
89424:   assert( p!=0 );
89425:   memset(&w, 0, sizeof(w));
89426:   w.xExprCallback = resolveExprStep;
89427:   w.xSelectCallback = resolveSelectStep;
89428:   w.pParse = pParse;
89429:   w.u.pNC = pOuterNC;
89430:   sqlite3WalkSelect(&w, p);
89431: }
89432: 
89433: /*
89434: ** Resolve names in expressions that can only reference a single table:
89435: **
89436: **    *   CHECK constraints
89437: **    *   WHERE clauses on partial indices
89438: **
89439: ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
89440: ** is set to -1 and the Expr.iColumn value is set to the column number.
89441: **
89442: ** Any errors cause an error message to be set in pParse.
89443: */
89444: SQLITE_PRIVATE void sqlite3ResolveSelfReference(
89445:   Parse *pParse,      /* Parsing context */
89446:   Table *pTab,        /* The table being referenced */
89447:   int type,           /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
89448:   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
89449:   ExprList *pList     /* Expression list to resolve.  May be NUL. */
89450: ){
89451:   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
89452:   NameContext sNC;                /* Name context for pParse->pNewTable */
89453: 
89454:   assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
89455:   memset(&sNC, 0, sizeof(sNC));
89456:   memset(&sSrc, 0, sizeof(sSrc));
89457:   sSrc.nSrc = 1;
89458:   sSrc.a[0].zName = pTab->zName;
89459:   sSrc.a[0].pTab = pTab;
89460:   sSrc.a[0].iCursor = -1;
89461:   sNC.pParse = pParse;
89462:   sNC.pSrcList = &sSrc;
89463:   sNC.ncFlags = type;
89464:   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
89465:   if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
89466: }
89467: 
89468: /************** End of resolve.c *********************************************/
89469: /************** Begin file expr.c ********************************************/
89470: /*
89471: ** 2001 September 15
89472: **
89473: ** The author disclaims copyright to this source code.  In place of
89474: ** a legal notice, here is a blessing:
89475: **
89476: **    May you do good and not evil.
89477: **    May you find forgiveness for yourself and forgive others.
89478: **    May you share freely, never taking more than you give.
89479: **
89480: *************************************************************************
89481: ** This file contains routines used for analyzing expressions and
89482: ** for generating VDBE code that evaluates expressions in SQLite.
89483: */
89484: /* #include "sqliteInt.h" */
89485: 
89486: /*
89487: ** Return the 'affinity' of the expression pExpr if any.
89488: **
89489: ** If pExpr is a column, a reference to a column via an 'AS' alias,
89490: ** or a sub-select with a column as the return value, then the 
89491: ** affinity of that column is returned. Otherwise, 0x00 is returned,
89492: ** indicating no affinity for the expression.
89493: **
89494: ** i.e. the WHERE clause expressions in the following statements all
89495: ** have an affinity:
89496: **
89497: ** CREATE TABLE t1(a);
89498: ** SELECT * FROM t1 WHERE a;
89499: ** SELECT a AS b FROM t1 WHERE b;
89500: ** SELECT * FROM t1 WHERE (select a from t1);
89501: */
89502: SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
89503:   int op;
89504:   pExpr = sqlite3ExprSkipCollate(pExpr);
89505:   if( pExpr->flags & EP_Generic ) return 0;
89506:   op = pExpr->op;
89507:   if( op==TK_SELECT ){
89508:     assert( pExpr->flags&EP_xIsSelect );
89509:     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
89510:   }
89511: #ifndef SQLITE_OMIT_CAST
89512:   if( op==TK_CAST ){
89513:     assert( !ExprHasProperty(pExpr, EP_IntValue) );
89514:     return sqlite3AffinityType(pExpr->u.zToken, 0);
89515:   }
89516: #endif
89517:   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
89518:    && pExpr->pTab!=0
89519:   ){
89520:     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
89521:     ** a TK_COLUMN but was previously evaluated and cached in a register */
89522:     int j = pExpr->iColumn;
89523:     if( j<0 ) return SQLITE_AFF_INTEGER;
89524:     assert( pExpr->pTab && j<pExpr->pTab->nCol );
89525:     return pExpr->pTab->aCol[j].affinity;
89526:   }
89527:   return pExpr->affinity;
89528: }
89529: 
89530: /*
89531: ** Set the collating sequence for expression pExpr to be the collating
89532: ** sequence named by pToken.   Return a pointer to a new Expr node that
89533: ** implements the COLLATE operator.
89534: **
89535: ** If a memory allocation error occurs, that fact is recorded in pParse->db
89536: ** and the pExpr parameter is returned unchanged.
89537: */
89538: SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
89539:   Parse *pParse,           /* Parsing context */
89540:   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
89541:   const Token *pCollName,  /* Name of collating sequence */
89542:   int dequote              /* True to dequote pCollName */
89543: ){
89544:   if( pCollName->n>0 ){
89545:     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
89546:     if( pNew ){
89547:       pNew->pLeft = pExpr;
89548:       pNew->flags |= EP_Collate|EP_Skip;
89549:       pExpr = pNew;
89550:     }
89551:   }
89552:   return pExpr;
89553: }
89554: SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
89555:   Token s;
89556:   assert( zC!=0 );
89557:   sqlite3TokenInit(&s, (char*)zC);
89558:   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
89559: }
89560: 
89561: /*
89562: ** Skip over any TK_COLLATE operators and any unlikely()
89563: ** or likelihood() function at the root of an expression.
89564: */
89565: SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
89566:   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
89567:     if( ExprHasProperty(pExpr, EP_Unlikely) ){
89568:       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89569:       assert( pExpr->x.pList->nExpr>0 );
89570:       assert( pExpr->op==TK_FUNCTION );
89571:       pExpr = pExpr->x.pList->a[0].pExpr;
89572:     }else{
89573:       assert( pExpr->op==TK_COLLATE );
89574:       pExpr = pExpr->pLeft;
89575:     }
89576:   }   
89577:   return pExpr;
89578: }
89579: 
89580: /*
89581: ** Return the collation sequence for the expression pExpr. If
89582: ** there is no defined collating sequence, return NULL.
89583: **
89584: ** The collating sequence might be determined by a COLLATE operator
89585: ** or by the presence of a column with a defined collating sequence.
89586: ** COLLATE operators take first precedence.  Left operands take
89587: ** precedence over right operands.
89588: */
89589: SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
89590:   sqlite3 *db = pParse->db;
89591:   CollSeq *pColl = 0;
89592:   Expr *p = pExpr;
89593:   while( p ){
89594:     int op = p->op;
89595:     if( p->flags & EP_Generic ) break;
89596:     if( op==TK_CAST || op==TK_UPLUS ){
89597:       p = p->pLeft;
89598:       continue;
89599:     }
89600:     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
89601:       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
89602:       break;
89603:     }
89604:     if( (op==TK_AGG_COLUMN || op==TK_COLUMN
89605:           || op==TK_REGISTER || op==TK_TRIGGER)
89606:      && p->pTab!=0
89607:     ){
89608:       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
89609:       ** a TK_COLUMN but was previously evaluated and cached in a register */
89610:       int j = p->iColumn;
89611:       if( j>=0 ){
89612:         const char *zColl = p->pTab->aCol[j].zColl;
89613:         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
89614:       }
89615:       break;
89616:     }
89617:     if( p->flags & EP_Collate ){
89618:       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
89619:         p = p->pLeft;
89620:       }else{
89621:         Expr *pNext  = p->pRight;
89622:         /* The Expr.x union is never used at the same time as Expr.pRight */
89623:         assert( p->x.pList==0 || p->pRight==0 );
89624:         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
89625:         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
89626:         ** least one EP_Collate. Thus the following two ALWAYS. */
89627:         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
89628:           int i;
89629:           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
89630:             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
89631:               pNext = p->x.pList->a[i].pExpr;
89632:               break;
89633:             }
89634:           }
89635:         }
89636:         p = pNext;
89637:       }
89638:     }else{
89639:       break;
89640:     }
89641:   }
89642:   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
89643:     pColl = 0;
89644:   }
89645:   return pColl;
89646: }
89647: 
89648: /*
89649: ** pExpr is an operand of a comparison operator.  aff2 is the
89650: ** type affinity of the other operand.  This routine returns the
89651: ** type affinity that should be used for the comparison operator.
89652: */
89653: SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
89654:   char aff1 = sqlite3ExprAffinity(pExpr);
89655:   if( aff1 && aff2 ){
89656:     /* Both sides of the comparison are columns. If one has numeric
89657:     ** affinity, use that. Otherwise use no affinity.
89658:     */
89659:     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
89660:       return SQLITE_AFF_NUMERIC;
89661:     }else{
89662:       return SQLITE_AFF_BLOB;
89663:     }
89664:   }else if( !aff1 && !aff2 ){
89665:     /* Neither side of the comparison is a column.  Compare the
89666:     ** results directly.
89667:     */
89668:     return SQLITE_AFF_BLOB;
89669:   }else{
89670:     /* One side is a column, the other is not. Use the columns affinity. */
89671:     assert( aff1==0 || aff2==0 );
89672:     return (aff1 + aff2);
89673:   }
89674: }
89675: 
89676: /*
89677: ** pExpr is a comparison operator.  Return the type affinity that should
89678: ** be applied to both operands prior to doing the comparison.
89679: */
89680: static char comparisonAffinity(Expr *pExpr){
89681:   char aff;
89682:   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
89683:           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
89684:           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
89685:   assert( pExpr->pLeft );
89686:   aff = sqlite3ExprAffinity(pExpr->pLeft);
89687:   if( pExpr->pRight ){
89688:     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
89689:   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89690:     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
89691:   }else if( !aff ){
89692:     aff = SQLITE_AFF_BLOB;
89693:   }
89694:   return aff;
89695: }
89696: 
89697: /*
89698: ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
89699: ** idx_affinity is the affinity of an indexed column. Return true
89700: ** if the index with affinity idx_affinity may be used to implement
89701: ** the comparison in pExpr.
89702: */
89703: SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
89704:   char aff = comparisonAffinity(pExpr);
89705:   switch( aff ){
89706:     case SQLITE_AFF_BLOB:
89707:       return 1;
89708:     case SQLITE_AFF_TEXT:
89709:       return idx_affinity==SQLITE_AFF_TEXT;
89710:     default:
89711:       return sqlite3IsNumericAffinity(idx_affinity);
89712:   }
89713: }
89714: 
89715: /*
89716: ** Return the P5 value that should be used for a binary comparison
89717: ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
89718: */
89719: static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
89720:   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
89721:   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
89722:   return aff;
89723: }
89724: 
89725: /*
89726: ** Return a pointer to the collation sequence that should be used by
89727: ** a binary comparison operator comparing pLeft and pRight.
89728: **
89729: ** If the left hand expression has a collating sequence type, then it is
89730: ** used. Otherwise the collation sequence for the right hand expression
89731: ** is used, or the default (BINARY) if neither expression has a collating
89732: ** type.
89733: **
89734: ** Argument pRight (but not pLeft) may be a null pointer. In this case,
89735: ** it is not considered.
89736: */
89737: SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
89738:   Parse *pParse, 
89739:   Expr *pLeft, 
89740:   Expr *pRight
89741: ){
89742:   CollSeq *pColl;
89743:   assert( pLeft );
89744:   if( pLeft->flags & EP_Collate ){
89745:     pColl = sqlite3ExprCollSeq(pParse, pLeft);
89746:   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
89747:     pColl = sqlite3ExprCollSeq(pParse, pRight);
89748:   }else{
89749:     pColl = sqlite3ExprCollSeq(pParse, pLeft);
89750:     if( !pColl ){
89751:       pColl = sqlite3ExprCollSeq(pParse, pRight);
89752:     }
89753:   }
89754:   return pColl;
89755: }
89756: 
89757: /*
89758: ** Generate code for a comparison operator.
89759: */
89760: static int codeCompare(
89761:   Parse *pParse,    /* The parsing (and code generating) context */
89762:   Expr *pLeft,      /* The left operand */
89763:   Expr *pRight,     /* The right operand */
89764:   int opcode,       /* The comparison opcode */
89765:   int in1, int in2, /* Register holding operands */
89766:   int dest,         /* Jump here if true.  */
89767:   int jumpIfNull    /* If true, jump if either operand is NULL */
89768: ){
89769:   int p5;
89770:   int addr;
89771:   CollSeq *p4;
89772: 
89773:   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
89774:   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
89775:   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
89776:                            (void*)p4, P4_COLLSEQ);
89777:   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
89778:   return addr;
89779: }
89780: 
89781: #if SQLITE_MAX_EXPR_DEPTH>0
89782: /*
89783: ** Check that argument nHeight is less than or equal to the maximum
89784: ** expression depth allowed. If it is not, leave an error message in
89785: ** pParse.
89786: */
89787: SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
89788:   int rc = SQLITE_OK;
89789:   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
89790:   if( nHeight>mxHeight ){
89791:     sqlite3ErrorMsg(pParse, 
89792:        "Expression tree is too large (maximum depth %d)", mxHeight
89793:     );
89794:     rc = SQLITE_ERROR;
89795:   }
89796:   return rc;
89797: }
89798: 
89799: /* The following three functions, heightOfExpr(), heightOfExprList()
89800: ** and heightOfSelect(), are used to determine the maximum height
89801: ** of any expression tree referenced by the structure passed as the
89802: ** first argument.
89803: **
89804: ** If this maximum height is greater than the current value pointed
89805: ** to by pnHeight, the second parameter, then set *pnHeight to that
89806: ** value.
89807: */
89808: static void heightOfExpr(Expr *p, int *pnHeight){
89809:   if( p ){
89810:     if( p->nHeight>*pnHeight ){
89811:       *pnHeight = p->nHeight;
89812:     }
89813:   }
89814: }
89815: static void heightOfExprList(ExprList *p, int *pnHeight){
89816:   if( p ){
89817:     int i;
89818:     for(i=0; i<p->nExpr; i++){
89819:       heightOfExpr(p->a[i].pExpr, pnHeight);
89820:     }
89821:   }
89822: }
89823: static void heightOfSelect(Select *p, int *pnHeight){
89824:   if( p ){
89825:     heightOfExpr(p->pWhere, pnHeight);
89826:     heightOfExpr(p->pHaving, pnHeight);
89827:     heightOfExpr(p->pLimit, pnHeight);
89828:     heightOfExpr(p->pOffset, pnHeight);
89829:     heightOfExprList(p->pEList, pnHeight);
89830:     heightOfExprList(p->pGroupBy, pnHeight);
89831:     heightOfExprList(p->pOrderBy, pnHeight);
89832:     heightOfSelect(p->pPrior, pnHeight);
89833:   }
89834: }
89835: 
89836: /*
89837: ** Set the Expr.nHeight variable in the structure passed as an 
89838: ** argument. An expression with no children, Expr.pList or 
89839: ** Expr.pSelect member has a height of 1. Any other expression
89840: ** has a height equal to the maximum height of any other 
89841: ** referenced Expr plus one.
89842: **
89843: ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
89844: ** if appropriate.
89845: */
89846: static void exprSetHeight(Expr *p){
89847:   int nHeight = 0;
89848:   heightOfExpr(p->pLeft, &nHeight);
89849:   heightOfExpr(p->pRight, &nHeight);
89850:   if( ExprHasProperty(p, EP_xIsSelect) ){
89851:     heightOfSelect(p->x.pSelect, &nHeight);
89852:   }else if( p->x.pList ){
89853:     heightOfExprList(p->x.pList, &nHeight);
89854:     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
89855:   }
89856:   p->nHeight = nHeight + 1;
89857: }
89858: 
89859: /*
89860: ** Set the Expr.nHeight variable using the exprSetHeight() function. If
89861: ** the height is greater than the maximum allowed expression depth,
89862: ** leave an error in pParse.
89863: **
89864: ** Also propagate all EP_Propagate flags from the Expr.x.pList into
89865: ** Expr.flags. 
89866: */
89867: SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
89868:   if( pParse->nErr ) return;
89869:   exprSetHeight(p);
89870:   sqlite3ExprCheckHeight(pParse, p->nHeight);
89871: }
89872: 
89873: /*
89874: ** Return the maximum height of any expression tree referenced
89875: ** by the select statement passed as an argument.
89876: */
89877: SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
89878:   int nHeight = 0;
89879:   heightOfSelect(p, &nHeight);
89880:   return nHeight;
89881: }
89882: #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
89883: /*
89884: ** Propagate all EP_Propagate flags from the Expr.x.pList into
89885: ** Expr.flags. 
89886: */
89887: SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
89888:   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
89889:     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
89890:   }
89891: }
89892: #define exprSetHeight(y)
89893: #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
89894: 
89895: /*
89896: ** This routine is the core allocator for Expr nodes.
89897: **
89898: ** Construct a new expression node and return a pointer to it.  Memory
89899: ** for this node and for the pToken argument is a single allocation
89900: ** obtained from sqlite3DbMalloc().  The calling function
89901: ** is responsible for making sure the node eventually gets freed.
89902: **
89903: ** If dequote is true, then the token (if it exists) is dequoted.
89904: ** If dequote is false, no dequoting is performed.  The deQuote
89905: ** parameter is ignored if pToken is NULL or if the token does not
89906: ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
89907: ** then the EP_DblQuoted flag is set on the expression node.
89908: **
89909: ** Special case:  If op==TK_INTEGER and pToken points to a string that
89910: ** can be translated into a 32-bit integer, then the token is not
89911: ** stored in u.zToken.  Instead, the integer values is written
89912: ** into u.iValue and the EP_IntValue flag is set.  No extra storage
89913: ** is allocated to hold the integer text and the dequote flag is ignored.
89914: */
89915: SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
89916:   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
89917:   int op,                 /* Expression opcode */
89918:   const Token *pToken,    /* Token argument.  Might be NULL */
89919:   int dequote             /* True to dequote */
89920: ){
89921:   Expr *pNew;
89922:   int nExtra = 0;
89923:   int iValue = 0;
89924: 
89925:   assert( db!=0 );
89926:   if( pToken ){
89927:     if( op!=TK_INTEGER || pToken->z==0
89928:           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
89929:       nExtra = pToken->n+1;
89930:       assert( iValue>=0 );
89931:     }
89932:   }
89933:   pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
89934:   if( pNew ){
89935:     memset(pNew, 0, sizeof(Expr));
89936:     pNew->op = (u8)op;
89937:     pNew->iAgg = -1;
89938:     if( pToken ){
89939:       if( nExtra==0 ){
89940:         pNew->flags |= EP_IntValue;
89941:         pNew->u.iValue = iValue;
89942:       }else{
89943:         pNew->u.zToken = (char*)&pNew[1];
89944:         assert( pToken->z!=0 || pToken->n==0 );
89945:         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
89946:         pNew->u.zToken[pToken->n] = 0;
89947:         if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
89948:           if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
89949:           sqlite3Dequote(pNew->u.zToken);
89950:         }
89951:       }
89952:     }
89953: #if SQLITE_MAX_EXPR_DEPTH>0
89954:     pNew->nHeight = 1;
89955: #endif  
89956:   }
89957:   return pNew;
89958: }
89959: 
89960: /*
89961: ** Allocate a new expression node from a zero-terminated token that has
89962: ** already been dequoted.
89963: */
89964: SQLITE_PRIVATE Expr *sqlite3Expr(
89965:   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
89966:   int op,                 /* Expression opcode */
89967:   const char *zToken      /* Token argument.  Might be NULL */
89968: ){
89969:   Token x;
89970:   x.z = zToken;
89971:   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
89972:   return sqlite3ExprAlloc(db, op, &x, 0);
89973: }
89974: 
89975: /*
89976: ** Attach subtrees pLeft and pRight to the Expr node pRoot.
89977: **
89978: ** If pRoot==NULL that means that a memory allocation error has occurred.
89979: ** In that case, delete the subtrees pLeft and pRight.
89980: */
89981: SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
89982:   sqlite3 *db,
89983:   Expr *pRoot,
89984:   Expr *pLeft,
89985:   Expr *pRight
89986: ){
89987:   if( pRoot==0 ){
89988:     assert( db->mallocFailed );
89989:     sqlite3ExprDelete(db, pLeft);
89990:     sqlite3ExprDelete(db, pRight);
89991:   }else{
89992:     if( pRight ){
89993:       pRoot->pRight = pRight;
89994:       pRoot->flags |= EP_Propagate & pRight->flags;
89995:     }
89996:     if( pLeft ){
89997:       pRoot->pLeft = pLeft;
89998:       pRoot->flags |= EP_Propagate & pLeft->flags;
89999:     }
90000:     exprSetHeight(pRoot);
90001:   }
90002: }
90003: 
90004: /*
90005: ** Allocate an Expr node which joins as many as two subtrees.
90006: **
90007: ** One or both of the subtrees can be NULL.  Return a pointer to the new
90008: ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
90009: ** free the subtrees and return NULL.
90010: */
90011: SQLITE_PRIVATE Expr *sqlite3PExpr(
90012:   Parse *pParse,          /* Parsing context */
90013:   int op,                 /* Expression opcode */
90014:   Expr *pLeft,            /* Left operand */
90015:   Expr *pRight,           /* Right operand */
90016:   const Token *pToken     /* Argument token */
90017: ){
90018:   Expr *p;
90019:   if( op==TK_AND && pParse->nErr==0 ){
90020:     /* Take advantage of short-circuit false optimization for AND */
90021:     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
90022:   }else{
90023:     p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
90024:     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
90025:   }
90026:   if( p ) {
90027:     sqlite3ExprCheckHeight(pParse, p->nHeight);
90028:   }
90029:   return p;
90030: }
90031: 
90032: /*
90033: ** Add pSelect to the Expr.x.pSelect field.  Or, if pExpr is NULL (due
90034: ** do a memory allocation failure) then delete the pSelect object.
90035: */
90036: SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
90037:   if( pExpr ){
90038:     pExpr->x.pSelect = pSelect;
90039:     ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
90040:     sqlite3ExprSetHeightAndFlags(pParse, pExpr);
90041:   }else{
90042:     assert( pParse->db->mallocFailed );
90043:     sqlite3SelectDelete(pParse->db, pSelect);
90044:   }
90045: }
90046: 
90047: 
90048: /*
90049: ** If the expression is always either TRUE or FALSE (respectively),
90050: ** then return 1.  If one cannot determine the truth value of the
90051: ** expression at compile-time return 0.
90052: **
90053: ** This is an optimization.  If is OK to return 0 here even if
90054: ** the expression really is always false or false (a false negative).
90055: ** But it is a bug to return 1 if the expression might have different
90056: ** boolean values in different circumstances (a false positive.)
90057: **
90058: ** Note that if the expression is part of conditional for a
90059: ** LEFT JOIN, then we cannot determine at compile-time whether or not
90060: ** is it true or false, so always return 0.
90061: */
90062: static int exprAlwaysTrue(Expr *p){
90063:   int v = 0;
90064:   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90065:   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90066:   return v!=0;
90067: }
90068: static int exprAlwaysFalse(Expr *p){
90069:   int v = 0;
90070:   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
90071:   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
90072:   return v==0;
90073: }
90074: 
90075: /*
90076: ** Join two expressions using an AND operator.  If either expression is
90077: ** NULL, then just return the other expression.
90078: **
90079: ** If one side or the other of the AND is known to be false, then instead
90080: ** of returning an AND expression, just return a constant expression with
90081: ** a value of false.
90082: */
90083: SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
90084:   if( pLeft==0 ){
90085:     return pRight;
90086:   }else if( pRight==0 ){
90087:     return pLeft;
90088:   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
90089:     sqlite3ExprDelete(db, pLeft);
90090:     sqlite3ExprDelete(db, pRight);
90091:     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
90092:   }else{
90093:     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
90094:     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
90095:     return pNew;
90096:   }
90097: }
90098: 
90099: /*
90100: ** Construct a new expression node for a function with multiple
90101: ** arguments.
90102: */
90103: SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
90104:   Expr *pNew;
90105:   sqlite3 *db = pParse->db;
90106:   assert( pToken );
90107:   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
90108:   if( pNew==0 ){
90109:     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
90110:     return 0;
90111:   }
90112:   pNew->x.pList = pList;
90113:   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
90114:   sqlite3ExprSetHeightAndFlags(pParse, pNew);
90115:   return pNew;
90116: }
90117: 
90118: /*
90119: ** Assign a variable number to an expression that encodes a wildcard
90120: ** in the original SQL statement.  
90121: **
90122: ** Wildcards consisting of a single "?" are assigned the next sequential
90123: ** variable number.
90124: **
90125: ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
90126: ** sure "nnn" is not too be to avoid a denial of service attack when
90127: ** the SQL statement comes from an external source.
90128: **
90129: ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
90130: ** as the previous instance of the same wildcard.  Or if this is the first
90131: ** instance of the wildcard, the next sequential variable number is
90132: ** assigned.
90133: */
90134: SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
90135:   sqlite3 *db = pParse->db;
90136:   const char *z;
90137: 
90138:   if( pExpr==0 ) return;
90139:   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
90140:   z = pExpr->u.zToken;
90141:   assert( z!=0 );
90142:   assert( z[0]!=0 );
90143:   if( z[1]==0 ){
90144:     /* Wildcard of the form "?".  Assign the next variable number */
90145:     assert( z[0]=='?' );
90146:     pExpr->iColumn = (ynVar)(++pParse->nVar);
90147:   }else{
90148:     ynVar x = 0;
90149:     u32 n = sqlite3Strlen30(z);
90150:     if( z[0]=='?' ){
90151:       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
90152:       ** use it as the variable number */
90153:       i64 i;
90154:       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
90155:       pExpr->iColumn = x = (ynVar)i;
90156:       testcase( i==0 );
90157:       testcase( i==1 );
90158:       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
90159:       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
90160:       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90161:         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
90162:             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
90163:         x = 0;
90164:       }
90165:       if( i>pParse->nVar ){
90166:         pParse->nVar = (int)i;
90167:       }
90168:     }else{
90169:       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
90170:       ** number as the prior appearance of the same name, or if the name
90171:       ** has never appeared before, reuse the same variable number
90172:       */
90173:       ynVar i;
90174:       for(i=0; i<pParse->nzVar; i++){
90175:         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
90176:           pExpr->iColumn = x = (ynVar)i+1;
90177:           break;
90178:         }
90179:       }
90180:       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
90181:     }
90182:     if( x>0 ){
90183:       if( x>pParse->nzVar ){
90184:         char **a;
90185:         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
90186:         if( a==0 ){
90187:           assert( db->mallocFailed ); /* Error reported through mallocFailed */
90188:           return;
90189:         }
90190:         pParse->azVar = a;
90191:         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
90192:         pParse->nzVar = x;
90193:       }
90194:       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
90195:         sqlite3DbFree(db, pParse->azVar[x-1]);
90196:         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
90197:       }
90198:     }
90199:   } 
90200:   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
90201:     sqlite3ErrorMsg(pParse, "too many SQL variables");
90202:   }
90203: }
90204: 
90205: /*
90206: ** Recursively delete an expression tree.
90207: */
90208: static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
90209:   assert( p!=0 );
90210:   /* Sanity check: Assert that the IntValue is non-negative if it exists */
90211:   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
90212:   if( !ExprHasProperty(p, EP_TokenOnly) ){
90213:     /* The Expr.x union is never used at the same time as Expr.pRight */
90214:     assert( p->x.pList==0 || p->pRight==0 );
90215:     sqlite3ExprDelete(db, p->pLeft);
90216:     sqlite3ExprDelete(db, p->pRight);
90217:     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
90218:     if( ExprHasProperty(p, EP_xIsSelect) ){
90219:       sqlite3SelectDelete(db, p->x.pSelect);
90220:     }else{
90221:       sqlite3ExprListDelete(db, p->x.pList);
90222:     }
90223:   }
90224:   if( !ExprHasProperty(p, EP_Static) ){
90225:     sqlite3DbFree(db, p);
90226:   }
90227: }
90228: SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
90229:   if( p ) sqlite3ExprDeleteNN(db, p);
90230: }
90231: 
90232: /*
90233: ** Return the number of bytes allocated for the expression structure 
90234: ** passed as the first argument. This is always one of EXPR_FULLSIZE,
90235: ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
90236: */
90237: static int exprStructSize(Expr *p){
90238:   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
90239:   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
90240:   return EXPR_FULLSIZE;
90241: }
90242: 
90243: /*
90244: ** The dupedExpr*Size() routines each return the number of bytes required
90245: ** to store a copy of an expression or expression tree.  They differ in
90246: ** how much of the tree is measured.
90247: **
90248: **     dupedExprStructSize()     Size of only the Expr structure 
90249: **     dupedExprNodeSize()       Size of Expr + space for token
90250: **     dupedExprSize()           Expr + token + subtree components
90251: **
90252: ***************************************************************************
90253: **
90254: ** The dupedExprStructSize() function returns two values OR-ed together:  
90255: ** (1) the space required for a copy of the Expr structure only and 
90256: ** (2) the EP_xxx flags that indicate what the structure size should be.
90257: ** The return values is always one of:
90258: **
90259: **      EXPR_FULLSIZE
90260: **      EXPR_REDUCEDSIZE   | EP_Reduced
90261: **      EXPR_TOKENONLYSIZE | EP_TokenOnly
90262: **
90263: ** The size of the structure can be found by masking the return value
90264: ** of this routine with 0xfff.  The flags can be found by masking the
90265: ** return value with EP_Reduced|EP_TokenOnly.
90266: **
90267: ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
90268: ** (unreduced) Expr objects as they or originally constructed by the parser.
90269: ** During expression analysis, extra information is computed and moved into
90270: ** later parts of teh Expr object and that extra information might get chopped
90271: ** off if the expression is reduced.  Note also that it does not work to
90272: ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
90273: ** to reduce a pristine expression tree from the parser.  The implementation
90274: ** of dupedExprStructSize() contain multiple assert() statements that attempt
90275: ** to enforce this constraint.
90276: */
90277: static int dupedExprStructSize(Expr *p, int flags){
90278:   int nSize;
90279:   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
90280:   assert( EXPR_FULLSIZE<=0xfff );
90281:   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
90282:   if( 0==flags ){
90283:     nSize = EXPR_FULLSIZE;
90284:   }else{
90285:     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
90286:     assert( !ExprHasProperty(p, EP_FromJoin) ); 
90287:     assert( !ExprHasProperty(p, EP_MemToken) );
90288:     assert( !ExprHasProperty(p, EP_NoReduce) );
90289:     if( p->pLeft || p->x.pList ){
90290:       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
90291:     }else{
90292:       assert( p->pRight==0 );
90293:       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
90294:     }
90295:   }
90296:   return nSize;
90297: }
90298: 
90299: /*
90300: ** This function returns the space in bytes required to store the copy 
90301: ** of the Expr structure and a copy of the Expr.u.zToken string (if that
90302: ** string is defined.)
90303: */
90304: static int dupedExprNodeSize(Expr *p, int flags){
90305:   int nByte = dupedExprStructSize(p, flags) & 0xfff;
90306:   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90307:     nByte += sqlite3Strlen30(p->u.zToken)+1;
90308:   }
90309:   return ROUND8(nByte);
90310: }
90311: 
90312: /*
90313: ** Return the number of bytes required to create a duplicate of the 
90314: ** expression passed as the first argument. The second argument is a
90315: ** mask containing EXPRDUP_XXX flags.
90316: **
90317: ** The value returned includes space to create a copy of the Expr struct
90318: ** itself and the buffer referred to by Expr.u.zToken, if any.
90319: **
90320: ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
90321: ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
90322: ** and Expr.pRight variables (but not for any structures pointed to or 
90323: ** descended from the Expr.x.pList or Expr.x.pSelect variables).
90324: */
90325: static int dupedExprSize(Expr *p, int flags){
90326:   int nByte = 0;
90327:   if( p ){
90328:     nByte = dupedExprNodeSize(p, flags);
90329:     if( flags&EXPRDUP_REDUCE ){
90330:       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
90331:     }
90332:   }
90333:   return nByte;
90334: }
90335: 
90336: /*
90337: ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
90338: ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
90339: ** to store the copy of expression p, the copies of p->u.zToken
90340: ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
90341: ** if any. Before returning, *pzBuffer is set to the first byte past the
90342: ** portion of the buffer copied into by this function.
90343: */
90344: static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
90345:   Expr *pNew;           /* Value to return */
90346:   u8 *zAlloc;           /* Memory space from which to build Expr object */
90347:   u32 staticFlag;       /* EP_Static if space not obtained from malloc */
90348: 
90349:   assert( db!=0 );
90350:   assert( p );
90351:   assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
90352:   assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
90353: 
90354:   /* Figure out where to write the new Expr structure. */
90355:   if( pzBuffer ){
90356:     zAlloc = *pzBuffer;
90357:     staticFlag = EP_Static;
90358:   }else{
90359:     zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
90360:     staticFlag = 0;
90361:   }
90362:   pNew = (Expr *)zAlloc;
90363: 
90364:   if( pNew ){
90365:     /* Set nNewSize to the size allocated for the structure pointed to
90366:     ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
90367:     ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
90368:     ** by the copy of the p->u.zToken string (if any).
90369:     */
90370:     const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
90371:     const int nNewSize = nStructSize & 0xfff;
90372:     int nToken;
90373:     if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
90374:       nToken = sqlite3Strlen30(p->u.zToken) + 1;
90375:     }else{
90376:       nToken = 0;
90377:     }
90378:     if( dupFlags ){
90379:       assert( ExprHasProperty(p, EP_Reduced)==0 );
90380:       memcpy(zAlloc, p, nNewSize);
90381:     }else{
90382:       u32 nSize = (u32)exprStructSize(p);
90383:       memcpy(zAlloc, p, nSize);
90384:       if( nSize<EXPR_FULLSIZE ){ 
90385:         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
90386:       }
90387:     }
90388: 
90389:     /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
90390:     pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
90391:     pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
90392:     pNew->flags |= staticFlag;
90393: 
90394:     /* Copy the p->u.zToken string, if any. */
90395:     if( nToken ){
90396:       char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
90397:       memcpy(zToken, p->u.zToken, nToken);
90398:     }
90399: 
90400:     if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
90401:       /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
90402:       if( ExprHasProperty(p, EP_xIsSelect) ){
90403:         pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
90404:       }else{
90405:         pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
90406:       }
90407:     }
90408: 
90409:     /* Fill in pNew->pLeft and pNew->pRight. */
90410:     if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
90411:       zAlloc += dupedExprNodeSize(p, dupFlags);
90412:       if( ExprHasProperty(pNew, EP_Reduced) ){
90413:         pNew->pLeft = p->pLeft ?
90414:                       exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
90415:         pNew->pRight = p->pRight ?
90416:                        exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
90417:       }
90418:       if( pzBuffer ){
90419:         *pzBuffer = zAlloc;
90420:       }
90421:     }else{
90422:       if( !ExprHasProperty(p, EP_TokenOnly) ){
90423:         pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
90424:         pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
90425:       }
90426:     }
90427:   }
90428:   return pNew;
90429: }
90430: 
90431: /*
90432: ** Create and return a deep copy of the object passed as the second 
90433: ** argument. If an OOM condition is encountered, NULL is returned
90434: ** and the db->mallocFailed flag set.
90435: */
90436: #ifndef SQLITE_OMIT_CTE
90437: static With *withDup(sqlite3 *db, With *p){
90438:   With *pRet = 0;
90439:   if( p ){
90440:     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
90441:     pRet = sqlite3DbMallocZero(db, nByte);
90442:     if( pRet ){
90443:       int i;
90444:       pRet->nCte = p->nCte;
90445:       for(i=0; i<p->nCte; i++){
90446:         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
90447:         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
90448:         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
90449:       }
90450:     }
90451:   }
90452:   return pRet;
90453: }
90454: #else
90455: # define withDup(x,y) 0
90456: #endif
90457: 
90458: /*
90459: ** The following group of routines make deep copies of expressions,
90460: ** expression lists, ID lists, and select statements.  The copies can
90461: ** be deleted (by being passed to their respective ...Delete() routines)
90462: ** without effecting the originals.
90463: **
90464: ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
90465: ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
90466: ** by subsequent calls to sqlite*ListAppend() routines.
90467: **
90468: ** Any tables that the SrcList might point to are not duplicated.
90469: **
90470: ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
90471: ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
90472: ** truncated version of the usual Expr structure that will be stored as
90473: ** part of the in-memory representation of the database schema.
90474: */
90475: SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
90476:   assert( flags==0 || flags==EXPRDUP_REDUCE );
90477:   return p ? exprDup(db, p, flags, 0) : 0;
90478: }
90479: SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
90480:   ExprList *pNew;
90481:   struct ExprList_item *pItem, *pOldItem;
90482:   int i;
90483:   assert( db!=0 );
90484:   if( p==0 ) return 0;
90485:   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
90486:   if( pNew==0 ) return 0;
90487:   pNew->nExpr = i = p->nExpr;
90488:   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
90489:   pNew->a = pItem = sqlite3DbMallocRawNN(db,  i*sizeof(p->a[0]) );
90490:   if( pItem==0 ){
90491:     sqlite3DbFree(db, pNew);
90492:     return 0;
90493:   } 
90494:   pOldItem = p->a;
90495:   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
90496:     Expr *pOldExpr = pOldItem->pExpr;
90497:     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
90498:     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90499:     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
90500:     pItem->sortOrder = pOldItem->sortOrder;
90501:     pItem->done = 0;
90502:     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
90503:     pItem->u = pOldItem->u;
90504:   }
90505:   return pNew;
90506: }
90507: 
90508: /*
90509: ** If cursors, triggers, views and subqueries are all omitted from
90510: ** the build, then none of the following routines, except for 
90511: ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
90512: ** called with a NULL argument.
90513: */
90514: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
90515:  || !defined(SQLITE_OMIT_SUBQUERY)
90516: SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
90517:   SrcList *pNew;
90518:   int i;
90519:   int nByte;
90520:   assert( db!=0 );
90521:   if( p==0 ) return 0;
90522:   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
90523:   pNew = sqlite3DbMallocRawNN(db, nByte );
90524:   if( pNew==0 ) return 0;
90525:   pNew->nSrc = pNew->nAlloc = p->nSrc;
90526:   for(i=0; i<p->nSrc; i++){
90527:     struct SrcList_item *pNewItem = &pNew->a[i];
90528:     struct SrcList_item *pOldItem = &p->a[i];
90529:     Table *pTab;
90530:     pNewItem->pSchema = pOldItem->pSchema;
90531:     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
90532:     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90533:     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
90534:     pNewItem->fg = pOldItem->fg;
90535:     pNewItem->iCursor = pOldItem->iCursor;
90536:     pNewItem->addrFillSub = pOldItem->addrFillSub;
90537:     pNewItem->regReturn = pOldItem->regReturn;
90538:     if( pNewItem->fg.isIndexedBy ){
90539:       pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
90540:     }
90541:     pNewItem->pIBIndex = pOldItem->pIBIndex;
90542:     if( pNewItem->fg.isTabFunc ){
90543:       pNewItem->u1.pFuncArg = 
90544:           sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
90545:     }
90546:     pTab = pNewItem->pTab = pOldItem->pTab;
90547:     if( pTab ){
90548:       pTab->nRef++;
90549:     }
90550:     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
90551:     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
90552:     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
90553:     pNewItem->colUsed = pOldItem->colUsed;
90554:   }
90555:   return pNew;
90556: }
90557: SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
90558:   IdList *pNew;
90559:   int i;
90560:   assert( db!=0 );
90561:   if( p==0 ) return 0;
90562:   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
90563:   if( pNew==0 ) return 0;
90564:   pNew->nId = p->nId;
90565:   pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
90566:   if( pNew->a==0 ){
90567:     sqlite3DbFree(db, pNew);
90568:     return 0;
90569:   }
90570:   /* Note that because the size of the allocation for p->a[] is not
90571:   ** necessarily a power of two, sqlite3IdListAppend() may not be called
90572:   ** on the duplicate created by this function. */
90573:   for(i=0; i<p->nId; i++){
90574:     struct IdList_item *pNewItem = &pNew->a[i];
90575:     struct IdList_item *pOldItem = &p->a[i];
90576:     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90577:     pNewItem->idx = pOldItem->idx;
90578:   }
90579:   return pNew;
90580: }
90581: SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
90582:   Select *pNew, *pPrior;
90583:   assert( db!=0 );
90584:   if( p==0 ) return 0;
90585:   pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
90586:   if( pNew==0 ) return 0;
90587:   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
90588:   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
90589:   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
90590:   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
90591:   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
90592:   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
90593:   pNew->op = p->op;
90594:   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
90595:   if( pPrior ) pPrior->pNext = pNew;
90596:   pNew->pNext = 0;
90597:   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
90598:   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
90599:   pNew->iLimit = 0;
90600:   pNew->iOffset = 0;
90601:   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
90602:   pNew->addrOpenEphm[0] = -1;
90603:   pNew->addrOpenEphm[1] = -1;
90604:   pNew->nSelectRow = p->nSelectRow;
90605:   pNew->pWith = withDup(db, p->pWith);
90606:   sqlite3SelectSetName(pNew, p->zSelName);
90607:   return pNew;
90608: }
90609: #else
90610: SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
90611:   assert( p==0 );
90612:   return 0;
90613: }
90614: #endif
90615: 
90616: 
90617: /*
90618: ** Add a new element to the end of an expression list.  If pList is
90619: ** initially NULL, then create a new expression list.
90620: **
90621: ** If a memory allocation error occurs, the entire list is freed and
90622: ** NULL is returned.  If non-NULL is returned, then it is guaranteed
90623: ** that the new entry was successfully appended.
90624: */
90625: SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
90626:   Parse *pParse,          /* Parsing context */
90627:   ExprList *pList,        /* List to which to append. Might be NULL */
90628:   Expr *pExpr             /* Expression to be appended. Might be NULL */
90629: ){
90630:   sqlite3 *db = pParse->db;
90631:   assert( db!=0 );
90632:   if( pList==0 ){
90633:     pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
90634:     if( pList==0 ){
90635:       goto no_mem;
90636:     }
90637:     pList->nExpr = 0;
90638:     pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
90639:     if( pList->a==0 ) goto no_mem;
90640:   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
90641:     struct ExprList_item *a;
90642:     assert( pList->nExpr>0 );
90643:     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
90644:     if( a==0 ){
90645:       goto no_mem;
90646:     }
90647:     pList->a = a;
90648:   }
90649:   assert( pList->a!=0 );
90650:   if( 1 ){
90651:     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
90652:     memset(pItem, 0, sizeof(*pItem));
90653:     pItem->pExpr = pExpr;
90654:   }
90655:   return pList;
90656: 
90657: no_mem:     
90658:   /* Avoid leaking memory if malloc has failed. */
90659:   sqlite3ExprDelete(db, pExpr);
90660:   sqlite3ExprListDelete(db, pList);
90661:   return 0;
90662: }
90663: 
90664: /*
90665: ** Set the sort order for the last element on the given ExprList.
90666: */
90667: SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
90668:   if( p==0 ) return;
90669:   assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
90670:   assert( p->nExpr>0 );
90671:   if( iSortOrder<0 ){
90672:     assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
90673:     return;
90674:   }
90675:   p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
90676: }
90677: 
90678: /*
90679: ** Set the ExprList.a[].zName element of the most recently added item
90680: ** on the expression list.
90681: **
90682: ** pList might be NULL following an OOM error.  But pName should never be
90683: ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
90684: ** is set.
90685: */
90686: SQLITE_PRIVATE void sqlite3ExprListSetName(
90687:   Parse *pParse,          /* Parsing context */
90688:   ExprList *pList,        /* List to which to add the span. */
90689:   Token *pName,           /* Name to be added */
90690:   int dequote             /* True to cause the name to be dequoted */
90691: ){
90692:   assert( pList!=0 || pParse->db->mallocFailed!=0 );
90693:   if( pList ){
90694:     struct ExprList_item *pItem;
90695:     assert( pList->nExpr>0 );
90696:     pItem = &pList->a[pList->nExpr-1];
90697:     assert( pItem->zName==0 );
90698:     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
90699:     if( dequote ) sqlite3Dequote(pItem->zName);
90700:   }
90701: }
90702: 
90703: /*
90704: ** Set the ExprList.a[].zSpan element of the most recently added item
90705: ** on the expression list.
90706: **
90707: ** pList might be NULL following an OOM error.  But pSpan should never be
90708: ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
90709: ** is set.
90710: */
90711: SQLITE_PRIVATE void sqlite3ExprListSetSpan(
90712:   Parse *pParse,          /* Parsing context */
90713:   ExprList *pList,        /* List to which to add the span. */
90714:   ExprSpan *pSpan         /* The span to be added */
90715: ){
90716:   sqlite3 *db = pParse->db;
90717:   assert( pList!=0 || db->mallocFailed!=0 );
90718:   if( pList ){
90719:     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
90720:     assert( pList->nExpr>0 );
90721:     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
90722:     sqlite3DbFree(db, pItem->zSpan);
90723:     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
90724:                                     (int)(pSpan->zEnd - pSpan->zStart));
90725:   }
90726: }
90727: 
90728: /*
90729: ** If the expression list pEList contains more than iLimit elements,
90730: ** leave an error message in pParse.
90731: */
90732: SQLITE_PRIVATE void sqlite3ExprListCheckLength(
90733:   Parse *pParse,
90734:   ExprList *pEList,
90735:   const char *zObject
90736: ){
90737:   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
90738:   testcase( pEList && pEList->nExpr==mx );
90739:   testcase( pEList && pEList->nExpr==mx+1 );
90740:   if( pEList && pEList->nExpr>mx ){
90741:     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
90742:   }
90743: }
90744: 
90745: /*
90746: ** Delete an entire expression list.
90747: */
90748: static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
90749:   int i;
90750:   struct ExprList_item *pItem;
90751:   assert( pList->a!=0 || pList->nExpr==0 );
90752:   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
90753:     sqlite3ExprDelete(db, pItem->pExpr);
90754:     sqlite3DbFree(db, pItem->zName);
90755:     sqlite3DbFree(db, pItem->zSpan);
90756:   }
90757:   sqlite3DbFree(db, pList->a);
90758:   sqlite3DbFree(db, pList);
90759: }
90760: SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
90761:   if( pList ) exprListDeleteNN(db, pList);
90762: }
90763: 
90764: /*
90765: ** Return the bitwise-OR of all Expr.flags fields in the given
90766: ** ExprList.
90767: */
90768: SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
90769:   int i;
90770:   u32 m = 0;
90771:   if( pList ){
90772:     for(i=0; i<pList->nExpr; i++){
90773:        Expr *pExpr = pList->a[i].pExpr;
90774:        assert( pExpr!=0 );
90775:        m |= pExpr->flags;
90776:     }
90777:   }
90778:   return m;
90779: }
90780: 
90781: /*
90782: ** These routines are Walker callbacks used to check expressions to
90783: ** see if they are "constant" for some definition of constant.  The
90784: ** Walker.eCode value determines the type of "constant" we are looking
90785: ** for.
90786: **
90787: ** These callback routines are used to implement the following:
90788: **
90789: **     sqlite3ExprIsConstant()                  pWalker->eCode==1
90790: **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
90791: **     sqlite3ExprIsTableConstant()             pWalker->eCode==3
90792: **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
90793: **
90794: ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
90795: ** is found to not be a constant.
90796: **
90797: ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
90798: ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
90799: ** an existing schema and 4 when processing a new statement.  A bound
90800: ** parameter raises an error for new statements, but is silently converted
90801: ** to NULL for existing schemas.  This allows sqlite_master tables that 
90802: ** contain a bound parameter because they were generated by older versions
90803: ** of SQLite to be parsed by newer versions of SQLite without raising a
90804: ** malformed schema error.
90805: */
90806: static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
90807: 
90808:   /* If pWalker->eCode is 2 then any term of the expression that comes from
90809:   ** the ON or USING clauses of a left join disqualifies the expression
90810:   ** from being considered constant. */
90811:   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
90812:     pWalker->eCode = 0;
90813:     return WRC_Abort;
90814:   }
90815: 
90816:   switch( pExpr->op ){
90817:     /* Consider functions to be constant if all their arguments are constant
90818:     ** and either pWalker->eCode==4 or 5 or the function has the
90819:     ** SQLITE_FUNC_CONST flag. */
90820:     case TK_FUNCTION:
90821:       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
90822:         return WRC_Continue;
90823:       }else{
90824:         pWalker->eCode = 0;
90825:         return WRC_Abort;
90826:       }
90827:     case TK_ID:
90828:     case TK_COLUMN:
90829:     case TK_AGG_FUNCTION:
90830:     case TK_AGG_COLUMN:
90831:       testcase( pExpr->op==TK_ID );
90832:       testcase( pExpr->op==TK_COLUMN );
90833:       testcase( pExpr->op==TK_AGG_FUNCTION );
90834:       testcase( pExpr->op==TK_AGG_COLUMN );
90835:       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
90836:         return WRC_Continue;
90837:       }else{
90838:         pWalker->eCode = 0;
90839:         return WRC_Abort;
90840:       }
90841:     case TK_VARIABLE:
90842:       if( pWalker->eCode==5 ){
90843:         /* Silently convert bound parameters that appear inside of CREATE
90844:         ** statements into a NULL when parsing the CREATE statement text out
90845:         ** of the sqlite_master table */
90846:         pExpr->op = TK_NULL;
90847:       }else if( pWalker->eCode==4 ){
90848:         /* A bound parameter in a CREATE statement that originates from
90849:         ** sqlite3_prepare() causes an error */
90850:         pWalker->eCode = 0;
90851:         return WRC_Abort;
90852:       }
90853:       /* Fall through */
90854:     default:
90855:       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
90856:       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
90857:       return WRC_Continue;
90858:   }
90859: }
90860: static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
90861:   UNUSED_PARAMETER(NotUsed);
90862:   pWalker->eCode = 0;
90863:   return WRC_Abort;
90864: }
90865: static int exprIsConst(Expr *p, int initFlag, int iCur){
90866:   Walker w;
90867:   memset(&w, 0, sizeof(w));
90868:   w.eCode = initFlag;
90869:   w.xExprCallback = exprNodeIsConstant;
90870:   w.xSelectCallback = selectNodeIsConstant;
90871:   w.u.iCur = iCur;
90872:   sqlite3WalkExpr(&w, p);
90873:   return w.eCode;
90874: }
90875: 
90876: /*
90877: ** Walk an expression tree.  Return non-zero if the expression is constant
90878: ** and 0 if it involves variables or function calls.
90879: **
90880: ** For the purposes of this function, a double-quoted string (ex: "abc")
90881: ** is considered a variable but a single-quoted string (ex: 'abc') is
90882: ** a constant.
90883: */
90884: SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
90885:   return exprIsConst(p, 1, 0);
90886: }
90887: 
90888: /*
90889: ** Walk an expression tree.  Return non-zero if the expression is constant
90890: ** that does no originate from the ON or USING clauses of a join.
90891: ** Return 0 if it involves variables or function calls or terms from
90892: ** an ON or USING clause.
90893: */
90894: SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
90895:   return exprIsConst(p, 2, 0);
90896: }
90897: 
90898: /*
90899: ** Walk an expression tree.  Return non-zero if the expression is constant
90900: ** for any single row of the table with cursor iCur.  In other words, the
90901: ** expression must not refer to any non-deterministic function nor any
90902: ** table other than iCur.
90903: */
90904: SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
90905:   return exprIsConst(p, 3, iCur);
90906: }
90907: 
90908: /*
90909: ** Walk an expression tree.  Return non-zero if the expression is constant
90910: ** or a function call with constant arguments.  Return and 0 if there
90911: ** are any variables.
90912: **
90913: ** For the purposes of this function, a double-quoted string (ex: "abc")
90914: ** is considered a variable but a single-quoted string (ex: 'abc') is
90915: ** a constant.
90916: */
90917: SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
90918:   assert( isInit==0 || isInit==1 );
90919:   return exprIsConst(p, 4+isInit, 0);
90920: }
90921: 
90922: #ifdef SQLITE_ENABLE_CURSOR_HINTS
90923: /*
90924: ** Walk an expression tree.  Return 1 if the expression contains a
90925: ** subquery of some kind.  Return 0 if there are no subqueries.
90926: */
90927: SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
90928:   Walker w;
90929:   memset(&w, 0, sizeof(w));
90930:   w.eCode = 1;
90931:   w.xExprCallback = sqlite3ExprWalkNoop;
90932:   w.xSelectCallback = selectNodeIsConstant;
90933:   sqlite3WalkExpr(&w, p);
90934:   return w.eCode==0;
90935: }
90936: #endif
90937: 
90938: /*
90939: ** If the expression p codes a constant integer that is small enough
90940: ** to fit in a 32-bit integer, return 1 and put the value of the integer
90941: ** in *pValue.  If the expression is not an integer or if it is too big
90942: ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
90943: */
90944: SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
90945:   int rc = 0;
90946: 
90947:   /* If an expression is an integer literal that fits in a signed 32-bit
90948:   ** integer, then the EP_IntValue flag will have already been set */
90949:   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
90950:            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
90951: 
90952:   if( p->flags & EP_IntValue ){
90953:     *pValue = p->u.iValue;
90954:     return 1;
90955:   }
90956:   switch( p->op ){
90957:     case TK_UPLUS: {
90958:       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
90959:       break;
90960:     }
90961:     case TK_UMINUS: {
90962:       int v;
90963:       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
90964:         assert( v!=(-2147483647-1) );
90965:         *pValue = -v;
90966:         rc = 1;
90967:       }
90968:       break;
90969:     }
90970:     default: break;
90971:   }
90972:   return rc;
90973: }
90974: 
90975: /*
90976: ** Return FALSE if there is no chance that the expression can be NULL.
90977: **
90978: ** If the expression might be NULL or if the expression is too complex
90979: ** to tell return TRUE.  
90980: **
90981: ** This routine is used as an optimization, to skip OP_IsNull opcodes
90982: ** when we know that a value cannot be NULL.  Hence, a false positive
90983: ** (returning TRUE when in fact the expression can never be NULL) might
90984: ** be a small performance hit but is otherwise harmless.  On the other
90985: ** hand, a false negative (returning FALSE when the result could be NULL)
90986: ** will likely result in an incorrect answer.  So when in doubt, return
90987: ** TRUE.
90988: */
90989: SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
90990:   u8 op;
90991:   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
90992:   op = p->op;
90993:   if( op==TK_REGISTER ) op = p->op2;
90994:   switch( op ){
90995:     case TK_INTEGER:
90996:     case TK_STRING:
90997:     case TK_FLOAT:
90998:     case TK_BLOB:
90999:       return 0;
91000:     case TK_COLUMN:
91001:       assert( p->pTab!=0 );
91002:       return ExprHasProperty(p, EP_CanBeNull) ||
91003:              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
91004:     default:
91005:       return 1;
91006:   }
91007: }
91008: 
91009: /*
91010: ** Return TRUE if the given expression is a constant which would be
91011: ** unchanged by OP_Affinity with the affinity given in the second
91012: ** argument.
91013: **
91014: ** This routine is used to determine if the OP_Affinity operation
91015: ** can be omitted.  When in doubt return FALSE.  A false negative
91016: ** is harmless.  A false positive, however, can result in the wrong
91017: ** answer.
91018: */
91019: SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
91020:   u8 op;
91021:   if( aff==SQLITE_AFF_BLOB ) return 1;
91022:   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
91023:   op = p->op;
91024:   if( op==TK_REGISTER ) op = p->op2;
91025:   switch( op ){
91026:     case TK_INTEGER: {
91027:       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
91028:     }
91029:     case TK_FLOAT: {
91030:       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
91031:     }
91032:     case TK_STRING: {
91033:       return aff==SQLITE_AFF_TEXT;
91034:     }
91035:     case TK_BLOB: {
91036:       return 1;
91037:     }
91038:     case TK_COLUMN: {
91039:       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
91040:       return p->iColumn<0
91041:           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
91042:     }
91043:     default: {
91044:       return 0;
91045:     }
91046:   }
91047: }
91048: 
91049: /*
91050: ** Return TRUE if the given string is a row-id column name.
91051: */
91052: SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
91053:   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
91054:   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
91055:   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
91056:   return 0;
91057: }
91058: 
91059: /*
91060: ** pX is the RHS of an IN operator.  If pX is a SELECT statement 
91061: ** that can be simplified to a direct table access, then return
91062: ** a pointer to the SELECT statement.  If pX is not a SELECT statement,
91063: ** or if the SELECT statement needs to be manifested into a transient
91064: ** table, then return NULL.
91065: */
91066: #ifndef SQLITE_OMIT_SUBQUERY
91067: static Select *isCandidateForInOpt(Expr *pX){
91068:   Select *p;
91069:   SrcList *pSrc;
91070:   ExprList *pEList;
91071:   Expr *pRes;
91072:   Table *pTab;
91073:   if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0;  /* Not a subquery */
91074:   if( ExprHasProperty(pX, EP_VarSelect)  ) return 0;  /* Correlated subq */
91075:   p = pX->x.pSelect;
91076:   if( p->pPrior ) return 0;              /* Not a compound SELECT */
91077:   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
91078:     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
91079:     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
91080:     return 0; /* No DISTINCT keyword and no aggregate functions */
91081:   }
91082:   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
91083:   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
91084:   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
91085:   if( p->pWhere ) return 0;              /* Has no WHERE clause */
91086:   pSrc = p->pSrc;
91087:   assert( pSrc!=0 );
91088:   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
91089:   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
91090:   pTab = pSrc->a[0].pTab;
91091:   assert( pTab!=0 );
91092:   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
91093:   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
91094:   pEList = p->pEList;
91095:   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
91096:   pRes = pEList->a[0].pExpr;
91097:   if( pRes->op!=TK_COLUMN ) return 0;    /* Result is a column */
91098:   assert( pRes->iTable==pSrc->a[0].iCursor );  /* Not a correlated subquery */
91099:   return p;
91100: }
91101: #endif /* SQLITE_OMIT_SUBQUERY */
91102: 
91103: /*
91104: ** Code an OP_Once instruction and allocate space for its flag. Return the 
91105: ** address of the new instruction.
91106: */
91107: SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
91108:   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
91109:   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
91110: }
91111: 
91112: /*
91113: ** Generate code that checks the left-most column of index table iCur to see if
91114: ** it contains any NULL entries.  Cause the register at regHasNull to be set
91115: ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
91116: ** to be set to NULL if iCur contains one or more NULL values.
91117: */
91118: static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
91119:   int addr1;
91120:   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
91121:   addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
91122:   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
91123:   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
91124:   VdbeComment((v, "first_entry_in(%d)", iCur));
91125:   sqlite3VdbeJumpHere(v, addr1);
91126: }
91127: 
91128: 
91129: #ifndef SQLITE_OMIT_SUBQUERY
91130: /*
91131: ** The argument is an IN operator with a list (not a subquery) on the 
91132: ** right-hand side.  Return TRUE if that list is constant.
91133: */
91134: static int sqlite3InRhsIsConstant(Expr *pIn){
91135:   Expr *pLHS;
91136:   int res;
91137:   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
91138:   pLHS = pIn->pLeft;
91139:   pIn->pLeft = 0;
91140:   res = sqlite3ExprIsConstant(pIn);
91141:   pIn->pLeft = pLHS;
91142:   return res;
91143: }
91144: #endif
91145: 
91146: /*
91147: ** This function is used by the implementation of the IN (...) operator.
91148: ** The pX parameter is the expression on the RHS of the IN operator, which
91149: ** might be either a list of expressions or a subquery.
91150: **
91151: ** The job of this routine is to find or create a b-tree object that can
91152: ** be used either to test for membership in the RHS set or to iterate through
91153: ** all members of the RHS set, skipping duplicates.
91154: **
91155: ** A cursor is opened on the b-tree object that is the RHS of the IN operator
91156: ** and pX->iTable is set to the index of that cursor.
91157: **
91158: ** The returned value of this function indicates the b-tree type, as follows:
91159: **
91160: **   IN_INDEX_ROWID      - The cursor was opened on a database table.
91161: **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
91162: **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
91163: **   IN_INDEX_EPH        - The cursor was opened on a specially created and
91164: **                         populated epheremal table.
91165: **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
91166: **                         implemented as a sequence of comparisons.
91167: **
91168: ** An existing b-tree might be used if the RHS expression pX is a simple
91169: ** subquery such as:
91170: **
91171: **     SELECT <column> FROM <table>
91172: **
91173: ** If the RHS of the IN operator is a list or a more complex subquery, then
91174: ** an ephemeral table might need to be generated from the RHS and then
91175: ** pX->iTable made to point to the ephemeral table instead of an
91176: ** existing table.
91177: **
91178: ** The inFlags parameter must contain exactly one of the bits
91179: ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
91180: ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
91181: ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
91182: ** IN index will be used to loop over all values of the RHS of the
91183: ** IN operator.
91184: **
91185: ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
91186: ** through the set members) then the b-tree must not contain duplicates.
91187: ** An epheremal table must be used unless the selected <column> is guaranteed
91188: ** to be unique - either because it is an INTEGER PRIMARY KEY or it
91189: ** has a UNIQUE constraint or UNIQUE index.
91190: **
91191: ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 
91192: ** for fast set membership tests) then an epheremal table must 
91193: ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
91194: ** be found with <column> as its left-most column.
91195: **
91196: ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
91197: ** if the RHS of the IN operator is a list (not a subquery) then this
91198: ** routine might decide that creating an ephemeral b-tree for membership
91199: ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
91200: ** calling routine should implement the IN operator using a sequence
91201: ** of Eq or Ne comparison operations.
91202: **
91203: ** When the b-tree is being used for membership tests, the calling function
91204: ** might need to know whether or not the RHS side of the IN operator
91205: ** contains a NULL.  If prRhsHasNull is not a NULL pointer and 
91206: ** if there is any chance that the (...) might contain a NULL value at
91207: ** runtime, then a register is allocated and the register number written
91208: ** to *prRhsHasNull. If there is no chance that the (...) contains a
91209: ** NULL value, then *prRhsHasNull is left unchanged.
91210: **
91211: ** If a register is allocated and its location stored in *prRhsHasNull, then
91212: ** the value in that register will be NULL if the b-tree contains one or more
91213: ** NULL values, and it will be some non-NULL value if the b-tree contains no
91214: ** NULL values.
91215: */
91216: #ifndef SQLITE_OMIT_SUBQUERY
91217: SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
91218:   Select *p;                            /* SELECT to the right of IN operator */
91219:   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
91220:   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
91221:   int mustBeUnique;                     /* True if RHS must be unique */
91222:   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
91223: 
91224:   assert( pX->op==TK_IN );
91225:   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
91226: 
91227:   /* Check to see if an existing table or index can be used to
91228:   ** satisfy the query.  This is preferable to generating a new 
91229:   ** ephemeral table.
91230:   */
91231:   if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
91232:     sqlite3 *db = pParse->db;              /* Database connection */
91233:     Table *pTab;                           /* Table <table>. */
91234:     Expr *pExpr;                           /* Expression <column> */
91235:     i16 iCol;                              /* Index of column <column> */
91236:     i16 iDb;                               /* Database idx for pTab */
91237: 
91238:     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
91239:     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
91240:     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
91241:     pTab = p->pSrc->a[0].pTab;
91242:     pExpr = p->pEList->a[0].pExpr;
91243:     iCol = (i16)pExpr->iColumn;
91244:    
91245:     /* Code an OP_Transaction and OP_TableLock for <table>. */
91246:     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91247:     sqlite3CodeVerifySchema(pParse, iDb);
91248:     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91249: 
91250:     /* This function is only called from two places. In both cases the vdbe
91251:     ** has already been allocated. So assume sqlite3GetVdbe() is always
91252:     ** successful here.
91253:     */
91254:     assert(v);
91255:     if( iCol<0 ){
91256:       int iAddr = sqlite3CodeOnce(pParse);
91257:       VdbeCoverage(v);
91258: 
91259:       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
91260:       eType = IN_INDEX_ROWID;
91261: 
91262:       sqlite3VdbeJumpHere(v, iAddr);
91263:     }else{
91264:       Index *pIdx;                         /* Iterator variable */
91265: 
91266:       /* The collation sequence used by the comparison. If an index is to
91267:       ** be used in place of a temp-table, it must be ordered according
91268:       ** to this collation sequence.  */
91269:       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
91270: 
91271:       /* Check that the affinity that will be used to perform the 
91272:       ** comparison is the same as the affinity of the column. If
91273:       ** it is not, it is not possible to use any index.
91274:       */
91275:       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
91276: 
91277:       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
91278:         if( (pIdx->aiColumn[0]==iCol)
91279:          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
91280:          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
91281:         ){
91282:           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
91283:           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
91284:           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91285:           VdbeComment((v, "%s", pIdx->zName));
91286:           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
91287:           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
91288: 
91289:           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
91290: #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
91291:             const i64 sOne = 1;
91292:             sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 
91293:                 iTab, 0, 0, (u8*)&sOne, P4_INT64);
91294: #endif
91295:             *prRhsHasNull = ++pParse->nMem;
91296:             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
91297:           }
91298:           sqlite3VdbeJumpHere(v, iAddr);
91299:         }
91300:       }
91301:     }
91302:   }
91303: 
91304:   /* If no preexisting index is available for the IN clause
91305:   ** and IN_INDEX_NOOP is an allowed reply
91306:   ** and the RHS of the IN operator is a list, not a subquery
91307:   ** and the RHS is not constant or has two or fewer terms,
91308:   ** then it is not worth creating an ephemeral table to evaluate
91309:   ** the IN operator so return IN_INDEX_NOOP.
91310:   */
91311:   if( eType==0
91312:    && (inFlags & IN_INDEX_NOOP_OK)
91313:    && !ExprHasProperty(pX, EP_xIsSelect)
91314:    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
91315:   ){
91316:     eType = IN_INDEX_NOOP;
91317:   }
91318:      
91319: 
91320:   if( eType==0 ){
91321:     /* Could not find an existing table or index to use as the RHS b-tree.
91322:     ** We will have to generate an ephemeral table to do the job.
91323:     */
91324:     u32 savedNQueryLoop = pParse->nQueryLoop;
91325:     int rMayHaveNull = 0;
91326:     eType = IN_INDEX_EPH;
91327:     if( inFlags & IN_INDEX_LOOP ){
91328:       pParse->nQueryLoop = 0;
91329:       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
91330:         eType = IN_INDEX_ROWID;
91331:       }
91332:     }else if( prRhsHasNull ){
91333:       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
91334:     }
91335:     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
91336:     pParse->nQueryLoop = savedNQueryLoop;
91337:   }else{
91338:     pX->iTable = iTab;
91339:   }
91340:   return eType;
91341: }
91342: #endif
91343: 
91344: /*
91345: ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
91346: ** or IN operators.  Examples:
91347: **
91348: **     (SELECT a FROM b)          -- subquery
91349: **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
91350: **     x IN (4,5,11)              -- IN operator with list on right-hand side
91351: **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
91352: **
91353: ** The pExpr parameter describes the expression that contains the IN
91354: ** operator or subquery.
91355: **
91356: ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
91357: ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
91358: ** to some integer key column of a table B-Tree. In this case, use an
91359: ** intkey B-Tree to store the set of IN(...) values instead of the usual
91360: ** (slower) variable length keys B-Tree.
91361: **
91362: ** If rMayHaveNull is non-zero, that means that the operation is an IN
91363: ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
91364: ** All this routine does is initialize the register given by rMayHaveNull
91365: ** to NULL.  Calling routines will take care of changing this register
91366: ** value to non-NULL if the RHS is NULL-free.
91367: **
91368: ** For a SELECT or EXISTS operator, return the register that holds the
91369: ** result.  For IN operators or if an error occurs, the return value is 0.
91370: */
91371: #ifndef SQLITE_OMIT_SUBQUERY
91372: SQLITE_PRIVATE int sqlite3CodeSubselect(
91373:   Parse *pParse,          /* Parsing context */
91374:   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
91375:   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
91376:   int isRowid             /* If true, LHS of IN operator is a rowid */
91377: ){
91378:   int jmpIfDynamic = -1;                      /* One-time test address */
91379:   int rReg = 0;                           /* Register storing resulting */
91380:   Vdbe *v = sqlite3GetVdbe(pParse);
91381:   if( NEVER(v==0) ) return 0;
91382:   sqlite3ExprCachePush(pParse);
91383: 
91384:   /* This code must be run in its entirety every time it is encountered
91385:   ** if any of the following is true:
91386:   **
91387:   **    *  The right-hand side is a correlated subquery
91388:   **    *  The right-hand side is an expression list containing variables
91389:   **    *  We are inside a trigger
91390:   **
91391:   ** If all of the above are false, then we can run this code just once
91392:   ** save the results, and reuse the same result on subsequent invocations.
91393:   */
91394:   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
91395:     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
91396:   }
91397: 
91398: #ifndef SQLITE_OMIT_EXPLAIN
91399:   if( pParse->explain==2 ){
91400:     char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
91401:         jmpIfDynamic>=0?"":"CORRELATED ",
91402:         pExpr->op==TK_IN?"LIST":"SCALAR",
91403:         pParse->iNextSelectId
91404:     );
91405:     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
91406:   }
91407: #endif
91408: 
91409:   switch( pExpr->op ){
91410:     case TK_IN: {
91411:       char affinity;              /* Affinity of the LHS of the IN */
91412:       int addr;                   /* Address of OP_OpenEphemeral instruction */
91413:       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
91414:       KeyInfo *pKeyInfo = 0;      /* Key information */
91415: 
91416:       affinity = sqlite3ExprAffinity(pLeft);
91417: 
91418:       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
91419:       ** expression it is handled the same way.  An ephemeral table is 
91420:       ** filled with single-field index keys representing the results
91421:       ** from the SELECT or the <exprlist>.
91422:       **
91423:       ** If the 'x' expression is a column value, or the SELECT...
91424:       ** statement returns a column value, then the affinity of that
91425:       ** column is used to build the index keys. If both 'x' and the
91426:       ** SELECT... statement are columns, then numeric affinity is used
91427:       ** if either column has NUMERIC or INTEGER affinity. If neither
91428:       ** 'x' nor the SELECT... statement are columns, then numeric affinity
91429:       ** is used.
91430:       */
91431:       pExpr->iTable = pParse->nTab++;
91432:       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
91433:       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
91434: 
91435:       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
91436:         /* Case 1:     expr IN (SELECT ...)
91437:         **
91438:         ** Generate code to write the results of the select into the temporary
91439:         ** table allocated and opened above.
91440:         */
91441:         Select *pSelect = pExpr->x.pSelect;
91442:         SelectDest dest;
91443:         ExprList *pEList;
91444: 
91445:         assert( !isRowid );
91446:         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
91447:         dest.affSdst = (u8)affinity;
91448:         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
91449:         pSelect->iLimit = 0;
91450:         testcase( pSelect->selFlags & SF_Distinct );
91451:         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
91452:         if( sqlite3Select(pParse, pSelect, &dest) ){
91453:           sqlite3KeyInfoUnref(pKeyInfo);
91454:           return 0;
91455:         }
91456:         pEList = pSelect->pEList;
91457:         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
91458:         assert( pEList!=0 );
91459:         assert( pEList->nExpr>0 );
91460:         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
91461:         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
91462:                                                          pEList->a[0].pExpr);
91463:       }else if( ALWAYS(pExpr->x.pList!=0) ){
91464:         /* Case 2:     expr IN (exprlist)
91465:         **
91466:         ** For each expression, build an index key from the evaluation and
91467:         ** store it in the temporary table. If <expr> is a column, then use
91468:         ** that columns affinity when building index keys. If <expr> is not
91469:         ** a column, use numeric affinity.
91470:         */
91471:         int i;
91472:         ExprList *pList = pExpr->x.pList;
91473:         struct ExprList_item *pItem;
91474:         int r1, r2, r3;
91475: 
91476:         if( !affinity ){
91477:           affinity = SQLITE_AFF_BLOB;
91478:         }
91479:         if( pKeyInfo ){
91480:           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
91481:           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
91482:         }
91483: 
91484:         /* Loop through each expression in <exprlist>. */
91485:         r1 = sqlite3GetTempReg(pParse);
91486:         r2 = sqlite3GetTempReg(pParse);
91487:         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
91488:         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
91489:           Expr *pE2 = pItem->pExpr;
91490:           int iValToIns;
91491: 
91492:           /* If the expression is not constant then we will need to
91493:           ** disable the test that was generated above that makes sure
91494:           ** this code only executes once.  Because for a non-constant
91495:           ** expression we need to rerun this code each time.
91496:           */
91497:           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
91498:             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
91499:             jmpIfDynamic = -1;
91500:           }
91501: 
91502:           /* Evaluate the expression and insert it into the temp table */
91503:           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
91504:             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
91505:           }else{
91506:             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
91507:             if( isRowid ){
91508:               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
91509:                                 sqlite3VdbeCurrentAddr(v)+2);
91510:               VdbeCoverage(v);
91511:               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
91512:             }else{
91513:               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
91514:               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
91515:               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
91516:             }
91517:           }
91518:         }
91519:         sqlite3ReleaseTempReg(pParse, r1);
91520:         sqlite3ReleaseTempReg(pParse, r2);
91521:       }
91522:       if( pKeyInfo ){
91523:         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
91524:       }
91525:       break;
91526:     }
91527: 
91528:     case TK_EXISTS:
91529:     case TK_SELECT:
91530:     default: {
91531:       /* If this has to be a scalar SELECT.  Generate code to put the
91532:       ** value of this select in a memory cell and record the number
91533:       ** of the memory cell in iColumn.  If this is an EXISTS, write
91534:       ** an integer 0 (not exists) or 1 (exists) into a memory cell
91535:       ** and record that memory cell in iColumn.
91536:       */
91537:       Select *pSel;                         /* SELECT statement to encode */
91538:       SelectDest dest;                      /* How to deal with SELECt result */
91539: 
91540:       testcase( pExpr->op==TK_EXISTS );
91541:       testcase( pExpr->op==TK_SELECT );
91542:       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
91543: 
91544:       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
91545:       pSel = pExpr->x.pSelect;
91546:       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
91547:       if( pExpr->op==TK_SELECT ){
91548:         dest.eDest = SRT_Mem;
91549:         dest.iSdst = dest.iSDParm;
91550:         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
91551:         VdbeComment((v, "Init subquery result"));
91552:       }else{
91553:         dest.eDest = SRT_Exists;
91554:         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
91555:         VdbeComment((v, "Init EXISTS result"));
91556:       }
91557:       sqlite3ExprDelete(pParse->db, pSel->pLimit);
91558:       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
91559:                                   &sqlite3IntTokens[1]);
91560:       pSel->iLimit = 0;
91561:       pSel->selFlags &= ~SF_MultiValue;
91562:       if( sqlite3Select(pParse, pSel, &dest) ){
91563:         return 0;
91564:       }
91565:       rReg = dest.iSDParm;
91566:       ExprSetVVAProperty(pExpr, EP_NoReduce);
91567:       break;
91568:     }
91569:   }
91570: 
91571:   if( rHasNullFlag ){
91572:     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
91573:   }
91574: 
91575:   if( jmpIfDynamic>=0 ){
91576:     sqlite3VdbeJumpHere(v, jmpIfDynamic);
91577:   }
91578:   sqlite3ExprCachePop(pParse);
91579: 
91580:   return rReg;
91581: }
91582: #endif /* SQLITE_OMIT_SUBQUERY */
91583: 
91584: #ifndef SQLITE_OMIT_SUBQUERY
91585: /*
91586: ** Generate code for an IN expression.
91587: **
91588: **      x IN (SELECT ...)
91589: **      x IN (value, value, ...)
91590: **
91591: ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
91592: ** is an array of zero or more values.  The expression is true if the LHS is
91593: ** contained within the RHS.  The value of the expression is unknown (NULL)
91594: ** if the LHS is NULL or if the LHS is not contained within the RHS and the
91595: ** RHS contains one or more NULL values.
91596: **
91597: ** This routine generates code that jumps to destIfFalse if the LHS is not 
91598: ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
91599: ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
91600: ** within the RHS then fall through.
91601: */
91602: static void sqlite3ExprCodeIN(
91603:   Parse *pParse,        /* Parsing and code generating context */
91604:   Expr *pExpr,          /* The IN expression */
91605:   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
91606:   int destIfNull        /* Jump here if the results are unknown due to NULLs */
91607: ){
91608:   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
91609:   char affinity;        /* Comparison affinity to use */
91610:   int eType;            /* Type of the RHS */
91611:   int r1;               /* Temporary use register */
91612:   Vdbe *v;              /* Statement under construction */
91613: 
91614:   /* Compute the RHS.   After this step, the table with cursor
91615:   ** pExpr->iTable will contains the values that make up the RHS.
91616:   */
91617:   v = pParse->pVdbe;
91618:   assert( v!=0 );       /* OOM detected prior to this routine */
91619:   VdbeNoopComment((v, "begin IN expr"));
91620:   eType = sqlite3FindInIndex(pParse, pExpr,
91621:                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
91622:                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
91623: 
91624:   /* Figure out the affinity to use to create a key from the results
91625:   ** of the expression. affinityStr stores a static string suitable for
91626:   ** P4 of OP_MakeRecord.
91627:   */
91628:   affinity = comparisonAffinity(pExpr);
91629: 
91630:   /* Code the LHS, the <expr> from "<expr> IN (...)".
91631:   */
91632:   sqlite3ExprCachePush(pParse);
91633:   r1 = sqlite3GetTempReg(pParse);
91634:   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
91635: 
91636:   /* If sqlite3FindInIndex() did not find or create an index that is
91637:   ** suitable for evaluating the IN operator, then evaluate using a
91638:   ** sequence of comparisons.
91639:   */
91640:   if( eType==IN_INDEX_NOOP ){
91641:     ExprList *pList = pExpr->x.pList;
91642:     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
91643:     int labelOk = sqlite3VdbeMakeLabel(v);
91644:     int r2, regToFree;
91645:     int regCkNull = 0;
91646:     int ii;
91647:     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91648:     if( destIfNull!=destIfFalse ){
91649:       regCkNull = sqlite3GetTempReg(pParse);
91650:       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
91651:     }
91652:     for(ii=0; ii<pList->nExpr; ii++){
91653:       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
91654:       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
91655:         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
91656:       }
91657:       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
91658:         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
91659:                           (void*)pColl, P4_COLLSEQ);
91660:         VdbeCoverageIf(v, ii<pList->nExpr-1);
91661:         VdbeCoverageIf(v, ii==pList->nExpr-1);
91662:         sqlite3VdbeChangeP5(v, affinity);
91663:       }else{
91664:         assert( destIfNull==destIfFalse );
91665:         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
91666:                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
91667:         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
91668:       }
91669:       sqlite3ReleaseTempReg(pParse, regToFree);
91670:     }
91671:     if( regCkNull ){
91672:       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
91673:       sqlite3VdbeGoto(v, destIfFalse);
91674:     }
91675:     sqlite3VdbeResolveLabel(v, labelOk);
91676:     sqlite3ReleaseTempReg(pParse, regCkNull);
91677:   }else{
91678:   
91679:     /* If the LHS is NULL, then the result is either false or NULL depending
91680:     ** on whether the RHS is empty or not, respectively.
91681:     */
91682:     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
91683:       if( destIfNull==destIfFalse ){
91684:         /* Shortcut for the common case where the false and NULL outcomes are
91685:         ** the same. */
91686:         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
91687:       }else{
91688:         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
91689:         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
91690:         VdbeCoverage(v);
91691:         sqlite3VdbeGoto(v, destIfNull);
91692:         sqlite3VdbeJumpHere(v, addr1);
91693:       }
91694:     }
91695:   
91696:     if( eType==IN_INDEX_ROWID ){
91697:       /* In this case, the RHS is the ROWID of table b-tree
91698:       */
91699:       sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
91700:       VdbeCoverage(v);
91701:     }else{
91702:       /* In this case, the RHS is an index b-tree.
91703:       */
91704:       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
91705:   
91706:       /* If the set membership test fails, then the result of the 
91707:       ** "x IN (...)" expression must be either 0 or NULL. If the set
91708:       ** contains no NULL values, then the result is 0. If the set 
91709:       ** contains one or more NULL values, then the result of the
91710:       ** expression is also NULL.
91711:       */
91712:       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
91713:       if( rRhsHasNull==0 ){
91714:         /* This branch runs if it is known at compile time that the RHS
91715:         ** cannot contain NULL values. This happens as the result
91716:         ** of a "NOT NULL" constraint in the database schema.
91717:         **
91718:         ** Also run this branch if NULL is equivalent to FALSE
91719:         ** for this particular IN operator.
91720:         */
91721:         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
91722:         VdbeCoverage(v);
91723:       }else{
91724:         /* In this branch, the RHS of the IN might contain a NULL and
91725:         ** the presence of a NULL on the RHS makes a difference in the
91726:         ** outcome.
91727:         */
91728:         int addr1;
91729:   
91730:         /* First check to see if the LHS is contained in the RHS.  If so,
91731:         ** then the answer is TRUE the presence of NULLs in the RHS does
91732:         ** not matter.  If the LHS is not contained in the RHS, then the
91733:         ** answer is NULL if the RHS contains NULLs and the answer is
91734:         ** FALSE if the RHS is NULL-free.
91735:         */
91736:         addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
91737:         VdbeCoverage(v);
91738:         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
91739:         VdbeCoverage(v);
91740:         sqlite3VdbeGoto(v, destIfFalse);
91741:         sqlite3VdbeJumpHere(v, addr1);
91742:       }
91743:     }
91744:   }
91745:   sqlite3ReleaseTempReg(pParse, r1);
91746:   sqlite3ExprCachePop(pParse);
91747:   VdbeComment((v, "end IN expr"));
91748: }
91749: #endif /* SQLITE_OMIT_SUBQUERY */
91750: 
91751: #ifndef SQLITE_OMIT_FLOATING_POINT
91752: /*
91753: ** Generate an instruction that will put the floating point
91754: ** value described by z[0..n-1] into register iMem.
91755: **
91756: ** The z[] string will probably not be zero-terminated.  But the 
91757: ** z[n] character is guaranteed to be something that does not look
91758: ** like the continuation of the number.
91759: */
91760: static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
91761:   if( ALWAYS(z!=0) ){
91762:     double value;
91763:     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
91764:     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
91765:     if( negateFlag ) value = -value;
91766:     sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
91767:   }
91768: }
91769: #endif
91770: 
91771: 
91772: /*
91773: ** Generate an instruction that will put the integer describe by
91774: ** text z[0..n-1] into register iMem.
91775: **
91776: ** Expr.u.zToken is always UTF8 and zero-terminated.
91777: */
91778: static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
91779:   Vdbe *v = pParse->pVdbe;
91780:   if( pExpr->flags & EP_IntValue ){
91781:     int i = pExpr->u.iValue;
91782:     assert( i>=0 );
91783:     if( negFlag ) i = -i;
91784:     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
91785:   }else{
91786:     int c;
91787:     i64 value;
91788:     const char *z = pExpr->u.zToken;
91789:     assert( z!=0 );
91790:     c = sqlite3DecOrHexToI64(z, &value);
91791:     if( c==0 || (c==2 && negFlag) ){
91792:       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
91793:       sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
91794:     }else{
91795: #ifdef SQLITE_OMIT_FLOATING_POINT
91796:       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
91797: #else
91798: #ifndef SQLITE_OMIT_HEX_INTEGER
91799:       if( sqlite3_strnicmp(z,"0x",2)==0 ){
91800:         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
91801:       }else
91802: #endif
91803:       {
91804:         codeReal(v, z, negFlag, iMem);
91805:       }
91806: #endif
91807:     }
91808:   }
91809: }
91810: 
91811: #if defined(SQLITE_DEBUG)
91812: /*
91813: ** Verify the consistency of the column cache
91814: */
91815: static int cacheIsValid(Parse *pParse){
91816:   int i, n;
91817:   for(i=n=0; i<SQLITE_N_COLCACHE; i++){
91818:     if( pParse->aColCache[i].iReg>0 ) n++;
91819:   }
91820:   return n==pParse->nColCache;
91821: }
91822: #endif
91823: 
91824: /*
91825: ** Clear a cache entry.
91826: */
91827: static void cacheEntryClear(Parse *pParse, struct yColCache *p){
91828:   if( p->tempReg ){
91829:     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
91830:       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
91831:     }
91832:     p->tempReg = 0;
91833:   }
91834:   p->iReg = 0;
91835:   pParse->nColCache--;
91836:   assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91837: }
91838: 
91839: 
91840: /*
91841: ** Record in the column cache that a particular column from a
91842: ** particular table is stored in a particular register.
91843: */
91844: SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
91845:   int i;
91846:   int minLru;
91847:   int idxLru;
91848:   struct yColCache *p;
91849: 
91850:   /* Unless an error has occurred, register numbers are always positive. */
91851:   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
91852:   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
91853: 
91854:   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
91855:   ** for testing only - to verify that SQLite always gets the same answer
91856:   ** with and without the column cache.
91857:   */
91858:   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
91859: 
91860:   /* First replace any existing entry.
91861:   **
91862:   ** Actually, the way the column cache is currently used, we are guaranteed
91863:   ** that the object will never already be in cache.  Verify this guarantee.
91864:   */
91865: #ifndef NDEBUG
91866:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91867:     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
91868:   }
91869: #endif
91870: 
91871:   /* Find an empty slot and replace it */
91872:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91873:     if( p->iReg==0 ){
91874:       p->iLevel = pParse->iCacheLevel;
91875:       p->iTable = iTab;
91876:       p->iColumn = iCol;
91877:       p->iReg = iReg;
91878:       p->tempReg = 0;
91879:       p->lru = pParse->iCacheCnt++;
91880:       pParse->nColCache++;
91881:       assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91882:       return;
91883:     }
91884:   }
91885: 
91886:   /* Replace the last recently used */
91887:   minLru = 0x7fffffff;
91888:   idxLru = -1;
91889:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91890:     if( p->lru<minLru ){
91891:       idxLru = i;
91892:       minLru = p->lru;
91893:     }
91894:   }
91895:   if( ALWAYS(idxLru>=0) ){
91896:     p = &pParse->aColCache[idxLru];
91897:     p->iLevel = pParse->iCacheLevel;
91898:     p->iTable = iTab;
91899:     p->iColumn = iCol;
91900:     p->iReg = iReg;
91901:     p->tempReg = 0;
91902:     p->lru = pParse->iCacheCnt++;
91903:     assert( cacheIsValid(pParse) );
91904:     return;
91905:   }
91906: }
91907: 
91908: /*
91909: ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
91910: ** Purge the range of registers from the column cache.
91911: */
91912: SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
91913:   struct yColCache *p;
91914:   if( iReg<=0 || pParse->nColCache==0 ) return;
91915:   p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
91916:   while(1){
91917:     if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
91918:     if( p==pParse->aColCache ) break;
91919:     p--;
91920:   }
91921: }
91922: 
91923: /*
91924: ** Remember the current column cache context.  Any new entries added
91925: ** added to the column cache after this call are removed when the
91926: ** corresponding pop occurs.
91927: */
91928: SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
91929:   pParse->iCacheLevel++;
91930: #ifdef SQLITE_DEBUG
91931:   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91932:     printf("PUSH to %d\n", pParse->iCacheLevel);
91933:   }
91934: #endif
91935: }
91936: 
91937: /*
91938: ** Remove from the column cache any entries that were added since the
91939: ** the previous sqlite3ExprCachePush operation.  In other words, restore
91940: ** the cache to the state it was in prior the most recent Push.
91941: */
91942: SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
91943:   int i;
91944:   struct yColCache *p;
91945:   assert( pParse->iCacheLevel>=1 );
91946:   pParse->iCacheLevel--;
91947: #ifdef SQLITE_DEBUG
91948:   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91949:     printf("POP  to %d\n", pParse->iCacheLevel);
91950:   }
91951: #endif
91952:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91953:     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
91954:       cacheEntryClear(pParse, p);
91955:     }
91956:   }
91957: }
91958: 
91959: /*
91960: ** When a cached column is reused, make sure that its register is
91961: ** no longer available as a temp register.  ticket #3879:  that same
91962: ** register might be in the cache in multiple places, so be sure to
91963: ** get them all.
91964: */
91965: static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
91966:   int i;
91967:   struct yColCache *p;
91968:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91969:     if( p->iReg==iReg ){
91970:       p->tempReg = 0;
91971:     }
91972:   }
91973: }
91974: 
91975: /* Generate code that will load into register regOut a value that is
91976: ** appropriate for the iIdxCol-th column of index pIdx.
91977: */
91978: SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
91979:   Parse *pParse,  /* The parsing context */
91980:   Index *pIdx,    /* The index whose column is to be loaded */
91981:   int iTabCur,    /* Cursor pointing to a table row */
91982:   int iIdxCol,    /* The column of the index to be loaded */
91983:   int regOut      /* Store the index column value in this register */
91984: ){
91985:   i16 iTabCol = pIdx->aiColumn[iIdxCol];
91986:   if( iTabCol==XN_EXPR ){
91987:     assert( pIdx->aColExpr );
91988:     assert( pIdx->aColExpr->nExpr>iIdxCol );
91989:     pParse->iSelfTab = iTabCur;
91990:     sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
91991:   }else{
91992:     sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
91993:                                     iTabCol, regOut);
91994:   }
91995: }
91996: 
91997: /*
91998: ** Generate code to extract the value of the iCol-th column of a table.
91999: */
92000: SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
92001:   Vdbe *v,        /* The VDBE under construction */
92002:   Table *pTab,    /* The table containing the value */
92003:   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
92004:   int iCol,       /* Index of the column to extract */
92005:   int regOut      /* Extract the value into this register */
92006: ){
92007:   if( iCol<0 || iCol==pTab->iPKey ){
92008:     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
92009:   }else{
92010:     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
92011:     int x = iCol;
92012:     if( !HasRowid(pTab) && !IsVirtual(pTab) ){
92013:       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
92014:     }
92015:     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
92016:   }
92017:   if( iCol>=0 ){
92018:     sqlite3ColumnDefault(v, pTab, iCol, regOut);
92019:   }
92020: }
92021: 
92022: /*
92023: ** Generate code that will extract the iColumn-th column from
92024: ** table pTab and store the column value in a register. 
92025: **
92026: ** An effort is made to store the column value in register iReg.  This
92027: ** is not garanteeed for GetColumn() - the result can be stored in
92028: ** any register.  But the result is guaranteed to land in register iReg
92029: ** for GetColumnToReg().
92030: **
92031: ** There must be an open cursor to pTab in iTable when this routine
92032: ** is called.  If iColumn<0 then code is generated that extracts the rowid.
92033: */
92034: SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
92035:   Parse *pParse,   /* Parsing and code generating context */
92036:   Table *pTab,     /* Description of the table we are reading from */
92037:   int iColumn,     /* Index of the table column */
92038:   int iTable,      /* The cursor pointing to the table */
92039:   int iReg,        /* Store results here */
92040:   u8 p5            /* P5 value for OP_Column + FLAGS */
92041: ){
92042:   Vdbe *v = pParse->pVdbe;
92043:   int i;
92044:   struct yColCache *p;
92045: 
92046:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92047:     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
92048:       p->lru = pParse->iCacheCnt++;
92049:       sqlite3ExprCachePinRegister(pParse, p->iReg);
92050:       return p->iReg;
92051:     }
92052:   }  
92053:   assert( v!=0 );
92054:   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
92055:   if( p5 ){
92056:     sqlite3VdbeChangeP5(v, p5);
92057:   }else{   
92058:     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
92059:   }
92060:   return iReg;
92061: }
92062: SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
92063:   Parse *pParse,   /* Parsing and code generating context */
92064:   Table *pTab,     /* Description of the table we are reading from */
92065:   int iColumn,     /* Index of the table column */
92066:   int iTable,      /* The cursor pointing to the table */
92067:   int iReg         /* Store results here */
92068: ){
92069:   int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
92070:   if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
92071: }
92072: 
92073: 
92074: /*
92075: ** Clear all column cache entries.
92076: */
92077: SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
92078:   int i;
92079:   struct yColCache *p;
92080: 
92081: #if SQLITE_DEBUG
92082:   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
92083:     printf("CLEAR\n");
92084:   }
92085: #endif
92086:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92087:     if( p->iReg ){
92088:       cacheEntryClear(pParse, p);
92089:     }
92090:   }
92091: }
92092: 
92093: /*
92094: ** Record the fact that an affinity change has occurred on iCount
92095: ** registers starting with iStart.
92096: */
92097: SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
92098:   sqlite3ExprCacheRemove(pParse, iStart, iCount);
92099: }
92100: 
92101: /*
92102: ** Generate code to move content from registers iFrom...iFrom+nReg-1
92103: ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
92104: */
92105: SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
92106:   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
92107:   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
92108:   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
92109: }
92110: 
92111: #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
92112: /*
92113: ** Return true if any register in the range iFrom..iTo (inclusive)
92114: ** is used as part of the column cache.
92115: **
92116: ** This routine is used within assert() and testcase() macros only
92117: ** and does not appear in a normal build.
92118: */
92119: static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
92120:   int i;
92121:   struct yColCache *p;
92122:   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
92123:     int r = p->iReg;
92124:     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
92125:   }
92126:   return 0;
92127: }
92128: #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
92129: 
92130: 
92131: /*
92132: ** Convert an expression node to a TK_REGISTER
92133: */
92134: static void exprToRegister(Expr *p, int iReg){
92135:   p->op2 = p->op;
92136:   p->op = TK_REGISTER;
92137:   p->iTable = iReg;
92138:   ExprClearProperty(p, EP_Skip);
92139: }
92140: 
92141: /*
92142: ** Generate code into the current Vdbe to evaluate the given
92143: ** expression.  Attempt to store the results in register "target".
92144: ** Return the register where results are stored.
92145: **
92146: ** With this routine, there is no guarantee that results will
92147: ** be stored in target.  The result might be stored in some other
92148: ** register if it is convenient to do so.  The calling function
92149: ** must check the return code and move the results to the desired
92150: ** register.
92151: */
92152: SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
92153:   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
92154:   int op;                   /* The opcode being coded */
92155:   int inReg = target;       /* Results stored in register inReg */
92156:   int regFree1 = 0;         /* If non-zero free this temporary register */
92157:   int regFree2 = 0;         /* If non-zero free this temporary register */
92158:   int r1, r2, r3, r4;       /* Various register numbers */
92159:   sqlite3 *db = pParse->db; /* The database connection */
92160:   Expr tempX;               /* Temporary expression node */
92161: 
92162:   assert( target>0 && target<=pParse->nMem );
92163:   if( v==0 ){
92164:     assert( pParse->db->mallocFailed );
92165:     return 0;
92166:   }
92167: 
92168:   if( pExpr==0 ){
92169:     op = TK_NULL;
92170:   }else{
92171:     op = pExpr->op;
92172:   }
92173:   switch( op ){
92174:     case TK_AGG_COLUMN: {
92175:       AggInfo *pAggInfo = pExpr->pAggInfo;
92176:       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
92177:       if( !pAggInfo->directMode ){
92178:         assert( pCol->iMem>0 );
92179:         inReg = pCol->iMem;
92180:         break;
92181:       }else if( pAggInfo->useSortingIdx ){
92182:         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
92183:                               pCol->iSorterColumn, target);
92184:         break;
92185:       }
92186:       /* Otherwise, fall thru into the TK_COLUMN case */
92187:     }
92188:     case TK_COLUMN: {
92189:       int iTab = pExpr->iTable;
92190:       if( iTab<0 ){
92191:         if( pParse->ckBase>0 ){
92192:           /* Generating CHECK constraints or inserting into partial index */
92193:           inReg = pExpr->iColumn + pParse->ckBase;
92194:           break;
92195:         }else{
92196:           /* Coding an expression that is part of an index where column names
92197:           ** in the index refer to the table to which the index belongs */
92198:           iTab = pParse->iSelfTab;
92199:         }
92200:       }
92201:       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
92202:                                pExpr->iColumn, iTab, target,
92203:                                pExpr->op2);
92204:       break;
92205:     }
92206:     case TK_INTEGER: {
92207:       codeInteger(pParse, pExpr, 0, target);
92208:       break;
92209:     }
92210: #ifndef SQLITE_OMIT_FLOATING_POINT
92211:     case TK_FLOAT: {
92212:       assert( !ExprHasProperty(pExpr, EP_IntValue) );
92213:       codeReal(v, pExpr->u.zToken, 0, target);
92214:       break;
92215:     }
92216: #endif
92217:     case TK_STRING: {
92218:       assert( !ExprHasProperty(pExpr, EP_IntValue) );
92219:       sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
92220:       break;
92221:     }
92222:     case TK_NULL: {
92223:       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92224:       break;
92225:     }
92226: #ifndef SQLITE_OMIT_BLOB_LITERAL
92227:     case TK_BLOB: {
92228:       int n;
92229:       const char *z;
92230:       char *zBlob;
92231:       assert( !ExprHasProperty(pExpr, EP_IntValue) );
92232:       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
92233:       assert( pExpr->u.zToken[1]=='\'' );
92234:       z = &pExpr->u.zToken[2];
92235:       n = sqlite3Strlen30(z) - 1;
92236:       assert( z[n]=='\'' );
92237:       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
92238:       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
92239:       break;
92240:     }
92241: #endif
92242:     case TK_VARIABLE: {
92243:       assert( !ExprHasProperty(pExpr, EP_IntValue) );
92244:       assert( pExpr->u.zToken!=0 );
92245:       assert( pExpr->u.zToken[0]!=0 );
92246:       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
92247:       if( pExpr->u.zToken[1]!=0 ){
92248:         assert( pExpr->u.zToken[0]=='?' 
92249:              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
92250:         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
92251:       }
92252:       break;
92253:     }
92254:     case TK_REGISTER: {
92255:       inReg = pExpr->iTable;
92256:       break;
92257:     }
92258: #ifndef SQLITE_OMIT_CAST
92259:     case TK_CAST: {
92260:       /* Expressions of the form:   CAST(pLeft AS token) */
92261:       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
92262:       if( inReg!=target ){
92263:         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
92264:         inReg = target;
92265:       }
92266:       sqlite3VdbeAddOp2(v, OP_Cast, target,
92267:                         sqlite3AffinityType(pExpr->u.zToken, 0));
92268:       testcase( usedAsColumnCache(pParse, inReg, inReg) );
92269:       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
92270:       break;
92271:     }
92272: #endif /* SQLITE_OMIT_CAST */
92273:     case TK_LT:
92274:     case TK_LE:
92275:     case TK_GT:
92276:     case TK_GE:
92277:     case TK_NE:
92278:     case TK_EQ: {
92279:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92280:       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92281:       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92282:                   r1, r2, inReg, SQLITE_STOREP2);
92283:       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
92284:       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
92285:       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
92286:       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
92287:       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
92288:       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
92289:       testcase( regFree1==0 );
92290:       testcase( regFree2==0 );
92291:       break;
92292:     }
92293:     case TK_IS:
92294:     case TK_ISNOT: {
92295:       testcase( op==TK_IS );
92296:       testcase( op==TK_ISNOT );
92297:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92298:       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92299:       op = (op==TK_IS) ? TK_EQ : TK_NE;
92300:       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92301:                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
92302:       VdbeCoverageIf(v, op==TK_EQ);
92303:       VdbeCoverageIf(v, op==TK_NE);
92304:       testcase( regFree1==0 );
92305:       testcase( regFree2==0 );
92306:       break;
92307:     }
92308:     case TK_AND:
92309:     case TK_OR:
92310:     case TK_PLUS:
92311:     case TK_STAR:
92312:     case TK_MINUS:
92313:     case TK_REM:
92314:     case TK_BITAND:
92315:     case TK_BITOR:
92316:     case TK_SLASH:
92317:     case TK_LSHIFT:
92318:     case TK_RSHIFT: 
92319:     case TK_CONCAT: {
92320:       assert( TK_AND==OP_And );            testcase( op==TK_AND );
92321:       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
92322:       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
92323:       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
92324:       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
92325:       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
92326:       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
92327:       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
92328:       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
92329:       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
92330:       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
92331:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92332:       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92333:       sqlite3VdbeAddOp3(v, op, r2, r1, target);
92334:       testcase( regFree1==0 );
92335:       testcase( regFree2==0 );
92336:       break;
92337:     }
92338:     case TK_UMINUS: {
92339:       Expr *pLeft = pExpr->pLeft;
92340:       assert( pLeft );
92341:       if( pLeft->op==TK_INTEGER ){
92342:         codeInteger(pParse, pLeft, 1, target);
92343: #ifndef SQLITE_OMIT_FLOATING_POINT
92344:       }else if( pLeft->op==TK_FLOAT ){
92345:         assert( !ExprHasProperty(pExpr, EP_IntValue) );
92346:         codeReal(v, pLeft->u.zToken, 1, target);
92347: #endif
92348:       }else{
92349:         tempX.op = TK_INTEGER;
92350:         tempX.flags = EP_IntValue|EP_TokenOnly;
92351:         tempX.u.iValue = 0;
92352:         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
92353:         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
92354:         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
92355:         testcase( regFree2==0 );
92356:       }
92357:       inReg = target;
92358:       break;
92359:     }
92360:     case TK_BITNOT:
92361:     case TK_NOT: {
92362:       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
92363:       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
92364:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92365:       testcase( regFree1==0 );
92366:       inReg = target;
92367:       sqlite3VdbeAddOp2(v, op, r1, inReg);
92368:       break;
92369:     }
92370:     case TK_ISNULL:
92371:     case TK_NOTNULL: {
92372:       int addr;
92373:       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
92374:       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
92375:       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
92376:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92377:       testcase( regFree1==0 );
92378:       addr = sqlite3VdbeAddOp1(v, op, r1);
92379:       VdbeCoverageIf(v, op==TK_ISNULL);
92380:       VdbeCoverageIf(v, op==TK_NOTNULL);
92381:       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
92382:       sqlite3VdbeJumpHere(v, addr);
92383:       break;
92384:     }
92385:     case TK_AGG_FUNCTION: {
92386:       AggInfo *pInfo = pExpr->pAggInfo;
92387:       if( pInfo==0 ){
92388:         assert( !ExprHasProperty(pExpr, EP_IntValue) );
92389:         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
92390:       }else{
92391:         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
92392:       }
92393:       break;
92394:     }
92395:     case TK_FUNCTION: {
92396:       ExprList *pFarg;       /* List of function arguments */
92397:       int nFarg;             /* Number of function arguments */
92398:       FuncDef *pDef;         /* The function definition object */
92399:       const char *zId;       /* The function name */
92400:       u32 constMask = 0;     /* Mask of function arguments that are constant */
92401:       int i;                 /* Loop counter */
92402:       u8 enc = ENC(db);      /* The text encoding used by this database */
92403:       CollSeq *pColl = 0;    /* A collating sequence */
92404: 
92405:       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92406:       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
92407:         pFarg = 0;
92408:       }else{
92409:         pFarg = pExpr->x.pList;
92410:       }
92411:       nFarg = pFarg ? pFarg->nExpr : 0;
92412:       assert( !ExprHasProperty(pExpr, EP_IntValue) );
92413:       zId = pExpr->u.zToken;
92414:       pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
92415: #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
92416:       if( pDef==0 && pParse->explain ){
92417:         pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
92418:       }
92419: #endif
92420:       if( pDef==0 || pDef->xFinalize!=0 ){
92421:         sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
92422:         break;
92423:       }
92424: 
92425:       /* Attempt a direct implementation of the built-in COALESCE() and
92426:       ** IFNULL() functions.  This avoids unnecessary evaluation of
92427:       ** arguments past the first non-NULL argument.
92428:       */
92429:       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
92430:         int endCoalesce = sqlite3VdbeMakeLabel(v);
92431:         assert( nFarg>=2 );
92432:         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
92433:         for(i=1; i<nFarg; i++){
92434:           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
92435:           VdbeCoverage(v);
92436:           sqlite3ExprCacheRemove(pParse, target, 1);
92437:           sqlite3ExprCachePush(pParse);
92438:           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
92439:           sqlite3ExprCachePop(pParse);
92440:         }
92441:         sqlite3VdbeResolveLabel(v, endCoalesce);
92442:         break;
92443:       }
92444: 
92445:       /* The UNLIKELY() function is a no-op.  The result is the value
92446:       ** of the first argument.
92447:       */
92448:       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
92449:         assert( nFarg>=1 );
92450:         inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
92451:         break;
92452:       }
92453: 
92454:       for(i=0; i<nFarg; i++){
92455:         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
92456:           testcase( i==31 );
92457:           constMask |= MASKBIT32(i);
92458:         }
92459:         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
92460:           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
92461:         }
92462:       }
92463:       if( pFarg ){
92464:         if( constMask ){
92465:           r1 = pParse->nMem+1;
92466:           pParse->nMem += nFarg;
92467:         }else{
92468:           r1 = sqlite3GetTempRange(pParse, nFarg);
92469:         }
92470: 
92471:         /* For length() and typeof() functions with a column argument,
92472:         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
92473:         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
92474:         ** loading.
92475:         */
92476:         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
92477:           u8 exprOp;
92478:           assert( nFarg==1 );
92479:           assert( pFarg->a[0].pExpr!=0 );
92480:           exprOp = pFarg->a[0].pExpr->op;
92481:           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
92482:             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
92483:             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
92484:             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
92485:             pFarg->a[0].pExpr->op2 = 
92486:                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
92487:           }
92488:         }
92489: 
92490:         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
92491:         sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
92492:                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
92493:         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
92494:       }else{
92495:         r1 = 0;
92496:       }
92497: #ifndef SQLITE_OMIT_VIRTUALTABLE
92498:       /* Possibly overload the function if the first argument is
92499:       ** a virtual table column.
92500:       **
92501:       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
92502:       ** second argument, not the first, as the argument to test to
92503:       ** see if it is a column in a virtual table.  This is done because
92504:       ** the left operand of infix functions (the operand we want to
92505:       ** control overloading) ends up as the second argument to the
92506:       ** function.  The expression "A glob B" is equivalent to 
92507:       ** "glob(B,A).  We want to use the A in "A glob B" to test
92508:       ** for function overloading.  But we use the B term in "glob(B,A)".
92509:       */
92510:       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
92511:         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
92512:       }else if( nFarg>0 ){
92513:         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
92514:       }
92515: #endif
92516:       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
92517:         if( !pColl ) pColl = db->pDfltColl; 
92518:         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
92519:       }
92520:       sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
92521:                         (char*)pDef, P4_FUNCDEF);
92522:       sqlite3VdbeChangeP5(v, (u8)nFarg);
92523:       if( nFarg && constMask==0 ){
92524:         sqlite3ReleaseTempRange(pParse, r1, nFarg);
92525:       }
92526:       break;
92527:     }
92528: #ifndef SQLITE_OMIT_SUBQUERY
92529:     case TK_EXISTS:
92530:     case TK_SELECT: {
92531:       testcase( op==TK_EXISTS );
92532:       testcase( op==TK_SELECT );
92533:       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
92534:       break;
92535:     }
92536:     case TK_IN: {
92537:       int destIfFalse = sqlite3VdbeMakeLabel(v);
92538:       int destIfNull = sqlite3VdbeMakeLabel(v);
92539:       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92540:       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
92541:       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
92542:       sqlite3VdbeResolveLabel(v, destIfFalse);
92543:       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
92544:       sqlite3VdbeResolveLabel(v, destIfNull);
92545:       break;
92546:     }
92547: #endif /* SQLITE_OMIT_SUBQUERY */
92548: 
92549: 
92550:     /*
92551:     **    x BETWEEN y AND z
92552:     **
92553:     ** This is equivalent to
92554:     **
92555:     **    x>=y AND x<=z
92556:     **
92557:     ** X is stored in pExpr->pLeft.
92558:     ** Y is stored in pExpr->pList->a[0].pExpr.
92559:     ** Z is stored in pExpr->pList->a[1].pExpr.
92560:     */
92561:     case TK_BETWEEN: {
92562:       Expr *pLeft = pExpr->pLeft;
92563:       struct ExprList_item *pLItem = pExpr->x.pList->a;
92564:       Expr *pRight = pLItem->pExpr;
92565: 
92566:       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
92567:       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
92568:       testcase( regFree1==0 );
92569:       testcase( regFree2==0 );
92570:       r3 = sqlite3GetTempReg(pParse);
92571:       r4 = sqlite3GetTempReg(pParse);
92572:       codeCompare(pParse, pLeft, pRight, OP_Ge,
92573:                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
92574:       pLItem++;
92575:       pRight = pLItem->pExpr;
92576:       sqlite3ReleaseTempReg(pParse, regFree2);
92577:       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
92578:       testcase( regFree2==0 );
92579:       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
92580:       VdbeCoverage(v);
92581:       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
92582:       sqlite3ReleaseTempReg(pParse, r3);
92583:       sqlite3ReleaseTempReg(pParse, r4);
92584:       break;
92585:     }
92586:     case TK_SPAN:
92587:     case TK_COLLATE: 
92588:     case TK_UPLUS: {
92589:       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
92590:       break;
92591:     }
92592: 
92593:     case TK_TRIGGER: {
92594:       /* If the opcode is TK_TRIGGER, then the expression is a reference
92595:       ** to a column in the new.* or old.* pseudo-tables available to
92596:       ** trigger programs. In this case Expr.iTable is set to 1 for the
92597:       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
92598:       ** is set to the column of the pseudo-table to read, or to -1 to
92599:       ** read the rowid field.
92600:       **
92601:       ** The expression is implemented using an OP_Param opcode. The p1
92602:       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
92603:       ** to reference another column of the old.* pseudo-table, where 
92604:       ** i is the index of the column. For a new.rowid reference, p1 is
92605:       ** set to (n+1), where n is the number of columns in each pseudo-table.
92606:       ** For a reference to any other column in the new.* pseudo-table, p1
92607:       ** is set to (n+2+i), where n and i are as defined previously. For
92608:       ** example, if the table on which triggers are being fired is
92609:       ** declared as:
92610:       **
92611:       **   CREATE TABLE t1(a, b);
92612:       **
92613:       ** Then p1 is interpreted as follows:
92614:       **
92615:       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
92616:       **   p1==1   ->    old.a         p1==4   ->    new.a
92617:       **   p1==2   ->    old.b         p1==5   ->    new.b       
92618:       */
92619:       Table *pTab = pExpr->pTab;
92620:       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
92621: 
92622:       assert( pExpr->iTable==0 || pExpr->iTable==1 );
92623:       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
92624:       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
92625:       assert( p1>=0 && p1<(pTab->nCol*2+2) );
92626: 
92627:       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
92628:       VdbeComment((v, "%s.%s -> $%d",
92629:         (pExpr->iTable ? "new" : "old"),
92630:         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
92631:         target
92632:       ));
92633: 
92634: #ifndef SQLITE_OMIT_FLOATING_POINT
92635:       /* If the column has REAL affinity, it may currently be stored as an
92636:       ** integer. Use OP_RealAffinity to make sure it is really real.
92637:       **
92638:       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
92639:       ** floating point when extracting it from the record.  */
92640:       if( pExpr->iColumn>=0 
92641:        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
92642:       ){
92643:         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
92644:       }
92645: #endif
92646:       break;
92647:     }
92648: 
92649: 
92650:     /*
92651:     ** Form A:
92652:     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92653:     **
92654:     ** Form B:
92655:     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92656:     **
92657:     ** Form A is can be transformed into the equivalent form B as follows:
92658:     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
92659:     **        WHEN x=eN THEN rN ELSE y END
92660:     **
92661:     ** X (if it exists) is in pExpr->pLeft.
92662:     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
92663:     ** odd.  The Y is also optional.  If the number of elements in x.pList
92664:     ** is even, then Y is omitted and the "otherwise" result is NULL.
92665:     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
92666:     **
92667:     ** The result of the expression is the Ri for the first matching Ei,
92668:     ** or if there is no matching Ei, the ELSE term Y, or if there is
92669:     ** no ELSE term, NULL.
92670:     */
92671:     default: assert( op==TK_CASE ); {
92672:       int endLabel;                     /* GOTO label for end of CASE stmt */
92673:       int nextCase;                     /* GOTO label for next WHEN clause */
92674:       int nExpr;                        /* 2x number of WHEN terms */
92675:       int i;                            /* Loop counter */
92676:       ExprList *pEList;                 /* List of WHEN terms */
92677:       struct ExprList_item *aListelem;  /* Array of WHEN terms */
92678:       Expr opCompare;                   /* The X==Ei expression */
92679:       Expr *pX;                         /* The X expression */
92680:       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
92681:       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
92682: 
92683:       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
92684:       assert(pExpr->x.pList->nExpr > 0);
92685:       pEList = pExpr->x.pList;
92686:       aListelem = pEList->a;
92687:       nExpr = pEList->nExpr;
92688:       endLabel = sqlite3VdbeMakeLabel(v);
92689:       if( (pX = pExpr->pLeft)!=0 ){
92690:         tempX = *pX;
92691:         testcase( pX->op==TK_COLUMN );
92692:         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
92693:         testcase( regFree1==0 );
92694:         opCompare.op = TK_EQ;
92695:         opCompare.pLeft = &tempX;
92696:         pTest = &opCompare;
92697:         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
92698:         ** The value in regFree1 might get SCopy-ed into the file result.
92699:         ** So make sure that the regFree1 register is not reused for other
92700:         ** purposes and possibly overwritten.  */
92701:         regFree1 = 0;
92702:       }
92703:       for(i=0; i<nExpr-1; i=i+2){
92704:         sqlite3ExprCachePush(pParse);
92705:         if( pX ){
92706:           assert( pTest!=0 );
92707:           opCompare.pRight = aListelem[i].pExpr;
92708:         }else{
92709:           pTest = aListelem[i].pExpr;
92710:         }
92711:         nextCase = sqlite3VdbeMakeLabel(v);
92712:         testcase( pTest->op==TK_COLUMN );
92713:         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
92714:         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
92715:         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
92716:         sqlite3VdbeGoto(v, endLabel);
92717:         sqlite3ExprCachePop(pParse);
92718:         sqlite3VdbeResolveLabel(v, nextCase);
92719:       }
92720:       if( (nExpr&1)!=0 ){
92721:         sqlite3ExprCachePush(pParse);
92722:         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
92723:         sqlite3ExprCachePop(pParse);
92724:       }else{
92725:         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92726:       }
92727:       assert( db->mallocFailed || pParse->nErr>0 
92728:            || pParse->iCacheLevel==iCacheLevel );
92729:       sqlite3VdbeResolveLabel(v, endLabel);
92730:       break;
92731:     }
92732: #ifndef SQLITE_OMIT_TRIGGER
92733:     case TK_RAISE: {
92734:       assert( pExpr->affinity==OE_Rollback 
92735:            || pExpr->affinity==OE_Abort
92736:            || pExpr->affinity==OE_Fail
92737:            || pExpr->affinity==OE_Ignore
92738:       );
92739:       if( !pParse->pTriggerTab ){
92740:         sqlite3ErrorMsg(pParse,
92741:                        "RAISE() may only be used within a trigger-program");
92742:         return 0;
92743:       }
92744:       if( pExpr->affinity==OE_Abort ){
92745:         sqlite3MayAbort(pParse);
92746:       }
92747:       assert( !ExprHasProperty(pExpr, EP_IntValue) );
92748:       if( pExpr->affinity==OE_Ignore ){
92749:         sqlite3VdbeAddOp4(
92750:             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
92751:         VdbeCoverage(v);
92752:       }else{
92753:         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
92754:                               pExpr->affinity, pExpr->u.zToken, 0, 0);
92755:       }
92756: 
92757:       break;
92758:     }
92759: #endif
92760:   }
92761:   sqlite3ReleaseTempReg(pParse, regFree1);
92762:   sqlite3ReleaseTempReg(pParse, regFree2);
92763:   return inReg;
92764: }
92765: 
92766: /*
92767: ** Factor out the code of the given expression to initialization time.
92768: */
92769: SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
92770:   Parse *pParse,    /* Parsing context */
92771:   Expr *pExpr,      /* The expression to code when the VDBE initializes */
92772:   int regDest,      /* Store the value in this register */
92773:   u8 reusable       /* True if this expression is reusable */
92774: ){
92775:   ExprList *p;
92776:   assert( ConstFactorOk(pParse) );
92777:   p = pParse->pConstExpr;
92778:   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
92779:   p = sqlite3ExprListAppend(pParse, p, pExpr);
92780:   if( p ){
92781:      struct ExprList_item *pItem = &p->a[p->nExpr-1];
92782:      pItem->u.iConstExprReg = regDest;
92783:      pItem->reusable = reusable;
92784:   }
92785:   pParse->pConstExpr = p;
92786: }
92787: 
92788: /*
92789: ** Generate code to evaluate an expression and store the results
92790: ** into a register.  Return the register number where the results
92791: ** are stored.
92792: **
92793: ** If the register is a temporary register that can be deallocated,
92794: ** then write its number into *pReg.  If the result register is not
92795: ** a temporary, then set *pReg to zero.
92796: **
92797: ** If pExpr is a constant, then this routine might generate this
92798: ** code to fill the register in the initialization section of the
92799: ** VDBE program, in order to factor it out of the evaluation loop.
92800: */
92801: SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
92802:   int r2;
92803:   pExpr = sqlite3ExprSkipCollate(pExpr);
92804:   if( ConstFactorOk(pParse)
92805:    && pExpr->op!=TK_REGISTER
92806:    && sqlite3ExprIsConstantNotJoin(pExpr)
92807:   ){
92808:     ExprList *p = pParse->pConstExpr;
92809:     int i;
92810:     *pReg  = 0;
92811:     if( p ){
92812:       struct ExprList_item *pItem;
92813:       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
92814:         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
92815:           return pItem->u.iConstExprReg;
92816:         }
92817:       }
92818:     }
92819:     r2 = ++pParse->nMem;
92820:     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
92821:   }else{
92822:     int r1 = sqlite3GetTempReg(pParse);
92823:     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
92824:     if( r2==r1 ){
92825:       *pReg = r1;
92826:     }else{
92827:       sqlite3ReleaseTempReg(pParse, r1);
92828:       *pReg = 0;
92829:     }
92830:   }
92831:   return r2;
92832: }
92833: 
92834: /*
92835: ** Generate code that will evaluate expression pExpr and store the
92836: ** results in register target.  The results are guaranteed to appear
92837: ** in register target.
92838: */
92839: SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
92840:   int inReg;
92841: 
92842:   assert( target>0 && target<=pParse->nMem );
92843:   if( pExpr && pExpr->op==TK_REGISTER ){
92844:     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
92845:   }else{
92846:     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
92847:     assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
92848:     if( inReg!=target && pParse->pVdbe ){
92849:       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
92850:     }
92851:   }
92852: }
92853: 
92854: /*
92855: ** Make a transient copy of expression pExpr and then code it using
92856: ** sqlite3ExprCode().  This routine works just like sqlite3ExprCode()
92857: ** except that the input expression is guaranteed to be unchanged.
92858: */
92859: SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
92860:   sqlite3 *db = pParse->db;
92861:   pExpr = sqlite3ExprDup(db, pExpr, 0);
92862:   if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
92863:   sqlite3ExprDelete(db, pExpr);
92864: }
92865: 
92866: /*
92867: ** Generate code that will evaluate expression pExpr and store the
92868: ** results in register target.  The results are guaranteed to appear
92869: ** in register target.  If the expression is constant, then this routine
92870: ** might choose to code the expression at initialization time.
92871: */
92872: SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
92873:   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
92874:     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
92875:   }else{
92876:     sqlite3ExprCode(pParse, pExpr, target);
92877:   }
92878: }
92879: 
92880: /*
92881: ** Generate code that evaluates the given expression and puts the result
92882: ** in register target.
92883: **
92884: ** Also make a copy of the expression results into another "cache" register
92885: ** and modify the expression so that the next time it is evaluated,
92886: ** the result is a copy of the cache register.
92887: **
92888: ** This routine is used for expressions that are used multiple 
92889: ** times.  They are evaluated once and the results of the expression
92890: ** are reused.
92891: */
92892: SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
92893:   Vdbe *v = pParse->pVdbe;
92894:   int iMem;
92895: 
92896:   assert( target>0 );
92897:   assert( pExpr->op!=TK_REGISTER );
92898:   sqlite3ExprCode(pParse, pExpr, target);
92899:   iMem = ++pParse->nMem;
92900:   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
92901:   exprToRegister(pExpr, iMem);
92902: }
92903: 
92904: /*
92905: ** Generate code that pushes the value of every element of the given
92906: ** expression list into a sequence of registers beginning at target.
92907: **
92908: ** Return the number of elements evaluated.
92909: **
92910: ** The SQLITE_ECEL_DUP flag prevents the arguments from being
92911: ** filled using OP_SCopy.  OP_Copy must be used instead.
92912: **
92913: ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
92914: ** factored out into initialization code.
92915: **
92916: ** The SQLITE_ECEL_REF flag means that expressions in the list with
92917: ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
92918: ** in registers at srcReg, and so the value can be copied from there.
92919: */
92920: SQLITE_PRIVATE int sqlite3ExprCodeExprList(
92921:   Parse *pParse,     /* Parsing context */
92922:   ExprList *pList,   /* The expression list to be coded */
92923:   int target,        /* Where to write results */
92924:   int srcReg,        /* Source registers if SQLITE_ECEL_REF */
92925:   u8 flags           /* SQLITE_ECEL_* flags */
92926: ){
92927:   struct ExprList_item *pItem;
92928:   int i, j, n;
92929:   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
92930:   Vdbe *v = pParse->pVdbe;
92931:   assert( pList!=0 );
92932:   assert( target>0 );
92933:   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
92934:   n = pList->nExpr;
92935:   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
92936:   for(pItem=pList->a, i=0; i<n; i++, pItem++){
92937:     Expr *pExpr = pItem->pExpr;
92938:     if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
92939:       sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
92940:     }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
92941:       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
92942:     }else{
92943:       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
92944:       if( inReg!=target+i ){
92945:         VdbeOp *pOp;
92946:         if( copyOp==OP_Copy
92947:          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
92948:          && pOp->p1+pOp->p3+1==inReg
92949:          && pOp->p2+pOp->p3+1==target+i
92950:         ){
92951:           pOp->p3++;
92952:         }else{
92953:           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
92954:         }
92955:       }
92956:     }
92957:   }
92958:   return n;
92959: }
92960: 
92961: /*
92962: ** Generate code for a BETWEEN operator.
92963: **
92964: **    x BETWEEN y AND z
92965: **
92966: ** The above is equivalent to 
92967: **
92968: **    x>=y AND x<=z
92969: **
92970: ** Code it as such, taking care to do the common subexpression
92971: ** elimination of x.
92972: */
92973: static void exprCodeBetween(
92974:   Parse *pParse,    /* Parsing and code generating context */
92975:   Expr *pExpr,      /* The BETWEEN expression */
92976:   int dest,         /* Jump here if the jump is taken */
92977:   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
92978:   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
92979: ){
92980:   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
92981:   Expr compLeft;    /* The  x>=y  term */
92982:   Expr compRight;   /* The  x<=z  term */
92983:   Expr exprX;       /* The  x  subexpression */
92984:   int regFree1 = 0; /* Temporary use register */
92985: 
92986:   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92987:   exprX = *pExpr->pLeft;
92988:   exprAnd.op = TK_AND;
92989:   exprAnd.pLeft = &compLeft;
92990:   exprAnd.pRight = &compRight;
92991:   compLeft.op = TK_GE;
92992:   compLeft.pLeft = &exprX;
92993:   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
92994:   compRight.op = TK_LE;
92995:   compRight.pLeft = &exprX;
92996:   compRight.pRight = pExpr->x.pList->a[1].pExpr;
92997:   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
92998:   if( jumpIfTrue ){
92999:     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
93000:   }else{
93001:     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
93002:   }
93003:   sqlite3ReleaseTempReg(pParse, regFree1);
93004: 
93005:   /* Ensure adequate test coverage */
93006:   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
93007:   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
93008:   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
93009:   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
93010:   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
93011:   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
93012:   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
93013:   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
93014: }
93015: 
93016: /*
93017: ** Generate code for a boolean expression such that a jump is made
93018: ** to the label "dest" if the expression is true but execution
93019: ** continues straight thru if the expression is false.
93020: **
93021: ** If the expression evaluates to NULL (neither true nor false), then
93022: ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
93023: **
93024: ** This code depends on the fact that certain token values (ex: TK_EQ)
93025: ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
93026: ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
93027: ** the make process cause these values to align.  Assert()s in the code
93028: ** below verify that the numbers are aligned correctly.
93029: */
93030: SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93031:   Vdbe *v = pParse->pVdbe;
93032:   int op = 0;
93033:   int regFree1 = 0;
93034:   int regFree2 = 0;
93035:   int r1, r2;
93036: 
93037:   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93038:   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
93039:   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
93040:   op = pExpr->op;
93041:   switch( op ){
93042:     case TK_AND: {
93043:       int d2 = sqlite3VdbeMakeLabel(v);
93044:       testcase( jumpIfNull==0 );
93045:       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
93046:       sqlite3ExprCachePush(pParse);
93047:       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93048:       sqlite3VdbeResolveLabel(v, d2);
93049:       sqlite3ExprCachePop(pParse);
93050:       break;
93051:     }
93052:     case TK_OR: {
93053:       testcase( jumpIfNull==0 );
93054:       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93055:       sqlite3ExprCachePush(pParse);
93056:       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
93057:       sqlite3ExprCachePop(pParse);
93058:       break;
93059:     }
93060:     case TK_NOT: {
93061:       testcase( jumpIfNull==0 );
93062:       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93063:       break;
93064:     }
93065:     case TK_IS:
93066:     case TK_ISNOT:
93067:       testcase( op==TK_IS );
93068:       testcase( op==TK_ISNOT );
93069:       op = (op==TK_IS) ? TK_EQ : TK_NE;
93070:       jumpIfNull = SQLITE_NULLEQ;
93071:       /* Fall thru */
93072:     case TK_LT:
93073:     case TK_LE:
93074:     case TK_GT:
93075:     case TK_GE:
93076:     case TK_NE:
93077:     case TK_EQ: {
93078:       testcase( jumpIfNull==0 );
93079:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93080:       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93081:       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93082:                   r1, r2, dest, jumpIfNull);
93083:       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93084:       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93085:       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93086:       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93087:       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93088:       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93089:       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93090:       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93091:       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93092:       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93093:       testcase( regFree1==0 );
93094:       testcase( regFree2==0 );
93095:       break;
93096:     }
93097:     case TK_ISNULL:
93098:     case TK_NOTNULL: {
93099:       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
93100:       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
93101:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93102:       sqlite3VdbeAddOp2(v, op, r1, dest);
93103:       VdbeCoverageIf(v, op==TK_ISNULL);
93104:       VdbeCoverageIf(v, op==TK_NOTNULL);
93105:       testcase( regFree1==0 );
93106:       break;
93107:     }
93108:     case TK_BETWEEN: {
93109:       testcase( jumpIfNull==0 );
93110:       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
93111:       break;
93112:     }
93113: #ifndef SQLITE_OMIT_SUBQUERY
93114:     case TK_IN: {
93115:       int destIfFalse = sqlite3VdbeMakeLabel(v);
93116:       int destIfNull = jumpIfNull ? dest : destIfFalse;
93117:       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
93118:       sqlite3VdbeGoto(v, dest);
93119:       sqlite3VdbeResolveLabel(v, destIfFalse);
93120:       break;
93121:     }
93122: #endif
93123:     default: {
93124:       if( exprAlwaysTrue(pExpr) ){
93125:         sqlite3VdbeGoto(v, dest);
93126:       }else if( exprAlwaysFalse(pExpr) ){
93127:         /* No-op */
93128:       }else{
93129:         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
93130:         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
93131:         VdbeCoverage(v);
93132:         testcase( regFree1==0 );
93133:         testcase( jumpIfNull==0 );
93134:       }
93135:       break;
93136:     }
93137:   }
93138:   sqlite3ReleaseTempReg(pParse, regFree1);
93139:   sqlite3ReleaseTempReg(pParse, regFree2);  
93140: }
93141: 
93142: /*
93143: ** Generate code for a boolean expression such that a jump is made
93144: ** to the label "dest" if the expression is false but execution
93145: ** continues straight thru if the expression is true.
93146: **
93147: ** If the expression evaluates to NULL (neither true nor false) then
93148: ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
93149: ** is 0.
93150: */
93151: SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
93152:   Vdbe *v = pParse->pVdbe;
93153:   int op = 0;
93154:   int regFree1 = 0;
93155:   int regFree2 = 0;
93156:   int r1, r2;
93157: 
93158:   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
93159:   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
93160:   if( pExpr==0 )    return;
93161: 
93162:   /* The value of pExpr->op and op are related as follows:
93163:   **
93164:   **       pExpr->op            op
93165:   **       ---------          ----------
93166:   **       TK_ISNULL          OP_NotNull
93167:   **       TK_NOTNULL         OP_IsNull
93168:   **       TK_NE              OP_Eq
93169:   **       TK_EQ              OP_Ne
93170:   **       TK_GT              OP_Le
93171:   **       TK_LE              OP_Gt
93172:   **       TK_GE              OP_Lt
93173:   **       TK_LT              OP_Ge
93174:   **
93175:   ** For other values of pExpr->op, op is undefined and unused.
93176:   ** The value of TK_ and OP_ constants are arranged such that we
93177:   ** can compute the mapping above using the following expression.
93178:   ** Assert()s verify that the computation is correct.
93179:   */
93180:   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
93181: 
93182:   /* Verify correct alignment of TK_ and OP_ constants
93183:   */
93184:   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
93185:   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
93186:   assert( pExpr->op!=TK_NE || op==OP_Eq );
93187:   assert( pExpr->op!=TK_EQ || op==OP_Ne );
93188:   assert( pExpr->op!=TK_LT || op==OP_Ge );
93189:   assert( pExpr->op!=TK_LE || op==OP_Gt );
93190:   assert( pExpr->op!=TK_GT || op==OP_Le );
93191:   assert( pExpr->op!=TK_GE || op==OP_Lt );
93192: 
93193:   switch( pExpr->op ){
93194:     case TK_AND: {
93195:       testcase( jumpIfNull==0 );
93196:       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
93197:       sqlite3ExprCachePush(pParse);
93198:       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
93199:       sqlite3ExprCachePop(pParse);
93200:       break;
93201:     }
93202:     case TK_OR: {
93203:       int d2 = sqlite3VdbeMakeLabel(v);
93204:       testcase( jumpIfNull==0 );
93205:       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
93206:       sqlite3ExprCachePush(pParse);
93207:       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
93208:       sqlite3VdbeResolveLabel(v, d2);
93209:       sqlite3ExprCachePop(pParse);
93210:       break;
93211:     }
93212:     case TK_NOT: {
93213:       testcase( jumpIfNull==0 );
93214:       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
93215:       break;
93216:     }
93217:     case TK_IS:
93218:     case TK_ISNOT:
93219:       testcase( pExpr->op==TK_IS );
93220:       testcase( pExpr->op==TK_ISNOT );
93221:       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
93222:       jumpIfNull = SQLITE_NULLEQ;
93223:       /* Fall thru */
93224:     case TK_LT:
93225:     case TK_LE:
93226:     case TK_GT:
93227:     case TK_GE:
93228:     case TK_NE:
93229:     case TK_EQ: {
93230:       testcase( jumpIfNull==0 );
93231:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93232:       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
93233:       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
93234:                   r1, r2, dest, jumpIfNull);
93235:       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
93236:       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
93237:       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
93238:       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
93239:       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
93240:       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
93241:       VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
93242:       assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
93243:       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
93244:       VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
93245:       testcase( regFree1==0 );
93246:       testcase( regFree2==0 );
93247:       break;
93248:     }
93249:     case TK_ISNULL:
93250:     case TK_NOTNULL: {
93251:       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
93252:       sqlite3VdbeAddOp2(v, op, r1, dest);
93253:       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
93254:       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
93255:       testcase( regFree1==0 );
93256:       break;
93257:     }
93258:     case TK_BETWEEN: {
93259:       testcase( jumpIfNull==0 );
93260:       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
93261:       break;
93262:     }
93263: #ifndef SQLITE_OMIT_SUBQUERY
93264:     case TK_IN: {
93265:       if( jumpIfNull ){
93266:         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
93267:       }else{
93268:         int destIfNull = sqlite3VdbeMakeLabel(v);
93269:         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
93270:         sqlite3VdbeResolveLabel(v, destIfNull);
93271:       }
93272:       break;
93273:     }
93274: #endif
93275:     default: {
93276:       if( exprAlwaysFalse(pExpr) ){
93277:         sqlite3VdbeGoto(v, dest);
93278:       }else if( exprAlwaysTrue(pExpr) ){
93279:         /* no-op */
93280:       }else{
93281:         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
93282:         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
93283:         VdbeCoverage(v);
93284:         testcase( regFree1==0 );
93285:         testcase( jumpIfNull==0 );
93286:       }
93287:       break;
93288:     }
93289:   }
93290:   sqlite3ReleaseTempReg(pParse, regFree1);
93291:   sqlite3ReleaseTempReg(pParse, regFree2);
93292: }
93293: 
93294: /*
93295: ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
93296: ** code generation, and that copy is deleted after code generation. This
93297: ** ensures that the original pExpr is unchanged.
93298: */
93299: SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
93300:   sqlite3 *db = pParse->db;
93301:   Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
93302:   if( db->mallocFailed==0 ){
93303:     sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
93304:   }
93305:   sqlite3ExprDelete(db, pCopy);
93306: }
93307: 
93308: 
93309: /*
93310: ** Do a deep comparison of two expression trees.  Return 0 if the two
93311: ** expressions are completely identical.  Return 1 if they differ only
93312: ** by a COLLATE operator at the top level.  Return 2 if there are differences
93313: ** other than the top-level COLLATE operator.
93314: **
93315: ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
93316: ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
93317: **
93318: ** The pA side might be using TK_REGISTER.  If that is the case and pB is
93319: ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
93320: **
93321: ** Sometimes this routine will return 2 even if the two expressions
93322: ** really are equivalent.  If we cannot prove that the expressions are
93323: ** identical, we return 2 just to be safe.  So if this routine
93324: ** returns 2, then you do not really know for certain if the two
93325: ** expressions are the same.  But if you get a 0 or 1 return, then you
93326: ** can be sure the expressions are the same.  In the places where
93327: ** this routine is used, it does not hurt to get an extra 2 - that
93328: ** just might result in some slightly slower code.  But returning
93329: ** an incorrect 0 or 1 could lead to a malfunction.
93330: */
93331: SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
93332:   u32 combinedFlags;
93333:   if( pA==0 || pB==0 ){
93334:     return pB==pA ? 0 : 2;
93335:   }
93336:   combinedFlags = pA->flags | pB->flags;
93337:   if( combinedFlags & EP_IntValue ){
93338:     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
93339:       return 0;
93340:     }
93341:     return 2;
93342:   }
93343:   if( pA->op!=pB->op ){
93344:     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
93345:       return 1;
93346:     }
93347:     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
93348:       return 1;
93349:     }
93350:     return 2;
93351:   }
93352:   if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
93353:     if( pA->op==TK_FUNCTION ){
93354:       if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
93355:     }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
93356:       return pA->op==TK_COLLATE ? 1 : 2;
93357:     }
93358:   }
93359:   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
93360:   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
93361:     if( combinedFlags & EP_xIsSelect ) return 2;
93362:     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
93363:     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
93364:     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
93365:     if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
93366:       if( pA->iColumn!=pB->iColumn ) return 2;
93367:       if( pA->iTable!=pB->iTable 
93368:        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
93369:     }
93370:   }
93371:   return 0;
93372: }
93373: 
93374: /*
93375: ** Compare two ExprList objects.  Return 0 if they are identical and 
93376: ** non-zero if they differ in any way.
93377: **
93378: ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
93379: ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
93380: **
93381: ** This routine might return non-zero for equivalent ExprLists.  The
93382: ** only consequence will be disabled optimizations.  But this routine
93383: ** must never return 0 if the two ExprList objects are different, or
93384: ** a malfunction will result.
93385: **
93386: ** Two NULL pointers are considered to be the same.  But a NULL pointer
93387: ** always differs from a non-NULL pointer.
93388: */
93389: SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
93390:   int i;
93391:   if( pA==0 && pB==0 ) return 0;
93392:   if( pA==0 || pB==0 ) return 1;
93393:   if( pA->nExpr!=pB->nExpr ) return 1;
93394:   for(i=0; i<pA->nExpr; i++){
93395:     Expr *pExprA = pA->a[i].pExpr;
93396:     Expr *pExprB = pB->a[i].pExpr;
93397:     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
93398:     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
93399:   }
93400:   return 0;
93401: }
93402: 
93403: /*
93404: ** Return true if we can prove the pE2 will always be true if pE1 is
93405: ** true.  Return false if we cannot complete the proof or if pE2 might
93406: ** be false.  Examples:
93407: **
93408: **     pE1: x==5       pE2: x==5             Result: true
93409: **     pE1: x>0        pE2: x==5             Result: false
93410: **     pE1: x=21       pE2: x=21 OR y=43     Result: true
93411: **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
93412: **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
93413: **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
93414: **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
93415: **
93416: ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
93417: ** Expr.iTable<0 then assume a table number given by iTab.
93418: **
93419: ** When in doubt, return false.  Returning true might give a performance
93420: ** improvement.  Returning false might cause a performance reduction, but
93421: ** it will always give the correct answer and is hence always safe.
93422: */
93423: SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
93424:   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
93425:     return 1;
93426:   }
93427:   if( pE2->op==TK_OR
93428:    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
93429:              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
93430:   ){
93431:     return 1;
93432:   }
93433:   if( pE2->op==TK_NOTNULL
93434:    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
93435:    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
93436:   ){
93437:     return 1;
93438:   }
93439:   return 0;
93440: }
93441: 
93442: /*
93443: ** An instance of the following structure is used by the tree walker
93444: ** to determine if an expression can be evaluated by reference to the
93445: ** index only, without having to do a search for the corresponding
93446: ** table entry.  The IdxCover.pIdx field is the index.  IdxCover.iCur
93447: ** is the cursor for the table.
93448: */
93449: struct IdxCover {
93450:   Index *pIdx;     /* The index to be tested for coverage */
93451:   int iCur;        /* Cursor number for the table corresponding to the index */
93452: };
93453: 
93454: /*
93455: ** Check to see if there are references to columns in table 
93456: ** pWalker->u.pIdxCover->iCur can be satisfied using the index
93457: ** pWalker->u.pIdxCover->pIdx.
93458: */
93459: static int exprIdxCover(Walker *pWalker, Expr *pExpr){
93460:   if( pExpr->op==TK_COLUMN
93461:    && pExpr->iTable==pWalker->u.pIdxCover->iCur
93462:    && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
93463:   ){
93464:     pWalker->eCode = 1;
93465:     return WRC_Abort;
93466:   }
93467:   return WRC_Continue;
93468: }
93469: 
93470: /*
93471: ** Determine if an index pIdx on table with cursor iCur contains will
93472: ** the expression pExpr.  Return true if the index does cover the
93473: ** expression and false if the pExpr expression references table columns
93474: ** that are not found in the index pIdx.
93475: **
93476: ** An index covering an expression means that the expression can be
93477: ** evaluated using only the index and without having to lookup the
93478: ** corresponding table entry.
93479: */
93480: SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
93481:   Expr *pExpr,        /* The index to be tested */
93482:   int iCur,           /* The cursor number for the corresponding table */
93483:   Index *pIdx         /* The index that might be used for coverage */
93484: ){
93485:   Walker w;
93486:   struct IdxCover xcov;
93487:   memset(&w, 0, sizeof(w));
93488:   xcov.iCur = iCur;
93489:   xcov.pIdx = pIdx;
93490:   w.xExprCallback = exprIdxCover;
93491:   w.u.pIdxCover = &xcov;
93492:   sqlite3WalkExpr(&w, pExpr);
93493:   return !w.eCode;
93494: }
93495: 
93496: 
93497: /*
93498: ** An instance of the following structure is used by the tree walker
93499: ** to count references to table columns in the arguments of an 
93500: ** aggregate function, in order to implement the
93501: ** sqlite3FunctionThisSrc() routine.
93502: */
93503: struct SrcCount {
93504:   SrcList *pSrc;   /* One particular FROM clause in a nested query */
93505:   int nThis;       /* Number of references to columns in pSrcList */
93506:   int nOther;      /* Number of references to columns in other FROM clauses */
93507: };
93508: 
93509: /*
93510: ** Count the number of references to columns.
93511: */
93512: static int exprSrcCount(Walker *pWalker, Expr *pExpr){
93513:   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
93514:   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
93515:   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
93516:   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
93517:   ** NEVER() will need to be removed. */
93518:   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
93519:     int i;
93520:     struct SrcCount *p = pWalker->u.pSrcCount;
93521:     SrcList *pSrc = p->pSrc;
93522:     int nSrc = pSrc ? pSrc->nSrc : 0;
93523:     for(i=0; i<nSrc; i++){
93524:       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
93525:     }
93526:     if( i<nSrc ){
93527:       p->nThis++;
93528:     }else{
93529:       p->nOther++;
93530:     }
93531:   }
93532:   return WRC_Continue;
93533: }
93534: 
93535: /*
93536: ** Determine if any of the arguments to the pExpr Function reference
93537: ** pSrcList.  Return true if they do.  Also return true if the function
93538: ** has no arguments or has only constant arguments.  Return false if pExpr
93539: ** references columns but not columns of tables found in pSrcList.
93540: */
93541: SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
93542:   Walker w;
93543:   struct SrcCount cnt;
93544:   assert( pExpr->op==TK_AGG_FUNCTION );
93545:   memset(&w, 0, sizeof(w));
93546:   w.xExprCallback = exprSrcCount;
93547:   w.u.pSrcCount = &cnt;
93548:   cnt.pSrc = pSrcList;
93549:   cnt.nThis = 0;
93550:   cnt.nOther = 0;
93551:   sqlite3WalkExprList(&w, pExpr->x.pList);
93552:   return cnt.nThis>0 || cnt.nOther==0;
93553: }
93554: 
93555: /*
93556: ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
93557: ** the new element.  Return a negative number if malloc fails.
93558: */
93559: static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
93560:   int i;
93561:   pInfo->aCol = sqlite3ArrayAllocate(
93562:        db,
93563:        pInfo->aCol,
93564:        sizeof(pInfo->aCol[0]),
93565:        &pInfo->nColumn,
93566:        &i
93567:   );
93568:   return i;
93569: }    
93570: 
93571: /*
93572: ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
93573: ** the new element.  Return a negative number if malloc fails.
93574: */
93575: static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
93576:   int i;
93577:   pInfo->aFunc = sqlite3ArrayAllocate(
93578:        db, 
93579:        pInfo->aFunc,
93580:        sizeof(pInfo->aFunc[0]),
93581:        &pInfo->nFunc,
93582:        &i
93583:   );
93584:   return i;
93585: }    
93586: 
93587: /*
93588: ** This is the xExprCallback for a tree walker.  It is used to
93589: ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
93590: ** for additional information.
93591: */
93592: static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
93593:   int i;
93594:   NameContext *pNC = pWalker->u.pNC;
93595:   Parse *pParse = pNC->pParse;
93596:   SrcList *pSrcList = pNC->pSrcList;
93597:   AggInfo *pAggInfo = pNC->pAggInfo;
93598: 
93599:   switch( pExpr->op ){
93600:     case TK_AGG_COLUMN:
93601:     case TK_COLUMN: {
93602:       testcase( pExpr->op==TK_AGG_COLUMN );
93603:       testcase( pExpr->op==TK_COLUMN );
93604:       /* Check to see if the column is in one of the tables in the FROM
93605:       ** clause of the aggregate query */
93606:       if( ALWAYS(pSrcList!=0) ){
93607:         struct SrcList_item *pItem = pSrcList->a;
93608:         for(i=0; i<pSrcList->nSrc; i++, pItem++){
93609:           struct AggInfo_col *pCol;
93610:           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
93611:           if( pExpr->iTable==pItem->iCursor ){
93612:             /* If we reach this point, it means that pExpr refers to a table
93613:             ** that is in the FROM clause of the aggregate query.  
93614:             **
93615:             ** Make an entry for the column in pAggInfo->aCol[] if there
93616:             ** is not an entry there already.
93617:             */
93618:             int k;
93619:             pCol = pAggInfo->aCol;
93620:             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
93621:               if( pCol->iTable==pExpr->iTable &&
93622:                   pCol->iColumn==pExpr->iColumn ){
93623:                 break;
93624:               }
93625:             }
93626:             if( (k>=pAggInfo->nColumn)
93627:              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
93628:             ){
93629:               pCol = &pAggInfo->aCol[k];
93630:               pCol->pTab = pExpr->pTab;
93631:               pCol->iTable = pExpr->iTable;
93632:               pCol->iColumn = pExpr->iColumn;
93633:               pCol->iMem = ++pParse->nMem;
93634:               pCol->iSorterColumn = -1;
93635:               pCol->pExpr = pExpr;
93636:               if( pAggInfo->pGroupBy ){
93637:                 int j, n;
93638:                 ExprList *pGB = pAggInfo->pGroupBy;
93639:                 struct ExprList_item *pTerm = pGB->a;
93640:                 n = pGB->nExpr;
93641:                 for(j=0; j<n; j++, pTerm++){
93642:                   Expr *pE = pTerm->pExpr;
93643:                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
93644:                       pE->iColumn==pExpr->iColumn ){
93645:                     pCol->iSorterColumn = j;
93646:                     break;
93647:                   }
93648:                 }
93649:               }
93650:               if( pCol->iSorterColumn<0 ){
93651:                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
93652:               }
93653:             }
93654:             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
93655:             ** because it was there before or because we just created it).
93656:             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
93657:             ** pAggInfo->aCol[] entry.
93658:             */
93659:             ExprSetVVAProperty(pExpr, EP_NoReduce);
93660:             pExpr->pAggInfo = pAggInfo;
93661:             pExpr->op = TK_AGG_COLUMN;
93662:             pExpr->iAgg = (i16)k;
93663:             break;
93664:           } /* endif pExpr->iTable==pItem->iCursor */
93665:         } /* end loop over pSrcList */
93666:       }
93667:       return WRC_Prune;
93668:     }
93669:     case TK_AGG_FUNCTION: {
93670:       if( (pNC->ncFlags & NC_InAggFunc)==0
93671:        && pWalker->walkerDepth==pExpr->op2
93672:       ){
93673:         /* Check to see if pExpr is a duplicate of another aggregate 
93674:         ** function that is already in the pAggInfo structure
93675:         */
93676:         struct AggInfo_func *pItem = pAggInfo->aFunc;
93677:         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
93678:           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
93679:             break;
93680:           }
93681:         }
93682:         if( i>=pAggInfo->nFunc ){
93683:           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
93684:           */
93685:           u8 enc = ENC(pParse->db);
93686:           i = addAggInfoFunc(pParse->db, pAggInfo);
93687:           if( i>=0 ){
93688:             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93689:             pItem = &pAggInfo->aFunc[i];
93690:             pItem->pExpr = pExpr;
93691:             pItem->iMem = ++pParse->nMem;
93692:             assert( !ExprHasProperty(pExpr, EP_IntValue) );
93693:             pItem->pFunc = sqlite3FindFunction(pParse->db,
93694:                    pExpr->u.zToken, 
93695:                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
93696:             if( pExpr->flags & EP_Distinct ){
93697:               pItem->iDistinct = pParse->nTab++;
93698:             }else{
93699:               pItem->iDistinct = -1;
93700:             }
93701:           }
93702:         }
93703:         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
93704:         */
93705:         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
93706:         ExprSetVVAProperty(pExpr, EP_NoReduce);
93707:         pExpr->iAgg = (i16)i;
93708:         pExpr->pAggInfo = pAggInfo;
93709:         return WRC_Prune;
93710:       }else{
93711:         return WRC_Continue;
93712:       }
93713:     }
93714:   }
93715:   return WRC_Continue;
93716: }
93717: static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
93718:   UNUSED_PARAMETER(pWalker);
93719:   UNUSED_PARAMETER(pSelect);
93720:   return WRC_Continue;
93721: }
93722: 
93723: /*
93724: ** Analyze the pExpr expression looking for aggregate functions and
93725: ** for variables that need to be added to AggInfo object that pNC->pAggInfo
93726: ** points to.  Additional entries are made on the AggInfo object as
93727: ** necessary.
93728: **
93729: ** This routine should only be called after the expression has been
93730: ** analyzed by sqlite3ResolveExprNames().
93731: */
93732: SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
93733:   Walker w;
93734:   memset(&w, 0, sizeof(w));
93735:   w.xExprCallback = analyzeAggregate;
93736:   w.xSelectCallback = analyzeAggregatesInSelect;
93737:   w.u.pNC = pNC;
93738:   assert( pNC->pSrcList!=0 );
93739:   sqlite3WalkExpr(&w, pExpr);
93740: }
93741: 
93742: /*
93743: ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
93744: ** expression list.  Return the number of errors.
93745: **
93746: ** If an error is found, the analysis is cut short.
93747: */
93748: SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
93749:   struct ExprList_item *pItem;
93750:   int i;
93751:   if( pList ){
93752:     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
93753:       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
93754:     }
93755:   }
93756: }
93757: 
93758: /*
93759: ** Allocate a single new register for use to hold some intermediate result.
93760: */
93761: SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
93762:   if( pParse->nTempReg==0 ){
93763:     return ++pParse->nMem;
93764:   }
93765:   return pParse->aTempReg[--pParse->nTempReg];
93766: }
93767: 
93768: /*
93769: ** Deallocate a register, making available for reuse for some other
93770: ** purpose.
93771: **
93772: ** If a register is currently being used by the column cache, then
93773: ** the deallocation is deferred until the column cache line that uses
93774: ** the register becomes stale.
93775: */
93776: SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
93777:   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
93778:     int i;
93779:     struct yColCache *p;
93780:     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
93781:       if( p->iReg==iReg ){
93782:         p->tempReg = 1;
93783:         return;
93784:       }
93785:     }
93786:     pParse->aTempReg[pParse->nTempReg++] = iReg;
93787:   }
93788: }
93789: 
93790: /*
93791: ** Allocate or deallocate a block of nReg consecutive registers
93792: */
93793: SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
93794:   int i, n;
93795:   i = pParse->iRangeReg;
93796:   n = pParse->nRangeReg;
93797:   if( nReg<=n ){
93798:     assert( !usedAsColumnCache(pParse, i, i+n-1) );
93799:     pParse->iRangeReg += nReg;
93800:     pParse->nRangeReg -= nReg;
93801:   }else{
93802:     i = pParse->nMem+1;
93803:     pParse->nMem += nReg;
93804:   }
93805:   return i;
93806: }
93807: SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
93808:   sqlite3ExprCacheRemove(pParse, iReg, nReg);
93809:   if( nReg>pParse->nRangeReg ){
93810:     pParse->nRangeReg = nReg;
93811:     pParse->iRangeReg = iReg;
93812:   }
93813: }
93814: 
93815: /*
93816: ** Mark all temporary registers as being unavailable for reuse.
93817: */
93818: SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
93819:   pParse->nTempReg = 0;
93820:   pParse->nRangeReg = 0;
93821: }
93822: 
93823: /*
93824: ** Validate that no temporary register falls within the range of
93825: ** iFirst..iLast, inclusive.  This routine is only call from within assert()
93826: ** statements.
93827: */
93828: #ifdef SQLITE_DEBUG
93829: SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
93830:   int i;
93831:   if( pParse->nRangeReg>0
93832:    && pParse->iRangeReg+pParse->nRangeReg<iLast
93833:    && pParse->iRangeReg>=iFirst
93834:   ){
93835:      return 0;
93836:   }
93837:   for(i=0; i<pParse->nTempReg; i++){
93838:     if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
93839:       return 0;
93840:     }
93841:   }
93842:   return 1;
93843: }
93844: #endif /* SQLITE_DEBUG */
93845: 
93846: /************** End of expr.c ************************************************/
93847: /************** Begin file alter.c *******************************************/
93848: /*
93849: ** 2005 February 15
93850: **
93851: ** The author disclaims copyright to this source code.  In place of
93852: ** a legal notice, here is a blessing:
93853: **
93854: **    May you do good and not evil.
93855: **    May you find forgiveness for yourself and forgive others.
93856: **    May you share freely, never taking more than you give.
93857: **
93858: *************************************************************************
93859: ** This file contains C code routines that used to generate VDBE code
93860: ** that implements the ALTER TABLE command.
93861: */
93862: /* #include "sqliteInt.h" */
93863: 
93864: /*
93865: ** The code in this file only exists if we are not omitting the
93866: ** ALTER TABLE logic from the build.
93867: */
93868: #ifndef SQLITE_OMIT_ALTERTABLE
93869: 
93870: 
93871: /*
93872: ** This function is used by SQL generated to implement the 
93873: ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
93874: ** CREATE INDEX command. The second is a table name. The table name in 
93875: ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
93876: ** argument and the result returned. Examples:
93877: **
93878: ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
93879: **     -> 'CREATE TABLE def(a, b, c)'
93880: **
93881: ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
93882: **     -> 'CREATE INDEX i ON def(a, b, c)'
93883: */
93884: static void renameTableFunc(
93885:   sqlite3_context *context,
93886:   int NotUsed,
93887:   sqlite3_value **argv
93888: ){
93889:   unsigned char const *zSql = sqlite3_value_text(argv[0]);
93890:   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
93891: 
93892:   int token;
93893:   Token tname;
93894:   unsigned char const *zCsr = zSql;
93895:   int len = 0;
93896:   char *zRet;
93897: 
93898:   sqlite3 *db = sqlite3_context_db_handle(context);
93899: 
93900:   UNUSED_PARAMETER(NotUsed);
93901: 
93902:   /* The principle used to locate the table name in the CREATE TABLE 
93903:   ** statement is that the table name is the first non-space token that
93904:   ** is immediately followed by a TK_LP or TK_USING token.
93905:   */
93906:   if( zSql ){
93907:     do {
93908:       if( !*zCsr ){
93909:         /* Ran out of input before finding an opening bracket. Return NULL. */
93910:         return;
93911:       }
93912: 
93913:       /* Store the token that zCsr points to in tname. */
93914:       tname.z = (char*)zCsr;
93915:       tname.n = len;
93916: 
93917:       /* Advance zCsr to the next token. Store that token type in 'token',
93918:       ** and its length in 'len' (to be used next iteration of this loop).
93919:       */
93920:       do {
93921:         zCsr += len;
93922:         len = sqlite3GetToken(zCsr, &token);
93923:       } while( token==TK_SPACE );
93924:       assert( len>0 );
93925:     } while( token!=TK_LP && token!=TK_USING );
93926: 
93927:     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
93928:        zSql, zTableName, tname.z+tname.n);
93929:     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
93930:   }
93931: }
93932: 
93933: /*
93934: ** This C function implements an SQL user function that is used by SQL code
93935: ** generated by the ALTER TABLE ... RENAME command to modify the definition
93936: ** of any foreign key constraints that use the table being renamed as the 
93937: ** parent table. It is passed three arguments:
93938: **
93939: **   1) The complete text of the CREATE TABLE statement being modified,
93940: **   2) The old name of the table being renamed, and
93941: **   3) The new name of the table being renamed.
93942: **
93943: ** It returns the new CREATE TABLE statement. For example:
93944: **
93945: **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
93946: **       -> 'CREATE TABLE t1(a REFERENCES t3)'
93947: */
93948: #ifndef SQLITE_OMIT_FOREIGN_KEY
93949: static void renameParentFunc(
93950:   sqlite3_context *context,
93951:   int NotUsed,
93952:   sqlite3_value **argv
93953: ){
93954:   sqlite3 *db = sqlite3_context_db_handle(context);
93955:   char *zOutput = 0;
93956:   char *zResult;
93957:   unsigned char const *zInput = sqlite3_value_text(argv[0]);
93958:   unsigned char const *zOld = sqlite3_value_text(argv[1]);
93959:   unsigned char const *zNew = sqlite3_value_text(argv[2]);
93960: 
93961:   unsigned const char *z;         /* Pointer to token */
93962:   int n;                          /* Length of token z */
93963:   int token;                      /* Type of token */
93964: 
93965:   UNUSED_PARAMETER(NotUsed);
93966:   if( zInput==0 || zOld==0 ) return;
93967:   for(z=zInput; *z; z=z+n){
93968:     n = sqlite3GetToken(z, &token);
93969:     if( token==TK_REFERENCES ){
93970:       char *zParent;
93971:       do {
93972:         z += n;
93973:         n = sqlite3GetToken(z, &token);
93974:       }while( token==TK_SPACE );
93975: 
93976:       if( token==TK_ILLEGAL ) break;
93977:       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
93978:       if( zParent==0 ) break;
93979:       sqlite3Dequote(zParent);
93980:       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
93981:         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
93982:             (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
93983:         );
93984:         sqlite3DbFree(db, zOutput);
93985:         zOutput = zOut;
93986:         zInput = &z[n];
93987:       }
93988:       sqlite3DbFree(db, zParent);
93989:     }
93990:   }
93991: 
93992:   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
93993:   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
93994:   sqlite3DbFree(db, zOutput);
93995: }
93996: #endif
93997: 
93998: #ifndef SQLITE_OMIT_TRIGGER
93999: /* This function is used by SQL generated to implement the
94000: ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
94001: ** statement. The second is a table name. The table name in the CREATE 
94002: ** TRIGGER statement is replaced with the third argument and the result 
94003: ** returned. This is analagous to renameTableFunc() above, except for CREATE
94004: ** TRIGGER, not CREATE INDEX and CREATE TABLE.
94005: */
94006: static void renameTriggerFunc(
94007:   sqlite3_context *context,
94008:   int NotUsed,
94009:   sqlite3_value **argv
94010: ){
94011:   unsigned char const *zSql = sqlite3_value_text(argv[0]);
94012:   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
94013: 
94014:   int token;
94015:   Token tname;
94016:   int dist = 3;
94017:   unsigned char const *zCsr = zSql;
94018:   int len = 0;
94019:   char *zRet;
94020:   sqlite3 *db = sqlite3_context_db_handle(context);
94021: 
94022:   UNUSED_PARAMETER(NotUsed);
94023: 
94024:   /* The principle used to locate the table name in the CREATE TRIGGER 
94025:   ** statement is that the table name is the first token that is immediately
94026:   ** preceded by either TK_ON or TK_DOT and immediately followed by one
94027:   ** of TK_WHEN, TK_BEGIN or TK_FOR.
94028:   */
94029:   if( zSql ){
94030:     do {
94031: 
94032:       if( !*zCsr ){
94033:         /* Ran out of input before finding the table name. Return NULL. */
94034:         return;
94035:       }
94036: 
94037:       /* Store the token that zCsr points to in tname. */
94038:       tname.z = (char*)zCsr;
94039:       tname.n = len;
94040: 
94041:       /* Advance zCsr to the next token. Store that token type in 'token',
94042:       ** and its length in 'len' (to be used next iteration of this loop).
94043:       */
94044:       do {
94045:         zCsr += len;
94046:         len = sqlite3GetToken(zCsr, &token);
94047:       }while( token==TK_SPACE );
94048:       assert( len>0 );
94049: 
94050:       /* Variable 'dist' stores the number of tokens read since the most
94051:       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
94052:       ** token is read and 'dist' equals 2, the condition stated above
94053:       ** to be met.
94054:       **
94055:       ** Note that ON cannot be a database, table or column name, so
94056:       ** there is no need to worry about syntax like 
94057:       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
94058:       */
94059:       dist++;
94060:       if( token==TK_DOT || token==TK_ON ){
94061:         dist = 0;
94062:       }
94063:     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
94064: 
94065:     /* Variable tname now contains the token that is the old table-name
94066:     ** in the CREATE TRIGGER statement.
94067:     */
94068:     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
94069:        zSql, zTableName, tname.z+tname.n);
94070:     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
94071:   }
94072: }
94073: #endif   /* !SQLITE_OMIT_TRIGGER */
94074: 
94075: /*
94076: ** Register built-in functions used to help implement ALTER TABLE
94077: */
94078: SQLITE_PRIVATE void sqlite3AlterFunctions(void){
94079:   static FuncDef aAlterTableFuncs[] = {
94080:     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
94081: #ifndef SQLITE_OMIT_TRIGGER
94082:     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
94083: #endif
94084: #ifndef SQLITE_OMIT_FOREIGN_KEY
94085:     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
94086: #endif
94087:   };
94088:   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
94089: }
94090: 
94091: /*
94092: ** This function is used to create the text of expressions of the form:
94093: **
94094: **   name=<constant1> OR name=<constant2> OR ...
94095: **
94096: ** If argument zWhere is NULL, then a pointer string containing the text 
94097: ** "name=<constant>" is returned, where <constant> is the quoted version
94098: ** of the string passed as argument zConstant. The returned buffer is
94099: ** allocated using sqlite3DbMalloc(). It is the responsibility of the
94100: ** caller to ensure that it is eventually freed.
94101: **
94102: ** If argument zWhere is not NULL, then the string returned is 
94103: ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
94104: ** In this case zWhere is passed to sqlite3DbFree() before returning.
94105: ** 
94106: */
94107: static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
94108:   char *zNew;
94109:   if( !zWhere ){
94110:     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
94111:   }else{
94112:     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
94113:     sqlite3DbFree(db, zWhere);
94114:   }
94115:   return zNew;
94116: }
94117: 
94118: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94119: /*
94120: ** Generate the text of a WHERE expression which can be used to select all
94121: ** tables that have foreign key constraints that refer to table pTab (i.e.
94122: ** constraints for which pTab is the parent table) from the sqlite_master
94123: ** table.
94124: */
94125: static char *whereForeignKeys(Parse *pParse, Table *pTab){
94126:   FKey *p;
94127:   char *zWhere = 0;
94128:   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
94129:     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
94130:   }
94131:   return zWhere;
94132: }
94133: #endif
94134: 
94135: /*
94136: ** Generate the text of a WHERE expression which can be used to select all
94137: ** temporary triggers on table pTab from the sqlite_temp_master table. If
94138: ** table pTab has no temporary triggers, or is itself stored in the 
94139: ** temporary database, NULL is returned.
94140: */
94141: static char *whereTempTriggers(Parse *pParse, Table *pTab){
94142:   Trigger *pTrig;
94143:   char *zWhere = 0;
94144:   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
94145: 
94146:   /* If the table is not located in the temp-db (in which case NULL is 
94147:   ** returned, loop through the tables list of triggers. For each trigger
94148:   ** that is not part of the temp-db schema, add a clause to the WHERE 
94149:   ** expression being built up in zWhere.
94150:   */
94151:   if( pTab->pSchema!=pTempSchema ){
94152:     sqlite3 *db = pParse->db;
94153:     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
94154:       if( pTrig->pSchema==pTempSchema ){
94155:         zWhere = whereOrName(db, zWhere, pTrig->zName);
94156:       }
94157:     }
94158:   }
94159:   if( zWhere ){
94160:     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
94161:     sqlite3DbFree(pParse->db, zWhere);
94162:     zWhere = zNew;
94163:   }
94164:   return zWhere;
94165: }
94166: 
94167: /*
94168: ** Generate code to drop and reload the internal representation of table
94169: ** pTab from the database, including triggers and temporary triggers.
94170: ** Argument zName is the name of the table in the database schema at
94171: ** the time the generated code is executed. This can be different from
94172: ** pTab->zName if this function is being called to code part of an 
94173: ** "ALTER TABLE RENAME TO" statement.
94174: */
94175: static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
94176:   Vdbe *v;
94177:   char *zWhere;
94178:   int iDb;                   /* Index of database containing pTab */
94179: #ifndef SQLITE_OMIT_TRIGGER
94180:   Trigger *pTrig;
94181: #endif
94182: 
94183:   v = sqlite3GetVdbe(pParse);
94184:   if( NEVER(v==0) ) return;
94185:   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
94186:   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94187:   assert( iDb>=0 );
94188: 
94189: #ifndef SQLITE_OMIT_TRIGGER
94190:   /* Drop any table triggers from the internal schema. */
94191:   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
94192:     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
94193:     assert( iTrigDb==iDb || iTrigDb==1 );
94194:     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
94195:   }
94196: #endif
94197: 
94198:   /* Drop the table and index from the internal schema.  */
94199:   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
94200: 
94201:   /* Reload the table, index and permanent trigger schemas. */
94202:   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
94203:   if( !zWhere ) return;
94204:   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
94205: 
94206: #ifndef SQLITE_OMIT_TRIGGER
94207:   /* Now, if the table is not stored in the temp database, reload any temp 
94208:   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
94209:   */
94210:   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
94211:     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
94212:   }
94213: #endif
94214: }
94215: 
94216: /*
94217: ** Parameter zName is the name of a table that is about to be altered
94218: ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
94219: ** If the table is a system table, this function leaves an error message
94220: ** in pParse->zErr (system tables may not be altered) and returns non-zero.
94221: **
94222: ** Or, if zName is not a system table, zero is returned.
94223: */
94224: static int isSystemTable(Parse *pParse, const char *zName){
94225:   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
94226:     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
94227:     return 1;
94228:   }
94229:   return 0;
94230: }
94231: 
94232: /*
94233: ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
94234: ** command. 
94235: */
94236: SQLITE_PRIVATE void sqlite3AlterRenameTable(
94237:   Parse *pParse,            /* Parser context. */
94238:   SrcList *pSrc,            /* The table to rename. */
94239:   Token *pName              /* The new table name. */
94240: ){
94241:   int iDb;                  /* Database that contains the table */
94242:   char *zDb;                /* Name of database iDb */
94243:   Table *pTab;              /* Table being renamed */
94244:   char *zName = 0;          /* NULL-terminated version of pName */ 
94245:   sqlite3 *db = pParse->db; /* Database connection */
94246:   int nTabName;             /* Number of UTF-8 characters in zTabName */
94247:   const char *zTabName;     /* Original name of the table */
94248:   Vdbe *v;
94249: #ifndef SQLITE_OMIT_TRIGGER
94250:   char *zWhere = 0;         /* Where clause to locate temp triggers */
94251: #endif
94252:   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
94253:   int savedDbFlags;         /* Saved value of db->flags */
94254: 
94255:   savedDbFlags = db->flags;  
94256:   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
94257:   assert( pSrc->nSrc==1 );
94258:   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
94259: 
94260:   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
94261:   if( !pTab ) goto exit_rename_table;
94262:   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94263:   zDb = db->aDb[iDb].zName;
94264:   db->flags |= SQLITE_PreferBuiltin;
94265: 
94266:   /* Get a NULL terminated version of the new table name. */
94267:   zName = sqlite3NameFromToken(db, pName);
94268:   if( !zName ) goto exit_rename_table;
94269: 
94270:   /* Check that a table or index named 'zName' does not already exist
94271:   ** in database iDb. If so, this is an error.
94272:   */
94273:   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
94274:     sqlite3ErrorMsg(pParse, 
94275:         "there is already another table or index with this name: %s", zName);
94276:     goto exit_rename_table;
94277:   }
94278: 
94279:   /* Make sure it is not a system table being altered, or a reserved name
94280:   ** that the table is being renamed to.
94281:   */
94282:   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
94283:     goto exit_rename_table;
94284:   }
94285:   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
94286:     exit_rename_table;
94287:   }
94288: 
94289: #ifndef SQLITE_OMIT_VIEW
94290:   if( pTab->pSelect ){
94291:     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
94292:     goto exit_rename_table;
94293:   }
94294: #endif
94295: 
94296: #ifndef SQLITE_OMIT_AUTHORIZATION
94297:   /* Invoke the authorization callback. */
94298:   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
94299:     goto exit_rename_table;
94300:   }
94301: #endif
94302: 
94303: #ifndef SQLITE_OMIT_VIRTUALTABLE
94304:   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
94305:     goto exit_rename_table;
94306:   }
94307:   if( IsVirtual(pTab) ){
94308:     pVTab = sqlite3GetVTable(db, pTab);
94309:     if( pVTab->pVtab->pModule->xRename==0 ){
94310:       pVTab = 0;
94311:     }
94312:   }
94313: #endif
94314: 
94315:   /* Begin a transaction for database iDb. 
94316:   ** Then modify the schema cookie (since the ALTER TABLE modifies the
94317:   ** schema). Open a statement transaction if the table is a virtual
94318:   ** table.
94319:   */
94320:   v = sqlite3GetVdbe(pParse);
94321:   if( v==0 ){
94322:     goto exit_rename_table;
94323:   }
94324:   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
94325:   sqlite3ChangeCookie(pParse, iDb);
94326: 
94327:   /* If this is a virtual table, invoke the xRename() function if
94328:   ** one is defined. The xRename() callback will modify the names
94329:   ** of any resources used by the v-table implementation (including other
94330:   ** SQLite tables) that are identified by the name of the virtual table.
94331:   */
94332: #ifndef SQLITE_OMIT_VIRTUALTABLE
94333:   if( pVTab ){
94334:     int i = ++pParse->nMem;
94335:     sqlite3VdbeLoadString(v, i, zName);
94336:     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
94337:     sqlite3MayAbort(pParse);
94338:   }
94339: #endif
94340: 
94341:   /* figure out how many UTF-8 characters are in zName */
94342:   zTabName = pTab->zName;
94343:   nTabName = sqlite3Utf8CharLen(zTabName, -1);
94344: 
94345: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94346:   if( db->flags&SQLITE_ForeignKeys ){
94347:     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
94348:     ** statements corresponding to all child tables of foreign key constraints
94349:     ** for which the renamed table is the parent table.  */
94350:     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
94351:       sqlite3NestedParse(pParse, 
94352:           "UPDATE \"%w\".%s SET "
94353:               "sql = sqlite_rename_parent(sql, %Q, %Q) "
94354:               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
94355:       sqlite3DbFree(db, zWhere);
94356:     }
94357:   }
94358: #endif
94359: 
94360:   /* Modify the sqlite_master table to use the new table name. */
94361:   sqlite3NestedParse(pParse,
94362:       "UPDATE %Q.%s SET "
94363: #ifdef SQLITE_OMIT_TRIGGER
94364:           "sql = sqlite_rename_table(sql, %Q), "
94365: #else
94366:           "sql = CASE "
94367:             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
94368:             "ELSE sqlite_rename_table(sql, %Q) END, "
94369: #endif
94370:           "tbl_name = %Q, "
94371:           "name = CASE "
94372:             "WHEN type='table' THEN %Q "
94373:             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
94374:              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
94375:             "ELSE name END "
94376:       "WHERE tbl_name=%Q COLLATE nocase AND "
94377:           "(type='table' OR type='index' OR type='trigger');", 
94378:       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
94379: #ifndef SQLITE_OMIT_TRIGGER
94380:       zName,
94381: #endif
94382:       zName, nTabName, zTabName
94383:   );
94384: 
94385: #ifndef SQLITE_OMIT_AUTOINCREMENT
94386:   /* If the sqlite_sequence table exists in this database, then update 
94387:   ** it with the new table name.
94388:   */
94389:   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
94390:     sqlite3NestedParse(pParse,
94391:         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
94392:         zDb, zName, pTab->zName);
94393:   }
94394: #endif
94395: 
94396: #ifndef SQLITE_OMIT_TRIGGER
94397:   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
94398:   ** table. Don't do this if the table being ALTERed is itself located in
94399:   ** the temp database.
94400:   */
94401:   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
94402:     sqlite3NestedParse(pParse, 
94403:         "UPDATE sqlite_temp_master SET "
94404:             "sql = sqlite_rename_trigger(sql, %Q), "
94405:             "tbl_name = %Q "
94406:             "WHERE %s;", zName, zName, zWhere);
94407:     sqlite3DbFree(db, zWhere);
94408:   }
94409: #endif
94410: 
94411: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
94412:   if( db->flags&SQLITE_ForeignKeys ){
94413:     FKey *p;
94414:     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
94415:       Table *pFrom = p->pFrom;
94416:       if( pFrom!=pTab ){
94417:         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
94418:       }
94419:     }
94420:   }
94421: #endif
94422: 
94423:   /* Drop and reload the internal table schema. */
94424:   reloadTableSchema(pParse, pTab, zName);
94425: 
94426: exit_rename_table:
94427:   sqlite3SrcListDelete(db, pSrc);
94428:   sqlite3DbFree(db, zName);
94429:   db->flags = savedDbFlags;
94430: }
94431: 
94432: /*
94433: ** This function is called after an "ALTER TABLE ... ADD" statement
94434: ** has been parsed. Argument pColDef contains the text of the new
94435: ** column definition.
94436: **
94437: ** The Table structure pParse->pNewTable was extended to include
94438: ** the new column during parsing.
94439: */
94440: SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
94441:   Table *pNew;              /* Copy of pParse->pNewTable */
94442:   Table *pTab;              /* Table being altered */
94443:   int iDb;                  /* Database number */
94444:   const char *zDb;          /* Database name */
94445:   const char *zTab;         /* Table name */
94446:   char *zCol;               /* Null-terminated column definition */
94447:   Column *pCol;             /* The new column */
94448:   Expr *pDflt;              /* Default value for the new column */
94449:   sqlite3 *db;              /* The database connection; */
94450:   Vdbe *v = pParse->pVdbe;  /* The prepared statement under construction */
94451:   int r1;                   /* Temporary registers */
94452: 
94453:   db = pParse->db;
94454:   if( pParse->nErr || db->mallocFailed ) return;
94455:   assert( v!=0 );
94456:   pNew = pParse->pNewTable;
94457:   assert( pNew );
94458: 
94459:   assert( sqlite3BtreeHoldsAllMutexes(db) );
94460:   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
94461:   zDb = db->aDb[iDb].zName;
94462:   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
94463:   pCol = &pNew->aCol[pNew->nCol-1];
94464:   pDflt = pCol->pDflt;
94465:   pTab = sqlite3FindTable(db, zTab, zDb);
94466:   assert( pTab );
94467: 
94468: #ifndef SQLITE_OMIT_AUTHORIZATION
94469:   /* Invoke the authorization callback. */
94470:   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
94471:     return;
94472:   }
94473: #endif
94474: 
94475:   /* If the default value for the new column was specified with a 
94476:   ** literal NULL, then set pDflt to 0. This simplifies checking
94477:   ** for an SQL NULL default below.
94478:   */
94479:   assert( pDflt==0 || pDflt->op==TK_SPAN );
94480:   if( pDflt && pDflt->pLeft->op==TK_NULL ){
94481:     pDflt = 0;
94482:   }
94483: 
94484:   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
94485:   ** If there is a NOT NULL constraint, then the default value for the
94486:   ** column must not be NULL.
94487:   */
94488:   if( pCol->colFlags & COLFLAG_PRIMKEY ){
94489:     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
94490:     return;
94491:   }
94492:   if( pNew->pIndex ){
94493:     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
94494:     return;
94495:   }
94496:   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
94497:     sqlite3ErrorMsg(pParse, 
94498:         "Cannot add a REFERENCES column with non-NULL default value");
94499:     return;
94500:   }
94501:   if( pCol->notNull && !pDflt ){
94502:     sqlite3ErrorMsg(pParse, 
94503:         "Cannot add a NOT NULL column with default value NULL");
94504:     return;
94505:   }
94506: 
94507:   /* Ensure the default expression is something that sqlite3ValueFromExpr()
94508:   ** can handle (i.e. not CURRENT_TIME etc.)
94509:   */
94510:   if( pDflt ){
94511:     sqlite3_value *pVal = 0;
94512:     int rc;
94513:     rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
94514:     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
94515:     if( rc!=SQLITE_OK ){
94516:       assert( db->mallocFailed == 1 );
94517:       return;
94518:     }
94519:     if( !pVal ){
94520:       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
94521:       return;
94522:     }
94523:     sqlite3ValueFree(pVal);
94524:   }
94525: 
94526:   /* Modify the CREATE TABLE statement. */
94527:   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
94528:   if( zCol ){
94529:     char *zEnd = &zCol[pColDef->n-1];
94530:     int savedDbFlags = db->flags;
94531:     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
94532:       *zEnd-- = '\0';
94533:     }
94534:     db->flags |= SQLITE_PreferBuiltin;
94535:     sqlite3NestedParse(pParse, 
94536:         "UPDATE \"%w\".%s SET "
94537:           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
94538:         "WHERE type = 'table' AND name = %Q", 
94539:       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
94540:       zTab
94541:     );
94542:     sqlite3DbFree(db, zCol);
94543:     db->flags = savedDbFlags;
94544:   }
94545: 
94546:   /* Make sure the schema version is at least 3.  But do not upgrade
94547:   ** from less than 3 to 4, as that will corrupt any preexisting DESC
94548:   ** index.
94549:   */
94550:   r1 = sqlite3GetTempReg(pParse);
94551:   sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
94552:   sqlite3VdbeUsesBtree(v, iDb);
94553:   sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
94554:   sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
94555:   VdbeCoverage(v);
94556:   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
94557:   sqlite3ReleaseTempReg(pParse, r1);
94558: 
94559:   /* Reload the schema of the modified table. */
94560:   reloadTableSchema(pParse, pTab, pTab->zName);
94561: }
94562: 
94563: /*
94564: ** This function is called by the parser after the table-name in
94565: ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
94566: ** pSrc is the full-name of the table being altered.
94567: **
94568: ** This routine makes a (partial) copy of the Table structure
94569: ** for the table being altered and sets Parse.pNewTable to point
94570: ** to it. Routines called by the parser as the column definition
94571: ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
94572: ** the copy. The copy of the Table structure is deleted by tokenize.c 
94573: ** after parsing is finished.
94574: **
94575: ** Routine sqlite3AlterFinishAddColumn() will be called to complete
94576: ** coding the "ALTER TABLE ... ADD" statement.
94577: */
94578: SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
94579:   Table *pNew;
94580:   Table *pTab;
94581:   Vdbe *v;
94582:   int iDb;
94583:   int i;
94584:   int nAlloc;
94585:   sqlite3 *db = pParse->db;
94586: 
94587:   /* Look up the table being altered. */
94588:   assert( pParse->pNewTable==0 );
94589:   assert( sqlite3BtreeHoldsAllMutexes(db) );
94590:   if( db->mallocFailed ) goto exit_begin_add_column;
94591:   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
94592:   if( !pTab ) goto exit_begin_add_column;
94593: 
94594: #ifndef SQLITE_OMIT_VIRTUALTABLE
94595:   if( IsVirtual(pTab) ){
94596:     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
94597:     goto exit_begin_add_column;
94598:   }
94599: #endif
94600: 
94601:   /* Make sure this is not an attempt to ALTER a view. */
94602:   if( pTab->pSelect ){
94603:     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
94604:     goto exit_begin_add_column;
94605:   }
94606:   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
94607:     goto exit_begin_add_column;
94608:   }
94609: 
94610:   assert( pTab->addColOffset>0 );
94611:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94612: 
94613:   /* Put a copy of the Table struct in Parse.pNewTable for the
94614:   ** sqlite3AddColumn() function and friends to modify.  But modify
94615:   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
94616:   ** prefix, we insure that the name will not collide with an existing
94617:   ** table because user table are not allowed to have the "sqlite_"
94618:   ** prefix on their name.
94619:   */
94620:   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
94621:   if( !pNew ) goto exit_begin_add_column;
94622:   pParse->pNewTable = pNew;
94623:   pNew->nRef = 1;
94624:   pNew->nCol = pTab->nCol;
94625:   assert( pNew->nCol>0 );
94626:   nAlloc = (((pNew->nCol-1)/8)*8)+8;
94627:   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
94628:   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
94629:   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
94630:   if( !pNew->aCol || !pNew->zName ){
94631:     assert( db->mallocFailed );
94632:     goto exit_begin_add_column;
94633:   }
94634:   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
94635:   for(i=0; i<pNew->nCol; i++){
94636:     Column *pCol = &pNew->aCol[i];
94637:     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
94638:     pCol->zColl = 0;
94639:     pCol->pDflt = 0;
94640:   }
94641:   pNew->pSchema = db->aDb[iDb].pSchema;
94642:   pNew->addColOffset = pTab->addColOffset;
94643:   pNew->nRef = 1;
94644: 
94645:   /* Begin a transaction and increment the schema cookie.  */
94646:   sqlite3BeginWriteOperation(pParse, 0, iDb);
94647:   v = sqlite3GetVdbe(pParse);
94648:   if( !v ) goto exit_begin_add_column;
94649:   sqlite3ChangeCookie(pParse, iDb);
94650: 
94651: exit_begin_add_column:
94652:   sqlite3SrcListDelete(db, pSrc);
94653:   return;
94654: }
94655: #endif  /* SQLITE_ALTER_TABLE */
94656: 
94657: /************** End of alter.c ***********************************************/
94658: /************** Begin file analyze.c *****************************************/
94659: /*
94660: ** 2005-07-08
94661: **
94662: ** The author disclaims copyright to this source code.  In place of
94663: ** a legal notice, here is a blessing:
94664: **
94665: **    May you do good and not evil.
94666: **    May you find forgiveness for yourself and forgive others.
94667: **    May you share freely, never taking more than you give.
94668: **
94669: *************************************************************************
94670: ** This file contains code associated with the ANALYZE command.
94671: **
94672: ** The ANALYZE command gather statistics about the content of tables
94673: ** and indices.  These statistics are made available to the query planner
94674: ** to help it make better decisions about how to perform queries.
94675: **
94676: ** The following system tables are or have been supported:
94677: **
94678: **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
94679: **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
94680: **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
94681: **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
94682: **
94683: ** Additional tables might be added in future releases of SQLite.
94684: ** The sqlite_stat2 table is not created or used unless the SQLite version
94685: ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
94686: ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
94687: ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
94688: ** created and used by SQLite versions 3.7.9 and later and with
94689: ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
94690: ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
94691: ** version of sqlite_stat3 and is only available when compiled with
94692: ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
94693: ** not possible to enable both STAT3 and STAT4 at the same time.  If they
94694: ** are both enabled, then STAT4 takes precedence.
94695: **
94696: ** For most applications, sqlite_stat1 provides all the statistics required
94697: ** for the query planner to make good choices.
94698: **
94699: ** Format of sqlite_stat1:
94700: **
94701: ** There is normally one row per index, with the index identified by the
94702: ** name in the idx column.  The tbl column is the name of the table to
94703: ** which the index belongs.  In each such row, the stat column will be
94704: ** a string consisting of a list of integers.  The first integer in this
94705: ** list is the number of rows in the index.  (This is the same as the
94706: ** number of rows in the table, except for partial indices.)  The second
94707: ** integer is the average number of rows in the index that have the same
94708: ** value in the first column of the index.  The third integer is the average
94709: ** number of rows in the index that have the same value for the first two
94710: ** columns.  The N-th integer (for N>1) is the average number of rows in 
94711: ** the index which have the same value for the first N-1 columns.  For
94712: ** a K-column index, there will be K+1 integers in the stat column.  If
94713: ** the index is unique, then the last integer will be 1.
94714: **
94715: ** The list of integers in the stat column can optionally be followed
94716: ** by the keyword "unordered".  The "unordered" keyword, if it is present,
94717: ** must be separated from the last integer by a single space.  If the
94718: ** "unordered" keyword is present, then the query planner assumes that
94719: ** the index is unordered and will not use the index for a range query.
94720: ** 
94721: ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
94722: ** column contains a single integer which is the (estimated) number of
94723: ** rows in the table identified by sqlite_stat1.tbl.
94724: **
94725: ** Format of sqlite_stat2:
94726: **
94727: ** The sqlite_stat2 is only created and is only used if SQLite is compiled
94728: ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
94729: ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
94730: ** about the distribution of keys within an index.  The index is identified by
94731: ** the "idx" column and the "tbl" column is the name of the table to which
94732: ** the index belongs.  There are usually 10 rows in the sqlite_stat2
94733: ** table for each index.
94734: **
94735: ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
94736: ** inclusive are samples of the left-most key value in the index taken at
94737: ** evenly spaced points along the index.  Let the number of samples be S
94738: ** (10 in the standard build) and let C be the number of rows in the index.
94739: ** Then the sampled rows are given by:
94740: **
94741: **     rownumber = (i*C*2 + C)/(S*2)
94742: **
94743: ** For i between 0 and S-1.  Conceptually, the index space is divided into
94744: ** S uniform buckets and the samples are the middle row from each bucket.
94745: **
94746: ** The format for sqlite_stat2 is recorded here for legacy reference.  This
94747: ** version of SQLite does not support sqlite_stat2.  It neither reads nor
94748: ** writes the sqlite_stat2 table.  This version of SQLite only supports
94749: ** sqlite_stat3.
94750: **
94751: ** Format for sqlite_stat3:
94752: **
94753: ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
94754: ** sqlite_stat4 format will be described first.  Further information
94755: ** about sqlite_stat3 follows the sqlite_stat4 description.
94756: **
94757: ** Format for sqlite_stat4:
94758: **
94759: ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
94760: ** to aid the query planner in choosing good indices based on the values
94761: ** that indexed columns are compared against in the WHERE clauses of
94762: ** queries.
94763: **
94764: ** The sqlite_stat4 table contains multiple entries for each index.
94765: ** The idx column names the index and the tbl column is the table of the
94766: ** index.  If the idx and tbl columns are the same, then the sample is
94767: ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
94768: ** binary encoding of a key from the index.  The nEq column is a
94769: ** list of integers.  The first integer is the approximate number
94770: ** of entries in the index whose left-most column exactly matches
94771: ** the left-most column of the sample.  The second integer in nEq
94772: ** is the approximate number of entries in the index where the
94773: ** first two columns match the first two columns of the sample.
94774: ** And so forth.  nLt is another list of integers that show the approximate
94775: ** number of entries that are strictly less than the sample.  The first
94776: ** integer in nLt contains the number of entries in the index where the
94777: ** left-most column is less than the left-most column of the sample.
94778: ** The K-th integer in the nLt entry is the number of index entries 
94779: ** where the first K columns are less than the first K columns of the
94780: ** sample.  The nDLt column is like nLt except that it contains the 
94781: ** number of distinct entries in the index that are less than the
94782: ** sample.
94783: **
94784: ** There can be an arbitrary number of sqlite_stat4 entries per index.
94785: ** The ANALYZE command will typically generate sqlite_stat4 tables
94786: ** that contain between 10 and 40 samples which are distributed across
94787: ** the key space, though not uniformly, and which include samples with
94788: ** large nEq values.
94789: **
94790: ** Format for sqlite_stat3 redux:
94791: **
94792: ** The sqlite_stat3 table is like sqlite_stat4 except that it only
94793: ** looks at the left-most column of the index.  The sqlite_stat3.sample
94794: ** column contains the actual value of the left-most column instead
94795: ** of a blob encoding of the complete index key as is found in
94796: ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
94797: ** all contain just a single integer which is the same as the first
94798: ** integer in the equivalent columns in sqlite_stat4.
94799: */
94800: #ifndef SQLITE_OMIT_ANALYZE
94801: /* #include "sqliteInt.h" */
94802: 
94803: #if defined(SQLITE_ENABLE_STAT4)
94804: # define IsStat4     1
94805: # define IsStat3     0
94806: #elif defined(SQLITE_ENABLE_STAT3)
94807: # define IsStat4     0
94808: # define IsStat3     1
94809: #else
94810: # define IsStat4     0
94811: # define IsStat3     0
94812: # undef SQLITE_STAT4_SAMPLES
94813: # define SQLITE_STAT4_SAMPLES 1
94814: #endif
94815: #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
94816: 
94817: /*
94818: ** This routine generates code that opens the sqlite_statN tables.
94819: ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
94820: ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
94821: ** appropriate compile-time options are provided.
94822: **
94823: ** If the sqlite_statN tables do not previously exist, it is created.
94824: **
94825: ** Argument zWhere may be a pointer to a buffer containing a table name,
94826: ** or it may be a NULL pointer. If it is not NULL, then all entries in
94827: ** the sqlite_statN tables associated with the named table are deleted.
94828: ** If zWhere==0, then code is generated to delete all stat table entries.
94829: */
94830: static void openStatTable(
94831:   Parse *pParse,          /* Parsing context */
94832:   int iDb,                /* The database we are looking in */
94833:   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
94834:   const char *zWhere,     /* Delete entries for this table or index */
94835:   const char *zWhereType  /* Either "tbl" or "idx" */
94836: ){
94837:   static const struct {
94838:     const char *zName;
94839:     const char *zCols;
94840:   } aTable[] = {
94841:     { "sqlite_stat1", "tbl,idx,stat" },
94842: #if defined(SQLITE_ENABLE_STAT4)
94843:     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
94844:     { "sqlite_stat3", 0 },
94845: #elif defined(SQLITE_ENABLE_STAT3)
94846:     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
94847:     { "sqlite_stat4", 0 },
94848: #else
94849:     { "sqlite_stat3", 0 },
94850:     { "sqlite_stat4", 0 },
94851: #endif
94852:   };
94853:   int i;
94854:   sqlite3 *db = pParse->db;
94855:   Db *pDb;
94856:   Vdbe *v = sqlite3GetVdbe(pParse);
94857:   int aRoot[ArraySize(aTable)];
94858:   u8 aCreateTbl[ArraySize(aTable)];
94859: 
94860:   if( v==0 ) return;
94861:   assert( sqlite3BtreeHoldsAllMutexes(db) );
94862:   assert( sqlite3VdbeDb(v)==db );
94863:   pDb = &db->aDb[iDb];
94864: 
94865:   /* Create new statistic tables if they do not exist, or clear them
94866:   ** if they do already exist.
94867:   */
94868:   for(i=0; i<ArraySize(aTable); i++){
94869:     const char *zTab = aTable[i].zName;
94870:     Table *pStat;
94871:     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
94872:       if( aTable[i].zCols ){
94873:         /* The sqlite_statN table does not exist. Create it. Note that a 
94874:         ** side-effect of the CREATE TABLE statement is to leave the rootpage 
94875:         ** of the new table in register pParse->regRoot. This is important 
94876:         ** because the OpenWrite opcode below will be needing it. */
94877:         sqlite3NestedParse(pParse,
94878:             "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
94879:         );
94880:         aRoot[i] = pParse->regRoot;
94881:         aCreateTbl[i] = OPFLAG_P2ISREG;
94882:       }
94883:     }else{
94884:       /* The table already exists. If zWhere is not NULL, delete all entries 
94885:       ** associated with the table zWhere. If zWhere is NULL, delete the
94886:       ** entire contents of the table. */
94887:       aRoot[i] = pStat->tnum;
94888:       aCreateTbl[i] = 0;
94889:       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
94890:       if( zWhere ){
94891:         sqlite3NestedParse(pParse,
94892:            "DELETE FROM %Q.%s WHERE %s=%Q",
94893:            pDb->zName, zTab, zWhereType, zWhere
94894:         );
94895:       }else{
94896:         /* The sqlite_stat[134] table already exists.  Delete all rows. */
94897:         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
94898:       }
94899:     }
94900:   }
94901: 
94902:   /* Open the sqlite_stat[134] tables for writing. */
94903:   for(i=0; aTable[i].zCols; i++){
94904:     assert( i<ArraySize(aTable) );
94905:     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
94906:     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
94907:     VdbeComment((v, aTable[i].zName));
94908:   }
94909: }
94910: 
94911: /*
94912: ** Recommended number of samples for sqlite_stat4
94913: */
94914: #ifndef SQLITE_STAT4_SAMPLES
94915: # define SQLITE_STAT4_SAMPLES 24
94916: #endif
94917: 
94918: /*
94919: ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
94920: ** share an instance of the following structure to hold their state
94921: ** information.
94922: */
94923: typedef struct Stat4Accum Stat4Accum;
94924: typedef struct Stat4Sample Stat4Sample;
94925: struct Stat4Sample {
94926:   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
94927:   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
94928: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94929:   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
94930:   union {
94931:     i64 iRowid;                     /* Rowid in main table of the key */
94932:     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
94933:   } u;
94934:   u32 nRowid;                     /* Sizeof aRowid[] */
94935:   u8 isPSample;                   /* True if a periodic sample */
94936:   int iCol;                       /* If !isPSample, the reason for inclusion */
94937:   u32 iHash;                      /* Tiebreaker hash */
94938: #endif
94939: };                                                    
94940: struct Stat4Accum {
94941:   tRowcnt nRow;             /* Number of rows in the entire table */
94942:   tRowcnt nPSample;         /* How often to do a periodic sample */
94943:   int nCol;                 /* Number of columns in index + pk/rowid */
94944:   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
94945:   int mxSample;             /* Maximum number of samples to accumulate */
94946:   Stat4Sample current;      /* Current row as a Stat4Sample */
94947:   u32 iPrn;                 /* Pseudo-random number used for sampling */
94948:   Stat4Sample *aBest;       /* Array of nCol best samples */
94949:   int iMin;                 /* Index in a[] of entry with minimum score */
94950:   int nSample;              /* Current number of samples */
94951:   int iGet;                 /* Index of current sample accessed by stat_get() */
94952:   Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
94953:   sqlite3 *db;              /* Database connection, for malloc() */
94954: };
94955: 
94956: /* Reclaim memory used by a Stat4Sample
94957: */
94958: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94959: static void sampleClear(sqlite3 *db, Stat4Sample *p){
94960:   assert( db!=0 );
94961:   if( p->nRowid ){
94962:     sqlite3DbFree(db, p->u.aRowid);
94963:     p->nRowid = 0;
94964:   }
94965: }
94966: #endif
94967: 
94968: /* Initialize the BLOB value of a ROWID
94969: */
94970: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94971: static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
94972:   assert( db!=0 );
94973:   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94974:   p->u.aRowid = sqlite3DbMallocRawNN(db, n);
94975:   if( p->u.aRowid ){
94976:     p->nRowid = n;
94977:     memcpy(p->u.aRowid, pData, n);
94978:   }else{
94979:     p->nRowid = 0;
94980:   }
94981: }
94982: #endif
94983: 
94984: /* Initialize the INTEGER value of a ROWID.
94985: */
94986: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94987: static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
94988:   assert( db!=0 );
94989:   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94990:   p->nRowid = 0;
94991:   p->u.iRowid = iRowid;
94992: }
94993: #endif
94994: 
94995: 
94996: /*
94997: ** Copy the contents of object (*pFrom) into (*pTo).
94998: */
94999: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95000: static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
95001:   pTo->isPSample = pFrom->isPSample;
95002:   pTo->iCol = pFrom->iCol;
95003:   pTo->iHash = pFrom->iHash;
95004:   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
95005:   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
95006:   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
95007:   if( pFrom->nRowid ){
95008:     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
95009:   }else{
95010:     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
95011:   }
95012: }
95013: #endif
95014: 
95015: /*
95016: ** Reclaim all memory of a Stat4Accum structure.
95017: */
95018: static void stat4Destructor(void *pOld){
95019:   Stat4Accum *p = (Stat4Accum*)pOld;
95020: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95021:   int i;
95022:   for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
95023:   for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
95024:   sampleClear(p->db, &p->current);
95025: #endif
95026:   sqlite3DbFree(p->db, p);
95027: }
95028: 
95029: /*
95030: ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
95031: ** are:
95032: **     N:    The number of columns in the index including the rowid/pk (note 1)
95033: **     K:    The number of columns in the index excluding the rowid/pk.
95034: **     C:    The number of rows in the index (note 2)
95035: **
95036: ** Note 1:  In the special case of the covering index that implements a
95037: ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
95038: ** total number of columns in the table.
95039: **
95040: ** Note 2:  C is only used for STAT3 and STAT4.
95041: **
95042: ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
95043: ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
95044: ** PRIMARY KEY of the table.  The covering index that implements the
95045: ** original WITHOUT ROWID table as N==K as a special case.
95046: **
95047: ** This routine allocates the Stat4Accum object in heap memory. The return 
95048: ** value is a pointer to the Stat4Accum object.  The datatype of the
95049: ** return value is BLOB, but it is really just a pointer to the Stat4Accum
95050: ** object.
95051: */
95052: static void statInit(
95053:   sqlite3_context *context,
95054:   int argc,
95055:   sqlite3_value **argv
95056: ){
95057:   Stat4Accum *p;
95058:   int nCol;                       /* Number of columns in index being sampled */
95059:   int nKeyCol;                    /* Number of key columns */
95060:   int nColUp;                     /* nCol rounded up for alignment */
95061:   int n;                          /* Bytes of space to allocate */
95062:   sqlite3 *db;                    /* Database connection */
95063: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95064:   int mxSample = SQLITE_STAT4_SAMPLES;
95065: #endif
95066: 
95067:   /* Decode the three function arguments */
95068:   UNUSED_PARAMETER(argc);
95069:   nCol = sqlite3_value_int(argv[0]);
95070:   assert( nCol>0 );
95071:   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
95072:   nKeyCol = sqlite3_value_int(argv[1]);
95073:   assert( nKeyCol<=nCol );
95074:   assert( nKeyCol>0 );
95075: 
95076:   /* Allocate the space required for the Stat4Accum object */
95077:   n = sizeof(*p) 
95078:     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
95079:     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
95080: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95081:     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
95082:     + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
95083:     + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
95084: #endif
95085:   ;
95086:   db = sqlite3_context_db_handle(context);
95087:   p = sqlite3DbMallocZero(db, n);
95088:   if( p==0 ){
95089:     sqlite3_result_error_nomem(context);
95090:     return;
95091:   }
95092: 
95093:   p->db = db;
95094:   p->nRow = 0;
95095:   p->nCol = nCol;
95096:   p->nKeyCol = nKeyCol;
95097:   p->current.anDLt = (tRowcnt*)&p[1];
95098:   p->current.anEq = &p->current.anDLt[nColUp];
95099: 
95100: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95101:   {
95102:     u8 *pSpace;                     /* Allocated space not yet assigned */
95103:     int i;                          /* Used to iterate through p->aSample[] */
95104: 
95105:     p->iGet = -1;
95106:     p->mxSample = mxSample;
95107:     p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
95108:     p->current.anLt = &p->current.anEq[nColUp];
95109:     p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
95110:   
95111:     /* Set up the Stat4Accum.a[] and aBest[] arrays */
95112:     p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
95113:     p->aBest = &p->a[mxSample];
95114:     pSpace = (u8*)(&p->a[mxSample+nCol]);
95115:     for(i=0; i<(mxSample+nCol); i++){
95116:       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95117:       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95118:       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
95119:     }
95120:     assert( (pSpace - (u8*)p)==n );
95121:   
95122:     for(i=0; i<nCol; i++){
95123:       p->aBest[i].iCol = i;
95124:     }
95125:   }
95126: #endif
95127: 
95128:   /* Return a pointer to the allocated object to the caller.  Note that
95129:   ** only the pointer (the 2nd parameter) matters.  The size of the object
95130:   ** (given by the 3rd parameter) is never used and can be any positive
95131:   ** value. */
95132:   sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
95133: }
95134: static const FuncDef statInitFuncdef = {
95135:   2+IsStat34,      /* nArg */
95136:   SQLITE_UTF8,     /* funcFlags */
95137:   0,               /* pUserData */
95138:   0,               /* pNext */
95139:   statInit,        /* xSFunc */
95140:   0,               /* xFinalize */
95141:   "stat_init",     /* zName */
95142:   {0}
95143: };
95144: 
95145: #ifdef SQLITE_ENABLE_STAT4
95146: /*
95147: ** pNew and pOld are both candidate non-periodic samples selected for 
95148: ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
95149: ** considering only any trailing columns and the sample hash value, this
95150: ** function returns true if sample pNew is to be preferred over pOld.
95151: ** In other words, if we assume that the cardinalities of the selected
95152: ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
95153: **
95154: ** This function assumes that for each argument sample, the contents of
95155: ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. 
95156: */
95157: static int sampleIsBetterPost(
95158:   Stat4Accum *pAccum, 
95159:   Stat4Sample *pNew, 
95160:   Stat4Sample *pOld
95161: ){
95162:   int nCol = pAccum->nCol;
95163:   int i;
95164:   assert( pNew->iCol==pOld->iCol );
95165:   for(i=pNew->iCol+1; i<nCol; i++){
95166:     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
95167:     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
95168:   }
95169:   if( pNew->iHash>pOld->iHash ) return 1;
95170:   return 0;
95171: }
95172: #endif
95173: 
95174: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95175: /*
95176: ** Return true if pNew is to be preferred over pOld.
95177: **
95178: ** This function assumes that for each argument sample, the contents of
95179: ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. 
95180: */
95181: static int sampleIsBetter(
95182:   Stat4Accum *pAccum, 
95183:   Stat4Sample *pNew, 
95184:   Stat4Sample *pOld
95185: ){
95186:   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
95187:   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
95188: 
95189:   assert( pOld->isPSample==0 && pNew->isPSample==0 );
95190:   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
95191: 
95192:   if( (nEqNew>nEqOld) ) return 1;
95193: #ifdef SQLITE_ENABLE_STAT4
95194:   if( nEqNew==nEqOld ){
95195:     if( pNew->iCol<pOld->iCol ) return 1;
95196:     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
95197:   }
95198:   return 0;
95199: #else
95200:   return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
95201: #endif
95202: }
95203: 
95204: /*
95205: ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
95206: ** remove the least desirable sample from p->a[] to make room.
95207: */
95208: static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
95209:   Stat4Sample *pSample = 0;
95210:   int i;
95211: 
95212:   assert( IsStat4 || nEqZero==0 );
95213: 
95214: #ifdef SQLITE_ENABLE_STAT4
95215:   if( pNew->isPSample==0 ){
95216:     Stat4Sample *pUpgrade = 0;
95217:     assert( pNew->anEq[pNew->iCol]>0 );
95218: 
95219:     /* This sample is being added because the prefix that ends in column 
95220:     ** iCol occurs many times in the table. However, if we have already
95221:     ** added a sample that shares this prefix, there is no need to add
95222:     ** this one. Instead, upgrade the priority of the highest priority
95223:     ** existing sample that shares this prefix.  */
95224:     for(i=p->nSample-1; i>=0; i--){
95225:       Stat4Sample *pOld = &p->a[i];
95226:       if( pOld->anEq[pNew->iCol]==0 ){
95227:         if( pOld->isPSample ) return;
95228:         assert( pOld->iCol>pNew->iCol );
95229:         assert( sampleIsBetter(p, pNew, pOld) );
95230:         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
95231:           pUpgrade = pOld;
95232:         }
95233:       }
95234:     }
95235:     if( pUpgrade ){
95236:       pUpgrade->iCol = pNew->iCol;
95237:       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
95238:       goto find_new_min;
95239:     }
95240:   }
95241: #endif
95242: 
95243:   /* If necessary, remove sample iMin to make room for the new sample. */
95244:   if( p->nSample>=p->mxSample ){
95245:     Stat4Sample *pMin = &p->a[p->iMin];
95246:     tRowcnt *anEq = pMin->anEq;
95247:     tRowcnt *anLt = pMin->anLt;
95248:     tRowcnt *anDLt = pMin->anDLt;
95249:     sampleClear(p->db, pMin);
95250:     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
95251:     pSample = &p->a[p->nSample-1];
95252:     pSample->nRowid = 0;
95253:     pSample->anEq = anEq;
95254:     pSample->anDLt = anDLt;
95255:     pSample->anLt = anLt;
95256:     p->nSample = p->mxSample-1;
95257:   }
95258: 
95259:   /* The "rows less-than" for the rowid column must be greater than that
95260:   ** for the last sample in the p->a[] array. Otherwise, the samples would
95261:   ** be out of order. */
95262: #ifdef SQLITE_ENABLE_STAT4
95263:   assert( p->nSample==0 
95264:        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
95265: #endif
95266: 
95267:   /* Insert the new sample */
95268:   pSample = &p->a[p->nSample];
95269:   sampleCopy(p, pSample, pNew);
95270:   p->nSample++;
95271: 
95272:   /* Zero the first nEqZero entries in the anEq[] array. */
95273:   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
95274: 
95275: #ifdef SQLITE_ENABLE_STAT4
95276:  find_new_min:
95277: #endif
95278:   if( p->nSample>=p->mxSample ){
95279:     int iMin = -1;
95280:     for(i=0; i<p->mxSample; i++){
95281:       if( p->a[i].isPSample ) continue;
95282:       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
95283:         iMin = i;
95284:       }
95285:     }
95286:     assert( iMin>=0 );
95287:     p->iMin = iMin;
95288:   }
95289: }
95290: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95291: 
95292: /*
95293: ** Field iChng of the index being scanned has changed. So at this point
95294: ** p->current contains a sample that reflects the previous row of the
95295: ** index. The value of anEq[iChng] and subsequent anEq[] elements are
95296: ** correct at this point.
95297: */
95298: static void samplePushPrevious(Stat4Accum *p, int iChng){
95299: #ifdef SQLITE_ENABLE_STAT4
95300:   int i;
95301: 
95302:   /* Check if any samples from the aBest[] array should be pushed
95303:   ** into IndexSample.a[] at this point.  */
95304:   for(i=(p->nCol-2); i>=iChng; i--){
95305:     Stat4Sample *pBest = &p->aBest[i];
95306:     pBest->anEq[i] = p->current.anEq[i];
95307:     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
95308:       sampleInsert(p, pBest, i);
95309:     }
95310:   }
95311: 
95312:   /* Update the anEq[] fields of any samples already collected. */
95313:   for(i=p->nSample-1; i>=0; i--){
95314:     int j;
95315:     for(j=iChng; j<p->nCol; j++){
95316:       if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
95317:     }
95318:   }
95319: #endif
95320: 
95321: #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
95322:   if( iChng==0 ){
95323:     tRowcnt nLt = p->current.anLt[0];
95324:     tRowcnt nEq = p->current.anEq[0];
95325: 
95326:     /* Check if this is to be a periodic sample. If so, add it. */
95327:     if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
95328:       p->current.isPSample = 1;
95329:       sampleInsert(p, &p->current, 0);
95330:       p->current.isPSample = 0;
95331:     }else 
95332: 
95333:     /* Or if it is a non-periodic sample. Add it in this case too. */
95334:     if( p->nSample<p->mxSample 
95335:      || sampleIsBetter(p, &p->current, &p->a[p->iMin]) 
95336:     ){
95337:       sampleInsert(p, &p->current, 0);
95338:     }
95339:   }
95340: #endif
95341: 
95342: #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
95343:   UNUSED_PARAMETER( p );
95344:   UNUSED_PARAMETER( iChng );
95345: #endif
95346: }
95347: 
95348: /*
95349: ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
95350: ** Arguments:
95351: **
95352: **    P     Pointer to the Stat4Accum object created by stat_init()
95353: **    C     Index of left-most column to differ from previous row
95354: **    R     Rowid for the current row.  Might be a key record for
95355: **          WITHOUT ROWID tables.
95356: **
95357: ** This SQL function always returns NULL.  It's purpose it to accumulate
95358: ** statistical data and/or samples in the Stat4Accum object about the
95359: ** index being analyzed.  The stat_get() SQL function will later be used to
95360: ** extract relevant information for constructing the sqlite_statN tables.
95361: **
95362: ** The R parameter is only used for STAT3 and STAT4
95363: */
95364: static void statPush(
95365:   sqlite3_context *context,
95366:   int argc,
95367:   sqlite3_value **argv
95368: ){
95369:   int i;
95370: 
95371:   /* The three function arguments */
95372:   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
95373:   int iChng = sqlite3_value_int(argv[1]);
95374: 
95375:   UNUSED_PARAMETER( argc );
95376:   UNUSED_PARAMETER( context );
95377:   assert( p->nCol>0 );
95378:   assert( iChng<p->nCol );
95379: 
95380:   if( p->nRow==0 ){
95381:     /* This is the first call to this function. Do initialization. */
95382:     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
95383:   }else{
95384:     /* Second and subsequent calls get processed here */
95385:     samplePushPrevious(p, iChng);
95386: 
95387:     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
95388:     ** to the current row of the index. */
95389:     for(i=0; i<iChng; i++){
95390:       p->current.anEq[i]++;
95391:     }
95392:     for(i=iChng; i<p->nCol; i++){
95393:       p->current.anDLt[i]++;
95394: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95395:       p->current.anLt[i] += p->current.anEq[i];
95396: #endif
95397:       p->current.anEq[i] = 1;
95398:     }
95399:   }
95400:   p->nRow++;
95401: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95402:   if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
95403:     sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
95404:   }else{
95405:     sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
95406:                                        sqlite3_value_blob(argv[2]));
95407:   }
95408:   p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
95409: #endif
95410: 
95411: #ifdef SQLITE_ENABLE_STAT4
95412:   {
95413:     tRowcnt nLt = p->current.anLt[p->nCol-1];
95414: 
95415:     /* Check if this is to be a periodic sample. If so, add it. */
95416:     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
95417:       p->current.isPSample = 1;
95418:       p->current.iCol = 0;
95419:       sampleInsert(p, &p->current, p->nCol-1);
95420:       p->current.isPSample = 0;
95421:     }
95422: 
95423:     /* Update the aBest[] array. */
95424:     for(i=0; i<(p->nCol-1); i++){
95425:       p->current.iCol = i;
95426:       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
95427:         sampleCopy(p, &p->aBest[i], &p->current);
95428:       }
95429:     }
95430:   }
95431: #endif
95432: }
95433: static const FuncDef statPushFuncdef = {
95434:   2+IsStat34,      /* nArg */
95435:   SQLITE_UTF8,     /* funcFlags */
95436:   0,               /* pUserData */
95437:   0,               /* pNext */
95438:   statPush,        /* xSFunc */
95439:   0,               /* xFinalize */
95440:   "stat_push",     /* zName */
95441:   {0}
95442: };
95443: 
95444: #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
95445: #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
95446: #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
95447: #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
95448: #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
95449: 
95450: /*
95451: ** Implementation of the stat_get(P,J) SQL function.  This routine is
95452: ** used to query statistical information that has been gathered into
95453: ** the Stat4Accum object by prior calls to stat_push().  The P parameter
95454: ** has type BLOB but it is really just a pointer to the Stat4Accum object.
95455: ** The content to returned is determined by the parameter J
95456: ** which is one of the STAT_GET_xxxx values defined above.
95457: **
95458: ** If neither STAT3 nor STAT4 are enabled, then J is always
95459: ** STAT_GET_STAT1 and is hence omitted and this routine becomes
95460: ** a one-parameter function, stat_get(P), that always returns the
95461: ** stat1 table entry information.
95462: */
95463: static void statGet(
95464:   sqlite3_context *context,
95465:   int argc,
95466:   sqlite3_value **argv
95467: ){
95468:   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
95469: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95470:   /* STAT3 and STAT4 have a parameter on this routine. */
95471:   int eCall = sqlite3_value_int(argv[1]);
95472:   assert( argc==2 );
95473:   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ 
95474:        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
95475:        || eCall==STAT_GET_NDLT 
95476:   );
95477:   if( eCall==STAT_GET_STAT1 )
95478: #else
95479:   assert( argc==1 );
95480: #endif
95481:   {
95482:     /* Return the value to store in the "stat" column of the sqlite_stat1
95483:     ** table for this index.
95484:     **
95485:     ** The value is a string composed of a list of integers describing 
95486:     ** the index. The first integer in the list is the total number of 
95487:     ** entries in the index. There is one additional integer in the list 
95488:     ** for each indexed column. This additional integer is an estimate of
95489:     ** the number of rows matched by a stabbing query on the index using
95490:     ** a key with the corresponding number of fields. In other words,
95491:     ** if the index is on columns (a,b) and the sqlite_stat1 value is 
95492:     ** "100 10 2", then SQLite estimates that:
95493:     **
95494:     **   * the index contains 100 rows,
95495:     **   * "WHERE a=?" matches 10 rows, and
95496:     **   * "WHERE a=? AND b=?" matches 2 rows.
95497:     **
95498:     ** If D is the count of distinct values and K is the total number of 
95499:     ** rows, then each estimate is computed as:
95500:     **
95501:     **        I = (K+D-1)/D
95502:     */
95503:     char *z;
95504:     int i;
95505: 
95506:     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
95507:     if( zRet==0 ){
95508:       sqlite3_result_error_nomem(context);
95509:       return;
95510:     }
95511: 
95512:     sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
95513:     z = zRet + sqlite3Strlen30(zRet);
95514:     for(i=0; i<p->nKeyCol; i++){
95515:       u64 nDistinct = p->current.anDLt[i] + 1;
95516:       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
95517:       sqlite3_snprintf(24, z, " %llu", iVal);
95518:       z += sqlite3Strlen30(z);
95519:       assert( p->current.anEq[i] );
95520:     }
95521:     assert( z[0]=='\0' && z>zRet );
95522: 
95523:     sqlite3_result_text(context, zRet, -1, sqlite3_free);
95524:   }
95525: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95526:   else if( eCall==STAT_GET_ROWID ){
95527:     if( p->iGet<0 ){
95528:       samplePushPrevious(p, 0);
95529:       p->iGet = 0;
95530:     }
95531:     if( p->iGet<p->nSample ){
95532:       Stat4Sample *pS = p->a + p->iGet;
95533:       if( pS->nRowid==0 ){
95534:         sqlite3_result_int64(context, pS->u.iRowid);
95535:       }else{
95536:         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
95537:                             SQLITE_TRANSIENT);
95538:       }
95539:     }
95540:   }else{
95541:     tRowcnt *aCnt = 0;
95542: 
95543:     assert( p->iGet<p->nSample );
95544:     switch( eCall ){
95545:       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
95546:       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
95547:       default: {
95548:         aCnt = p->a[p->iGet].anDLt; 
95549:         p->iGet++;
95550:         break;
95551:       }
95552:     }
95553: 
95554:     if( IsStat3 ){
95555:       sqlite3_result_int64(context, (i64)aCnt[0]);
95556:     }else{
95557:       char *zRet = sqlite3MallocZero(p->nCol * 25);
95558:       if( zRet==0 ){
95559:         sqlite3_result_error_nomem(context);
95560:       }else{
95561:         int i;
95562:         char *z = zRet;
95563:         for(i=0; i<p->nCol; i++){
95564:           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
95565:           z += sqlite3Strlen30(z);
95566:         }
95567:         assert( z[0]=='\0' && z>zRet );
95568:         z[-1] = '\0';
95569:         sqlite3_result_text(context, zRet, -1, sqlite3_free);
95570:       }
95571:     }
95572:   }
95573: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95574: #ifndef SQLITE_DEBUG
95575:   UNUSED_PARAMETER( argc );
95576: #endif
95577: }
95578: static const FuncDef statGetFuncdef = {
95579:   1+IsStat34,      /* nArg */
95580:   SQLITE_UTF8,     /* funcFlags */
95581:   0,               /* pUserData */
95582:   0,               /* pNext */
95583:   statGet,         /* xSFunc */
95584:   0,               /* xFinalize */
95585:   "stat_get",      /* zName */
95586:   {0}
95587: };
95588: 
95589: static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
95590:   assert( regOut!=regStat4 && regOut!=regStat4+1 );
95591: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95592:   sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
95593: #elif SQLITE_DEBUG
95594:   assert( iParam==STAT_GET_STAT1 );
95595: #else
95596:   UNUSED_PARAMETER( iParam );
95597: #endif
95598:   sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
95599:                     (char*)&statGetFuncdef, P4_FUNCDEF);
95600:   sqlite3VdbeChangeP5(v, 1 + IsStat34);
95601: }
95602: 
95603: /*
95604: ** Generate code to do an analysis of all indices associated with
95605: ** a single table.
95606: */
95607: static void analyzeOneTable(
95608:   Parse *pParse,   /* Parser context */
95609:   Table *pTab,     /* Table whose indices are to be analyzed */
95610:   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
95611:   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
95612:   int iMem,        /* Available memory locations begin here */
95613:   int iTab         /* Next available cursor */
95614: ){
95615:   sqlite3 *db = pParse->db;    /* Database handle */
95616:   Index *pIdx;                 /* An index to being analyzed */
95617:   int iIdxCur;                 /* Cursor open on index being analyzed */
95618:   int iTabCur;                 /* Table cursor */
95619:   Vdbe *v;                     /* The virtual machine being built up */
95620:   int i;                       /* Loop counter */
95621:   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
95622:   int iDb;                     /* Index of database containing pTab */
95623:   u8 needTableCnt = 1;         /* True to count the table */
95624:   int regNewRowid = iMem++;    /* Rowid for the inserted record */
95625:   int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
95626:   int regChng = iMem++;        /* Index of changed index field */
95627: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95628:   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
95629: #endif
95630:   int regTemp = iMem++;        /* Temporary use register */
95631:   int regTabname = iMem++;     /* Register containing table name */
95632:   int regIdxname = iMem++;     /* Register containing index name */
95633:   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
95634:   int regPrev = iMem;          /* MUST BE LAST (see below) */
95635: 
95636:   pParse->nMem = MAX(pParse->nMem, iMem);
95637:   v = sqlite3GetVdbe(pParse);
95638:   if( v==0 || NEVER(pTab==0) ){
95639:     return;
95640:   }
95641:   if( pTab->tnum==0 ){
95642:     /* Do not gather statistics on views or virtual tables */
95643:     return;
95644:   }
95645:   if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
95646:     /* Do not gather statistics on system tables */
95647:     return;
95648:   }
95649:   assert( sqlite3BtreeHoldsAllMutexes(db) );
95650:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95651:   assert( iDb>=0 );
95652:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95653: #ifndef SQLITE_OMIT_AUTHORIZATION
95654:   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
95655:       db->aDb[iDb].zName ) ){
95656:     return;
95657:   }
95658: #endif
95659: 
95660:   /* Establish a read-lock on the table at the shared-cache level. 
95661:   ** Open a read-only cursor on the table. Also allocate a cursor number
95662:   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
95663:   ** this time though.  */
95664:   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
95665:   iTabCur = iTab++;
95666:   iIdxCur = iTab++;
95667:   pParse->nTab = MAX(pParse->nTab, iTab);
95668:   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
95669:   sqlite3VdbeLoadString(v, regTabname, pTab->zName);
95670: 
95671:   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95672:     int nCol;                     /* Number of columns in pIdx. "N" */
95673:     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
95674:     int addrNextRow;              /* Address of "next_row:" */
95675:     const char *zIdxName;         /* Name of the index */
95676:     int nColTest;                 /* Number of columns to test for changes */
95677: 
95678:     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
95679:     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
95680:     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
95681:       nCol = pIdx->nKeyCol;
95682:       zIdxName = pTab->zName;
95683:       nColTest = nCol - 1;
95684:     }else{
95685:       nCol = pIdx->nColumn;
95686:       zIdxName = pIdx->zName;
95687:       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
95688:     }
95689: 
95690:     /* Populate the register containing the index name. */
95691:     sqlite3VdbeLoadString(v, regIdxname, zIdxName);
95692:     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
95693: 
95694:     /*
95695:     ** Pseudo-code for loop that calls stat_push():
95696:     **
95697:     **   Rewind csr
95698:     **   if eof(csr) goto end_of_scan;
95699:     **   regChng = 0
95700:     **   goto chng_addr_0;
95701:     **
95702:     **  next_row:
95703:     **   regChng = 0
95704:     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
95705:     **   regChng = 1
95706:     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
95707:     **   ...
95708:     **   regChng = N
95709:     **   goto chng_addr_N
95710:     **
95711:     **  chng_addr_0:
95712:     **   regPrev(0) = idx(0)
95713:     **  chng_addr_1:
95714:     **   regPrev(1) = idx(1)
95715:     **  ...
95716:     **
95717:     **  endDistinctTest:
95718:     **   regRowid = idx(rowid)
95719:     **   stat_push(P, regChng, regRowid)
95720:     **   Next csr
95721:     **   if !eof(csr) goto next_row;
95722:     **
95723:     **  end_of_scan:
95724:     */
95725: 
95726:     /* Make sure there are enough memory cells allocated to accommodate 
95727:     ** the regPrev array and a trailing rowid (the rowid slot is required
95728:     ** when building a record to insert into the sample column of 
95729:     ** the sqlite_stat4 table.  */
95730:     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
95731: 
95732:     /* Open a read-only cursor on the index being analyzed. */
95733:     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
95734:     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
95735:     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
95736:     VdbeComment((v, "%s", pIdx->zName));
95737: 
95738:     /* Invoke the stat_init() function. The arguments are:
95739:     ** 
95740:     **    (1) the number of columns in the index including the rowid
95741:     **        (or for a WITHOUT ROWID table, the number of PK columns),
95742:     **    (2) the number of columns in the key without the rowid/pk
95743:     **    (3) the number of rows in the index,
95744:     **
95745:     **
95746:     ** The third argument is only used for STAT3 and STAT4
95747:     */
95748: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95749:     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
95750: #endif
95751:     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
95752:     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
95753:     sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
95754:                      (char*)&statInitFuncdef, P4_FUNCDEF);
95755:     sqlite3VdbeChangeP5(v, 2+IsStat34);
95756: 
95757:     /* Implementation of the following:
95758:     **
95759:     **   Rewind csr
95760:     **   if eof(csr) goto end_of_scan;
95761:     **   regChng = 0
95762:     **   goto next_push_0;
95763:     **
95764:     */
95765:     addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
95766:     VdbeCoverage(v);
95767:     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
95768:     addrNextRow = sqlite3VdbeCurrentAddr(v);
95769: 
95770:     if( nColTest>0 ){
95771:       int endDistinctTest = sqlite3VdbeMakeLabel(v);
95772:       int *aGotoChng;               /* Array of jump instruction addresses */
95773:       aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
95774:       if( aGotoChng==0 ) continue;
95775: 
95776:       /*
95777:       **  next_row:
95778:       **   regChng = 0
95779:       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
95780:       **   regChng = 1
95781:       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
95782:       **   ...
95783:       **   regChng = N
95784:       **   goto endDistinctTest
95785:       */
95786:       sqlite3VdbeAddOp0(v, OP_Goto);
95787:       addrNextRow = sqlite3VdbeCurrentAddr(v);
95788:       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
95789:         /* For a single-column UNIQUE index, once we have found a non-NULL
95790:         ** row, we know that all the rest will be distinct, so skip 
95791:         ** subsequent distinctness tests. */
95792:         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
95793:         VdbeCoverage(v);
95794:       }
95795:       for(i=0; i<nColTest; i++){
95796:         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
95797:         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
95798:         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
95799:         aGotoChng[i] = 
95800:         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
95801:         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
95802:         VdbeCoverage(v);
95803:       }
95804:       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
95805:       sqlite3VdbeGoto(v, endDistinctTest);
95806:   
95807:   
95808:       /*
95809:       **  chng_addr_0:
95810:       **   regPrev(0) = idx(0)
95811:       **  chng_addr_1:
95812:       **   regPrev(1) = idx(1)
95813:       **  ...
95814:       */
95815:       sqlite3VdbeJumpHere(v, addrNextRow-1);
95816:       for(i=0; i<nColTest; i++){
95817:         sqlite3VdbeJumpHere(v, aGotoChng[i]);
95818:         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
95819:       }
95820:       sqlite3VdbeResolveLabel(v, endDistinctTest);
95821:       sqlite3DbFree(db, aGotoChng);
95822:     }
95823:   
95824:     /*
95825:     **  chng_addr_N:
95826:     **   regRowid = idx(rowid)            // STAT34 only
95827:     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
95828:     **   Next csr
95829:     **   if !eof(csr) goto next_row;
95830:     */
95831: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95832:     assert( regRowid==(regStat4+2) );
95833:     if( HasRowid(pTab) ){
95834:       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
95835:     }else{
95836:       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
95837:       int j, k, regKey;
95838:       regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
95839:       for(j=0; j<pPk->nKeyCol; j++){
95840:         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
95841:         assert( k>=0 && k<pTab->nCol );
95842:         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
95843:         VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
95844:       }
95845:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
95846:       sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
95847:     }
95848: #endif
95849:     assert( regChng==(regStat4+1) );
95850:     sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
95851:                      (char*)&statPushFuncdef, P4_FUNCDEF);
95852:     sqlite3VdbeChangeP5(v, 2+IsStat34);
95853:     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
95854: 
95855:     /* Add the entry to the stat1 table. */
95856:     callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
95857:     assert( "BBB"[0]==SQLITE_AFF_TEXT );
95858:     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95859:     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95860:     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95861:     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95862: 
95863:     /* Add the entries to the stat3 or stat4 table. */
95864: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95865:     {
95866:       int regEq = regStat1;
95867:       int regLt = regStat1+1;
95868:       int regDLt = regStat1+2;
95869:       int regSample = regStat1+3;
95870:       int regCol = regStat1+4;
95871:       int regSampleRowid = regCol + nCol;
95872:       int addrNext;
95873:       int addrIsNull;
95874:       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
95875: 
95876:       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
95877: 
95878:       addrNext = sqlite3VdbeCurrentAddr(v);
95879:       callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
95880:       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
95881:       VdbeCoverage(v);
95882:       callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
95883:       callStatGet(v, regStat4, STAT_GET_NLT, regLt);
95884:       callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
95885:       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
95886:       /* We know that the regSampleRowid row exists because it was read by
95887:       ** the previous loop.  Thus the not-found jump of seekOp will never
95888:       ** be taken */
95889:       VdbeCoverageNeverTaken(v);
95890: #ifdef SQLITE_ENABLE_STAT3
95891:       sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
95892: #else
95893:       for(i=0; i<nCol; i++){
95894:         sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
95895:       }
95896:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
95897: #endif
95898:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
95899:       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
95900:       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
95901:       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
95902:       sqlite3VdbeJumpHere(v, addrIsNull);
95903:     }
95904: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95905: 
95906:     /* End of analysis */
95907:     sqlite3VdbeJumpHere(v, addrRewind);
95908:   }
95909: 
95910: 
95911:   /* Create a single sqlite_stat1 entry containing NULL as the index
95912:   ** name and the row count as the content.
95913:   */
95914:   if( pOnlyIdx==0 && needTableCnt ){
95915:     VdbeComment((v, "%s", pTab->zName));
95916:     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
95917:     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
95918:     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
95919:     assert( "BBB"[0]==SQLITE_AFF_TEXT );
95920:     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95921:     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95922:     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95923:     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95924:     sqlite3VdbeJumpHere(v, jZeroRows);
95925:   }
95926: }
95927: 
95928: 
95929: /*
95930: ** Generate code that will cause the most recent index analysis to
95931: ** be loaded into internal hash tables where is can be used.
95932: */
95933: static void loadAnalysis(Parse *pParse, int iDb){
95934:   Vdbe *v = sqlite3GetVdbe(pParse);
95935:   if( v ){
95936:     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
95937:   }
95938: }
95939: 
95940: /*
95941: ** Generate code that will do an analysis of an entire database
95942: */
95943: static void analyzeDatabase(Parse *pParse, int iDb){
95944:   sqlite3 *db = pParse->db;
95945:   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
95946:   HashElem *k;
95947:   int iStatCur;
95948:   int iMem;
95949:   int iTab;
95950: 
95951:   sqlite3BeginWriteOperation(pParse, 0, iDb);
95952:   iStatCur = pParse->nTab;
95953:   pParse->nTab += 3;
95954:   openStatTable(pParse, iDb, iStatCur, 0, 0);
95955:   iMem = pParse->nMem+1;
95956:   iTab = pParse->nTab;
95957:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95958:   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
95959:     Table *pTab = (Table*)sqliteHashData(k);
95960:     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
95961:   }
95962:   loadAnalysis(pParse, iDb);
95963: }
95964: 
95965: /*
95966: ** Generate code that will do an analysis of a single table in
95967: ** a database.  If pOnlyIdx is not NULL then it is a single index
95968: ** in pTab that should be analyzed.
95969: */
95970: static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
95971:   int iDb;
95972:   int iStatCur;
95973: 
95974:   assert( pTab!=0 );
95975:   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95976:   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95977:   sqlite3BeginWriteOperation(pParse, 0, iDb);
95978:   iStatCur = pParse->nTab;
95979:   pParse->nTab += 3;
95980:   if( pOnlyIdx ){
95981:     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
95982:   }else{
95983:     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
95984:   }
95985:   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
95986:   loadAnalysis(pParse, iDb);
95987: }
95988: 
95989: /*
95990: ** Generate code for the ANALYZE command.  The parser calls this routine
95991: ** when it recognizes an ANALYZE command.
95992: **
95993: **        ANALYZE                            -- 1
95994: **        ANALYZE  <database>                -- 2
95995: **        ANALYZE  ?<database>.?<tablename>  -- 3
95996: **
95997: ** Form 1 causes all indices in all attached databases to be analyzed.
95998: ** Form 2 analyzes all indices the single database named.
95999: ** Form 3 analyzes all indices associated with the named table.
96000: */
96001: SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
96002:   sqlite3 *db = pParse->db;
96003:   int iDb;
96004:   int i;
96005:   char *z, *zDb;
96006:   Table *pTab;
96007:   Index *pIdx;
96008:   Token *pTableName;
96009:   Vdbe *v;
96010: 
96011:   /* Read the database schema. If an error occurs, leave an error message
96012:   ** and code in pParse and return NULL. */
96013:   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
96014:   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
96015:     return;
96016:   }
96017: 
96018:   assert( pName2!=0 || pName1==0 );
96019:   if( pName1==0 ){
96020:     /* Form 1:  Analyze everything */
96021:     for(i=0; i<db->nDb; i++){
96022:       if( i==1 ) continue;  /* Do not analyze the TEMP database */
96023:       analyzeDatabase(pParse, i);
96024:     }
96025:   }else if( pName2->n==0 ){
96026:     /* Form 2:  Analyze the database or table named */
96027:     iDb = sqlite3FindDb(db, pName1);
96028:     if( iDb>=0 ){
96029:       analyzeDatabase(pParse, iDb);
96030:     }else{
96031:       z = sqlite3NameFromToken(db, pName1);
96032:       if( z ){
96033:         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
96034:           analyzeTable(pParse, pIdx->pTable, pIdx);
96035:         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
96036:           analyzeTable(pParse, pTab, 0);
96037:         }
96038:         sqlite3DbFree(db, z);
96039:       }
96040:     }
96041:   }else{
96042:     /* Form 3: Analyze the fully qualified table name */
96043:     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
96044:     if( iDb>=0 ){
96045:       zDb = db->aDb[iDb].zName;
96046:       z = sqlite3NameFromToken(db, pTableName);
96047:       if( z ){
96048:         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
96049:           analyzeTable(pParse, pIdx->pTable, pIdx);
96050:         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
96051:           analyzeTable(pParse, pTab, 0);
96052:         }
96053:         sqlite3DbFree(db, z);
96054:       }
96055:     }   
96056:   }
96057:   v = sqlite3GetVdbe(pParse);
96058:   if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
96059: }
96060: 
96061: /*
96062: ** Used to pass information from the analyzer reader through to the
96063: ** callback routine.
96064: */
96065: typedef struct analysisInfo analysisInfo;
96066: struct analysisInfo {
96067:   sqlite3 *db;
96068:   const char *zDatabase;
96069: };
96070: 
96071: /*
96072: ** The first argument points to a nul-terminated string containing a
96073: ** list of space separated integers. Read the first nOut of these into
96074: ** the array aOut[].
96075: */
96076: static void decodeIntArray(
96077:   char *zIntArray,       /* String containing int array to decode */
96078:   int nOut,              /* Number of slots in aOut[] */
96079:   tRowcnt *aOut,         /* Store integers here */
96080:   LogEst *aLog,          /* Or, if aOut==0, here */
96081:   Index *pIndex          /* Handle extra flags for this index, if not NULL */
96082: ){
96083:   char *z = zIntArray;
96084:   int c;
96085:   int i;
96086:   tRowcnt v;
96087: 
96088: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96089:   if( z==0 ) z = "";
96090: #else
96091:   assert( z!=0 );
96092: #endif
96093:   for(i=0; *z && i<nOut; i++){
96094:     v = 0;
96095:     while( (c=z[0])>='0' && c<='9' ){
96096:       v = v*10 + c - '0';
96097:       z++;
96098:     }
96099: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96100:     if( aOut ) aOut[i] = v;
96101:     if( aLog ) aLog[i] = sqlite3LogEst(v);
96102: #else
96103:     assert( aOut==0 );
96104:     UNUSED_PARAMETER(aOut);
96105:     assert( aLog!=0 );
96106:     aLog[i] = sqlite3LogEst(v);
96107: #endif
96108:     if( *z==' ' ) z++;
96109:   }
96110: #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
96111:   assert( pIndex!=0 ); {
96112: #else
96113:   if( pIndex ){
96114: #endif
96115:     pIndex->bUnordered = 0;
96116:     pIndex->noSkipScan = 0;
96117:     while( z[0] ){
96118:       if( sqlite3_strglob("unordered*", z)==0 ){
96119:         pIndex->bUnordered = 1;
96120:       }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
96121:         pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
96122:       }else if( sqlite3_strglob("noskipscan*", z)==0 ){
96123:         pIndex->noSkipScan = 1;
96124:       }
96125: #ifdef SQLITE_ENABLE_COSTMULT
96126:       else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
96127:         pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
96128:       }
96129: #endif
96130:       while( z[0]!=0 && z[0]!=' ' ) z++;
96131:       while( z[0]==' ' ) z++;
96132:     }
96133:   }
96134: }
96135: 
96136: /*
96137: ** This callback is invoked once for each index when reading the
96138: ** sqlite_stat1 table.  
96139: **
96140: **     argv[0] = name of the table
96141: **     argv[1] = name of the index (might be NULL)
96142: **     argv[2] = results of analysis - on integer for each column
96143: **
96144: ** Entries for which argv[1]==NULL simply record the number of rows in
96145: ** the table.
96146: */
96147: static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
96148:   analysisInfo *pInfo = (analysisInfo*)pData;
96149:   Index *pIndex;
96150:   Table *pTable;
96151:   const char *z;
96152: 
96153:   assert( argc==3 );
96154:   UNUSED_PARAMETER2(NotUsed, argc);
96155: 
96156:   if( argv==0 || argv[0]==0 || argv[2]==0 ){
96157:     return 0;
96158:   }
96159:   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
96160:   if( pTable==0 ){
96161:     return 0;
96162:   }
96163:   if( argv[1]==0 ){
96164:     pIndex = 0;
96165:   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
96166:     pIndex = sqlite3PrimaryKeyIndex(pTable);
96167:   }else{
96168:     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
96169:   }
96170:   z = argv[2];
96171: 
96172:   if( pIndex ){
96173:     tRowcnt *aiRowEst = 0;
96174:     int nCol = pIndex->nKeyCol+1;
96175: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96176:     /* Index.aiRowEst may already be set here if there are duplicate 
96177:     ** sqlite_stat1 entries for this index. In that case just clobber
96178:     ** the old data with the new instead of allocating a new array.  */
96179:     if( pIndex->aiRowEst==0 ){
96180:       pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
96181:       if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
96182:     }
96183:     aiRowEst = pIndex->aiRowEst;
96184: #endif
96185:     pIndex->bUnordered = 0;
96186:     decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
96187:     if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
96188:   }else{
96189:     Index fakeIdx;
96190:     fakeIdx.szIdxRow = pTable->szTabRow;
96191: #ifdef SQLITE_ENABLE_COSTMULT
96192:     fakeIdx.pTable = pTable;
96193: #endif
96194:     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
96195:     pTable->szTabRow = fakeIdx.szIdxRow;
96196:   }
96197: 
96198:   return 0;
96199: }
96200: 
96201: /*
96202: ** If the Index.aSample variable is not NULL, delete the aSample[] array
96203: ** and its contents.
96204: */
96205: SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
96206: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96207:   if( pIdx->aSample ){
96208:     int j;
96209:     for(j=0; j<pIdx->nSample; j++){
96210:       IndexSample *p = &pIdx->aSample[j];
96211:       sqlite3DbFree(db, p->p);
96212:     }
96213:     sqlite3DbFree(db, pIdx->aSample);
96214:   }
96215:   if( db && db->pnBytesFreed==0 ){
96216:     pIdx->nSample = 0;
96217:     pIdx->aSample = 0;
96218:   }
96219: #else
96220:   UNUSED_PARAMETER(db);
96221:   UNUSED_PARAMETER(pIdx);
96222: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96223: }
96224: 
96225: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96226: /*
96227: ** Populate the pIdx->aAvgEq[] array based on the samples currently
96228: ** stored in pIdx->aSample[]. 
96229: */
96230: static void initAvgEq(Index *pIdx){
96231:   if( pIdx ){
96232:     IndexSample *aSample = pIdx->aSample;
96233:     IndexSample *pFinal = &aSample[pIdx->nSample-1];
96234:     int iCol;
96235:     int nCol = 1;
96236:     if( pIdx->nSampleCol>1 ){
96237:       /* If this is stat4 data, then calculate aAvgEq[] values for all
96238:       ** sample columns except the last. The last is always set to 1, as
96239:       ** once the trailing PK fields are considered all index keys are
96240:       ** unique.  */
96241:       nCol = pIdx->nSampleCol-1;
96242:       pIdx->aAvgEq[nCol] = 1;
96243:     }
96244:     for(iCol=0; iCol<nCol; iCol++){
96245:       int nSample = pIdx->nSample;
96246:       int i;                    /* Used to iterate through samples */
96247:       tRowcnt sumEq = 0;        /* Sum of the nEq values */
96248:       tRowcnt avgEq = 0;
96249:       tRowcnt nRow;             /* Number of rows in index */
96250:       i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
96251:       i64 nDist100;             /* Number of distinct values in index */
96252: 
96253:       if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
96254:         nRow = pFinal->anLt[iCol];
96255:         nDist100 = (i64)100 * pFinal->anDLt[iCol];
96256:         nSample--;
96257:       }else{
96258:         nRow = pIdx->aiRowEst[0];
96259:         nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
96260:       }
96261:       pIdx->nRowEst0 = nRow;
96262: 
96263:       /* Set nSum to the number of distinct (iCol+1) field prefixes that
96264:       ** occur in the stat4 table for this index. Set sumEq to the sum of 
96265:       ** the nEq values for column iCol for the same set (adding the value 
96266:       ** only once where there exist duplicate prefixes).  */
96267:       for(i=0; i<nSample; i++){
96268:         if( i==(pIdx->nSample-1)
96269:          || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] 
96270:         ){
96271:           sumEq += aSample[i].anEq[iCol];
96272:           nSum100 += 100;
96273:         }
96274:       }
96275: 
96276:       if( nDist100>nSum100 ){
96277:         avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
96278:       }
96279:       if( avgEq==0 ) avgEq = 1;
96280:       pIdx->aAvgEq[iCol] = avgEq;
96281:     }
96282:   }
96283: }
96284: 
96285: /*
96286: ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
96287: ** is supplied instead, find the PRIMARY KEY index for that table.
96288: */
96289: static Index *findIndexOrPrimaryKey(
96290:   sqlite3 *db,
96291:   const char *zName,
96292:   const char *zDb
96293: ){
96294:   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
96295:   if( pIdx==0 ){
96296:     Table *pTab = sqlite3FindTable(db, zName, zDb);
96297:     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
96298:   }
96299:   return pIdx;
96300: }
96301: 
96302: /*
96303: ** Load the content from either the sqlite_stat4 or sqlite_stat3 table 
96304: ** into the relevant Index.aSample[] arrays.
96305: **
96306: ** Arguments zSql1 and zSql2 must point to SQL statements that return
96307: ** data equivalent to the following (statements are different for stat3,
96308: ** see the caller of this function for details):
96309: **
96310: **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
96311: **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
96312: **
96313: ** where %Q is replaced with the database name before the SQL is executed.
96314: */
96315: static int loadStatTbl(
96316:   sqlite3 *db,                  /* Database handle */
96317:   int bStat3,                   /* Assume single column records only */
96318:   const char *zSql1,            /* SQL statement 1 (see above) */
96319:   const char *zSql2,            /* SQL statement 2 (see above) */
96320:   const char *zDb               /* Database name (e.g. "main") */
96321: ){
96322:   int rc;                       /* Result codes from subroutines */
96323:   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
96324:   char *zSql;                   /* Text of the SQL statement */
96325:   Index *pPrevIdx = 0;          /* Previous index in the loop */
96326:   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
96327: 
96328:   assert( db->lookaside.bDisable );
96329:   zSql = sqlite3MPrintf(db, zSql1, zDb);
96330:   if( !zSql ){
96331:     return SQLITE_NOMEM_BKPT;
96332:   }
96333:   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96334:   sqlite3DbFree(db, zSql);
96335:   if( rc ) return rc;
96336: 
96337:   while( sqlite3_step(pStmt)==SQLITE_ROW ){
96338:     int nIdxCol = 1;              /* Number of columns in stat4 records */
96339: 
96340:     char *zIndex;   /* Index name */
96341:     Index *pIdx;    /* Pointer to the index object */
96342:     int nSample;    /* Number of samples */
96343:     int nByte;      /* Bytes of space required */
96344:     int i;          /* Bytes of space required */
96345:     tRowcnt *pSpace;
96346: 
96347:     zIndex = (char *)sqlite3_column_text(pStmt, 0);
96348:     if( zIndex==0 ) continue;
96349:     nSample = sqlite3_column_int(pStmt, 1);
96350:     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
96351:     assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
96352:     /* Index.nSample is non-zero at this point if data has already been
96353:     ** loaded from the stat4 table. In this case ignore stat3 data.  */
96354:     if( pIdx==0 || pIdx->nSample ) continue;
96355:     if( bStat3==0 ){
96356:       assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
96357:       if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
96358:         nIdxCol = pIdx->nKeyCol;
96359:       }else{
96360:         nIdxCol = pIdx->nColumn;
96361:       }
96362:     }
96363:     pIdx->nSampleCol = nIdxCol;
96364:     nByte = sizeof(IndexSample) * nSample;
96365:     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
96366:     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
96367: 
96368:     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
96369:     if( pIdx->aSample==0 ){
96370:       sqlite3_finalize(pStmt);
96371:       return SQLITE_NOMEM_BKPT;
96372:     }
96373:     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
96374:     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
96375:     for(i=0; i<nSample; i++){
96376:       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
96377:       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
96378:       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
96379:     }
96380:     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
96381:   }
96382:   rc = sqlite3_finalize(pStmt);
96383:   if( rc ) return rc;
96384: 
96385:   zSql = sqlite3MPrintf(db, zSql2, zDb);
96386:   if( !zSql ){
96387:     return SQLITE_NOMEM_BKPT;
96388:   }
96389:   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
96390:   sqlite3DbFree(db, zSql);
96391:   if( rc ) return rc;
96392: 
96393:   while( sqlite3_step(pStmt)==SQLITE_ROW ){
96394:     char *zIndex;                 /* Index name */
96395:     Index *pIdx;                  /* Pointer to the index object */
96396:     int nCol = 1;                 /* Number of columns in index */
96397: 
96398:     zIndex = (char *)sqlite3_column_text(pStmt, 0);
96399:     if( zIndex==0 ) continue;
96400:     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
96401:     if( pIdx==0 ) continue;
96402:     /* This next condition is true if data has already been loaded from 
96403:     ** the sqlite_stat4 table. In this case ignore stat3 data.  */
96404:     nCol = pIdx->nSampleCol;
96405:     if( bStat3 && nCol>1 ) continue;
96406:     if( pIdx!=pPrevIdx ){
96407:       initAvgEq(pPrevIdx);
96408:       pPrevIdx = pIdx;
96409:     }
96410:     pSample = &pIdx->aSample[pIdx->nSample];
96411:     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
96412:     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
96413:     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
96414: 
96415:     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
96416:     ** This is in case the sample record is corrupted. In that case, the
96417:     ** sqlite3VdbeRecordCompare() may read up to two varints past the
96418:     ** end of the allocated buffer before it realizes it is dealing with
96419:     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
96420:     ** a buffer overread.  */
96421:     pSample->n = sqlite3_column_bytes(pStmt, 4);
96422:     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
96423:     if( pSample->p==0 ){
96424:       sqlite3_finalize(pStmt);
96425:       return SQLITE_NOMEM_BKPT;
96426:     }
96427:     memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
96428:     pIdx->nSample++;
96429:   }
96430:   rc = sqlite3_finalize(pStmt);
96431:   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
96432:   return rc;
96433: }
96434: 
96435: /*
96436: ** Load content from the sqlite_stat4 and sqlite_stat3 tables into 
96437: ** the Index.aSample[] arrays of all indices.
96438: */
96439: static int loadStat4(sqlite3 *db, const char *zDb){
96440:   int rc = SQLITE_OK;             /* Result codes from subroutines */
96441: 
96442:   assert( db->lookaside.bDisable );
96443:   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
96444:     rc = loadStatTbl(db, 0,
96445:       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
96446:       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
96447:       zDb
96448:     );
96449:   }
96450: 
96451:   if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
96452:     rc = loadStatTbl(db, 1,
96453:       "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", 
96454:       "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
96455:       zDb
96456:     );
96457:   }
96458: 
96459:   return rc;
96460: }
96461: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
96462: 
96463: /*
96464: ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
96465: ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
96466: ** arrays. The contents of sqlite_stat3/4 are used to populate the
96467: ** Index.aSample[] arrays.
96468: **
96469: ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
96470: ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined 
96471: ** during compilation and the sqlite_stat3/4 table is present, no data is 
96472: ** read from it.
96473: **
96474: ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the 
96475: ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
96476: ** returned. However, in this case, data is read from the sqlite_stat1
96477: ** table (if it is present) before returning.
96478: **
96479: ** If an OOM error occurs, this function always sets db->mallocFailed.
96480: ** This means if the caller does not care about other errors, the return
96481: ** code may be ignored.
96482: */
96483: SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
96484:   analysisInfo sInfo;
96485:   HashElem *i;
96486:   char *zSql;
96487:   int rc = SQLITE_OK;
96488: 
96489:   assert( iDb>=0 && iDb<db->nDb );
96490:   assert( db->aDb[iDb].pBt!=0 );
96491: 
96492:   /* Clear any prior statistics */
96493:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96494:   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96495:     Index *pIdx = sqliteHashData(i);
96496:     pIdx->aiRowLogEst[0] = 0;
96497: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96498:     sqlite3DeleteIndexSamples(db, pIdx);
96499:     pIdx->aSample = 0;
96500: #endif
96501:   }
96502: 
96503:   /* Load new statistics out of the sqlite_stat1 table */
96504:   sInfo.db = db;
96505:   sInfo.zDatabase = db->aDb[iDb].zName;
96506:   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
96507:     zSql = sqlite3MPrintf(db, 
96508:         "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
96509:     if( zSql==0 ){
96510:       rc = SQLITE_NOMEM_BKPT;
96511:     }else{
96512:       rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
96513:       sqlite3DbFree(db, zSql);
96514:     }
96515:   }
96516: 
96517:   /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
96518:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
96519:   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96520:     Index *pIdx = sqliteHashData(i);
96521:     if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
96522:   }
96523: 
96524:   /* Load the statistics from the sqlite_stat4 table. */
96525: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
96526:   if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
96527:     db->lookaside.bDisable++;
96528:     rc = loadStat4(db, sInfo.zDatabase);
96529:     db->lookaside.bDisable--;
96530:   }
96531:   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
96532:     Index *pIdx = sqliteHashData(i);
96533:     sqlite3_free(pIdx->aiRowEst);
96534:     pIdx->aiRowEst = 0;
96535:   }
96536: #endif
96537: 
96538:   if( rc==SQLITE_NOMEM ){
96539:     sqlite3OomFault(db);
96540:   }
96541:   return rc;
96542: }
96543: 
96544: 
96545: #endif /* SQLITE_OMIT_ANALYZE */
96546: 
96547: /************** End of analyze.c *********************************************/
96548: /************** Begin file attach.c ******************************************/
96549: /*
96550: ** 2003 April 6
96551: **
96552: ** The author disclaims copyright to this source code.  In place of
96553: ** a legal notice, here is a blessing:
96554: **
96555: **    May you do good and not evil.
96556: **    May you find forgiveness for yourself and forgive others.
96557: **    May you share freely, never taking more than you give.
96558: **
96559: *************************************************************************
96560: ** This file contains code used to implement the ATTACH and DETACH commands.
96561: */
96562: /* #include "sqliteInt.h" */
96563: 
96564: #ifndef SQLITE_OMIT_ATTACH
96565: /*
96566: ** Resolve an expression that was part of an ATTACH or DETACH statement. This
96567: ** is slightly different from resolving a normal SQL expression, because simple
96568: ** identifiers are treated as strings, not possible column names or aliases.
96569: **
96570: ** i.e. if the parser sees:
96571: **
96572: **     ATTACH DATABASE abc AS def
96573: **
96574: ** it treats the two expressions as literal strings 'abc' and 'def' instead of
96575: ** looking for columns of the same name.
96576: **
96577: ** This only applies to the root node of pExpr, so the statement:
96578: **
96579: **     ATTACH DATABASE abc||def AS 'db2'
96580: **
96581: ** will fail because neither abc or def can be resolved.
96582: */
96583: static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
96584: {
96585:   int rc = SQLITE_OK;
96586:   if( pExpr ){
96587:     if( pExpr->op!=TK_ID ){
96588:       rc = sqlite3ResolveExprNames(pName, pExpr);
96589:     }else{
96590:       pExpr->op = TK_STRING;
96591:     }
96592:   }
96593:   return rc;
96594: }
96595: 
96596: /*
96597: ** An SQL user-function registered to do the work of an ATTACH statement. The
96598: ** three arguments to the function come directly from an attach statement:
96599: **
96600: **     ATTACH DATABASE x AS y KEY z
96601: **
96602: **     SELECT sqlite_attach(x, y, z)
96603: **
96604: ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
96605: ** third argument.
96606: */
96607: static void attachFunc(
96608:   sqlite3_context *context,
96609:   int NotUsed,
96610:   sqlite3_value **argv
96611: ){
96612:   int i;
96613:   int rc = 0;
96614:   sqlite3 *db = sqlite3_context_db_handle(context);
96615:   const char *zName;
96616:   const char *zFile;
96617:   char *zPath = 0;
96618:   char *zErr = 0;
96619:   unsigned int flags;
96620:   Db *aNew;
96621:   char *zErrDyn = 0;
96622:   sqlite3_vfs *pVfs;
96623: 
96624:   UNUSED_PARAMETER(NotUsed);
96625: 
96626:   zFile = (const char *)sqlite3_value_text(argv[0]);
96627:   zName = (const char *)sqlite3_value_text(argv[1]);
96628:   if( zFile==0 ) zFile = "";
96629:   if( zName==0 ) zName = "";
96630: 
96631:   /* Check for the following errors:
96632:   **
96633:   **     * Too many attached databases,
96634:   **     * Transaction currently open
96635:   **     * Specified database name already being used.
96636:   */
96637:   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
96638:     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
96639:       db->aLimit[SQLITE_LIMIT_ATTACHED]
96640:     );
96641:     goto attach_error;
96642:   }
96643:   if( !db->autoCommit ){
96644:     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
96645:     goto attach_error;
96646:   }
96647:   for(i=0; i<db->nDb; i++){
96648:     char *z = db->aDb[i].zName;
96649:     assert( z && zName );
96650:     if( sqlite3StrICmp(z, zName)==0 ){
96651:       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
96652:       goto attach_error;
96653:     }
96654:   }
96655: 
96656:   /* Allocate the new entry in the db->aDb[] array and initialize the schema
96657:   ** hash tables.
96658:   */
96659:   if( db->aDb==db->aDbStatic ){
96660:     aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
96661:     if( aNew==0 ) return;
96662:     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
96663:   }else{
96664:     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
96665:     if( aNew==0 ) return;
96666:   }
96667:   db->aDb = aNew;
96668:   aNew = &db->aDb[db->nDb];
96669:   memset(aNew, 0, sizeof(*aNew));
96670: 
96671:   /* Open the database file. If the btree is successfully opened, use
96672:   ** it to obtain the database schema. At this point the schema may
96673:   ** or may not be initialized.
96674:   */
96675:   flags = db->openFlags;
96676:   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
96677:   if( rc!=SQLITE_OK ){
96678:     if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
96679:     sqlite3_result_error(context, zErr, -1);
96680:     sqlite3_free(zErr);
96681:     return;
96682:   }
96683:   assert( pVfs );
96684:   flags |= SQLITE_OPEN_MAIN_DB;
96685:   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
96686:   sqlite3_free( zPath );
96687:   db->nDb++;
96688:   if( rc==SQLITE_CONSTRAINT ){
96689:     rc = SQLITE_ERROR;
96690:     zErrDyn = sqlite3MPrintf(db, "database is already attached");
96691:   }else if( rc==SQLITE_OK ){
96692:     Pager *pPager;
96693:     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
96694:     if( !aNew->pSchema ){
96695:       rc = SQLITE_NOMEM_BKPT;
96696:     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
96697:       zErrDyn = sqlite3MPrintf(db, 
96698:         "attached databases must use the same text encoding as main database");
96699:       rc = SQLITE_ERROR;
96700:     }
96701:     sqlite3BtreeEnter(aNew->pBt);
96702:     pPager = sqlite3BtreePager(aNew->pBt);
96703:     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
96704:     sqlite3BtreeSecureDelete(aNew->pBt,
96705:                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
96706: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
96707:     sqlite3BtreeSetPagerFlags(aNew->pBt,
96708:                       PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
96709: #endif
96710:     sqlite3BtreeLeave(aNew->pBt);
96711:   }
96712:   aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
96713:   aNew->zName = sqlite3DbStrDup(db, zName);
96714:   if( rc==SQLITE_OK && aNew->zName==0 ){
96715:     rc = SQLITE_NOMEM_BKPT;
96716:   }
96717: 
96718: 
96719: #ifdef SQLITE_HAS_CODEC
96720:   if( rc==SQLITE_OK ){
96721:     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
96722:     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96723:     int nKey;
96724:     char *zKey;
96725:     int t = sqlite3_value_type(argv[2]);
96726:     switch( t ){
96727:       case SQLITE_INTEGER:
96728:       case SQLITE_FLOAT:
96729:         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
96730:         rc = SQLITE_ERROR;
96731:         break;
96732:         
96733:       case SQLITE_TEXT:
96734:       case SQLITE_BLOB:
96735:         nKey = sqlite3_value_bytes(argv[2]);
96736:         zKey = (char *)sqlite3_value_blob(argv[2]);
96737:         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96738:         break;
96739: 
96740:       case SQLITE_NULL:
96741:         /* No key specified.  Use the key from the main database */
96742:         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96743:         if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
96744:           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96745:         }
96746:         break;
96747:     }
96748:   }
96749: #endif
96750: 
96751:   /* If the file was opened successfully, read the schema for the new database.
96752:   ** If this fails, or if opening the file failed, then close the file and 
96753:   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
96754:   ** we found it.
96755:   */
96756:   if( rc==SQLITE_OK ){
96757:     sqlite3BtreeEnterAll(db);
96758:     rc = sqlite3Init(db, &zErrDyn);
96759:     sqlite3BtreeLeaveAll(db);
96760:   }
96761: #ifdef SQLITE_USER_AUTHENTICATION
96762:   if( rc==SQLITE_OK ){
96763:     u8 newAuth = 0;
96764:     rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
96765:     if( newAuth<db->auth.authLevel ){
96766:       rc = SQLITE_AUTH_USER;
96767:     }
96768:   }
96769: #endif
96770:   if( rc ){
96771:     int iDb = db->nDb - 1;
96772:     assert( iDb>=2 );
96773:     if( db->aDb[iDb].pBt ){
96774:       sqlite3BtreeClose(db->aDb[iDb].pBt);
96775:       db->aDb[iDb].pBt = 0;
96776:       db->aDb[iDb].pSchema = 0;
96777:     }
96778:     sqlite3ResetAllSchemasOfConnection(db);
96779:     db->nDb = iDb;
96780:     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
96781:       sqlite3OomFault(db);
96782:       sqlite3DbFree(db, zErrDyn);
96783:       zErrDyn = sqlite3MPrintf(db, "out of memory");
96784:     }else if( zErrDyn==0 ){
96785:       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
96786:     }
96787:     goto attach_error;
96788:   }
96789:   
96790:   return;
96791: 
96792: attach_error:
96793:   /* Return an error if we get here */
96794:   if( zErrDyn ){
96795:     sqlite3_result_error(context, zErrDyn, -1);
96796:     sqlite3DbFree(db, zErrDyn);
96797:   }
96798:   if( rc ) sqlite3_result_error_code(context, rc);
96799: }
96800: 
96801: /*
96802: ** An SQL user-function registered to do the work of an DETACH statement. The
96803: ** three arguments to the function come directly from a detach statement:
96804: **
96805: **     DETACH DATABASE x
96806: **
96807: **     SELECT sqlite_detach(x)
96808: */
96809: static void detachFunc(
96810:   sqlite3_context *context,
96811:   int NotUsed,
96812:   sqlite3_value **argv
96813: ){
96814:   const char *zName = (const char *)sqlite3_value_text(argv[0]);
96815:   sqlite3 *db = sqlite3_context_db_handle(context);
96816:   int i;
96817:   Db *pDb = 0;
96818:   char zErr[128];
96819: 
96820:   UNUSED_PARAMETER(NotUsed);
96821: 
96822:   if( zName==0 ) zName = "";
96823:   for(i=0; i<db->nDb; i++){
96824:     pDb = &db->aDb[i];
96825:     if( pDb->pBt==0 ) continue;
96826:     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
96827:   }
96828: 
96829:   if( i>=db->nDb ){
96830:     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
96831:     goto detach_error;
96832:   }
96833:   if( i<2 ){
96834:     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
96835:     goto detach_error;
96836:   }
96837:   if( !db->autoCommit ){
96838:     sqlite3_snprintf(sizeof(zErr), zErr,
96839:                      "cannot DETACH database within transaction");
96840:     goto detach_error;
96841:   }
96842:   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
96843:     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
96844:     goto detach_error;
96845:   }
96846: 
96847:   sqlite3BtreeClose(pDb->pBt);
96848:   pDb->pBt = 0;
96849:   pDb->pSchema = 0;
96850:   sqlite3CollapseDatabaseArray(db);
96851:   return;
96852: 
96853: detach_error:
96854:   sqlite3_result_error(context, zErr, -1);
96855: }
96856: 
96857: /*
96858: ** This procedure generates VDBE code for a single invocation of either the
96859: ** sqlite_detach() or sqlite_attach() SQL user functions.
96860: */
96861: static void codeAttach(
96862:   Parse *pParse,       /* The parser context */
96863:   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
96864:   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
96865:   Expr *pAuthArg,      /* Expression to pass to authorization callback */
96866:   Expr *pFilename,     /* Name of database file */
96867:   Expr *pDbname,       /* Name of the database to use internally */
96868:   Expr *pKey           /* Database key for encryption extension */
96869: ){
96870:   int rc;
96871:   NameContext sName;
96872:   Vdbe *v;
96873:   sqlite3* db = pParse->db;
96874:   int regArgs;
96875: 
96876:   memset(&sName, 0, sizeof(NameContext));
96877:   sName.pParse = pParse;
96878: 
96879:   if( 
96880:       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
96881:       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
96882:       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
96883:   ){
96884:     goto attach_end;
96885:   }
96886: 
96887: #ifndef SQLITE_OMIT_AUTHORIZATION
96888:   if( pAuthArg ){
96889:     char *zAuthArg;
96890:     if( pAuthArg->op==TK_STRING ){
96891:       zAuthArg = pAuthArg->u.zToken;
96892:     }else{
96893:       zAuthArg = 0;
96894:     }
96895:     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
96896:     if(rc!=SQLITE_OK ){
96897:       goto attach_end;
96898:     }
96899:   }
96900: #endif /* SQLITE_OMIT_AUTHORIZATION */
96901: 
96902: 
96903:   v = sqlite3GetVdbe(pParse);
96904:   regArgs = sqlite3GetTempRange(pParse, 4);
96905:   sqlite3ExprCode(pParse, pFilename, regArgs);
96906:   sqlite3ExprCode(pParse, pDbname, regArgs+1);
96907:   sqlite3ExprCode(pParse, pKey, regArgs+2);
96908: 
96909:   assert( v || db->mallocFailed );
96910:   if( v ){
96911:     sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
96912:                       (char *)pFunc, P4_FUNCDEF);
96913:     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
96914:     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
96915:  
96916:     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
96917:     ** statement only). For DETACH, set it to false (expire all existing
96918:     ** statements).
96919:     */
96920:     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
96921:   }
96922:   
96923: attach_end:
96924:   sqlite3ExprDelete(db, pFilename);
96925:   sqlite3ExprDelete(db, pDbname);
96926:   sqlite3ExprDelete(db, pKey);
96927: }
96928: 
96929: /*
96930: ** Called by the parser to compile a DETACH statement.
96931: **
96932: **     DETACH pDbname
96933: */
96934: SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
96935:   static const FuncDef detach_func = {
96936:     1,                /* nArg */
96937:     SQLITE_UTF8,      /* funcFlags */
96938:     0,                /* pUserData */
96939:     0,                /* pNext */
96940:     detachFunc,       /* xSFunc */
96941:     0,                /* xFinalize */
96942:     "sqlite_detach",  /* zName */
96943:     {0}
96944:   };
96945:   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
96946: }
96947: 
96948: /*
96949: ** Called by the parser to compile an ATTACH statement.
96950: **
96951: **     ATTACH p AS pDbname KEY pKey
96952: */
96953: SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
96954:   static const FuncDef attach_func = {
96955:     3,                /* nArg */
96956:     SQLITE_UTF8,      /* funcFlags */
96957:     0,                /* pUserData */
96958:     0,                /* pNext */
96959:     attachFunc,       /* xSFunc */
96960:     0,                /* xFinalize */
96961:     "sqlite_attach",  /* zName */
96962:     {0}
96963:   };
96964:   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
96965: }
96966: #endif /* SQLITE_OMIT_ATTACH */
96967: 
96968: /*
96969: ** Initialize a DbFixer structure.  This routine must be called prior
96970: ** to passing the structure to one of the sqliteFixAAAA() routines below.
96971: */
96972: SQLITE_PRIVATE void sqlite3FixInit(
96973:   DbFixer *pFix,      /* The fixer to be initialized */
96974:   Parse *pParse,      /* Error messages will be written here */
96975:   int iDb,            /* This is the database that must be used */
96976:   const char *zType,  /* "view", "trigger", or "index" */
96977:   const Token *pName  /* Name of the view, trigger, or index */
96978: ){
96979:   sqlite3 *db;
96980: 
96981:   db = pParse->db;
96982:   assert( db->nDb>iDb );
96983:   pFix->pParse = pParse;
96984:   pFix->zDb = db->aDb[iDb].zName;
96985:   pFix->pSchema = db->aDb[iDb].pSchema;
96986:   pFix->zType = zType;
96987:   pFix->pName = pName;
96988:   pFix->bVarOnly = (iDb==1);
96989: }
96990: 
96991: /*
96992: ** The following set of routines walk through the parse tree and assign
96993: ** a specific database to all table references where the database name
96994: ** was left unspecified in the original SQL statement.  The pFix structure
96995: ** must have been initialized by a prior call to sqlite3FixInit().
96996: **
96997: ** These routines are used to make sure that an index, trigger, or
96998: ** view in one database does not refer to objects in a different database.
96999: ** (Exception: indices, triggers, and views in the TEMP database are
97000: ** allowed to refer to anything.)  If a reference is explicitly made
97001: ** to an object in a different database, an error message is added to
97002: ** pParse->zErrMsg and these routines return non-zero.  If everything
97003: ** checks out, these routines return 0.
97004: */
97005: SQLITE_PRIVATE int sqlite3FixSrcList(
97006:   DbFixer *pFix,       /* Context of the fixation */
97007:   SrcList *pList       /* The Source list to check and modify */
97008: ){
97009:   int i;
97010:   const char *zDb;
97011:   struct SrcList_item *pItem;
97012: 
97013:   if( NEVER(pList==0) ) return 0;
97014:   zDb = pFix->zDb;
97015:   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
97016:     if( pFix->bVarOnly==0 ){
97017:       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
97018:         sqlite3ErrorMsg(pFix->pParse,
97019:             "%s %T cannot reference objects in database %s",
97020:             pFix->zType, pFix->pName, pItem->zDatabase);
97021:         return 1;
97022:       }
97023:       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
97024:       pItem->zDatabase = 0;
97025:       pItem->pSchema = pFix->pSchema;
97026:     }
97027: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97028:     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
97029:     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
97030: #endif
97031:   }
97032:   return 0;
97033: }
97034: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
97035: SQLITE_PRIVATE int sqlite3FixSelect(
97036:   DbFixer *pFix,       /* Context of the fixation */
97037:   Select *pSelect      /* The SELECT statement to be fixed to one database */
97038: ){
97039:   while( pSelect ){
97040:     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
97041:       return 1;
97042:     }
97043:     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
97044:       return 1;
97045:     }
97046:     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
97047:       return 1;
97048:     }
97049:     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
97050:       return 1;
97051:     }
97052:     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
97053:       return 1;
97054:     }
97055:     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
97056:       return 1;
97057:     }
97058:     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
97059:       return 1;
97060:     }
97061:     if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
97062:       return 1;
97063:     }
97064:     pSelect = pSelect->pPrior;
97065:   }
97066:   return 0;
97067: }
97068: SQLITE_PRIVATE int sqlite3FixExpr(
97069:   DbFixer *pFix,     /* Context of the fixation */
97070:   Expr *pExpr        /* The expression to be fixed to one database */
97071: ){
97072:   while( pExpr ){
97073:     if( pExpr->op==TK_VARIABLE ){
97074:       if( pFix->pParse->db->init.busy ){
97075:         pExpr->op = TK_NULL;
97076:       }else{
97077:         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
97078:         return 1;
97079:       }
97080:     }
97081:     if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
97082:     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97083:       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
97084:     }else{
97085:       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
97086:     }
97087:     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
97088:       return 1;
97089:     }
97090:     pExpr = pExpr->pLeft;
97091:   }
97092:   return 0;
97093: }
97094: SQLITE_PRIVATE int sqlite3FixExprList(
97095:   DbFixer *pFix,     /* Context of the fixation */
97096:   ExprList *pList    /* The expression to be fixed to one database */
97097: ){
97098:   int i;
97099:   struct ExprList_item *pItem;
97100:   if( pList==0 ) return 0;
97101:   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
97102:     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
97103:       return 1;
97104:     }
97105:   }
97106:   return 0;
97107: }
97108: #endif
97109: 
97110: #ifndef SQLITE_OMIT_TRIGGER
97111: SQLITE_PRIVATE int sqlite3FixTriggerStep(
97112:   DbFixer *pFix,     /* Context of the fixation */
97113:   TriggerStep *pStep /* The trigger step be fixed to one database */
97114: ){
97115:   while( pStep ){
97116:     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
97117:       return 1;
97118:     }
97119:     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
97120:       return 1;
97121:     }
97122:     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
97123:       return 1;
97124:     }
97125:     pStep = pStep->pNext;
97126:   }
97127:   return 0;
97128: }
97129: #endif
97130: 
97131: /************** End of attach.c **********************************************/
97132: /************** Begin file auth.c ********************************************/
97133: /*
97134: ** 2003 January 11
97135: **
97136: ** The author disclaims copyright to this source code.  In place of
97137: ** a legal notice, here is a blessing:
97138: **
97139: **    May you do good and not evil.
97140: **    May you find forgiveness for yourself and forgive others.
97141: **    May you share freely, never taking more than you give.
97142: **
97143: *************************************************************************
97144: ** This file contains code used to implement the sqlite3_set_authorizer()
97145: ** API.  This facility is an optional feature of the library.  Embedded
97146: ** systems that do not need this facility may omit it by recompiling
97147: ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
97148: */
97149: /* #include "sqliteInt.h" */
97150: 
97151: /*
97152: ** All of the code in this file may be omitted by defining a single
97153: ** macro.
97154: */
97155: #ifndef SQLITE_OMIT_AUTHORIZATION
97156: 
97157: /*
97158: ** Set or clear the access authorization function.
97159: **
97160: ** The access authorization function is be called during the compilation
97161: ** phase to verify that the user has read and/or write access permission on
97162: ** various fields of the database.  The first argument to the auth function
97163: ** is a copy of the 3rd argument to this routine.  The second argument
97164: ** to the auth function is one of these constants:
97165: **
97166: **       SQLITE_CREATE_INDEX
97167: **       SQLITE_CREATE_TABLE
97168: **       SQLITE_CREATE_TEMP_INDEX
97169: **       SQLITE_CREATE_TEMP_TABLE
97170: **       SQLITE_CREATE_TEMP_TRIGGER
97171: **       SQLITE_CREATE_TEMP_VIEW
97172: **       SQLITE_CREATE_TRIGGER
97173: **       SQLITE_CREATE_VIEW
97174: **       SQLITE_DELETE
97175: **       SQLITE_DROP_INDEX
97176: **       SQLITE_DROP_TABLE
97177: **       SQLITE_DROP_TEMP_INDEX
97178: **       SQLITE_DROP_TEMP_TABLE
97179: **       SQLITE_DROP_TEMP_TRIGGER
97180: **       SQLITE_DROP_TEMP_VIEW
97181: **       SQLITE_DROP_TRIGGER
97182: **       SQLITE_DROP_VIEW
97183: **       SQLITE_INSERT
97184: **       SQLITE_PRAGMA
97185: **       SQLITE_READ
97186: **       SQLITE_SELECT
97187: **       SQLITE_TRANSACTION
97188: **       SQLITE_UPDATE
97189: **
97190: ** The third and fourth arguments to the auth function are the name of
97191: ** the table and the column that are being accessed.  The auth function
97192: ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
97193: ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
97194: ** means that the SQL statement will never-run - the sqlite3_exec() call
97195: ** will return with an error.  SQLITE_IGNORE means that the SQL statement
97196: ** should run but attempts to read the specified column will return NULL
97197: ** and attempts to write the column will be ignored.
97198: **
97199: ** Setting the auth function to NULL disables this hook.  The default
97200: ** setting of the auth function is NULL.
97201: */
97202: SQLITE_API int sqlite3_set_authorizer(
97203:   sqlite3 *db,
97204:   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
97205:   void *pArg
97206: ){
97207: #ifdef SQLITE_ENABLE_API_ARMOR
97208:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
97209: #endif
97210:   sqlite3_mutex_enter(db->mutex);
97211:   db->xAuth = (sqlite3_xauth)xAuth;
97212:   db->pAuthArg = pArg;
97213:   sqlite3ExpirePreparedStatements(db);
97214:   sqlite3_mutex_leave(db->mutex);
97215:   return SQLITE_OK;
97216: }
97217: 
97218: /*
97219: ** Write an error message into pParse->zErrMsg that explains that the
97220: ** user-supplied authorization function returned an illegal value.
97221: */
97222: static void sqliteAuthBadReturnCode(Parse *pParse){
97223:   sqlite3ErrorMsg(pParse, "authorizer malfunction");
97224:   pParse->rc = SQLITE_ERROR;
97225: }
97226: 
97227: /*
97228: ** Invoke the authorization callback for permission to read column zCol from
97229: ** table zTab in database zDb. This function assumes that an authorization
97230: ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
97231: **
97232: ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
97233: ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
97234: ** is treated as SQLITE_DENY. In this case an error is left in pParse.
97235: */
97236: SQLITE_PRIVATE int sqlite3AuthReadCol(
97237:   Parse *pParse,                  /* The parser context */
97238:   const char *zTab,               /* Table name */
97239:   const char *zCol,               /* Column name */
97240:   int iDb                         /* Index of containing database. */
97241: ){
97242:   sqlite3 *db = pParse->db;       /* Database handle */
97243:   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
97244:   int rc;                         /* Auth callback return code */
97245: 
97246:   if( db->init.busy ) return SQLITE_OK;
97247:   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
97248: #ifdef SQLITE_USER_AUTHENTICATION
97249:                  ,db->auth.zAuthUser
97250: #endif
97251:                 );
97252:   if( rc==SQLITE_DENY ){
97253:     if( db->nDb>2 || iDb!=0 ){
97254:       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
97255:     }else{
97256:       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
97257:     }
97258:     pParse->rc = SQLITE_AUTH;
97259:   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
97260:     sqliteAuthBadReturnCode(pParse);
97261:   }
97262:   return rc;
97263: }
97264: 
97265: /*
97266: ** The pExpr should be a TK_COLUMN expression.  The table referred to
97267: ** is in pTabList or else it is the NEW or OLD table of a trigger.  
97268: ** Check to see if it is OK to read this particular column.
97269: **
97270: ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
97271: ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
97272: ** then generate an error.
97273: */
97274: SQLITE_PRIVATE void sqlite3AuthRead(
97275:   Parse *pParse,        /* The parser context */
97276:   Expr *pExpr,          /* The expression to check authorization on */
97277:   Schema *pSchema,      /* The schema of the expression */
97278:   SrcList *pTabList     /* All table that pExpr might refer to */
97279: ){
97280:   sqlite3 *db = pParse->db;
97281:   Table *pTab = 0;      /* The table being read */
97282:   const char *zCol;     /* Name of the column of the table */
97283:   int iSrc;             /* Index in pTabList->a[] of table being read */
97284:   int iDb;              /* The index of the database the expression refers to */
97285:   int iCol;             /* Index of column in table */
97286: 
97287:   if( db->xAuth==0 ) return;
97288:   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
97289:   if( iDb<0 ){
97290:     /* An attempt to read a column out of a subquery or other
97291:     ** temporary table. */
97292:     return;
97293:   }
97294: 
97295:   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
97296:   if( pExpr->op==TK_TRIGGER ){
97297:     pTab = pParse->pTriggerTab;
97298:   }else{
97299:     assert( pTabList );
97300:     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
97301:       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
97302:         pTab = pTabList->a[iSrc].pTab;
97303:         break;
97304:       }
97305:     }
97306:   }
97307:   iCol = pExpr->iColumn;
97308:   if( NEVER(pTab==0) ) return;
97309: 
97310:   if( iCol>=0 ){
97311:     assert( iCol<pTab->nCol );
97312:     zCol = pTab->aCol[iCol].zName;
97313:   }else if( pTab->iPKey>=0 ){
97314:     assert( pTab->iPKey<pTab->nCol );
97315:     zCol = pTab->aCol[pTab->iPKey].zName;
97316:   }else{
97317:     zCol = "ROWID";
97318:   }
97319:   assert( iDb>=0 && iDb<db->nDb );
97320:   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
97321:     pExpr->op = TK_NULL;
97322:   }
97323: }
97324: 
97325: /*
97326: ** Do an authorization check using the code and arguments given.  Return
97327: ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
97328: ** is returned, then the error count and error message in pParse are
97329: ** modified appropriately.
97330: */
97331: SQLITE_PRIVATE int sqlite3AuthCheck(
97332:   Parse *pParse,
97333:   int code,
97334:   const char *zArg1,
97335:   const char *zArg2,
97336:   const char *zArg3
97337: ){
97338:   sqlite3 *db = pParse->db;
97339:   int rc;
97340: 
97341:   /* Don't do any authorization checks if the database is initialising
97342:   ** or if the parser is being invoked from within sqlite3_declare_vtab.
97343:   */
97344:   if( db->init.busy || IN_DECLARE_VTAB ){
97345:     return SQLITE_OK;
97346:   }
97347: 
97348:   if( db->xAuth==0 ){
97349:     return SQLITE_OK;
97350:   }
97351:   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
97352: #ifdef SQLITE_USER_AUTHENTICATION
97353:                  ,db->auth.zAuthUser
97354: #endif
97355:                 );
97356:   if( rc==SQLITE_DENY ){
97357:     sqlite3ErrorMsg(pParse, "not authorized");
97358:     pParse->rc = SQLITE_AUTH;
97359:   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
97360:     rc = SQLITE_DENY;
97361:     sqliteAuthBadReturnCode(pParse);
97362:   }
97363:   return rc;
97364: }
97365: 
97366: /*
97367: ** Push an authorization context.  After this routine is called, the
97368: ** zArg3 argument to authorization callbacks will be zContext until
97369: ** popped.  Or if pParse==0, this routine is a no-op.
97370: */
97371: SQLITE_PRIVATE void sqlite3AuthContextPush(
97372:   Parse *pParse,
97373:   AuthContext *pContext, 
97374:   const char *zContext
97375: ){
97376:   assert( pParse );
97377:   pContext->pParse = pParse;
97378:   pContext->zAuthContext = pParse->zAuthContext;
97379:   pParse->zAuthContext = zContext;
97380: }
97381: 
97382: /*
97383: ** Pop an authorization context that was previously pushed
97384: ** by sqlite3AuthContextPush
97385: */
97386: SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
97387:   if( pContext->pParse ){
97388:     pContext->pParse->zAuthContext = pContext->zAuthContext;
97389:     pContext->pParse = 0;
97390:   }
97391: }
97392: 
97393: #endif /* SQLITE_OMIT_AUTHORIZATION */
97394: 
97395: /************** End of auth.c ************************************************/
97396: /************** Begin file build.c *******************************************/
97397: /*
97398: ** 2001 September 15
97399: **
97400: ** The author disclaims copyright to this source code.  In place of
97401: ** a legal notice, here is a blessing:
97402: **
97403: **    May you do good and not evil.
97404: **    May you find forgiveness for yourself and forgive others.
97405: **    May you share freely, never taking more than you give.
97406: **
97407: *************************************************************************
97408: ** This file contains C code routines that are called by the SQLite parser
97409: ** when syntax rules are reduced.  The routines in this file handle the
97410: ** following kinds of SQL syntax:
97411: **
97412: **     CREATE TABLE
97413: **     DROP TABLE
97414: **     CREATE INDEX
97415: **     DROP INDEX
97416: **     creating ID lists
97417: **     BEGIN TRANSACTION
97418: **     COMMIT
97419: **     ROLLBACK
97420: */
97421: /* #include "sqliteInt.h" */
97422: 
97423: #ifndef SQLITE_OMIT_SHARED_CACHE
97424: /*
97425: ** The TableLock structure is only used by the sqlite3TableLock() and
97426: ** codeTableLocks() functions.
97427: */
97428: struct TableLock {
97429:   int iDb;             /* The database containing the table to be locked */
97430:   int iTab;            /* The root page of the table to be locked */
97431:   u8 isWriteLock;      /* True for write lock.  False for a read lock */
97432:   const char *zName;   /* Name of the table */
97433: };
97434: 
97435: /*
97436: ** Record the fact that we want to lock a table at run-time.  
97437: **
97438: ** The table to be locked has root page iTab and is found in database iDb.
97439: ** A read or a write lock can be taken depending on isWritelock.
97440: **
97441: ** This routine just records the fact that the lock is desired.  The
97442: ** code to make the lock occur is generated by a later call to
97443: ** codeTableLocks() which occurs during sqlite3FinishCoding().
97444: */
97445: SQLITE_PRIVATE void sqlite3TableLock(
97446:   Parse *pParse,     /* Parsing context */
97447:   int iDb,           /* Index of the database containing the table to lock */
97448:   int iTab,          /* Root page number of the table to be locked */
97449:   u8 isWriteLock,    /* True for a write lock */
97450:   const char *zName  /* Name of the table to be locked */
97451: ){
97452:   Parse *pToplevel = sqlite3ParseToplevel(pParse);
97453:   int i;
97454:   int nBytes;
97455:   TableLock *p;
97456:   assert( iDb>=0 );
97457: 
97458:   for(i=0; i<pToplevel->nTableLock; i++){
97459:     p = &pToplevel->aTableLock[i];
97460:     if( p->iDb==iDb && p->iTab==iTab ){
97461:       p->isWriteLock = (p->isWriteLock || isWriteLock);
97462:       return;
97463:     }
97464:   }
97465: 
97466:   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
97467:   pToplevel->aTableLock =
97468:       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
97469:   if( pToplevel->aTableLock ){
97470:     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
97471:     p->iDb = iDb;
97472:     p->iTab = iTab;
97473:     p->isWriteLock = isWriteLock;
97474:     p->zName = zName;
97475:   }else{
97476:     pToplevel->nTableLock = 0;
97477:     sqlite3OomFault(pToplevel->db);
97478:   }
97479: }
97480: 
97481: /*
97482: ** Code an OP_TableLock instruction for each table locked by the
97483: ** statement (configured by calls to sqlite3TableLock()).
97484: */
97485: static void codeTableLocks(Parse *pParse){
97486:   int i;
97487:   Vdbe *pVdbe; 
97488: 
97489:   pVdbe = sqlite3GetVdbe(pParse);
97490:   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
97491: 
97492:   for(i=0; i<pParse->nTableLock; i++){
97493:     TableLock *p = &pParse->aTableLock[i];
97494:     int p1 = p->iDb;
97495:     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
97496:                       p->zName, P4_STATIC);
97497:   }
97498: }
97499: #else
97500:   #define codeTableLocks(x)
97501: #endif
97502: 
97503: /*
97504: ** Return TRUE if the given yDbMask object is empty - if it contains no
97505: ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
97506: ** macros when SQLITE_MAX_ATTACHED is greater than 30.
97507: */
97508: #if SQLITE_MAX_ATTACHED>30
97509: SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
97510:   int i;
97511:   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
97512:   return 1;
97513: }
97514: #endif
97515: 
97516: /*
97517: ** This routine is called after a single SQL statement has been
97518: ** parsed and a VDBE program to execute that statement has been
97519: ** prepared.  This routine puts the finishing touches on the
97520: ** VDBE program and resets the pParse structure for the next
97521: ** parse.
97522: **
97523: ** Note that if an error occurred, it might be the case that
97524: ** no VDBE code was generated.
97525: */
97526: SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
97527:   sqlite3 *db;
97528:   Vdbe *v;
97529: 
97530:   assert( pParse->pToplevel==0 );
97531:   db = pParse->db;
97532:   if( pParse->nested ) return;
97533:   if( db->mallocFailed || pParse->nErr ){
97534:     if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
97535:     return;
97536:   }
97537: 
97538:   /* Begin by generating some termination code at the end of the
97539:   ** vdbe program
97540:   */
97541:   v = sqlite3GetVdbe(pParse);
97542:   assert( !pParse->isMultiWrite 
97543:        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
97544:   if( v ){
97545:     while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
97546:     sqlite3VdbeAddOp0(v, OP_Halt);
97547: 
97548: #if SQLITE_USER_AUTHENTICATION
97549:     if( pParse->nTableLock>0 && db->init.busy==0 ){
97550:       sqlite3UserAuthInit(db);
97551:       if( db->auth.authLevel<UAUTH_User ){
97552:         pParse->rc = SQLITE_AUTH_USER;
97553:         sqlite3ErrorMsg(pParse, "user not authenticated");
97554:         return;
97555:       }
97556:     }
97557: #endif
97558: 
97559:     /* The cookie mask contains one bit for each database file open.
97560:     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
97561:     ** set for each database that is used.  Generate code to start a
97562:     ** transaction on each used database and to verify the schema cookie
97563:     ** on each used database.
97564:     */
97565:     if( db->mallocFailed==0 
97566:      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
97567:     ){
97568:       int iDb, i;
97569:       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
97570:       sqlite3VdbeJumpHere(v, 0);
97571:       for(iDb=0; iDb<db->nDb; iDb++){
97572:         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
97573:         sqlite3VdbeUsesBtree(v, iDb);
97574:         sqlite3VdbeAddOp4Int(v,
97575:           OP_Transaction,                    /* Opcode */
97576:           iDb,                               /* P1 */
97577:           DbMaskTest(pParse->writeMask,iDb), /* P2 */
97578:           pParse->cookieValue[iDb],          /* P3 */
97579:           db->aDb[iDb].pSchema->iGeneration  /* P4 */
97580:         );
97581:         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
97582:         VdbeComment((v,
97583:               "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
97584:       }
97585: #ifndef SQLITE_OMIT_VIRTUALTABLE
97586:       for(i=0; i<pParse->nVtabLock; i++){
97587:         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
97588:         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
97589:       }
97590:       pParse->nVtabLock = 0;
97591: #endif
97592: 
97593:       /* Once all the cookies have been verified and transactions opened, 
97594:       ** obtain the required table-locks. This is a no-op unless the 
97595:       ** shared-cache feature is enabled.
97596:       */
97597:       codeTableLocks(pParse);
97598: 
97599:       /* Initialize any AUTOINCREMENT data structures required.
97600:       */
97601:       sqlite3AutoincrementBegin(pParse);
97602: 
97603:       /* Code constant expressions that where factored out of inner loops */
97604:       if( pParse->pConstExpr ){
97605:         ExprList *pEL = pParse->pConstExpr;
97606:         pParse->okConstFactor = 0;
97607:         for(i=0; i<pEL->nExpr; i++){
97608:           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
97609:         }
97610:       }
97611: 
97612:       /* Finally, jump back to the beginning of the executable code. */
97613:       sqlite3VdbeGoto(v, 1);
97614:     }
97615:   }
97616: 
97617: 
97618:   /* Get the VDBE program ready for execution
97619:   */
97620:   if( v && pParse->nErr==0 && !db->mallocFailed ){
97621:     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
97622:     /* A minimum of one cursor is required if autoincrement is used
97623:     *  See ticket [a696379c1f08866] */
97624:     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
97625:     sqlite3VdbeMakeReady(v, pParse);
97626:     pParse->rc = SQLITE_DONE;
97627:   }else{
97628:     pParse->rc = SQLITE_ERROR;
97629:   }
97630: 
97631:   /* We are done with this Parse object. There is no need to de-initialize it */
97632: #if 0
97633:   pParse->colNamesSet = 0;
97634:   pParse->nTab = 0;
97635:   pParse->nMem = 0;
97636:   pParse->nSet = 0;
97637:   pParse->nVar = 0;
97638:   DbMaskZero(pParse->cookieMask);
97639: #endif
97640: }
97641: 
97642: /*
97643: ** Run the parser and code generator recursively in order to generate
97644: ** code for the SQL statement given onto the end of the pParse context
97645: ** currently under construction.  When the parser is run recursively
97646: ** this way, the final OP_Halt is not appended and other initialization
97647: ** and finalization steps are omitted because those are handling by the
97648: ** outermost parser.
97649: **
97650: ** Not everything is nestable.  This facility is designed to permit
97651: ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
97652: ** care if you decide to try to use this routine for some other purposes.
97653: */
97654: SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
97655:   va_list ap;
97656:   char *zSql;
97657:   char *zErrMsg = 0;
97658:   sqlite3 *db = pParse->db;
97659: # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
97660:   char saveBuf[SAVE_SZ];
97661: 
97662:   if( pParse->nErr ) return;
97663:   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
97664:   va_start(ap, zFormat);
97665:   zSql = sqlite3VMPrintf(db, zFormat, ap);
97666:   va_end(ap);
97667:   if( zSql==0 ){
97668:     return;   /* A malloc must have failed */
97669:   }
97670:   pParse->nested++;
97671:   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
97672:   memset(&pParse->nVar, 0, SAVE_SZ);
97673:   sqlite3RunParser(pParse, zSql, &zErrMsg);
97674:   sqlite3DbFree(db, zErrMsg);
97675:   sqlite3DbFree(db, zSql);
97676:   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
97677:   pParse->nested--;
97678: }
97679: 
97680: #if SQLITE_USER_AUTHENTICATION
97681: /*
97682: ** Return TRUE if zTable is the name of the system table that stores the
97683: ** list of users and their access credentials.
97684: */
97685: SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
97686:   return sqlite3_stricmp(zTable, "sqlite_user")==0;
97687: }
97688: #endif
97689: 
97690: /*
97691: ** Locate the in-memory structure that describes a particular database
97692: ** table given the name of that table and (optionally) the name of the
97693: ** database containing the table.  Return NULL if not found.
97694: **
97695: ** If zDatabase is 0, all databases are searched for the table and the
97696: ** first matching table is returned.  (No checking for duplicate table
97697: ** names is done.)  The search order is TEMP first, then MAIN, then any
97698: ** auxiliary databases added using the ATTACH command.
97699: **
97700: ** See also sqlite3LocateTable().
97701: */
97702: SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
97703:   Table *p = 0;
97704:   int i;
97705: 
97706:   /* All mutexes are required for schema access.  Make sure we hold them. */
97707:   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97708: #if SQLITE_USER_AUTHENTICATION
97709:   /* Only the admin user is allowed to know that the sqlite_user table
97710:   ** exists */
97711:   if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
97712:     return 0;
97713:   }
97714: #endif
97715:   for(i=OMIT_TEMPDB; i<db->nDb; i++){
97716:     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
97717:     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
97718:     assert( sqlite3SchemaMutexHeld(db, j, 0) );
97719:     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
97720:     if( p ) break;
97721:   }
97722:   return p;
97723: }
97724: 
97725: /*
97726: ** Locate the in-memory structure that describes a particular database
97727: ** table given the name of that table and (optionally) the name of the
97728: ** database containing the table.  Return NULL if not found.  Also leave an
97729: ** error message in pParse->zErrMsg.
97730: **
97731: ** The difference between this routine and sqlite3FindTable() is that this
97732: ** routine leaves an error message in pParse->zErrMsg where
97733: ** sqlite3FindTable() does not.
97734: */
97735: SQLITE_PRIVATE Table *sqlite3LocateTable(
97736:   Parse *pParse,         /* context in which to report errors */
97737:   u32 flags,             /* LOCATE_VIEW or LOCATE_NOERR */
97738:   const char *zName,     /* Name of the table we are looking for */
97739:   const char *zDbase     /* Name of the database.  Might be NULL */
97740: ){
97741:   Table *p;
97742: 
97743:   /* Read the database schema. If an error occurs, leave an error message
97744:   ** and code in pParse and return NULL. */
97745:   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97746:     return 0;
97747:   }
97748: 
97749:   p = sqlite3FindTable(pParse->db, zName, zDbase);
97750:   if( p==0 ){
97751:     const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
97752: #ifndef SQLITE_OMIT_VIRTUALTABLE
97753:     if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
97754:       /* If zName is the not the name of a table in the schema created using
97755:       ** CREATE, then check to see if it is the name of an virtual table that
97756:       ** can be an eponymous virtual table. */
97757:       Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
97758:       if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
97759:         return pMod->pEpoTab;
97760:       }
97761:     }
97762: #endif
97763:     if( (flags & LOCATE_NOERR)==0 ){
97764:       if( zDbase ){
97765:         sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
97766:       }else{
97767:         sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
97768:       }
97769:       pParse->checkSchema = 1;
97770:     }
97771:   }
97772: 
97773:   return p;
97774: }
97775: 
97776: /*
97777: ** Locate the table identified by *p.
97778: **
97779: ** This is a wrapper around sqlite3LocateTable(). The difference between
97780: ** sqlite3LocateTable() and this function is that this function restricts
97781: ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
97782: ** non-NULL if it is part of a view or trigger program definition. See
97783: ** sqlite3FixSrcList() for details.
97784: */
97785: SQLITE_PRIVATE Table *sqlite3LocateTableItem(
97786:   Parse *pParse, 
97787:   u32 flags,
97788:   struct SrcList_item *p
97789: ){
97790:   const char *zDb;
97791:   assert( p->pSchema==0 || p->zDatabase==0 );
97792:   if( p->pSchema ){
97793:     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
97794:     zDb = pParse->db->aDb[iDb].zName;
97795:   }else{
97796:     zDb = p->zDatabase;
97797:   }
97798:   return sqlite3LocateTable(pParse, flags, p->zName, zDb);
97799: }
97800: 
97801: /*
97802: ** Locate the in-memory structure that describes 
97803: ** a particular index given the name of that index
97804: ** and the name of the database that contains the index.
97805: ** Return NULL if not found.
97806: **
97807: ** If zDatabase is 0, all databases are searched for the
97808: ** table and the first matching index is returned.  (No checking
97809: ** for duplicate index names is done.)  The search order is
97810: ** TEMP first, then MAIN, then any auxiliary databases added
97811: ** using the ATTACH command.
97812: */
97813: SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
97814:   Index *p = 0;
97815:   int i;
97816:   /* All mutexes are required for schema access.  Make sure we hold them. */
97817:   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97818:   for(i=OMIT_TEMPDB; i<db->nDb; i++){
97819:     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
97820:     Schema *pSchema = db->aDb[j].pSchema;
97821:     assert( pSchema );
97822:     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
97823:     assert( sqlite3SchemaMutexHeld(db, j, 0) );
97824:     p = sqlite3HashFind(&pSchema->idxHash, zName);
97825:     if( p ) break;
97826:   }
97827:   return p;
97828: }
97829: 
97830: /*
97831: ** Reclaim the memory used by an index
97832: */
97833: static void freeIndex(sqlite3 *db, Index *p){
97834: #ifndef SQLITE_OMIT_ANALYZE
97835:   sqlite3DeleteIndexSamples(db, p);
97836: #endif
97837:   sqlite3ExprDelete(db, p->pPartIdxWhere);
97838:   sqlite3ExprListDelete(db, p->aColExpr);
97839:   sqlite3DbFree(db, p->zColAff);
97840:   if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
97841: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97842:   sqlite3_free(p->aiRowEst);
97843: #endif
97844:   sqlite3DbFree(db, p);
97845: }
97846: 
97847: /*
97848: ** For the index called zIdxName which is found in the database iDb,
97849: ** unlike that index from its Table then remove the index from
97850: ** the index hash table and free all memory structures associated
97851: ** with the index.
97852: */
97853: SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
97854:   Index *pIndex;
97855:   Hash *pHash;
97856: 
97857:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97858:   pHash = &db->aDb[iDb].pSchema->idxHash;
97859:   pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
97860:   if( ALWAYS(pIndex) ){
97861:     if( pIndex->pTable->pIndex==pIndex ){
97862:       pIndex->pTable->pIndex = pIndex->pNext;
97863:     }else{
97864:       Index *p;
97865:       /* Justification of ALWAYS();  The index must be on the list of
97866:       ** indices. */
97867:       p = pIndex->pTable->pIndex;
97868:       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
97869:       if( ALWAYS(p && p->pNext==pIndex) ){
97870:         p->pNext = pIndex->pNext;
97871:       }
97872:     }
97873:     freeIndex(db, pIndex);
97874:   }
97875:   db->flags |= SQLITE_InternChanges;
97876: }
97877: 
97878: /*
97879: ** Look through the list of open database files in db->aDb[] and if
97880: ** any have been closed, remove them from the list.  Reallocate the
97881: ** db->aDb[] structure to a smaller size, if possible.
97882: **
97883: ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
97884: ** are never candidates for being collapsed.
97885: */
97886: SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
97887:   int i, j;
97888:   for(i=j=2; i<db->nDb; i++){
97889:     struct Db *pDb = &db->aDb[i];
97890:     if( pDb->pBt==0 ){
97891:       sqlite3DbFree(db, pDb->zName);
97892:       pDb->zName = 0;
97893:       continue;
97894:     }
97895:     if( j<i ){
97896:       db->aDb[j] = db->aDb[i];
97897:     }
97898:     j++;
97899:   }
97900:   db->nDb = j;
97901:   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
97902:     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
97903:     sqlite3DbFree(db, db->aDb);
97904:     db->aDb = db->aDbStatic;
97905:   }
97906: }
97907: 
97908: /*
97909: ** Reset the schema for the database at index iDb.  Also reset the
97910: ** TEMP schema.
97911: */
97912: SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
97913:   Db *pDb;
97914:   assert( iDb<db->nDb );
97915: 
97916:   /* Case 1:  Reset the single schema identified by iDb */
97917:   pDb = &db->aDb[iDb];
97918:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97919:   assert( pDb->pSchema!=0 );
97920:   sqlite3SchemaClear(pDb->pSchema);
97921: 
97922:   /* If any database other than TEMP is reset, then also reset TEMP
97923:   ** since TEMP might be holding triggers that reference tables in the
97924:   ** other database.
97925:   */
97926:   if( iDb!=1 ){
97927:     pDb = &db->aDb[1];
97928:     assert( pDb->pSchema!=0 );
97929:     sqlite3SchemaClear(pDb->pSchema);
97930:   }
97931:   return;
97932: }
97933: 
97934: /*
97935: ** Erase all schema information from all attached databases (including
97936: ** "main" and "temp") for a single database connection.
97937: */
97938: SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
97939:   int i;
97940:   sqlite3BtreeEnterAll(db);
97941:   for(i=0; i<db->nDb; i++){
97942:     Db *pDb = &db->aDb[i];
97943:     if( pDb->pSchema ){
97944:       sqlite3SchemaClear(pDb->pSchema);
97945:     }
97946:   }
97947:   db->flags &= ~SQLITE_InternChanges;
97948:   sqlite3VtabUnlockList(db);
97949:   sqlite3BtreeLeaveAll(db);
97950:   sqlite3CollapseDatabaseArray(db);
97951: }
97952: 
97953: /*
97954: ** This routine is called when a commit occurs.
97955: */
97956: SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
97957:   db->flags &= ~SQLITE_InternChanges;
97958: }
97959: 
97960: /*
97961: ** Delete memory allocated for the column names of a table or view (the
97962: ** Table.aCol[] array).
97963: */
97964: SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
97965:   int i;
97966:   Column *pCol;
97967:   assert( pTable!=0 );
97968:   if( (pCol = pTable->aCol)!=0 ){
97969:     for(i=0; i<pTable->nCol; i++, pCol++){
97970:       sqlite3DbFree(db, pCol->zName);
97971:       sqlite3ExprDelete(db, pCol->pDflt);
97972:       sqlite3DbFree(db, pCol->zColl);
97973:     }
97974:     sqlite3DbFree(db, pTable->aCol);
97975:   }
97976: }
97977: 
97978: /*
97979: ** Remove the memory data structures associated with the given
97980: ** Table.  No changes are made to disk by this routine.
97981: **
97982: ** This routine just deletes the data structure.  It does not unlink
97983: ** the table data structure from the hash table.  But it does destroy
97984: ** memory structures of the indices and foreign keys associated with 
97985: ** the table.
97986: **
97987: ** The db parameter is optional.  It is needed if the Table object 
97988: ** contains lookaside memory.  (Table objects in the schema do not use
97989: ** lookaside memory, but some ephemeral Table objects do.)  Or the
97990: ** db parameter can be used with db->pnBytesFreed to measure the memory
97991: ** used by the Table object.
97992: */
97993: static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
97994:   Index *pIndex, *pNext;
97995:   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
97996: 
97997:   /* Record the number of outstanding lookaside allocations in schema Tables
97998:   ** prior to doing any free() operations.  Since schema Tables do not use
97999:   ** lookaside, this number should not change. */
98000:   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
98001:                          db->lookaside.nOut : 0 );
98002: 
98003:   /* Delete all indices associated with this table. */
98004:   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
98005:     pNext = pIndex->pNext;
98006:     assert( pIndex->pSchema==pTable->pSchema
98007:          || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
98008:     if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
98009:       char *zName = pIndex->zName; 
98010:       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
98011:          &pIndex->pSchema->idxHash, zName, 0
98012:       );
98013:       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
98014:       assert( pOld==pIndex || pOld==0 );
98015:     }
98016:     freeIndex(db, pIndex);
98017:   }
98018: 
98019:   /* Delete any foreign keys attached to this table. */
98020:   sqlite3FkDelete(db, pTable);
98021: 
98022:   /* Delete the Table structure itself.
98023:   */
98024:   sqlite3DeleteColumnNames(db, pTable);
98025:   sqlite3DbFree(db, pTable->zName);
98026:   sqlite3DbFree(db, pTable->zColAff);
98027:   sqlite3SelectDelete(db, pTable->pSelect);
98028:   sqlite3ExprListDelete(db, pTable->pCheck);
98029: #ifndef SQLITE_OMIT_VIRTUALTABLE
98030:   sqlite3VtabClear(db, pTable);
98031: #endif
98032:   sqlite3DbFree(db, pTable);
98033: 
98034:   /* Verify that no lookaside memory was used by schema tables */
98035:   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
98036: }
98037: SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
98038:   /* Do not delete the table until the reference count reaches zero. */
98039:   if( !pTable ) return;
98040:   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
98041:   deleteTable(db, pTable);
98042: }
98043: 
98044: 
98045: /*
98046: ** Unlink the given table from the hash tables and the delete the
98047: ** table structure with all its indices and foreign keys.
98048: */
98049: SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
98050:   Table *p;
98051:   Db *pDb;
98052: 
98053:   assert( db!=0 );
98054:   assert( iDb>=0 && iDb<db->nDb );
98055:   assert( zTabName );
98056:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98057:   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
98058:   pDb = &db->aDb[iDb];
98059:   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
98060:   sqlite3DeleteTable(db, p);
98061:   db->flags |= SQLITE_InternChanges;
98062: }
98063: 
98064: /*
98065: ** Given a token, return a string that consists of the text of that
98066: ** token.  Space to hold the returned string
98067: ** is obtained from sqliteMalloc() and must be freed by the calling
98068: ** function.
98069: **
98070: ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
98071: ** surround the body of the token are removed.
98072: **
98073: ** Tokens are often just pointers into the original SQL text and so
98074: ** are not \000 terminated and are not persistent.  The returned string
98075: ** is \000 terminated and is persistent.
98076: */
98077: SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
98078:   char *zName;
98079:   if( pName ){
98080:     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
98081:     sqlite3Dequote(zName);
98082:   }else{
98083:     zName = 0;
98084:   }
98085:   return zName;
98086: }
98087: 
98088: /*
98089: ** Open the sqlite_master table stored in database number iDb for
98090: ** writing. The table is opened using cursor 0.
98091: */
98092: SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
98093:   Vdbe *v = sqlite3GetVdbe(p);
98094:   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
98095:   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
98096:   if( p->nTab==0 ){
98097:     p->nTab = 1;
98098:   }
98099: }
98100: 
98101: /*
98102: ** Parameter zName points to a nul-terminated buffer containing the name
98103: ** of a database ("main", "temp" or the name of an attached db). This
98104: ** function returns the index of the named database in db->aDb[], or
98105: ** -1 if the named db cannot be found.
98106: */
98107: SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
98108:   int i = -1;         /* Database number */
98109:   if( zName ){
98110:     Db *pDb;
98111:     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
98112:       if( 0==sqlite3StrICmp(pDb->zName, zName) ) break;
98113:     }
98114:   }
98115:   return i;
98116: }
98117: 
98118: /*
98119: ** The token *pName contains the name of a database (either "main" or
98120: ** "temp" or the name of an attached db). This routine returns the
98121: ** index of the named database in db->aDb[], or -1 if the named db 
98122: ** does not exist.
98123: */
98124: SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
98125:   int i;                               /* Database number */
98126:   char *zName;                         /* Name we are searching for */
98127:   zName = sqlite3NameFromToken(db, pName);
98128:   i = sqlite3FindDbName(db, zName);
98129:   sqlite3DbFree(db, zName);
98130:   return i;
98131: }
98132: 
98133: /* The table or view or trigger name is passed to this routine via tokens
98134: ** pName1 and pName2. If the table name was fully qualified, for example:
98135: **
98136: ** CREATE TABLE xxx.yyy (...);
98137: ** 
98138: ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
98139: ** the table name is not fully qualified, i.e.:
98140: **
98141: ** CREATE TABLE yyy(...);
98142: **
98143: ** Then pName1 is set to "yyy" and pName2 is "".
98144: **
98145: ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
98146: ** pName2) that stores the unqualified table name.  The index of the
98147: ** database "xxx" is returned.
98148: */
98149: SQLITE_PRIVATE int sqlite3TwoPartName(
98150:   Parse *pParse,      /* Parsing and code generating context */
98151:   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
98152:   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
98153:   Token **pUnqual     /* Write the unqualified object name here */
98154: ){
98155:   int iDb;                    /* Database holding the object */
98156:   sqlite3 *db = pParse->db;
98157: 
98158:   assert( pName2!=0 );
98159:   if( pName2->n>0 ){
98160:     if( db->init.busy ) {
98161:       sqlite3ErrorMsg(pParse, "corrupt database");
98162:       return -1;
98163:     }
98164:     *pUnqual = pName2;
98165:     iDb = sqlite3FindDb(db, pName1);
98166:     if( iDb<0 ){
98167:       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
98168:       return -1;
98169:     }
98170:   }else{
98171:     assert( db->init.iDb==0 || db->init.busy );
98172:     iDb = db->init.iDb;
98173:     *pUnqual = pName1;
98174:   }
98175:   return iDb;
98176: }
98177: 
98178: /*
98179: ** This routine is used to check if the UTF-8 string zName is a legal
98180: ** unqualified name for a new schema object (table, index, view or
98181: ** trigger). All names are legal except those that begin with the string
98182: ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
98183: ** is reserved for internal use.
98184: */
98185: SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
98186:   if( !pParse->db->init.busy && pParse->nested==0 
98187:           && (pParse->db->flags & SQLITE_WriteSchema)==0
98188:           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
98189:     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
98190:     return SQLITE_ERROR;
98191:   }
98192:   return SQLITE_OK;
98193: }
98194: 
98195: /*
98196: ** Return the PRIMARY KEY index of a table
98197: */
98198: SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
98199:   Index *p;
98200:   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
98201:   return p;
98202: }
98203: 
98204: /*
98205: ** Return the column of index pIdx that corresponds to table
98206: ** column iCol.  Return -1 if not found.
98207: */
98208: SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
98209:   int i;
98210:   for(i=0; i<pIdx->nColumn; i++){
98211:     if( iCol==pIdx->aiColumn[i] ) return i;
98212:   }
98213:   return -1;
98214: }
98215: 
98216: /*
98217: ** Begin constructing a new table representation in memory.  This is
98218: ** the first of several action routines that get called in response
98219: ** to a CREATE TABLE statement.  In particular, this routine is called
98220: ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
98221: ** flag is true if the table should be stored in the auxiliary database
98222: ** file instead of in the main database file.  This is normally the case
98223: ** when the "TEMP" or "TEMPORARY" keyword occurs in between
98224: ** CREATE and TABLE.
98225: **
98226: ** The new table record is initialized and put in pParse->pNewTable.
98227: ** As more of the CREATE TABLE statement is parsed, additional action
98228: ** routines will be called to add more information to this record.
98229: ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
98230: ** is called to complete the construction of the new table record.
98231: */
98232: SQLITE_PRIVATE void sqlite3StartTable(
98233:   Parse *pParse,   /* Parser context */
98234:   Token *pName1,   /* First part of the name of the table or view */
98235:   Token *pName2,   /* Second part of the name of the table or view */
98236:   int isTemp,      /* True if this is a TEMP table */
98237:   int isView,      /* True if this is a VIEW */
98238:   int isVirtual,   /* True if this is a VIRTUAL table */
98239:   int noErr        /* Do nothing if table already exists */
98240: ){
98241:   Table *pTable;
98242:   char *zName = 0; /* The name of the new table */
98243:   sqlite3 *db = pParse->db;
98244:   Vdbe *v;
98245:   int iDb;         /* Database number to create the table in */
98246:   Token *pName;    /* Unqualified name of the table to create */
98247: 
98248:   if( db->init.busy && db->init.newTnum==1 ){
98249:     /* Special case:  Parsing the sqlite_master or sqlite_temp_master schema */
98250:     iDb = db->init.iDb;
98251:     zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
98252:     pName = pName1;
98253:   }else{
98254:     /* The common case */
98255:     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
98256:     if( iDb<0 ) return;
98257:     if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
98258:       /* If creating a temp table, the name may not be qualified. Unless 
98259:       ** the database name is "temp" anyway.  */
98260:       sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
98261:       return;
98262:     }
98263:     if( !OMIT_TEMPDB && isTemp ) iDb = 1;
98264:     zName = sqlite3NameFromToken(db, pName);
98265:   }
98266:   pParse->sNameToken = *pName;
98267:   if( zName==0 ) return;
98268:   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
98269:     goto begin_table_error;
98270:   }
98271:   if( db->init.iDb==1 ) isTemp = 1;
98272: #ifndef SQLITE_OMIT_AUTHORIZATION
98273:   assert( isTemp==0 || isTemp==1 );
98274:   assert( isView==0 || isView==1 );
98275:   {
98276:     static const u8 aCode[] = {
98277:        SQLITE_CREATE_TABLE,
98278:        SQLITE_CREATE_TEMP_TABLE,
98279:        SQLITE_CREATE_VIEW,
98280:        SQLITE_CREATE_TEMP_VIEW
98281:     };
98282:     char *zDb = db->aDb[iDb].zName;
98283:     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
98284:       goto begin_table_error;
98285:     }
98286:     if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
98287:                                        zName, 0, zDb) ){
98288:       goto begin_table_error;
98289:     }
98290:   }
98291: #endif
98292: 
98293:   /* Make sure the new table name does not collide with an existing
98294:   ** index or table name in the same database.  Issue an error message if
98295:   ** it does. The exception is if the statement being parsed was passed
98296:   ** to an sqlite3_declare_vtab() call. In that case only the column names
98297:   ** and types will be used, so there is no need to test for namespace
98298:   ** collisions.
98299:   */
98300:   if( !IN_DECLARE_VTAB ){
98301:     char *zDb = db->aDb[iDb].zName;
98302:     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
98303:       goto begin_table_error;
98304:     }
98305:     pTable = sqlite3FindTable(db, zName, zDb);
98306:     if( pTable ){
98307:       if( !noErr ){
98308:         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
98309:       }else{
98310:         assert( !db->init.busy || CORRUPT_DB );
98311:         sqlite3CodeVerifySchema(pParse, iDb);
98312:       }
98313:       goto begin_table_error;
98314:     }
98315:     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
98316:       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
98317:       goto begin_table_error;
98318:     }
98319:   }
98320: 
98321:   pTable = sqlite3DbMallocZero(db, sizeof(Table));
98322:   if( pTable==0 ){
98323:     assert( db->mallocFailed );
98324:     pParse->rc = SQLITE_NOMEM_BKPT;
98325:     pParse->nErr++;
98326:     goto begin_table_error;
98327:   }
98328:   pTable->zName = zName;
98329:   pTable->iPKey = -1;
98330:   pTable->pSchema = db->aDb[iDb].pSchema;
98331:   pTable->nRef = 1;
98332:   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
98333:   assert( pParse->pNewTable==0 );
98334:   pParse->pNewTable = pTable;
98335: 
98336:   /* If this is the magic sqlite_sequence table used by autoincrement,
98337:   ** then record a pointer to this table in the main database structure
98338:   ** so that INSERT can find the table easily.
98339:   */
98340: #ifndef SQLITE_OMIT_AUTOINCREMENT
98341:   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
98342:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98343:     pTable->pSchema->pSeqTab = pTable;
98344:   }
98345: #endif
98346: 
98347:   /* Begin generating the code that will insert the table record into
98348:   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
98349:   ** and allocate the record number for the table entry now.  Before any
98350:   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
98351:   ** indices to be created and the table record must come before the 
98352:   ** indices.  Hence, the record number for the table must be allocated
98353:   ** now.
98354:   */
98355:   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
98356:     int addr1;
98357:     int fileFormat;
98358:     int reg1, reg2, reg3;
98359:     /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
98360:     static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
98361:     sqlite3BeginWriteOperation(pParse, 1, iDb);
98362: 
98363: #ifndef SQLITE_OMIT_VIRTUALTABLE
98364:     if( isVirtual ){
98365:       sqlite3VdbeAddOp0(v, OP_VBegin);
98366:     }
98367: #endif
98368: 
98369:     /* If the file format and encoding in the database have not been set, 
98370:     ** set them now.
98371:     */
98372:     reg1 = pParse->regRowid = ++pParse->nMem;
98373:     reg2 = pParse->regRoot = ++pParse->nMem;
98374:     reg3 = ++pParse->nMem;
98375:     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
98376:     sqlite3VdbeUsesBtree(v, iDb);
98377:     addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
98378:     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
98379:                   1 : SQLITE_MAX_FILE_FORMAT;
98380:     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
98381:     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
98382:     sqlite3VdbeJumpHere(v, addr1);
98383: 
98384:     /* This just creates a place-holder record in the sqlite_master table.
98385:     ** The record created does not contain anything yet.  It will be replaced
98386:     ** by the real entry in code generated at sqlite3EndTable().
98387:     **
98388:     ** The rowid for the new entry is left in register pParse->regRowid.
98389:     ** The root page number of the new table is left in reg pParse->regRoot.
98390:     ** The rowid and root page number values are needed by the code that
98391:     ** sqlite3EndTable will generate.
98392:     */
98393: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
98394:     if( isView || isVirtual ){
98395:       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
98396:     }else
98397: #endif
98398:     {
98399:       pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
98400:     }
98401:     sqlite3OpenMasterTable(pParse, iDb);
98402:     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
98403:     sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
98404:     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
98405:     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98406:     sqlite3VdbeAddOp0(v, OP_Close);
98407:   }
98408: 
98409:   /* Normal (non-error) return. */
98410:   return;
98411: 
98412:   /* If an error occurs, we jump here */
98413: begin_table_error:
98414:   sqlite3DbFree(db, zName);
98415:   return;
98416: }
98417: 
98418: /* Set properties of a table column based on the (magical)
98419: ** name of the column.
98420: */
98421: #if SQLITE_ENABLE_HIDDEN_COLUMNS
98422: SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
98423:   if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
98424:     pCol->colFlags |= COLFLAG_HIDDEN;
98425:   }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
98426:     pTab->tabFlags |= TF_OOOHidden;
98427:   }
98428: }
98429: #endif
98430: 
98431: 
98432: /*
98433: ** Add a new column to the table currently being constructed.
98434: **
98435: ** The parser calls this routine once for each column declaration
98436: ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
98437: ** first to get things going.  Then this routine is called for each
98438: ** column.
98439: */
98440: SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
98441:   Table *p;
98442:   int i;
98443:   char *z;
98444:   char *zType;
98445:   Column *pCol;
98446:   sqlite3 *db = pParse->db;
98447:   if( (p = pParse->pNewTable)==0 ) return;
98448: #if SQLITE_MAX_COLUMN
98449:   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
98450:     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
98451:     return;
98452:   }
98453: #endif
98454:   z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
98455:   if( z==0 ) return;
98456:   memcpy(z, pName->z, pName->n);
98457:   z[pName->n] = 0;
98458:   sqlite3Dequote(z);
98459:   for(i=0; i<p->nCol; i++){
98460:     if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
98461:       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
98462:       sqlite3DbFree(db, z);
98463:       return;
98464:     }
98465:   }
98466:   if( (p->nCol & 0x7)==0 ){
98467:     Column *aNew;
98468:     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
98469:     if( aNew==0 ){
98470:       sqlite3DbFree(db, z);
98471:       return;
98472:     }
98473:     p->aCol = aNew;
98474:   }
98475:   pCol = &p->aCol[p->nCol];
98476:   memset(pCol, 0, sizeof(p->aCol[0]));
98477:   pCol->zName = z;
98478:   sqlite3ColumnPropertiesFromName(p, pCol);
98479:  
98480:   if( pType->n==0 ){
98481:     /* If there is no type specified, columns have the default affinity
98482:     ** 'BLOB'. */
98483:     pCol->affinity = SQLITE_AFF_BLOB;
98484:     pCol->szEst = 1;
98485:   }else{
98486:     zType = z + sqlite3Strlen30(z) + 1;
98487:     memcpy(zType, pType->z, pType->n);
98488:     zType[pType->n] = 0;
98489:     sqlite3Dequote(zType);
98490:     pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
98491:     pCol->colFlags |= COLFLAG_HASTYPE;
98492:   }
98493:   p->nCol++;
98494:   pParse->constraintName.n = 0;
98495: }
98496: 
98497: /*
98498: ** This routine is called by the parser while in the middle of
98499: ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
98500: ** been seen on a column.  This routine sets the notNull flag on
98501: ** the column currently under construction.
98502: */
98503: SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
98504:   Table *p;
98505:   p = pParse->pNewTable;
98506:   if( p==0 || NEVER(p->nCol<1) ) return;
98507:   p->aCol[p->nCol-1].notNull = (u8)onError;
98508: }
98509: 
98510: /*
98511: ** Scan the column type name zType (length nType) and return the
98512: ** associated affinity type.
98513: **
98514: ** This routine does a case-independent search of zType for the 
98515: ** substrings in the following table. If one of the substrings is
98516: ** found, the corresponding affinity is returned. If zType contains
98517: ** more than one of the substrings, entries toward the top of 
98518: ** the table take priority. For example, if zType is 'BLOBINT', 
98519: ** SQLITE_AFF_INTEGER is returned.
98520: **
98521: ** Substring     | Affinity
98522: ** --------------------------------
98523: ** 'INT'         | SQLITE_AFF_INTEGER
98524: ** 'CHAR'        | SQLITE_AFF_TEXT
98525: ** 'CLOB'        | SQLITE_AFF_TEXT
98526: ** 'TEXT'        | SQLITE_AFF_TEXT
98527: ** 'BLOB'        | SQLITE_AFF_BLOB
98528: ** 'REAL'        | SQLITE_AFF_REAL
98529: ** 'FLOA'        | SQLITE_AFF_REAL
98530: ** 'DOUB'        | SQLITE_AFF_REAL
98531: **
98532: ** If none of the substrings in the above table are found,
98533: ** SQLITE_AFF_NUMERIC is returned.
98534: */
98535: SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
98536:   u32 h = 0;
98537:   char aff = SQLITE_AFF_NUMERIC;
98538:   const char *zChar = 0;
98539: 
98540:   assert( zIn!=0 );
98541:   while( zIn[0] ){
98542:     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
98543:     zIn++;
98544:     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
98545:       aff = SQLITE_AFF_TEXT;
98546:       zChar = zIn;
98547:     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
98548:       aff = SQLITE_AFF_TEXT;
98549:     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
98550:       aff = SQLITE_AFF_TEXT;
98551:     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
98552:         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
98553:       aff = SQLITE_AFF_BLOB;
98554:       if( zIn[0]=='(' ) zChar = zIn;
98555: #ifndef SQLITE_OMIT_FLOATING_POINT
98556:     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
98557:         && aff==SQLITE_AFF_NUMERIC ){
98558:       aff = SQLITE_AFF_REAL;
98559:     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
98560:         && aff==SQLITE_AFF_NUMERIC ){
98561:       aff = SQLITE_AFF_REAL;
98562:     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
98563:         && aff==SQLITE_AFF_NUMERIC ){
98564:       aff = SQLITE_AFF_REAL;
98565: #endif
98566:     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
98567:       aff = SQLITE_AFF_INTEGER;
98568:       break;
98569:     }
98570:   }
98571: 
98572:   /* If pszEst is not NULL, store an estimate of the field size.  The
98573:   ** estimate is scaled so that the size of an integer is 1.  */
98574:   if( pszEst ){
98575:     *pszEst = 1;   /* default size is approx 4 bytes */
98576:     if( aff<SQLITE_AFF_NUMERIC ){
98577:       if( zChar ){
98578:         while( zChar[0] ){
98579:           if( sqlite3Isdigit(zChar[0]) ){
98580:             int v = 0;
98581:             sqlite3GetInt32(zChar, &v);
98582:             v = v/4 + 1;
98583:             if( v>255 ) v = 255;
98584:             *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
98585:             break;
98586:           }
98587:           zChar++;
98588:         }
98589:       }else{
98590:         *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
98591:       }
98592:     }
98593:   }
98594:   return aff;
98595: }
98596: 
98597: /*
98598: ** The expression is the default value for the most recently added column
98599: ** of the table currently under construction.
98600: **
98601: ** Default value expressions must be constant.  Raise an exception if this
98602: ** is not the case.
98603: **
98604: ** This routine is called by the parser while in the middle of
98605: ** parsing a CREATE TABLE statement.
98606: */
98607: SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
98608:   Table *p;
98609:   Column *pCol;
98610:   sqlite3 *db = pParse->db;
98611:   p = pParse->pNewTable;
98612:   if( p!=0 ){
98613:     pCol = &(p->aCol[p->nCol-1]);
98614:     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
98615:       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
98616:           pCol->zName);
98617:     }else{
98618:       /* A copy of pExpr is used instead of the original, as pExpr contains
98619:       ** tokens that point to volatile memory. The 'span' of the expression
98620:       ** is required by pragma table_info.
98621:       */
98622:       Expr x;
98623:       sqlite3ExprDelete(db, pCol->pDflt);
98624:       memset(&x, 0, sizeof(x));
98625:       x.op = TK_SPAN;
98626:       x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
98627:                                     (int)(pSpan->zEnd - pSpan->zStart));
98628:       x.pLeft = pSpan->pExpr;
98629:       x.flags = EP_Skip;
98630:       pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
98631:       sqlite3DbFree(db, x.u.zToken);
98632:     }
98633:   }
98634:   sqlite3ExprDelete(db, pSpan->pExpr);
98635: }
98636: 
98637: /*
98638: ** Backwards Compatibility Hack:
98639: ** 
98640: ** Historical versions of SQLite accepted strings as column names in
98641: ** indexes and PRIMARY KEY constraints and in UNIQUE constraints.  Example:
98642: **
98643: **     CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
98644: **     CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
98645: **
98646: ** This is goofy.  But to preserve backwards compatibility we continue to
98647: ** accept it.  This routine does the necessary conversion.  It converts
98648: ** the expression given in its argument from a TK_STRING into a TK_ID
98649: ** if the expression is just a TK_STRING with an optional COLLATE clause.
98650: ** If the epxression is anything other than TK_STRING, the expression is
98651: ** unchanged.
98652: */
98653: static void sqlite3StringToId(Expr *p){
98654:   if( p->op==TK_STRING ){
98655:     p->op = TK_ID;
98656:   }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
98657:     p->pLeft->op = TK_ID;
98658:   }
98659: }
98660: 
98661: /*
98662: ** Designate the PRIMARY KEY for the table.  pList is a list of names 
98663: ** of columns that form the primary key.  If pList is NULL, then the
98664: ** most recently added column of the table is the primary key.
98665: **
98666: ** A table can have at most one primary key.  If the table already has
98667: ** a primary key (and this is the second primary key) then create an
98668: ** error.
98669: **
98670: ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
98671: ** then we will try to use that column as the rowid.  Set the Table.iPKey
98672: ** field of the table under construction to be the index of the
98673: ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
98674: ** no INTEGER PRIMARY KEY.
98675: **
98676: ** If the key is not an INTEGER PRIMARY KEY, then create a unique
98677: ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
98678: */
98679: SQLITE_PRIVATE void sqlite3AddPrimaryKey(
98680:   Parse *pParse,    /* Parsing context */
98681:   ExprList *pList,  /* List of field names to be indexed */
98682:   int onError,      /* What to do with a uniqueness conflict */
98683:   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
98684:   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
98685: ){
98686:   Table *pTab = pParse->pNewTable;
98687:   Column *pCol = 0;
98688:   int iCol = -1, i;
98689:   int nTerm;
98690:   if( pTab==0 ) goto primary_key_exit;
98691:   if( pTab->tabFlags & TF_HasPrimaryKey ){
98692:     sqlite3ErrorMsg(pParse, 
98693:       "table \"%s\" has more than one primary key", pTab->zName);
98694:     goto primary_key_exit;
98695:   }
98696:   pTab->tabFlags |= TF_HasPrimaryKey;
98697:   if( pList==0 ){
98698:     iCol = pTab->nCol - 1;
98699:     pCol = &pTab->aCol[iCol];
98700:     pCol->colFlags |= COLFLAG_PRIMKEY;
98701:     nTerm = 1;
98702:   }else{
98703:     nTerm = pList->nExpr;
98704:     for(i=0; i<nTerm; i++){
98705:       Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
98706:       assert( pCExpr!=0 );
98707:       sqlite3StringToId(pCExpr);
98708:       if( pCExpr->op==TK_ID ){
98709:         const char *zCName = pCExpr->u.zToken;
98710:         for(iCol=0; iCol<pTab->nCol; iCol++){
98711:           if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
98712:             pCol = &pTab->aCol[iCol];
98713:             pCol->colFlags |= COLFLAG_PRIMKEY;
98714:             break;
98715:           }
98716:         }
98717:       }
98718:     }
98719:   }
98720:   if( nTerm==1
98721:    && pCol
98722:    && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
98723:    && sortOrder!=SQLITE_SO_DESC
98724:   ){
98725:     pTab->iPKey = iCol;
98726:     pTab->keyConf = (u8)onError;
98727:     assert( autoInc==0 || autoInc==1 );
98728:     pTab->tabFlags |= autoInc*TF_Autoincrement;
98729:     if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
98730:   }else if( autoInc ){
98731: #ifndef SQLITE_OMIT_AUTOINCREMENT
98732:     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
98733:        "INTEGER PRIMARY KEY");
98734: #endif
98735:   }else{
98736:     sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
98737:                            0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
98738:     pList = 0;
98739:   }
98740: 
98741: primary_key_exit:
98742:   sqlite3ExprListDelete(pParse->db, pList);
98743:   return;
98744: }
98745: 
98746: /*
98747: ** Add a new CHECK constraint to the table currently under construction.
98748: */
98749: SQLITE_PRIVATE void sqlite3AddCheckConstraint(
98750:   Parse *pParse,    /* Parsing context */
98751:   Expr *pCheckExpr  /* The check expression */
98752: ){
98753: #ifndef SQLITE_OMIT_CHECK
98754:   Table *pTab = pParse->pNewTable;
98755:   sqlite3 *db = pParse->db;
98756:   if( pTab && !IN_DECLARE_VTAB
98757:    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
98758:   ){
98759:     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
98760:     if( pParse->constraintName.n ){
98761:       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
98762:     }
98763:   }else
98764: #endif
98765:   {
98766:     sqlite3ExprDelete(pParse->db, pCheckExpr);
98767:   }
98768: }
98769: 
98770: /*
98771: ** Set the collation function of the most recently parsed table column
98772: ** to the CollSeq given.
98773: */
98774: SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
98775:   Table *p;
98776:   int i;
98777:   char *zColl;              /* Dequoted name of collation sequence */
98778:   sqlite3 *db;
98779: 
98780:   if( (p = pParse->pNewTable)==0 ) return;
98781:   i = p->nCol-1;
98782:   db = pParse->db;
98783:   zColl = sqlite3NameFromToken(db, pToken);
98784:   if( !zColl ) return;
98785: 
98786:   if( sqlite3LocateCollSeq(pParse, zColl) ){
98787:     Index *pIdx;
98788:     sqlite3DbFree(db, p->aCol[i].zColl);
98789:     p->aCol[i].zColl = zColl;
98790:   
98791:     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
98792:     ** then an index may have been created on this column before the
98793:     ** collation type was added. Correct this if it is the case.
98794:     */
98795:     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
98796:       assert( pIdx->nKeyCol==1 );
98797:       if( pIdx->aiColumn[0]==i ){
98798:         pIdx->azColl[0] = p->aCol[i].zColl;
98799:       }
98800:     }
98801:   }else{
98802:     sqlite3DbFree(db, zColl);
98803:   }
98804: }
98805: 
98806: /*
98807: ** This function returns the collation sequence for database native text
98808: ** encoding identified by the string zName, length nName.
98809: **
98810: ** If the requested collation sequence is not available, or not available
98811: ** in the database native encoding, the collation factory is invoked to
98812: ** request it. If the collation factory does not supply such a sequence,
98813: ** and the sequence is available in another text encoding, then that is
98814: ** returned instead.
98815: **
98816: ** If no versions of the requested collations sequence are available, or
98817: ** another error occurs, NULL is returned and an error message written into
98818: ** pParse.
98819: **
98820: ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
98821: ** invokes the collation factory if the named collation cannot be found
98822: ** and generates an error message.
98823: **
98824: ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
98825: */
98826: SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
98827:   sqlite3 *db = pParse->db;
98828:   u8 enc = ENC(db);
98829:   u8 initbusy = db->init.busy;
98830:   CollSeq *pColl;
98831: 
98832:   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
98833:   if( !initbusy && (!pColl || !pColl->xCmp) ){
98834:     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
98835:   }
98836: 
98837:   return pColl;
98838: }
98839: 
98840: 
98841: /*
98842: ** Generate code that will increment the schema cookie.
98843: **
98844: ** The schema cookie is used to determine when the schema for the
98845: ** database changes.  After each schema change, the cookie value
98846: ** changes.  When a process first reads the schema it records the
98847: ** cookie.  Thereafter, whenever it goes to access the database,
98848: ** it checks the cookie to make sure the schema has not changed
98849: ** since it was last read.
98850: **
98851: ** This plan is not completely bullet-proof.  It is possible for
98852: ** the schema to change multiple times and for the cookie to be
98853: ** set back to prior value.  But schema changes are infrequent
98854: ** and the probability of hitting the same cookie value is only
98855: ** 1 chance in 2^32.  So we're safe enough.
98856: */
98857: SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
98858:   sqlite3 *db = pParse->db;
98859:   Vdbe *v = pParse->pVdbe;
98860:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98861:   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, 
98862:                     db->aDb[iDb].pSchema->schema_cookie+1);
98863: }
98864: 
98865: /*
98866: ** Measure the number of characters needed to output the given
98867: ** identifier.  The number returned includes any quotes used
98868: ** but does not include the null terminator.
98869: **
98870: ** The estimate is conservative.  It might be larger that what is
98871: ** really needed.
98872: */
98873: static int identLength(const char *z){
98874:   int n;
98875:   for(n=0; *z; n++, z++){
98876:     if( *z=='"' ){ n++; }
98877:   }
98878:   return n + 2;
98879: }
98880: 
98881: /*
98882: ** The first parameter is a pointer to an output buffer. The second 
98883: ** parameter is a pointer to an integer that contains the offset at
98884: ** which to write into the output buffer. This function copies the
98885: ** nul-terminated string pointed to by the third parameter, zSignedIdent,
98886: ** to the specified offset in the buffer and updates *pIdx to refer
98887: ** to the first byte after the last byte written before returning.
98888: ** 
98889: ** If the string zSignedIdent consists entirely of alpha-numeric
98890: ** characters, does not begin with a digit and is not an SQL keyword,
98891: ** then it is copied to the output buffer exactly as it is. Otherwise,
98892: ** it is quoted using double-quotes.
98893: */
98894: static void identPut(char *z, int *pIdx, char *zSignedIdent){
98895:   unsigned char *zIdent = (unsigned char*)zSignedIdent;
98896:   int i, j, needQuote;
98897:   i = *pIdx;
98898: 
98899:   for(j=0; zIdent[j]; j++){
98900:     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
98901:   }
98902:   needQuote = sqlite3Isdigit(zIdent[0])
98903:             || sqlite3KeywordCode(zIdent, j)!=TK_ID
98904:             || zIdent[j]!=0
98905:             || j==0;
98906: 
98907:   if( needQuote ) z[i++] = '"';
98908:   for(j=0; zIdent[j]; j++){
98909:     z[i++] = zIdent[j];
98910:     if( zIdent[j]=='"' ) z[i++] = '"';
98911:   }
98912:   if( needQuote ) z[i++] = '"';
98913:   z[i] = 0;
98914:   *pIdx = i;
98915: }
98916: 
98917: /*
98918: ** Generate a CREATE TABLE statement appropriate for the given
98919: ** table.  Memory to hold the text of the statement is obtained
98920: ** from sqliteMalloc() and must be freed by the calling function.
98921: */
98922: static char *createTableStmt(sqlite3 *db, Table *p){
98923:   int i, k, n;
98924:   char *zStmt;
98925:   char *zSep, *zSep2, *zEnd;
98926:   Column *pCol;
98927:   n = 0;
98928:   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
98929:     n += identLength(pCol->zName) + 5;
98930:   }
98931:   n += identLength(p->zName);
98932:   if( n<50 ){ 
98933:     zSep = "";
98934:     zSep2 = ",";
98935:     zEnd = ")";
98936:   }else{
98937:     zSep = "\n  ";
98938:     zSep2 = ",\n  ";
98939:     zEnd = "\n)";
98940:   }
98941:   n += 35 + 6*p->nCol;
98942:   zStmt = sqlite3DbMallocRaw(0, n);
98943:   if( zStmt==0 ){
98944:     sqlite3OomFault(db);
98945:     return 0;
98946:   }
98947:   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
98948:   k = sqlite3Strlen30(zStmt);
98949:   identPut(zStmt, &k, p->zName);
98950:   zStmt[k++] = '(';
98951:   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
98952:     static const char * const azType[] = {
98953:         /* SQLITE_AFF_BLOB    */ "",
98954:         /* SQLITE_AFF_TEXT    */ " TEXT",
98955:         /* SQLITE_AFF_NUMERIC */ " NUM",
98956:         /* SQLITE_AFF_INTEGER */ " INT",
98957:         /* SQLITE_AFF_REAL    */ " REAL"
98958:     };
98959:     int len;
98960:     const char *zType;
98961: 
98962:     sqlite3_snprintf(n-k, &zStmt[k], zSep);
98963:     k += sqlite3Strlen30(&zStmt[k]);
98964:     zSep = zSep2;
98965:     identPut(zStmt, &k, pCol->zName);
98966:     assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
98967:     assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
98968:     testcase( pCol->affinity==SQLITE_AFF_BLOB );
98969:     testcase( pCol->affinity==SQLITE_AFF_TEXT );
98970:     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
98971:     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
98972:     testcase( pCol->affinity==SQLITE_AFF_REAL );
98973:     
98974:     zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
98975:     len = sqlite3Strlen30(zType);
98976:     assert( pCol->affinity==SQLITE_AFF_BLOB 
98977:             || pCol->affinity==sqlite3AffinityType(zType, 0) );
98978:     memcpy(&zStmt[k], zType, len);
98979:     k += len;
98980:     assert( k<=n );
98981:   }
98982:   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
98983:   return zStmt;
98984: }
98985: 
98986: /*
98987: ** Resize an Index object to hold N columns total.  Return SQLITE_OK
98988: ** on success and SQLITE_NOMEM on an OOM error.
98989: */
98990: static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
98991:   char *zExtra;
98992:   int nByte;
98993:   if( pIdx->nColumn>=N ) return SQLITE_OK;
98994:   assert( pIdx->isResized==0 );
98995:   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
98996:   zExtra = sqlite3DbMallocZero(db, nByte);
98997:   if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
98998:   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
98999:   pIdx->azColl = (const char**)zExtra;
99000:   zExtra += sizeof(char*)*N;
99001:   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
99002:   pIdx->aiColumn = (i16*)zExtra;
99003:   zExtra += sizeof(i16)*N;
99004:   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
99005:   pIdx->aSortOrder = (u8*)zExtra;
99006:   pIdx->nColumn = N;
99007:   pIdx->isResized = 1;
99008:   return SQLITE_OK;
99009: }
99010: 
99011: /*
99012: ** Estimate the total row width for a table.
99013: */
99014: static void estimateTableWidth(Table *pTab){
99015:   unsigned wTable = 0;
99016:   const Column *pTabCol;
99017:   int i;
99018:   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
99019:     wTable += pTabCol->szEst;
99020:   }
99021:   if( pTab->iPKey<0 ) wTable++;
99022:   pTab->szTabRow = sqlite3LogEst(wTable*4);
99023: }
99024: 
99025: /*
99026: ** Estimate the average size of a row for an index.
99027: */
99028: static void estimateIndexWidth(Index *pIdx){
99029:   unsigned wIndex = 0;
99030:   int i;
99031:   const Column *aCol = pIdx->pTable->aCol;
99032:   for(i=0; i<pIdx->nColumn; i++){
99033:     i16 x = pIdx->aiColumn[i];
99034:     assert( x<pIdx->pTable->nCol );
99035:     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
99036:   }
99037:   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
99038: }
99039: 
99040: /* Return true if value x is found any of the first nCol entries of aiCol[]
99041: */
99042: static int hasColumn(const i16 *aiCol, int nCol, int x){
99043:   while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
99044:   return 0;
99045: }
99046: 
99047: /*
99048: ** This routine runs at the end of parsing a CREATE TABLE statement that
99049: ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
99050: ** internal schema data structures and the generated VDBE code so that they
99051: ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
99052: ** Changes include:
99053: **
99054: **     (1)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
99055: **     (2)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
99056: **          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
99057: **          data storage is a covering index btree.
99058: **     (3)  Bypass the creation of the sqlite_master table entry
99059: **          for the PRIMARY KEY as the primary key index is now
99060: **          identified by the sqlite_master table entry of the table itself.
99061: **     (4)  Set the Index.tnum of the PRIMARY KEY Index object in the
99062: **          schema to the rootpage from the main table.
99063: **     (5)  Add all table columns to the PRIMARY KEY Index object
99064: **          so that the PRIMARY KEY is a covering index.  The surplus
99065: **          columns are part of KeyInfo.nXField and are not used for
99066: **          sorting or lookup or uniqueness checks.
99067: **     (6)  Replace the rowid tail on all automatically generated UNIQUE
99068: **          indices with the PRIMARY KEY columns.
99069: **
99070: ** For virtual tables, only (1) is performed.
99071: */
99072: static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
99073:   Index *pIdx;
99074:   Index *pPk;
99075:   int nPk;
99076:   int i, j;
99077:   sqlite3 *db = pParse->db;
99078:   Vdbe *v = pParse->pVdbe;
99079: 
99080:   /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
99081:   */
99082:   if( !db->init.imposterTable ){
99083:     for(i=0; i<pTab->nCol; i++){
99084:       if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
99085:         pTab->aCol[i].notNull = OE_Abort;
99086:       }
99087:     }
99088:   }
99089: 
99090:   /* The remaining transformations only apply to b-tree tables, not to
99091:   ** virtual tables */
99092:   if( IN_DECLARE_VTAB ) return;
99093: 
99094:   /* Convert the OP_CreateTable opcode that would normally create the
99095:   ** root-page for the table into an OP_CreateIndex opcode.  The index
99096:   ** created will become the PRIMARY KEY index.
99097:   */
99098:   if( pParse->addrCrTab ){
99099:     assert( v );
99100:     sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
99101:   }
99102: 
99103:   /* Locate the PRIMARY KEY index.  Or, if this table was originally
99104:   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
99105:   */
99106:   if( pTab->iPKey>=0 ){
99107:     ExprList *pList;
99108:     Token ipkToken;
99109:     sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
99110:     pList = sqlite3ExprListAppend(pParse, 0, 
99111:                   sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
99112:     if( pList==0 ) return;
99113:     pList->a[0].sortOrder = pParse->iPkSortOrder;
99114:     assert( pParse->pNewTable==pTab );
99115:     sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
99116:                        SQLITE_IDXTYPE_PRIMARYKEY);
99117:     if( db->mallocFailed ) return;
99118:     pPk = sqlite3PrimaryKeyIndex(pTab);
99119:     pTab->iPKey = -1;
99120:   }else{
99121:     pPk = sqlite3PrimaryKeyIndex(pTab);
99122: 
99123:     /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
99124:     ** table entry. This is only required if currently generating VDBE
99125:     ** code for a CREATE TABLE (not when parsing one as part of reading
99126:     ** a database schema).  */
99127:     if( v ){
99128:       assert( db->init.busy==0 );
99129:       sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
99130:     }
99131: 
99132:     /*
99133:     ** Remove all redundant columns from the PRIMARY KEY.  For example, change
99134:     ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
99135:     ** code assumes the PRIMARY KEY contains no repeated columns.
99136:     */
99137:     for(i=j=1; i<pPk->nKeyCol; i++){
99138:       if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
99139:         pPk->nColumn--;
99140:       }else{
99141:         pPk->aiColumn[j++] = pPk->aiColumn[i];
99142:       }
99143:     }
99144:     pPk->nKeyCol = j;
99145:   }
99146:   assert( pPk!=0 );
99147:   pPk->isCovering = 1;
99148:   if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
99149:   nPk = pPk->nKeyCol;
99150: 
99151:   /* The root page of the PRIMARY KEY is the table root page */
99152:   pPk->tnum = pTab->tnum;
99153: 
99154:   /* Update the in-memory representation of all UNIQUE indices by converting
99155:   ** the final rowid column into one or more columns of the PRIMARY KEY.
99156:   */
99157:   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99158:     int n;
99159:     if( IsPrimaryKeyIndex(pIdx) ) continue;
99160:     for(i=n=0; i<nPk; i++){
99161:       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
99162:     }
99163:     if( n==0 ){
99164:       /* This index is a superset of the primary key */
99165:       pIdx->nColumn = pIdx->nKeyCol;
99166:       continue;
99167:     }
99168:     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
99169:     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
99170:       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
99171:         pIdx->aiColumn[j] = pPk->aiColumn[i];
99172:         pIdx->azColl[j] = pPk->azColl[i];
99173:         j++;
99174:       }
99175:     }
99176:     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
99177:     assert( pIdx->nColumn>=j );
99178:   }
99179: 
99180:   /* Add all table columns to the PRIMARY KEY index
99181:   */
99182:   if( nPk<pTab->nCol ){
99183:     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
99184:     for(i=0, j=nPk; i<pTab->nCol; i++){
99185:       if( !hasColumn(pPk->aiColumn, j, i) ){
99186:         assert( j<pPk->nColumn );
99187:         pPk->aiColumn[j] = i;
99188:         pPk->azColl[j] = sqlite3StrBINARY;
99189:         j++;
99190:       }
99191:     }
99192:     assert( pPk->nColumn==j );
99193:     assert( pTab->nCol==j );
99194:   }else{
99195:     pPk->nColumn = pTab->nCol;
99196:   }
99197: }
99198: 
99199: /*
99200: ** This routine is called to report the final ")" that terminates
99201: ** a CREATE TABLE statement.
99202: **
99203: ** The table structure that other action routines have been building
99204: ** is added to the internal hash tables, assuming no errors have
99205: ** occurred.
99206: **
99207: ** An entry for the table is made in the master table on disk, unless
99208: ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
99209: ** it means we are reading the sqlite_master table because we just
99210: ** connected to the database or because the sqlite_master table has
99211: ** recently changed, so the entry for this table already exists in
99212: ** the sqlite_master table.  We do not want to create it again.
99213: **
99214: ** If the pSelect argument is not NULL, it means that this routine
99215: ** was called to create a table generated from a 
99216: ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
99217: ** the new table will match the result set of the SELECT.
99218: */
99219: SQLITE_PRIVATE void sqlite3EndTable(
99220:   Parse *pParse,          /* Parse context */
99221:   Token *pCons,           /* The ',' token after the last column defn. */
99222:   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
99223:   u8 tabOpts,             /* Extra table options. Usually 0. */
99224:   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
99225: ){
99226:   Table *p;                 /* The new table */
99227:   sqlite3 *db = pParse->db; /* The database connection */
99228:   int iDb;                  /* Database in which the table lives */
99229:   Index *pIdx;              /* An implied index of the table */
99230: 
99231:   if( pEnd==0 && pSelect==0 ){
99232:     return;
99233:   }
99234:   assert( !db->mallocFailed );
99235:   p = pParse->pNewTable;
99236:   if( p==0 ) return;
99237: 
99238:   assert( !db->init.busy || !pSelect );
99239: 
99240:   /* If the db->init.busy is 1 it means we are reading the SQL off the
99241:   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
99242:   ** So do not write to the disk again.  Extract the root page number
99243:   ** for the table from the db->init.newTnum field.  (The page number
99244:   ** should have been put there by the sqliteOpenCb routine.)
99245:   **
99246:   ** If the root page number is 1, that means this is the sqlite_master
99247:   ** table itself.  So mark it read-only.
99248:   */
99249:   if( db->init.busy ){
99250:     p->tnum = db->init.newTnum;
99251:     if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
99252:   }
99253: 
99254:   /* Special processing for WITHOUT ROWID Tables */
99255:   if( tabOpts & TF_WithoutRowid ){
99256:     if( (p->tabFlags & TF_Autoincrement) ){
99257:       sqlite3ErrorMsg(pParse,
99258:           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
99259:       return;
99260:     }
99261:     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
99262:       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
99263:     }else{
99264:       p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
99265:       convertToWithoutRowidTable(pParse, p);
99266:     }
99267:   }
99268: 
99269:   iDb = sqlite3SchemaToIndex(db, p->pSchema);
99270: 
99271: #ifndef SQLITE_OMIT_CHECK
99272:   /* Resolve names in all CHECK constraint expressions.
99273:   */
99274:   if( p->pCheck ){
99275:     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
99276:   }
99277: #endif /* !defined(SQLITE_OMIT_CHECK) */
99278: 
99279:   /* Estimate the average row size for the table and for all implied indices */
99280:   estimateTableWidth(p);
99281:   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
99282:     estimateIndexWidth(pIdx);
99283:   }
99284: 
99285:   /* If not initializing, then create a record for the new table
99286:   ** in the SQLITE_MASTER table of the database.
99287:   **
99288:   ** If this is a TEMPORARY table, write the entry into the auxiliary
99289:   ** file instead of into the main database file.
99290:   */
99291:   if( !db->init.busy ){
99292:     int n;
99293:     Vdbe *v;
99294:     char *zType;    /* "view" or "table" */
99295:     char *zType2;   /* "VIEW" or "TABLE" */
99296:     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
99297: 
99298:     v = sqlite3GetVdbe(pParse);
99299:     if( NEVER(v==0) ) return;
99300: 
99301:     sqlite3VdbeAddOp1(v, OP_Close, 0);
99302: 
99303:     /* 
99304:     ** Initialize zType for the new view or table.
99305:     */
99306:     if( p->pSelect==0 ){
99307:       /* A regular table */
99308:       zType = "table";
99309:       zType2 = "TABLE";
99310: #ifndef SQLITE_OMIT_VIEW
99311:     }else{
99312:       /* A view */
99313:       zType = "view";
99314:       zType2 = "VIEW";
99315: #endif
99316:     }
99317: 
99318:     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
99319:     ** statement to populate the new table. The root-page number for the
99320:     ** new table is in register pParse->regRoot.
99321:     **
99322:     ** Once the SELECT has been coded by sqlite3Select(), it is in a
99323:     ** suitable state to query for the column names and types to be used
99324:     ** by the new table.
99325:     **
99326:     ** A shared-cache write-lock is not required to write to the new table,
99327:     ** as a schema-lock must have already been obtained to create it. Since
99328:     ** a schema-lock excludes all other database users, the write-lock would
99329:     ** be redundant.
99330:     */
99331:     if( pSelect ){
99332:       SelectDest dest;    /* Where the SELECT should store results */
99333:       int regYield;       /* Register holding co-routine entry-point */
99334:       int addrTop;        /* Top of the co-routine */
99335:       int regRec;         /* A record to be insert into the new table */
99336:       int regRowid;       /* Rowid of the next row to insert */
99337:       int addrInsLoop;    /* Top of the loop for inserting rows */
99338:       Table *pSelTab;     /* A table that describes the SELECT results */
99339: 
99340:       regYield = ++pParse->nMem;
99341:       regRec = ++pParse->nMem;
99342:       regRowid = ++pParse->nMem;
99343:       assert(pParse->nTab==1);
99344:       sqlite3MayAbort(pParse);
99345:       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
99346:       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
99347:       pParse->nTab = 2;
99348:       addrTop = sqlite3VdbeCurrentAddr(v) + 1;
99349:       sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
99350:       sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
99351:       sqlite3Select(pParse, pSelect, &dest);
99352:       sqlite3VdbeEndCoroutine(v, regYield);
99353:       sqlite3VdbeJumpHere(v, addrTop - 1);
99354:       if( pParse->nErr ) return;
99355:       pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
99356:       if( pSelTab==0 ) return;
99357:       assert( p->aCol==0 );
99358:       p->nCol = pSelTab->nCol;
99359:       p->aCol = pSelTab->aCol;
99360:       pSelTab->nCol = 0;
99361:       pSelTab->aCol = 0;
99362:       sqlite3DeleteTable(db, pSelTab);
99363:       addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
99364:       VdbeCoverage(v);
99365:       sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
99366:       sqlite3TableAffinity(v, p, 0);
99367:       sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
99368:       sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
99369:       sqlite3VdbeGoto(v, addrInsLoop);
99370:       sqlite3VdbeJumpHere(v, addrInsLoop);
99371:       sqlite3VdbeAddOp1(v, OP_Close, 1);
99372:     }
99373: 
99374:     /* Compute the complete text of the CREATE statement */
99375:     if( pSelect ){
99376:       zStmt = createTableStmt(db, p);
99377:     }else{
99378:       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
99379:       n = (int)(pEnd2->z - pParse->sNameToken.z);
99380:       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
99381:       zStmt = sqlite3MPrintf(db, 
99382:           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
99383:       );
99384:     }
99385: 
99386:     /* A slot for the record has already been allocated in the 
99387:     ** SQLITE_MASTER table.  We just need to update that slot with all
99388:     ** the information we've collected.
99389:     */
99390:     sqlite3NestedParse(pParse,
99391:       "UPDATE %Q.%s "
99392:          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
99393:        "WHERE rowid=#%d",
99394:       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
99395:       zType,
99396:       p->zName,
99397:       p->zName,
99398:       pParse->regRoot,
99399:       zStmt,
99400:       pParse->regRowid
99401:     );
99402:     sqlite3DbFree(db, zStmt);
99403:     sqlite3ChangeCookie(pParse, iDb);
99404: 
99405: #ifndef SQLITE_OMIT_AUTOINCREMENT
99406:     /* Check to see if we need to create an sqlite_sequence table for
99407:     ** keeping track of autoincrement keys.
99408:     */
99409:     if( p->tabFlags & TF_Autoincrement ){
99410:       Db *pDb = &db->aDb[iDb];
99411:       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99412:       if( pDb->pSchema->pSeqTab==0 ){
99413:         sqlite3NestedParse(pParse,
99414:           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
99415:           pDb->zName
99416:         );
99417:       }
99418:     }
99419: #endif
99420: 
99421:     /* Reparse everything to update our internal data structures */
99422:     sqlite3VdbeAddParseSchemaOp(v, iDb,
99423:            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
99424:   }
99425: 
99426: 
99427:   /* Add the table to the in-memory representation of the database.
99428:   */
99429:   if( db->init.busy ){
99430:     Table *pOld;
99431:     Schema *pSchema = p->pSchema;
99432:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99433:     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
99434:     if( pOld ){
99435:       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
99436:       sqlite3OomFault(db);
99437:       return;
99438:     }
99439:     pParse->pNewTable = 0;
99440:     db->flags |= SQLITE_InternChanges;
99441: 
99442: #ifndef SQLITE_OMIT_ALTERTABLE
99443:     if( !p->pSelect ){
99444:       const char *zName = (const char *)pParse->sNameToken.z;
99445:       int nName;
99446:       assert( !pSelect && pCons && pEnd );
99447:       if( pCons->z==0 ){
99448:         pCons = pEnd;
99449:       }
99450:       nName = (int)((const char *)pCons->z - zName);
99451:       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
99452:     }
99453: #endif
99454:   }
99455: }
99456: 
99457: #ifndef SQLITE_OMIT_VIEW
99458: /*
99459: ** The parser calls this routine in order to create a new VIEW
99460: */
99461: SQLITE_PRIVATE void sqlite3CreateView(
99462:   Parse *pParse,     /* The parsing context */
99463:   Token *pBegin,     /* The CREATE token that begins the statement */
99464:   Token *pName1,     /* The token that holds the name of the view */
99465:   Token *pName2,     /* The token that holds the name of the view */
99466:   ExprList *pCNames, /* Optional list of view column names */
99467:   Select *pSelect,   /* A SELECT statement that will become the new view */
99468:   int isTemp,        /* TRUE for a TEMPORARY view */
99469:   int noErr          /* Suppress error messages if VIEW already exists */
99470: ){
99471:   Table *p;
99472:   int n;
99473:   const char *z;
99474:   Token sEnd;
99475:   DbFixer sFix;
99476:   Token *pName = 0;
99477:   int iDb;
99478:   sqlite3 *db = pParse->db;
99479: 
99480:   if( pParse->nVar>0 ){
99481:     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
99482:     goto create_view_fail;
99483:   }
99484:   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
99485:   p = pParse->pNewTable;
99486:   if( p==0 || pParse->nErr ) goto create_view_fail;
99487:   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99488:   iDb = sqlite3SchemaToIndex(db, p->pSchema);
99489:   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
99490:   if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
99491: 
99492:   /* Make a copy of the entire SELECT statement that defines the view.
99493:   ** This will force all the Expr.token.z values to be dynamically
99494:   ** allocated rather than point to the input string - which means that
99495:   ** they will persist after the current sqlite3_exec() call returns.
99496:   */
99497:   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99498:   p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
99499:   if( db->mallocFailed ) goto create_view_fail;
99500: 
99501:   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
99502:   ** the end.
99503:   */
99504:   sEnd = pParse->sLastToken;
99505:   assert( sEnd.z[0]!=0 );
99506:   if( sEnd.z[0]!=';' ){
99507:     sEnd.z += sEnd.n;
99508:   }
99509:   sEnd.n = 0;
99510:   n = (int)(sEnd.z - pBegin->z);
99511:   assert( n>0 );
99512:   z = pBegin->z;
99513:   while( sqlite3Isspace(z[n-1]) ){ n--; }
99514:   sEnd.z = &z[n-1];
99515:   sEnd.n = 1;
99516: 
99517:   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
99518:   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
99519: 
99520: create_view_fail:
99521:   sqlite3SelectDelete(db, pSelect);
99522:   sqlite3ExprListDelete(db, pCNames);
99523:   return;
99524: }
99525: #endif /* SQLITE_OMIT_VIEW */
99526: 
99527: #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
99528: /*
99529: ** The Table structure pTable is really a VIEW.  Fill in the names of
99530: ** the columns of the view in the pTable structure.  Return the number
99531: ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
99532: */
99533: SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
99534:   Table *pSelTab;   /* A fake table from which we get the result set */
99535:   Select *pSel;     /* Copy of the SELECT that implements the view */
99536:   int nErr = 0;     /* Number of errors encountered */
99537:   int n;            /* Temporarily holds the number of cursors assigned */
99538:   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
99539:   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
99540: 
99541:   assert( pTable );
99542: 
99543: #ifndef SQLITE_OMIT_VIRTUALTABLE
99544:   if( sqlite3VtabCallConnect(pParse, pTable) ){
99545:     return SQLITE_ERROR;
99546:   }
99547:   if( IsVirtual(pTable) ) return 0;
99548: #endif
99549: 
99550: #ifndef SQLITE_OMIT_VIEW
99551:   /* A positive nCol means the columns names for this view are
99552:   ** already known.
99553:   */
99554:   if( pTable->nCol>0 ) return 0;
99555: 
99556:   /* A negative nCol is a special marker meaning that we are currently
99557:   ** trying to compute the column names.  If we enter this routine with
99558:   ** a negative nCol, it means two or more views form a loop, like this:
99559:   **
99560:   **     CREATE VIEW one AS SELECT * FROM two;
99561:   **     CREATE VIEW two AS SELECT * FROM one;
99562:   **
99563:   ** Actually, the error above is now caught prior to reaching this point.
99564:   ** But the following test is still important as it does come up
99565:   ** in the following:
99566:   ** 
99567:   **     CREATE TABLE main.ex1(a);
99568:   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
99569:   **     SELECT * FROM temp.ex1;
99570:   */
99571:   if( pTable->nCol<0 ){
99572:     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
99573:     return 1;
99574:   }
99575:   assert( pTable->nCol>=0 );
99576: 
99577:   /* If we get this far, it means we need to compute the table names.
99578:   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
99579:   ** "*" elements in the results set of the view and will assign cursors
99580:   ** to the elements of the FROM clause.  But we do not want these changes
99581:   ** to be permanent.  So the computation is done on a copy of the SELECT
99582:   ** statement that defines the view.
99583:   */
99584:   assert( pTable->pSelect );
99585:   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
99586:   if( pSel ){
99587:     n = pParse->nTab;
99588:     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
99589:     pTable->nCol = -1;
99590:     db->lookaside.bDisable++;
99591: #ifndef SQLITE_OMIT_AUTHORIZATION
99592:     xAuth = db->xAuth;
99593:     db->xAuth = 0;
99594:     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
99595:     db->xAuth = xAuth;
99596: #else
99597:     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
99598: #endif
99599:     pParse->nTab = n;
99600:     if( pTable->pCheck ){
99601:       /* CREATE VIEW name(arglist) AS ...
99602:       ** The names of the columns in the table are taken from
99603:       ** arglist which is stored in pTable->pCheck.  The pCheck field
99604:       ** normally holds CHECK constraints on an ordinary table, but for
99605:       ** a VIEW it holds the list of column names.
99606:       */
99607:       sqlite3ColumnsFromExprList(pParse, pTable->pCheck, 
99608:                                  &pTable->nCol, &pTable->aCol);
99609:       if( db->mallocFailed==0 
99610:        && pParse->nErr==0
99611:        && pTable->nCol==pSel->pEList->nExpr
99612:       ){
99613:         sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
99614:       }
99615:     }else if( pSelTab ){
99616:       /* CREATE VIEW name AS...  without an argument list.  Construct
99617:       ** the column names from the SELECT statement that defines the view.
99618:       */
99619:       assert( pTable->aCol==0 );
99620:       pTable->nCol = pSelTab->nCol;
99621:       pTable->aCol = pSelTab->aCol;
99622:       pSelTab->nCol = 0;
99623:       pSelTab->aCol = 0;
99624:       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
99625:     }else{
99626:       pTable->nCol = 0;
99627:       nErr++;
99628:     }
99629:     sqlite3DeleteTable(db, pSelTab);
99630:     sqlite3SelectDelete(db, pSel);
99631:     db->lookaside.bDisable--;
99632:   } else {
99633:     nErr++;
99634:   }
99635:   pTable->pSchema->schemaFlags |= DB_UnresetViews;
99636: #endif /* SQLITE_OMIT_VIEW */
99637:   return nErr;  
99638: }
99639: #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
99640: 
99641: #ifndef SQLITE_OMIT_VIEW
99642: /*
99643: ** Clear the column names from every VIEW in database idx.
99644: */
99645: static void sqliteViewResetAll(sqlite3 *db, int idx){
99646:   HashElem *i;
99647:   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
99648:   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
99649:   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
99650:     Table *pTab = sqliteHashData(i);
99651:     if( pTab->pSelect ){
99652:       sqlite3DeleteColumnNames(db, pTab);
99653:       pTab->aCol = 0;
99654:       pTab->nCol = 0;
99655:     }
99656:   }
99657:   DbClearProperty(db, idx, DB_UnresetViews);
99658: }
99659: #else
99660: # define sqliteViewResetAll(A,B)
99661: #endif /* SQLITE_OMIT_VIEW */
99662: 
99663: /*
99664: ** This function is called by the VDBE to adjust the internal schema
99665: ** used by SQLite when the btree layer moves a table root page. The
99666: ** root-page of a table or index in database iDb has changed from iFrom
99667: ** to iTo.
99668: **
99669: ** Ticket #1728:  The symbol table might still contain information
99670: ** on tables and/or indices that are the process of being deleted.
99671: ** If you are unlucky, one of those deleted indices or tables might
99672: ** have the same rootpage number as the real table or index that is
99673: ** being moved.  So we cannot stop searching after the first match 
99674: ** because the first match might be for one of the deleted indices
99675: ** or tables and not the table/index that is actually being moved.
99676: ** We must continue looping until all tables and indices with
99677: ** rootpage==iFrom have been converted to have a rootpage of iTo
99678: ** in order to be certain that we got the right one.
99679: */
99680: #ifndef SQLITE_OMIT_AUTOVACUUM
99681: SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
99682:   HashElem *pElem;
99683:   Hash *pHash;
99684:   Db *pDb;
99685: 
99686:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99687:   pDb = &db->aDb[iDb];
99688:   pHash = &pDb->pSchema->tblHash;
99689:   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99690:     Table *pTab = sqliteHashData(pElem);
99691:     if( pTab->tnum==iFrom ){
99692:       pTab->tnum = iTo;
99693:     }
99694:   }
99695:   pHash = &pDb->pSchema->idxHash;
99696:   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99697:     Index *pIdx = sqliteHashData(pElem);
99698:     if( pIdx->tnum==iFrom ){
99699:       pIdx->tnum = iTo;
99700:     }
99701:   }
99702: }
99703: #endif
99704: 
99705: /*
99706: ** Write code to erase the table with root-page iTable from database iDb.
99707: ** Also write code to modify the sqlite_master table and internal schema
99708: ** if a root-page of another table is moved by the btree-layer whilst
99709: ** erasing iTable (this can happen with an auto-vacuum database).
99710: */ 
99711: static void destroyRootPage(Parse *pParse, int iTable, int iDb){
99712:   Vdbe *v = sqlite3GetVdbe(pParse);
99713:   int r1 = sqlite3GetTempReg(pParse);
99714:   assert( iTable>1 );
99715:   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
99716:   sqlite3MayAbort(pParse);
99717: #ifndef SQLITE_OMIT_AUTOVACUUM
99718:   /* OP_Destroy stores an in integer r1. If this integer
99719:   ** is non-zero, then it is the root page number of a table moved to
99720:   ** location iTable. The following code modifies the sqlite_master table to
99721:   ** reflect this.
99722:   **
99723:   ** The "#NNN" in the SQL is a special constant that means whatever value
99724:   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
99725:   ** token for additional information.
99726:   */
99727:   sqlite3NestedParse(pParse, 
99728:      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
99729:      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
99730: #endif
99731:   sqlite3ReleaseTempReg(pParse, r1);
99732: }
99733: 
99734: /*
99735: ** Write VDBE code to erase table pTab and all associated indices on disk.
99736: ** Code to update the sqlite_master tables and internal schema definitions
99737: ** in case a root-page belonging to another table is moved by the btree layer
99738: ** is also added (this can happen with an auto-vacuum database).
99739: */
99740: static void destroyTable(Parse *pParse, Table *pTab){
99741: #ifdef SQLITE_OMIT_AUTOVACUUM
99742:   Index *pIdx;
99743:   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99744:   destroyRootPage(pParse, pTab->tnum, iDb);
99745:   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99746:     destroyRootPage(pParse, pIdx->tnum, iDb);
99747:   }
99748: #else
99749:   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
99750:   ** is not defined), then it is important to call OP_Destroy on the
99751:   ** table and index root-pages in order, starting with the numerically 
99752:   ** largest root-page number. This guarantees that none of the root-pages
99753:   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
99754:   ** following were coded:
99755:   **
99756:   ** OP_Destroy 4 0
99757:   ** ...
99758:   ** OP_Destroy 5 0
99759:   **
99760:   ** and root page 5 happened to be the largest root-page number in the
99761:   ** database, then root page 5 would be moved to page 4 by the 
99762:   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
99763:   ** a free-list page.
99764:   */
99765:   int iTab = pTab->tnum;
99766:   int iDestroyed = 0;
99767: 
99768:   while( 1 ){
99769:     Index *pIdx;
99770:     int iLargest = 0;
99771: 
99772:     if( iDestroyed==0 || iTab<iDestroyed ){
99773:       iLargest = iTab;
99774:     }
99775:     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99776:       int iIdx = pIdx->tnum;
99777:       assert( pIdx->pSchema==pTab->pSchema );
99778:       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
99779:         iLargest = iIdx;
99780:       }
99781:     }
99782:     if( iLargest==0 ){
99783:       return;
99784:     }else{
99785:       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99786:       assert( iDb>=0 && iDb<pParse->db->nDb );
99787:       destroyRootPage(pParse, iLargest, iDb);
99788:       iDestroyed = iLargest;
99789:     }
99790:   }
99791: #endif
99792: }
99793: 
99794: /*
99795: ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
99796: ** after a DROP INDEX or DROP TABLE command.
99797: */
99798: static void sqlite3ClearStatTables(
99799:   Parse *pParse,         /* The parsing context */
99800:   int iDb,               /* The database number */
99801:   const char *zType,     /* "idx" or "tbl" */
99802:   const char *zName      /* Name of index or table */
99803: ){
99804:   int i;
99805:   const char *zDbName = pParse->db->aDb[iDb].zName;
99806:   for(i=1; i<=4; i++){
99807:     char zTab[24];
99808:     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
99809:     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
99810:       sqlite3NestedParse(pParse,
99811:         "DELETE FROM %Q.%s WHERE %s=%Q",
99812:         zDbName, zTab, zType, zName
99813:       );
99814:     }
99815:   }
99816: }
99817: 
99818: /*
99819: ** Generate code to drop a table.
99820: */
99821: SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
99822:   Vdbe *v;
99823:   sqlite3 *db = pParse->db;
99824:   Trigger *pTrigger;
99825:   Db *pDb = &db->aDb[iDb];
99826: 
99827:   v = sqlite3GetVdbe(pParse);
99828:   assert( v!=0 );
99829:   sqlite3BeginWriteOperation(pParse, 1, iDb);
99830: 
99831: #ifndef SQLITE_OMIT_VIRTUALTABLE
99832:   if( IsVirtual(pTab) ){
99833:     sqlite3VdbeAddOp0(v, OP_VBegin);
99834:   }
99835: #endif
99836: 
99837:   /* Drop all triggers associated with the table being dropped. Code
99838:   ** is generated to remove entries from sqlite_master and/or
99839:   ** sqlite_temp_master if required.
99840:   */
99841:   pTrigger = sqlite3TriggerList(pParse, pTab);
99842:   while( pTrigger ){
99843:     assert( pTrigger->pSchema==pTab->pSchema || 
99844:         pTrigger->pSchema==db->aDb[1].pSchema );
99845:     sqlite3DropTriggerPtr(pParse, pTrigger);
99846:     pTrigger = pTrigger->pNext;
99847:   }
99848: 
99849: #ifndef SQLITE_OMIT_AUTOINCREMENT
99850:   /* Remove any entries of the sqlite_sequence table associated with
99851:   ** the table being dropped. This is done before the table is dropped
99852:   ** at the btree level, in case the sqlite_sequence table needs to
99853:   ** move as a result of the drop (can happen in auto-vacuum mode).
99854:   */
99855:   if( pTab->tabFlags & TF_Autoincrement ){
99856:     sqlite3NestedParse(pParse,
99857:       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
99858:       pDb->zName, pTab->zName
99859:     );
99860:   }
99861: #endif
99862: 
99863:   /* Drop all SQLITE_MASTER table and index entries that refer to the
99864:   ** table. The program name loops through the master table and deletes
99865:   ** every row that refers to a table of the same name as the one being
99866:   ** dropped. Triggers are handled separately because a trigger can be
99867:   ** created in the temp database that refers to a table in another
99868:   ** database.
99869:   */
99870:   sqlite3NestedParse(pParse, 
99871:       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
99872:       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
99873:   if( !isView && !IsVirtual(pTab) ){
99874:     destroyTable(pParse, pTab);
99875:   }
99876: 
99877:   /* Remove the table entry from SQLite's internal schema and modify
99878:   ** the schema cookie.
99879:   */
99880:   if( IsVirtual(pTab) ){
99881:     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
99882:   }
99883:   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
99884:   sqlite3ChangeCookie(pParse, iDb);
99885:   sqliteViewResetAll(db, iDb);
99886: }
99887: 
99888: /*
99889: ** This routine is called to do the work of a DROP TABLE statement.
99890: ** pName is the name of the table to be dropped.
99891: */
99892: SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
99893:   Table *pTab;
99894:   Vdbe *v;
99895:   sqlite3 *db = pParse->db;
99896:   int iDb;
99897: 
99898:   if( db->mallocFailed ){
99899:     goto exit_drop_table;
99900:   }
99901:   assert( pParse->nErr==0 );
99902:   assert( pName->nSrc==1 );
99903:   if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
99904:   if( noErr ) db->suppressErr++;
99905:   assert( isView==0 || isView==LOCATE_VIEW );
99906:   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
99907:   if( noErr ) db->suppressErr--;
99908: 
99909:   if( pTab==0 ){
99910:     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
99911:     goto exit_drop_table;
99912:   }
99913:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99914:   assert( iDb>=0 && iDb<db->nDb );
99915: 
99916:   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
99917:   ** it is initialized.
99918:   */
99919:   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
99920:     goto exit_drop_table;
99921:   }
99922: #ifndef SQLITE_OMIT_AUTHORIZATION
99923:   {
99924:     int code;
99925:     const char *zTab = SCHEMA_TABLE(iDb);
99926:     const char *zDb = db->aDb[iDb].zName;
99927:     const char *zArg2 = 0;
99928:     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
99929:       goto exit_drop_table;
99930:     }
99931:     if( isView ){
99932:       if( !OMIT_TEMPDB && iDb==1 ){
99933:         code = SQLITE_DROP_TEMP_VIEW;
99934:       }else{
99935:         code = SQLITE_DROP_VIEW;
99936:       }
99937: #ifndef SQLITE_OMIT_VIRTUALTABLE
99938:     }else if( IsVirtual(pTab) ){
99939:       code = SQLITE_DROP_VTABLE;
99940:       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
99941: #endif
99942:     }else{
99943:       if( !OMIT_TEMPDB && iDb==1 ){
99944:         code = SQLITE_DROP_TEMP_TABLE;
99945:       }else{
99946:         code = SQLITE_DROP_TABLE;
99947:       }
99948:     }
99949:     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
99950:       goto exit_drop_table;
99951:     }
99952:     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
99953:       goto exit_drop_table;
99954:     }
99955:   }
99956: #endif
99957:   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
99958:     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
99959:     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
99960:     goto exit_drop_table;
99961:   }
99962: 
99963: #ifndef SQLITE_OMIT_VIEW
99964:   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
99965:   ** on a table.
99966:   */
99967:   if( isView && pTab->pSelect==0 ){
99968:     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
99969:     goto exit_drop_table;
99970:   }
99971:   if( !isView && pTab->pSelect ){
99972:     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
99973:     goto exit_drop_table;
99974:   }
99975: #endif
99976: 
99977:   /* Generate code to remove the table from the master table
99978:   ** on disk.
99979:   */
99980:   v = sqlite3GetVdbe(pParse);
99981:   if( v ){
99982:     sqlite3BeginWriteOperation(pParse, 1, iDb);
99983:     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
99984:     sqlite3FkDropTable(pParse, pName, pTab);
99985:     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
99986:   }
99987: 
99988: exit_drop_table:
99989:   sqlite3SrcListDelete(db, pName);
99990: }
99991: 
99992: /*
99993: ** This routine is called to create a new foreign key on the table
99994: ** currently under construction.  pFromCol determines which columns
99995: ** in the current table point to the foreign key.  If pFromCol==0 then
99996: ** connect the key to the last column inserted.  pTo is the name of
99997: ** the table referred to (a.k.a the "parent" table).  pToCol is a list
99998: ** of tables in the parent pTo table.  flags contains all
99999: ** information about the conflict resolution algorithms specified
100000: ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
100001: **
100002: ** An FKey structure is created and added to the table currently
100003: ** under construction in the pParse->pNewTable field.
100004: **
100005: ** The foreign key is set for IMMEDIATE processing.  A subsequent call
100006: ** to sqlite3DeferForeignKey() might change this to DEFERRED.
100007: */
100008: SQLITE_PRIVATE void sqlite3CreateForeignKey(
100009:   Parse *pParse,       /* Parsing context */
100010:   ExprList *pFromCol,  /* Columns in this table that point to other table */
100011:   Token *pTo,          /* Name of the other table */
100012:   ExprList *pToCol,    /* Columns in the other table */
100013:   int flags            /* Conflict resolution algorithms. */
100014: ){
100015:   sqlite3 *db = pParse->db;
100016: #ifndef SQLITE_OMIT_FOREIGN_KEY
100017:   FKey *pFKey = 0;
100018:   FKey *pNextTo;
100019:   Table *p = pParse->pNewTable;
100020:   int nByte;
100021:   int i;
100022:   int nCol;
100023:   char *z;
100024: 
100025:   assert( pTo!=0 );
100026:   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
100027:   if( pFromCol==0 ){
100028:     int iCol = p->nCol-1;
100029:     if( NEVER(iCol<0) ) goto fk_end;
100030:     if( pToCol && pToCol->nExpr!=1 ){
100031:       sqlite3ErrorMsg(pParse, "foreign key on %s"
100032:          " should reference only one column of table %T",
100033:          p->aCol[iCol].zName, pTo);
100034:       goto fk_end;
100035:     }
100036:     nCol = 1;
100037:   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
100038:     sqlite3ErrorMsg(pParse,
100039:         "number of columns in foreign key does not match the number of "
100040:         "columns in the referenced table");
100041:     goto fk_end;
100042:   }else{
100043:     nCol = pFromCol->nExpr;
100044:   }
100045:   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
100046:   if( pToCol ){
100047:     for(i=0; i<pToCol->nExpr; i++){
100048:       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
100049:     }
100050:   }
100051:   pFKey = sqlite3DbMallocZero(db, nByte );
100052:   if( pFKey==0 ){
100053:     goto fk_end;
100054:   }
100055:   pFKey->pFrom = p;
100056:   pFKey->pNextFrom = p->pFKey;
100057:   z = (char*)&pFKey->aCol[nCol];
100058:   pFKey->zTo = z;
100059:   memcpy(z, pTo->z, pTo->n);
100060:   z[pTo->n] = 0;
100061:   sqlite3Dequote(z);
100062:   z += pTo->n+1;
100063:   pFKey->nCol = nCol;
100064:   if( pFromCol==0 ){
100065:     pFKey->aCol[0].iFrom = p->nCol-1;
100066:   }else{
100067:     for(i=0; i<nCol; i++){
100068:       int j;
100069:       for(j=0; j<p->nCol; j++){
100070:         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
100071:           pFKey->aCol[i].iFrom = j;
100072:           break;
100073:         }
100074:       }
100075:       if( j>=p->nCol ){
100076:         sqlite3ErrorMsg(pParse, 
100077:           "unknown column \"%s\" in foreign key definition", 
100078:           pFromCol->a[i].zName);
100079:         goto fk_end;
100080:       }
100081:     }
100082:   }
100083:   if( pToCol ){
100084:     for(i=0; i<nCol; i++){
100085:       int n = sqlite3Strlen30(pToCol->a[i].zName);
100086:       pFKey->aCol[i].zCol = z;
100087:       memcpy(z, pToCol->a[i].zName, n);
100088:       z[n] = 0;
100089:       z += n+1;
100090:     }
100091:   }
100092:   pFKey->isDeferred = 0;
100093:   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
100094:   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
100095: 
100096:   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
100097:   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
100098:       pFKey->zTo, (void *)pFKey
100099:   );
100100:   if( pNextTo==pFKey ){
100101:     sqlite3OomFault(db);
100102:     goto fk_end;
100103:   }
100104:   if( pNextTo ){
100105:     assert( pNextTo->pPrevTo==0 );
100106:     pFKey->pNextTo = pNextTo;
100107:     pNextTo->pPrevTo = pFKey;
100108:   }
100109: 
100110:   /* Link the foreign key to the table as the last step.
100111:   */
100112:   p->pFKey = pFKey;
100113:   pFKey = 0;
100114: 
100115: fk_end:
100116:   sqlite3DbFree(db, pFKey);
100117: #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
100118:   sqlite3ExprListDelete(db, pFromCol);
100119:   sqlite3ExprListDelete(db, pToCol);
100120: }
100121: 
100122: /*
100123: ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
100124: ** clause is seen as part of a foreign key definition.  The isDeferred
100125: ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
100126: ** The behavior of the most recently created foreign key is adjusted
100127: ** accordingly.
100128: */
100129: SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
100130: #ifndef SQLITE_OMIT_FOREIGN_KEY
100131:   Table *pTab;
100132:   FKey *pFKey;
100133:   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
100134:   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
100135:   pFKey->isDeferred = (u8)isDeferred;
100136: #endif
100137: }
100138: 
100139: /*
100140: ** Generate code that will erase and refill index *pIdx.  This is
100141: ** used to initialize a newly created index or to recompute the
100142: ** content of an index in response to a REINDEX command.
100143: **
100144: ** if memRootPage is not negative, it means that the index is newly
100145: ** created.  The register specified by memRootPage contains the
100146: ** root page number of the index.  If memRootPage is negative, then
100147: ** the index already exists and must be cleared before being refilled and
100148: ** the root page number of the index is taken from pIndex->tnum.
100149: */
100150: static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
100151:   Table *pTab = pIndex->pTable;  /* The table that is indexed */
100152:   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
100153:   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
100154:   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
100155:   int addr1;                     /* Address of top of loop */
100156:   int addr2;                     /* Address to jump to for next iteration */
100157:   int tnum;                      /* Root page of index */
100158:   int iPartIdxLabel;             /* Jump to this label to skip a row */
100159:   Vdbe *v;                       /* Generate code into this virtual machine */
100160:   KeyInfo *pKey;                 /* KeyInfo for index */
100161:   int regRecord;                 /* Register holding assembled index record */
100162:   sqlite3 *db = pParse->db;      /* The database connection */
100163:   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
100164: 
100165: #ifndef SQLITE_OMIT_AUTHORIZATION
100166:   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
100167:       db->aDb[iDb].zName ) ){
100168:     return;
100169:   }
100170: #endif
100171: 
100172:   /* Require a write-lock on the table to perform this operation */
100173:   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
100174: 
100175:   v = sqlite3GetVdbe(pParse);
100176:   if( v==0 ) return;
100177:   if( memRootPage>=0 ){
100178:     tnum = memRootPage;
100179:   }else{
100180:     tnum = pIndex->tnum;
100181:   }
100182:   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
100183:   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
100184: 
100185:   /* Open the sorter cursor if we are to use one. */
100186:   iSorter = pParse->nTab++;
100187:   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
100188:                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
100189: 
100190:   /* Open the table. Loop through all rows of the table, inserting index
100191:   ** records into the sorter. */
100192:   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
100193:   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
100194:   regRecord = sqlite3GetTempReg(pParse);
100195: 
100196:   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
100197:   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
100198:   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
100199:   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
100200:   sqlite3VdbeJumpHere(v, addr1);
100201:   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
100202:   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
100203:                     (char *)pKey, P4_KEYINFO);
100204:   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
100205: 
100206:   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
100207:   if( IsUniqueIndex(pIndex) ){
100208:     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
100209:     sqlite3VdbeGoto(v, j2);
100210:     addr2 = sqlite3VdbeCurrentAddr(v);
100211:     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
100212:                          pIndex->nKeyCol); VdbeCoverage(v);
100213:     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
100214:   }else{
100215:     addr2 = sqlite3VdbeCurrentAddr(v);
100216:   }
100217:   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
100218:   sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
100219:   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
100220:   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
100221:   sqlite3ReleaseTempReg(pParse, regRecord);
100222:   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
100223:   sqlite3VdbeJumpHere(v, addr1);
100224: 
100225:   sqlite3VdbeAddOp1(v, OP_Close, iTab);
100226:   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
100227:   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
100228: }
100229: 
100230: /*
100231: ** Allocate heap space to hold an Index object with nCol columns.
100232: **
100233: ** Increase the allocation size to provide an extra nExtra bytes
100234: ** of 8-byte aligned space after the Index object and return a
100235: ** pointer to this extra space in *ppExtra.
100236: */
100237: SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
100238:   sqlite3 *db,         /* Database connection */
100239:   i16 nCol,            /* Total number of columns in the index */
100240:   int nExtra,          /* Number of bytes of extra space to alloc */
100241:   char **ppExtra       /* Pointer to the "extra" space */
100242: ){
100243:   Index *p;            /* Allocated index object */
100244:   int nByte;           /* Bytes of space for Index object + arrays */
100245: 
100246:   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
100247:           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
100248:           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
100249:                  sizeof(i16)*nCol +            /* Index.aiColumn   */
100250:                  sizeof(u8)*nCol);             /* Index.aSortOrder */
100251:   p = sqlite3DbMallocZero(db, nByte + nExtra);
100252:   if( p ){
100253:     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
100254:     p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
100255:     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
100256:     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
100257:     p->aSortOrder = (u8*)pExtra;
100258:     p->nColumn = nCol;
100259:     p->nKeyCol = nCol - 1;
100260:     *ppExtra = ((char*)p) + nByte;
100261:   }
100262:   return p;
100263: }
100264: 
100265: /*
100266: ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
100267: ** and pTblList is the name of the table that is to be indexed.  Both will 
100268: ** be NULL for a primary key or an index that is created to satisfy a
100269: ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
100270: ** as the table to be indexed.  pParse->pNewTable is a table that is
100271: ** currently being constructed by a CREATE TABLE statement.
100272: **
100273: ** pList is a list of columns to be indexed.  pList will be NULL if this
100274: ** is a primary key or unique-constraint on the most recent column added
100275: ** to the table currently under construction.  
100276: */
100277: SQLITE_PRIVATE void sqlite3CreateIndex(
100278:   Parse *pParse,     /* All information about this parse */
100279:   Token *pName1,     /* First part of index name. May be NULL */
100280:   Token *pName2,     /* Second part of index name. May be NULL */
100281:   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
100282:   ExprList *pList,   /* A list of columns to be indexed */
100283:   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
100284:   Token *pStart,     /* The CREATE token that begins this statement */
100285:   Expr *pPIWhere,    /* WHERE clause for partial indices */
100286:   int sortOrder,     /* Sort order of primary key when pList==NULL */
100287:   int ifNotExist,    /* Omit error if index already exists */
100288:   u8 idxType         /* The index type */
100289: ){
100290:   Table *pTab = 0;     /* Table to be indexed */
100291:   Index *pIndex = 0;   /* The index to be created */
100292:   char *zName = 0;     /* Name of the index */
100293:   int nName;           /* Number of characters in zName */
100294:   int i, j;
100295:   DbFixer sFix;        /* For assigning database names to pTable */
100296:   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
100297:   sqlite3 *db = pParse->db;
100298:   Db *pDb;             /* The specific table containing the indexed database */
100299:   int iDb;             /* Index of the database that is being written */
100300:   Token *pName = 0;    /* Unqualified name of the index to create */
100301:   struct ExprList_item *pListItem; /* For looping over pList */
100302:   int nExtra = 0;                  /* Space allocated for zExtra[] */
100303:   int nExtraCol;                   /* Number of extra columns needed */
100304:   char *zExtra = 0;                /* Extra space after the Index object */
100305:   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
100306: 
100307:   if( db->mallocFailed || pParse->nErr>0 ){
100308:     goto exit_create_index;
100309:   }
100310:   if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
100311:     goto exit_create_index;
100312:   }
100313:   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100314:     goto exit_create_index;
100315:   }
100316: 
100317:   /*
100318:   ** Find the table that is to be indexed.  Return early if not found.
100319:   */
100320:   if( pTblName!=0 ){
100321: 
100322:     /* Use the two-part index name to determine the database 
100323:     ** to search for the table. 'Fix' the table name to this db
100324:     ** before looking up the table.
100325:     */
100326:     assert( pName1 && pName2 );
100327:     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
100328:     if( iDb<0 ) goto exit_create_index;
100329:     assert( pName && pName->z );
100330: 
100331: #ifndef SQLITE_OMIT_TEMPDB
100332:     /* If the index name was unqualified, check if the table
100333:     ** is a temp table. If so, set the database to 1. Do not do this
100334:     ** if initialising a database schema.
100335:     */
100336:     if( !db->init.busy ){
100337:       pTab = sqlite3SrcListLookup(pParse, pTblName);
100338:       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
100339:         iDb = 1;
100340:       }
100341:     }
100342: #endif
100343: 
100344:     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
100345:     if( sqlite3FixSrcList(&sFix, pTblName) ){
100346:       /* Because the parser constructs pTblName from a single identifier,
100347:       ** sqlite3FixSrcList can never fail. */
100348:       assert(0);
100349:     }
100350:     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
100351:     assert( db->mallocFailed==0 || pTab==0 );
100352:     if( pTab==0 ) goto exit_create_index;
100353:     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
100354:       sqlite3ErrorMsg(pParse, 
100355:            "cannot create a TEMP index on non-TEMP table \"%s\"",
100356:            pTab->zName);
100357:       goto exit_create_index;
100358:     }
100359:     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
100360:   }else{
100361:     assert( pName==0 );
100362:     assert( pStart==0 );
100363:     pTab = pParse->pNewTable;
100364:     if( !pTab ) goto exit_create_index;
100365:     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
100366:   }
100367:   pDb = &db->aDb[iDb];
100368: 
100369:   assert( pTab!=0 );
100370:   assert( pParse->nErr==0 );
100371:   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
100372:        && db->init.busy==0
100373: #if SQLITE_USER_AUTHENTICATION
100374:        && sqlite3UserAuthTable(pTab->zName)==0
100375: #endif
100376:        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
100377:     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
100378:     goto exit_create_index;
100379:   }
100380: #ifndef SQLITE_OMIT_VIEW
100381:   if( pTab->pSelect ){
100382:     sqlite3ErrorMsg(pParse, "views may not be indexed");
100383:     goto exit_create_index;
100384:   }
100385: #endif
100386: #ifndef SQLITE_OMIT_VIRTUALTABLE
100387:   if( IsVirtual(pTab) ){
100388:     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
100389:     goto exit_create_index;
100390:   }
100391: #endif
100392: 
100393:   /*
100394:   ** Find the name of the index.  Make sure there is not already another
100395:   ** index or table with the same name.  
100396:   **
100397:   ** Exception:  If we are reading the names of permanent indices from the
100398:   ** sqlite_master table (because some other process changed the schema) and
100399:   ** one of the index names collides with the name of a temporary table or
100400:   ** index, then we will continue to process this index.
100401:   **
100402:   ** If pName==0 it means that we are
100403:   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
100404:   ** own name.
100405:   */
100406:   if( pName ){
100407:     zName = sqlite3NameFromToken(db, pName);
100408:     if( zName==0 ) goto exit_create_index;
100409:     assert( pName->z!=0 );
100410:     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
100411:       goto exit_create_index;
100412:     }
100413:     if( !db->init.busy ){
100414:       if( sqlite3FindTable(db, zName, 0)!=0 ){
100415:         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
100416:         goto exit_create_index;
100417:       }
100418:     }
100419:     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
100420:       if( !ifNotExist ){
100421:         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
100422:       }else{
100423:         assert( !db->init.busy );
100424:         sqlite3CodeVerifySchema(pParse, iDb);
100425:       }
100426:       goto exit_create_index;
100427:     }
100428:   }else{
100429:     int n;
100430:     Index *pLoop;
100431:     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
100432:     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
100433:     if( zName==0 ){
100434:       goto exit_create_index;
100435:     }
100436: 
100437:     /* Automatic index names generated from within sqlite3_declare_vtab()
100438:     ** must have names that are distinct from normal automatic index names.
100439:     ** The following statement converts "sqlite3_autoindex..." into
100440:     ** "sqlite3_butoindex..." in order to make the names distinct.
100441:     ** The "vtab_err.test" test demonstrates the need of this statement. */
100442:     if( IN_DECLARE_VTAB ) zName[7]++;
100443:   }
100444: 
100445:   /* Check for authorization to create an index.
100446:   */
100447: #ifndef SQLITE_OMIT_AUTHORIZATION
100448:   {
100449:     const char *zDb = pDb->zName;
100450:     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
100451:       goto exit_create_index;
100452:     }
100453:     i = SQLITE_CREATE_INDEX;
100454:     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
100455:     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
100456:       goto exit_create_index;
100457:     }
100458:   }
100459: #endif
100460: 
100461:   /* If pList==0, it means this routine was called to make a primary
100462:   ** key out of the last column added to the table under construction.
100463:   ** So create a fake list to simulate this.
100464:   */
100465:   if( pList==0 ){
100466:     Token prevCol;
100467:     sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
100468:     pList = sqlite3ExprListAppend(pParse, 0,
100469:               sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
100470:     if( pList==0 ) goto exit_create_index;
100471:     assert( pList->nExpr==1 );
100472:     sqlite3ExprListSetSortOrder(pList, sortOrder);
100473:   }else{
100474:     sqlite3ExprListCheckLength(pParse, pList, "index");
100475:   }
100476: 
100477:   /* Figure out how many bytes of space are required to store explicitly
100478:   ** specified collation sequence names.
100479:   */
100480:   for(i=0; i<pList->nExpr; i++){
100481:     Expr *pExpr = pList->a[i].pExpr;
100482:     assert( pExpr!=0 );
100483:     if( pExpr->op==TK_COLLATE ){
100484:       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
100485:     }
100486:   }
100487: 
100488:   /* 
100489:   ** Allocate the index structure. 
100490:   */
100491:   nName = sqlite3Strlen30(zName);
100492:   nExtraCol = pPk ? pPk->nKeyCol : 1;
100493:   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
100494:                                       nName + nExtra + 1, &zExtra);
100495:   if( db->mallocFailed ){
100496:     goto exit_create_index;
100497:   }
100498:   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
100499:   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
100500:   pIndex->zName = zExtra;
100501:   zExtra += nName + 1;
100502:   memcpy(pIndex->zName, zName, nName+1);
100503:   pIndex->pTable = pTab;
100504:   pIndex->onError = (u8)onError;
100505:   pIndex->uniqNotNull = onError!=OE_None;
100506:   pIndex->idxType = idxType;
100507:   pIndex->pSchema = db->aDb[iDb].pSchema;
100508:   pIndex->nKeyCol = pList->nExpr;
100509:   if( pPIWhere ){
100510:     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
100511:     pIndex->pPartIdxWhere = pPIWhere;
100512:     pPIWhere = 0;
100513:   }
100514:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100515: 
100516:   /* Check to see if we should honor DESC requests on index columns
100517:   */
100518:   if( pDb->pSchema->file_format>=4 ){
100519:     sortOrderMask = -1;   /* Honor DESC */
100520:   }else{
100521:     sortOrderMask = 0;    /* Ignore DESC */
100522:   }
100523: 
100524:   /* Analyze the list of expressions that form the terms of the index and
100525:   ** report any errors.  In the common case where the expression is exactly
100526:   ** a table column, store that column in aiColumn[].  For general expressions,
100527:   ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
100528:   **
100529:   ** TODO: Issue a warning if two or more columns of the index are identical.
100530:   ** TODO: Issue a warning if the table primary key is used as part of the
100531:   ** index key.
100532:   */
100533:   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
100534:     Expr *pCExpr;                  /* The i-th index expression */
100535:     int requestedSortOrder;        /* ASC or DESC on the i-th expression */
100536:     const char *zColl;             /* Collation sequence name */
100537: 
100538:     sqlite3StringToId(pListItem->pExpr);
100539:     sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
100540:     if( pParse->nErr ) goto exit_create_index;
100541:     pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
100542:     if( pCExpr->op!=TK_COLUMN ){
100543:       if( pTab==pParse->pNewTable ){
100544:         sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
100545:                                 "UNIQUE constraints");
100546:         goto exit_create_index;
100547:       }
100548:       if( pIndex->aColExpr==0 ){
100549:         ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
100550:         pIndex->aColExpr = pCopy;
100551:         if( !db->mallocFailed ){
100552:           assert( pCopy!=0 );
100553:           pListItem = &pCopy->a[i];
100554:         }
100555:       }
100556:       j = XN_EXPR;
100557:       pIndex->aiColumn[i] = XN_EXPR;
100558:       pIndex->uniqNotNull = 0;
100559:     }else{
100560:       j = pCExpr->iColumn;
100561:       assert( j<=0x7fff );
100562:       if( j<0 ){
100563:         j = pTab->iPKey;
100564:       }else if( pTab->aCol[j].notNull==0 ){
100565:         pIndex->uniqNotNull = 0;
100566:       }
100567:       pIndex->aiColumn[i] = (i16)j;
100568:     }
100569:     zColl = 0;
100570:     if( pListItem->pExpr->op==TK_COLLATE ){
100571:       int nColl;
100572:       zColl = pListItem->pExpr->u.zToken;
100573:       nColl = sqlite3Strlen30(zColl) + 1;
100574:       assert( nExtra>=nColl );
100575:       memcpy(zExtra, zColl, nColl);
100576:       zColl = zExtra;
100577:       zExtra += nColl;
100578:       nExtra -= nColl;
100579:     }else if( j>=0 ){
100580:       zColl = pTab->aCol[j].zColl;
100581:     }
100582:     if( !zColl ) zColl = sqlite3StrBINARY;
100583:     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
100584:       goto exit_create_index;
100585:     }
100586:     pIndex->azColl[i] = zColl;
100587:     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
100588:     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
100589:   }
100590: 
100591:   /* Append the table key to the end of the index.  For WITHOUT ROWID
100592:   ** tables (when pPk!=0) this will be the declared PRIMARY KEY.  For
100593:   ** normal tables (when pPk==0) this will be the rowid.
100594:   */
100595:   if( pPk ){
100596:     for(j=0; j<pPk->nKeyCol; j++){
100597:       int x = pPk->aiColumn[j];
100598:       assert( x>=0 );
100599:       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
100600:         pIndex->nColumn--; 
100601:       }else{
100602:         pIndex->aiColumn[i] = x;
100603:         pIndex->azColl[i] = pPk->azColl[j];
100604:         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
100605:         i++;
100606:       }
100607:     }
100608:     assert( i==pIndex->nColumn );
100609:   }else{
100610:     pIndex->aiColumn[i] = XN_ROWID;
100611:     pIndex->azColl[i] = sqlite3StrBINARY;
100612:   }
100613:   sqlite3DefaultRowEst(pIndex);
100614:   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
100615: 
100616:   /* If this index contains every column of its table, then mark
100617:   ** it as a covering index */
100618:   assert( HasRowid(pTab) 
100619:       || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
100620:   if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
100621:     pIndex->isCovering = 1;
100622:     for(j=0; j<pTab->nCol; j++){
100623:       if( j==pTab->iPKey ) continue;
100624:       if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
100625:       pIndex->isCovering = 0;
100626:       break;
100627:     }
100628:   }
100629: 
100630:   if( pTab==pParse->pNewTable ){
100631:     /* This routine has been called to create an automatic index as a
100632:     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
100633:     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
100634:     ** i.e. one of:
100635:     **
100636:     ** CREATE TABLE t(x PRIMARY KEY, y);
100637:     ** CREATE TABLE t(x, y, UNIQUE(x, y));
100638:     **
100639:     ** Either way, check to see if the table already has such an index. If
100640:     ** so, don't bother creating this one. This only applies to
100641:     ** automatically created indices. Users can do as they wish with
100642:     ** explicit indices.
100643:     **
100644:     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
100645:     ** (and thus suppressing the second one) even if they have different
100646:     ** sort orders.
100647:     **
100648:     ** If there are different collating sequences or if the columns of
100649:     ** the constraint occur in different orders, then the constraints are
100650:     ** considered distinct and both result in separate indices.
100651:     */
100652:     Index *pIdx;
100653:     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100654:       int k;
100655:       assert( IsUniqueIndex(pIdx) );
100656:       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
100657:       assert( IsUniqueIndex(pIndex) );
100658: 
100659:       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
100660:       for(k=0; k<pIdx->nKeyCol; k++){
100661:         const char *z1;
100662:         const char *z2;
100663:         assert( pIdx->aiColumn[k]>=0 );
100664:         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
100665:         z1 = pIdx->azColl[k];
100666:         z2 = pIndex->azColl[k];
100667:         if( sqlite3StrICmp(z1, z2) ) break;
100668:       }
100669:       if( k==pIdx->nKeyCol ){
100670:         if( pIdx->onError!=pIndex->onError ){
100671:           /* This constraint creates the same index as a previous
100672:           ** constraint specified somewhere in the CREATE TABLE statement.
100673:           ** However the ON CONFLICT clauses are different. If both this 
100674:           ** constraint and the previous equivalent constraint have explicit
100675:           ** ON CONFLICT clauses this is an error. Otherwise, use the
100676:           ** explicitly specified behavior for the index.
100677:           */
100678:           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
100679:             sqlite3ErrorMsg(pParse, 
100680:                 "conflicting ON CONFLICT clauses specified", 0);
100681:           }
100682:           if( pIdx->onError==OE_Default ){
100683:             pIdx->onError = pIndex->onError;
100684:           }
100685:         }
100686:         if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
100687:         goto exit_create_index;
100688:       }
100689:     }
100690:   }
100691: 
100692:   /* Link the new Index structure to its table and to the other
100693:   ** in-memory database structures. 
100694:   */
100695:   assert( pParse->nErr==0 );
100696:   if( db->init.busy ){
100697:     Index *p;
100698:     assert( !IN_DECLARE_VTAB );
100699:     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
100700:     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
100701:                           pIndex->zName, pIndex);
100702:     if( p ){
100703:       assert( p==pIndex );  /* Malloc must have failed */
100704:       sqlite3OomFault(db);
100705:       goto exit_create_index;
100706:     }
100707:     db->flags |= SQLITE_InternChanges;
100708:     if( pTblName!=0 ){
100709:       pIndex->tnum = db->init.newTnum;
100710:     }
100711:   }
100712: 
100713:   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
100714:   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
100715:   ** emit code to allocate the index rootpage on disk and make an entry for
100716:   ** the index in the sqlite_master table and populate the index with
100717:   ** content.  But, do not do this if we are simply reading the sqlite_master
100718:   ** table to parse the schema, or if this index is the PRIMARY KEY index
100719:   ** of a WITHOUT ROWID table.
100720:   **
100721:   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
100722:   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
100723:   ** has just been created, it contains no data and the index initialization
100724:   ** step can be skipped.
100725:   */
100726:   else if( HasRowid(pTab) || pTblName!=0 ){
100727:     Vdbe *v;
100728:     char *zStmt;
100729:     int iMem = ++pParse->nMem;
100730: 
100731:     v = sqlite3GetVdbe(pParse);
100732:     if( v==0 ) goto exit_create_index;
100733: 
100734:     sqlite3BeginWriteOperation(pParse, 1, iDb);
100735: 
100736:     /* Create the rootpage for the index using CreateIndex. But before
100737:     ** doing so, code a Noop instruction and store its address in 
100738:     ** Index.tnum. This is required in case this index is actually a 
100739:     ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In 
100740:     ** that case the convertToWithoutRowidTable() routine will replace
100741:     ** the Noop with a Goto to jump over the VDBE code generated below. */
100742:     pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
100743:     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
100744: 
100745:     /* Gather the complete text of the CREATE INDEX statement into
100746:     ** the zStmt variable
100747:     */
100748:     if( pStart ){
100749:       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
100750:       if( pName->z[n-1]==';' ) n--;
100751:       /* A named index with an explicit CREATE INDEX statement */
100752:       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
100753:         onError==OE_None ? "" : " UNIQUE", n, pName->z);
100754:     }else{
100755:       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
100756:       /* zStmt = sqlite3MPrintf(""); */
100757:       zStmt = 0;
100758:     }
100759: 
100760:     /* Add an entry in sqlite_master for this index
100761:     */
100762:     sqlite3NestedParse(pParse, 
100763:         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
100764:         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
100765:         pIndex->zName,
100766:         pTab->zName,
100767:         iMem,
100768:         zStmt
100769:     );
100770:     sqlite3DbFree(db, zStmt);
100771: 
100772:     /* Fill the index with data and reparse the schema. Code an OP_Expire
100773:     ** to invalidate all pre-compiled statements.
100774:     */
100775:     if( pTblName ){
100776:       sqlite3RefillIndex(pParse, pIndex, iMem);
100777:       sqlite3ChangeCookie(pParse, iDb);
100778:       sqlite3VdbeAddParseSchemaOp(v, iDb,
100779:          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
100780:       sqlite3VdbeAddOp0(v, OP_Expire);
100781:     }
100782: 
100783:     sqlite3VdbeJumpHere(v, pIndex->tnum);
100784:   }
100785: 
100786:   /* When adding an index to the list of indices for a table, make
100787:   ** sure all indices labeled OE_Replace come after all those labeled
100788:   ** OE_Ignore.  This is necessary for the correct constraint check
100789:   ** processing (in sqlite3GenerateConstraintChecks()) as part of
100790:   ** UPDATE and INSERT statements.  
100791:   */
100792:   if( db->init.busy || pTblName==0 ){
100793:     if( onError!=OE_Replace || pTab->pIndex==0
100794:          || pTab->pIndex->onError==OE_Replace){
100795:       pIndex->pNext = pTab->pIndex;
100796:       pTab->pIndex = pIndex;
100797:     }else{
100798:       Index *pOther = pTab->pIndex;
100799:       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
100800:         pOther = pOther->pNext;
100801:       }
100802:       pIndex->pNext = pOther->pNext;
100803:       pOther->pNext = pIndex;
100804:     }
100805:     pIndex = 0;
100806:   }
100807: 
100808:   /* Clean up before exiting */
100809: exit_create_index:
100810:   if( pIndex ) freeIndex(db, pIndex);
100811:   sqlite3ExprDelete(db, pPIWhere);
100812:   sqlite3ExprListDelete(db, pList);
100813:   sqlite3SrcListDelete(db, pTblName);
100814:   sqlite3DbFree(db, zName);
100815: }
100816: 
100817: /*
100818: ** Fill the Index.aiRowEst[] array with default information - information
100819: ** to be used when we have not run the ANALYZE command.
100820: **
100821: ** aiRowEst[0] is supposed to contain the number of elements in the index.
100822: ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
100823: ** number of rows in the table that match any particular value of the
100824: ** first column of the index.  aiRowEst[2] is an estimate of the number
100825: ** of rows that match any particular combination of the first 2 columns
100826: ** of the index.  And so forth.  It must always be the case that
100827: *
100828: **           aiRowEst[N]<=aiRowEst[N-1]
100829: **           aiRowEst[N]>=1
100830: **
100831: ** Apart from that, we have little to go on besides intuition as to
100832: ** how aiRowEst[] should be initialized.  The numbers generated here
100833: ** are based on typical values found in actual indices.
100834: */
100835: SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
100836:   /*                10,  9,  8,  7,  6 */
100837:   LogEst aVal[] = { 33, 32, 30, 28, 26 };
100838:   LogEst *a = pIdx->aiRowLogEst;
100839:   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
100840:   int i;
100841: 
100842:   /* Set the first entry (number of rows in the index) to the estimated 
100843:   ** number of rows in the table, or half the number of rows in the table
100844:   ** for a partial index.   But do not let the estimate drop below 10. */
100845:   a[0] = pIdx->pTable->nRowLogEst;
100846:   if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10;  assert( 10==sqlite3LogEst(2) );
100847:   if( a[0]<33 ) a[0] = 33;                  assert( 33==sqlite3LogEst(10) );
100848: 
100849:   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
100850:   ** 6 and each subsequent value (if any) is 5.  */
100851:   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
100852:   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
100853:     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
100854:   }
100855: 
100856:   assert( 0==sqlite3LogEst(1) );
100857:   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
100858: }
100859: 
100860: /*
100861: ** This routine will drop an existing named index.  This routine
100862: ** implements the DROP INDEX statement.
100863: */
100864: SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
100865:   Index *pIndex;
100866:   Vdbe *v;
100867:   sqlite3 *db = pParse->db;
100868:   int iDb;
100869: 
100870:   assert( pParse->nErr==0 );   /* Never called with prior errors */
100871:   if( db->mallocFailed ){
100872:     goto exit_drop_index;
100873:   }
100874:   assert( pName->nSrc==1 );
100875:   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100876:     goto exit_drop_index;
100877:   }
100878:   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
100879:   if( pIndex==0 ){
100880:     if( !ifExists ){
100881:       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
100882:     }else{
100883:       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
100884:     }
100885:     pParse->checkSchema = 1;
100886:     goto exit_drop_index;
100887:   }
100888:   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
100889:     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
100890:       "or PRIMARY KEY constraint cannot be dropped", 0);
100891:     goto exit_drop_index;
100892:   }
100893:   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
100894: #ifndef SQLITE_OMIT_AUTHORIZATION
100895:   {
100896:     int code = SQLITE_DROP_INDEX;
100897:     Table *pTab = pIndex->pTable;
100898:     const char *zDb = db->aDb[iDb].zName;
100899:     const char *zTab = SCHEMA_TABLE(iDb);
100900:     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
100901:       goto exit_drop_index;
100902:     }
100903:     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
100904:     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
100905:       goto exit_drop_index;
100906:     }
100907:   }
100908: #endif
100909: 
100910:   /* Generate code to remove the index and from the master table */
100911:   v = sqlite3GetVdbe(pParse);
100912:   if( v ){
100913:     sqlite3BeginWriteOperation(pParse, 1, iDb);
100914:     sqlite3NestedParse(pParse,
100915:        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
100916:        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
100917:     );
100918:     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
100919:     sqlite3ChangeCookie(pParse, iDb);
100920:     destroyRootPage(pParse, pIndex->tnum, iDb);
100921:     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
100922:   }
100923: 
100924: exit_drop_index:
100925:   sqlite3SrcListDelete(db, pName);
100926: }
100927: 
100928: /*
100929: ** pArray is a pointer to an array of objects. Each object in the
100930: ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
100931: ** to extend the array so that there is space for a new object at the end.
100932: **
100933: ** When this function is called, *pnEntry contains the current size of
100934: ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
100935: ** in total).
100936: **
100937: ** If the realloc() is successful (i.e. if no OOM condition occurs), the
100938: ** space allocated for the new object is zeroed, *pnEntry updated to
100939: ** reflect the new size of the array and a pointer to the new allocation
100940: ** returned. *pIdx is set to the index of the new array entry in this case.
100941: **
100942: ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
100943: ** unchanged and a copy of pArray returned.
100944: */
100945: SQLITE_PRIVATE void *sqlite3ArrayAllocate(
100946:   sqlite3 *db,      /* Connection to notify of malloc failures */
100947:   void *pArray,     /* Array of objects.  Might be reallocated */
100948:   int szEntry,      /* Size of each object in the array */
100949:   int *pnEntry,     /* Number of objects currently in use */
100950:   int *pIdx         /* Write the index of a new slot here */
100951: ){
100952:   char *z;
100953:   int n = *pnEntry;
100954:   if( (n & (n-1))==0 ){
100955:     int sz = (n==0) ? 1 : 2*n;
100956:     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
100957:     if( pNew==0 ){
100958:       *pIdx = -1;
100959:       return pArray;
100960:     }
100961:     pArray = pNew;
100962:   }
100963:   z = (char*)pArray;
100964:   memset(&z[n * szEntry], 0, szEntry);
100965:   *pIdx = n;
100966:   ++*pnEntry;
100967:   return pArray;
100968: }
100969: 
100970: /*
100971: ** Append a new element to the given IdList.  Create a new IdList if
100972: ** need be.
100973: **
100974: ** A new IdList is returned, or NULL if malloc() fails.
100975: */
100976: SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
100977:   int i;
100978:   if( pList==0 ){
100979:     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
100980:     if( pList==0 ) return 0;
100981:   }
100982:   pList->a = sqlite3ArrayAllocate(
100983:       db,
100984:       pList->a,
100985:       sizeof(pList->a[0]),
100986:       &pList->nId,
100987:       &i
100988:   );
100989:   if( i<0 ){
100990:     sqlite3IdListDelete(db, pList);
100991:     return 0;
100992:   }
100993:   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
100994:   return pList;
100995: }
100996: 
100997: /*
100998: ** Delete an IdList.
100999: */
101000: SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
101001:   int i;
101002:   if( pList==0 ) return;
101003:   for(i=0; i<pList->nId; i++){
101004:     sqlite3DbFree(db, pList->a[i].zName);
101005:   }
101006:   sqlite3DbFree(db, pList->a);
101007:   sqlite3DbFree(db, pList);
101008: }
101009: 
101010: /*
101011: ** Return the index in pList of the identifier named zId.  Return -1
101012: ** if not found.
101013: */
101014: SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
101015:   int i;
101016:   if( pList==0 ) return -1;
101017:   for(i=0; i<pList->nId; i++){
101018:     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
101019:   }
101020:   return -1;
101021: }
101022: 
101023: /*
101024: ** Expand the space allocated for the given SrcList object by
101025: ** creating nExtra new slots beginning at iStart.  iStart is zero based.
101026: ** New slots are zeroed.
101027: **
101028: ** For example, suppose a SrcList initially contains two entries: A,B.
101029: ** To append 3 new entries onto the end, do this:
101030: **
101031: **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
101032: **
101033: ** After the call above it would contain:  A, B, nil, nil, nil.
101034: ** If the iStart argument had been 1 instead of 2, then the result
101035: ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
101036: ** the iStart value would be 0.  The result then would
101037: ** be: nil, nil, nil, A, B.
101038: **
101039: ** If a memory allocation fails the SrcList is unchanged.  The
101040: ** db->mallocFailed flag will be set to true.
101041: */
101042: SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
101043:   sqlite3 *db,       /* Database connection to notify of OOM errors */
101044:   SrcList *pSrc,     /* The SrcList to be enlarged */
101045:   int nExtra,        /* Number of new slots to add to pSrc->a[] */
101046:   int iStart         /* Index in pSrc->a[] of first new slot */
101047: ){
101048:   int i;
101049: 
101050:   /* Sanity checking on calling parameters */
101051:   assert( iStart>=0 );
101052:   assert( nExtra>=1 );
101053:   assert( pSrc!=0 );
101054:   assert( iStart<=pSrc->nSrc );
101055: 
101056:   /* Allocate additional space if needed */
101057:   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
101058:     SrcList *pNew;
101059:     int nAlloc = pSrc->nSrc+nExtra;
101060:     int nGot;
101061:     pNew = sqlite3DbRealloc(db, pSrc,
101062:                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
101063:     if( pNew==0 ){
101064:       assert( db->mallocFailed );
101065:       return pSrc;
101066:     }
101067:     pSrc = pNew;
101068:     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
101069:     pSrc->nAlloc = nGot;
101070:   }
101071: 
101072:   /* Move existing slots that come after the newly inserted slots
101073:   ** out of the way */
101074:   for(i=pSrc->nSrc-1; i>=iStart; i--){
101075:     pSrc->a[i+nExtra] = pSrc->a[i];
101076:   }
101077:   pSrc->nSrc += nExtra;
101078: 
101079:   /* Zero the newly allocated slots */
101080:   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
101081:   for(i=iStart; i<iStart+nExtra; i++){
101082:     pSrc->a[i].iCursor = -1;
101083:   }
101084: 
101085:   /* Return a pointer to the enlarged SrcList */
101086:   return pSrc;
101087: }
101088: 
101089: 
101090: /*
101091: ** Append a new table name to the given SrcList.  Create a new SrcList if
101092: ** need be.  A new entry is created in the SrcList even if pTable is NULL.
101093: **
101094: ** A SrcList is returned, or NULL if there is an OOM error.  The returned
101095: ** SrcList might be the same as the SrcList that was input or it might be
101096: ** a new one.  If an OOM error does occurs, then the prior value of pList
101097: ** that is input to this routine is automatically freed.
101098: **
101099: ** If pDatabase is not null, it means that the table has an optional
101100: ** database name prefix.  Like this:  "database.table".  The pDatabase
101101: ** points to the table name and the pTable points to the database name.
101102: ** The SrcList.a[].zName field is filled with the table name which might
101103: ** come from pTable (if pDatabase is NULL) or from pDatabase.  
101104: ** SrcList.a[].zDatabase is filled with the database name from pTable,
101105: ** or with NULL if no database is specified.
101106: **
101107: ** In other words, if call like this:
101108: **
101109: **         sqlite3SrcListAppend(D,A,B,0);
101110: **
101111: ** Then B is a table name and the database name is unspecified.  If called
101112: ** like this:
101113: **
101114: **         sqlite3SrcListAppend(D,A,B,C);
101115: **
101116: ** Then C is the table name and B is the database name.  If C is defined
101117: ** then so is B.  In other words, we never have a case where:
101118: **
101119: **         sqlite3SrcListAppend(D,A,0,C);
101120: **
101121: ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
101122: ** before being added to the SrcList.
101123: */
101124: SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
101125:   sqlite3 *db,        /* Connection to notify of malloc failures */
101126:   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
101127:   Token *pTable,      /* Table to append */
101128:   Token *pDatabase    /* Database of the table */
101129: ){
101130:   struct SrcList_item *pItem;
101131:   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
101132:   assert( db!=0 );
101133:   if( pList==0 ){
101134:     pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
101135:     if( pList==0 ) return 0;
101136:     pList->nAlloc = 1;
101137:     pList->nSrc = 0;
101138:   }
101139:   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
101140:   if( db->mallocFailed ){
101141:     sqlite3SrcListDelete(db, pList);
101142:     return 0;
101143:   }
101144:   pItem = &pList->a[pList->nSrc-1];
101145:   if( pDatabase && pDatabase->z==0 ){
101146:     pDatabase = 0;
101147:   }
101148:   if( pDatabase ){
101149:     Token *pTemp = pDatabase;
101150:     pDatabase = pTable;
101151:     pTable = pTemp;
101152:   }
101153:   pItem->zName = sqlite3NameFromToken(db, pTable);
101154:   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
101155:   return pList;
101156: }
101157: 
101158: /*
101159: ** Assign VdbeCursor index numbers to all tables in a SrcList
101160: */
101161: SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
101162:   int i;
101163:   struct SrcList_item *pItem;
101164:   assert(pList || pParse->db->mallocFailed );
101165:   if( pList ){
101166:     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
101167:       if( pItem->iCursor>=0 ) break;
101168:       pItem->iCursor = pParse->nTab++;
101169:       if( pItem->pSelect ){
101170:         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
101171:       }
101172:     }
101173:   }
101174: }
101175: 
101176: /*
101177: ** Delete an entire SrcList including all its substructure.
101178: */
101179: SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
101180:   int i;
101181:   struct SrcList_item *pItem;
101182:   if( pList==0 ) return;
101183:   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
101184:     sqlite3DbFree(db, pItem->zDatabase);
101185:     sqlite3DbFree(db, pItem->zName);
101186:     sqlite3DbFree(db, pItem->zAlias);
101187:     if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
101188:     if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
101189:     sqlite3DeleteTable(db, pItem->pTab);
101190:     sqlite3SelectDelete(db, pItem->pSelect);
101191:     sqlite3ExprDelete(db, pItem->pOn);
101192:     sqlite3IdListDelete(db, pItem->pUsing);
101193:   }
101194:   sqlite3DbFree(db, pList);
101195: }
101196: 
101197: /*
101198: ** This routine is called by the parser to add a new term to the
101199: ** end of a growing FROM clause.  The "p" parameter is the part of
101200: ** the FROM clause that has already been constructed.  "p" is NULL
101201: ** if this is the first term of the FROM clause.  pTable and pDatabase
101202: ** are the name of the table and database named in the FROM clause term.
101203: ** pDatabase is NULL if the database name qualifier is missing - the
101204: ** usual case.  If the term has an alias, then pAlias points to the
101205: ** alias token.  If the term is a subquery, then pSubquery is the
101206: ** SELECT statement that the subquery encodes.  The pTable and
101207: ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
101208: ** parameters are the content of the ON and USING clauses.
101209: **
101210: ** Return a new SrcList which encodes is the FROM with the new
101211: ** term added.
101212: */
101213: SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
101214:   Parse *pParse,          /* Parsing context */
101215:   SrcList *p,             /* The left part of the FROM clause already seen */
101216:   Token *pTable,          /* Name of the table to add to the FROM clause */
101217:   Token *pDatabase,       /* Name of the database containing pTable */
101218:   Token *pAlias,          /* The right-hand side of the AS subexpression */
101219:   Select *pSubquery,      /* A subquery used in place of a table name */
101220:   Expr *pOn,              /* The ON clause of a join */
101221:   IdList *pUsing          /* The USING clause of a join */
101222: ){
101223:   struct SrcList_item *pItem;
101224:   sqlite3 *db = pParse->db;
101225:   if( !p && (pOn || pUsing) ){
101226:     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
101227:       (pOn ? "ON" : "USING")
101228:     );
101229:     goto append_from_error;
101230:   }
101231:   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
101232:   if( p==0 || NEVER(p->nSrc==0) ){
101233:     goto append_from_error;
101234:   }
101235:   pItem = &p->a[p->nSrc-1];
101236:   assert( pAlias!=0 );
101237:   if( pAlias->n ){
101238:     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
101239:   }
101240:   pItem->pSelect = pSubquery;
101241:   pItem->pOn = pOn;
101242:   pItem->pUsing = pUsing;
101243:   return p;
101244: 
101245:  append_from_error:
101246:   assert( p==0 );
101247:   sqlite3ExprDelete(db, pOn);
101248:   sqlite3IdListDelete(db, pUsing);
101249:   sqlite3SelectDelete(db, pSubquery);
101250:   return 0;
101251: }
101252: 
101253: /*
101254: ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
101255: ** element of the source-list passed as the second argument.
101256: */
101257: SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
101258:   assert( pIndexedBy!=0 );
101259:   if( p && ALWAYS(p->nSrc>0) ){
101260:     struct SrcList_item *pItem = &p->a[p->nSrc-1];
101261:     assert( pItem->fg.notIndexed==0 );
101262:     assert( pItem->fg.isIndexedBy==0 );
101263:     assert( pItem->fg.isTabFunc==0 );
101264:     if( pIndexedBy->n==1 && !pIndexedBy->z ){
101265:       /* A "NOT INDEXED" clause was supplied. See parse.y 
101266:       ** construct "indexed_opt" for details. */
101267:       pItem->fg.notIndexed = 1;
101268:     }else{
101269:       pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
101270:       pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
101271:     }
101272:   }
101273: }
101274: 
101275: /*
101276: ** Add the list of function arguments to the SrcList entry for a
101277: ** table-valued-function.
101278: */
101279: SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
101280:   if( p ){
101281:     struct SrcList_item *pItem = &p->a[p->nSrc-1];
101282:     assert( pItem->fg.notIndexed==0 );
101283:     assert( pItem->fg.isIndexedBy==0 );
101284:     assert( pItem->fg.isTabFunc==0 );
101285:     pItem->u1.pFuncArg = pList;
101286:     pItem->fg.isTabFunc = 1;
101287:   }else{
101288:     sqlite3ExprListDelete(pParse->db, pList);
101289:   }
101290: }
101291: 
101292: /*
101293: ** When building up a FROM clause in the parser, the join operator
101294: ** is initially attached to the left operand.  But the code generator
101295: ** expects the join operator to be on the right operand.  This routine
101296: ** Shifts all join operators from left to right for an entire FROM
101297: ** clause.
101298: **
101299: ** Example: Suppose the join is like this:
101300: **
101301: **           A natural cross join B
101302: **
101303: ** The operator is "natural cross join".  The A and B operands are stored
101304: ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
101305: ** operator with A.  This routine shifts that operator over to B.
101306: */
101307: SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
101308:   if( p ){
101309:     int i;
101310:     for(i=p->nSrc-1; i>0; i--){
101311:       p->a[i].fg.jointype = p->a[i-1].fg.jointype;
101312:     }
101313:     p->a[0].fg.jointype = 0;
101314:   }
101315: }
101316: 
101317: /*
101318: ** Generate VDBE code for a BEGIN statement.
101319: */
101320: SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
101321:   sqlite3 *db;
101322:   Vdbe *v;
101323:   int i;
101324: 
101325:   assert( pParse!=0 );
101326:   db = pParse->db;
101327:   assert( db!=0 );
101328:   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
101329:     return;
101330:   }
101331:   v = sqlite3GetVdbe(pParse);
101332:   if( !v ) return;
101333:   if( type!=TK_DEFERRED ){
101334:     for(i=0; i<db->nDb; i++){
101335:       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
101336:       sqlite3VdbeUsesBtree(v, i);
101337:     }
101338:   }
101339:   sqlite3VdbeAddOp0(v, OP_AutoCommit);
101340: }
101341: 
101342: /*
101343: ** Generate VDBE code for a COMMIT statement.
101344: */
101345: SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
101346:   Vdbe *v;
101347: 
101348:   assert( pParse!=0 );
101349:   assert( pParse->db!=0 );
101350:   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
101351:     return;
101352:   }
101353:   v = sqlite3GetVdbe(pParse);
101354:   if( v ){
101355:     sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
101356:   }
101357: }
101358: 
101359: /*
101360: ** Generate VDBE code for a ROLLBACK statement.
101361: */
101362: SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
101363:   Vdbe *v;
101364: 
101365:   assert( pParse!=0 );
101366:   assert( pParse->db!=0 );
101367:   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
101368:     return;
101369:   }
101370:   v = sqlite3GetVdbe(pParse);
101371:   if( v ){
101372:     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
101373:   }
101374: }
101375: 
101376: /*
101377: ** This function is called by the parser when it parses a command to create,
101378: ** release or rollback an SQL savepoint. 
101379: */
101380: SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
101381:   char *zName = sqlite3NameFromToken(pParse->db, pName);
101382:   if( zName ){
101383:     Vdbe *v = sqlite3GetVdbe(pParse);
101384: #ifndef SQLITE_OMIT_AUTHORIZATION
101385:     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
101386:     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
101387: #endif
101388:     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
101389:       sqlite3DbFree(pParse->db, zName);
101390:       return;
101391:     }
101392:     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
101393:   }
101394: }
101395: 
101396: /*
101397: ** Make sure the TEMP database is open and available for use.  Return
101398: ** the number of errors.  Leave any error messages in the pParse structure.
101399: */
101400: SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
101401:   sqlite3 *db = pParse->db;
101402:   if( db->aDb[1].pBt==0 && !pParse->explain ){
101403:     int rc;
101404:     Btree *pBt;
101405:     static const int flags = 
101406:           SQLITE_OPEN_READWRITE |
101407:           SQLITE_OPEN_CREATE |
101408:           SQLITE_OPEN_EXCLUSIVE |
101409:           SQLITE_OPEN_DELETEONCLOSE |
101410:           SQLITE_OPEN_TEMP_DB;
101411: 
101412:     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
101413:     if( rc!=SQLITE_OK ){
101414:       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
101415:         "file for storing temporary tables");
101416:       pParse->rc = rc;
101417:       return 1;
101418:     }
101419:     db->aDb[1].pBt = pBt;
101420:     assert( db->aDb[1].pSchema );
101421:     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
101422:       sqlite3OomFault(db);
101423:       return 1;
101424:     }
101425:   }
101426:   return 0;
101427: }
101428: 
101429: /*
101430: ** Record the fact that the schema cookie will need to be verified
101431: ** for database iDb.  The code to actually verify the schema cookie
101432: ** will occur at the end of the top-level VDBE and will be generated
101433: ** later, by sqlite3FinishCoding().
101434: */
101435: SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
101436:   Parse *pToplevel = sqlite3ParseToplevel(pParse);
101437:   sqlite3 *db = pToplevel->db;
101438: 
101439:   assert( iDb>=0 && iDb<db->nDb );
101440:   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
101441:   assert( iDb<SQLITE_MAX_ATTACHED+2 );
101442:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101443:   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
101444:     DbMaskSet(pToplevel->cookieMask, iDb);
101445:     pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
101446:     if( !OMIT_TEMPDB && iDb==1 ){
101447:       sqlite3OpenTempDatabase(pToplevel);
101448:     }
101449:   }
101450: }
101451: 
101452: /*
101453: ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
101454: ** attached database. Otherwise, invoke it for the database named zDb only.
101455: */
101456: SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
101457:   sqlite3 *db = pParse->db;
101458:   int i;
101459:   for(i=0; i<db->nDb; i++){
101460:     Db *pDb = &db->aDb[i];
101461:     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
101462:       sqlite3CodeVerifySchema(pParse, i);
101463:     }
101464:   }
101465: }
101466: 
101467: /*
101468: ** Generate VDBE code that prepares for doing an operation that
101469: ** might change the database.
101470: **
101471: ** This routine starts a new transaction if we are not already within
101472: ** a transaction.  If we are already within a transaction, then a checkpoint
101473: ** is set if the setStatement parameter is true.  A checkpoint should
101474: ** be set for operations that might fail (due to a constraint) part of
101475: ** the way through and which will need to undo some writes without having to
101476: ** rollback the whole transaction.  For operations where all constraints
101477: ** can be checked before any changes are made to the database, it is never
101478: ** necessary to undo a write and the checkpoint should not be set.
101479: */
101480: SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
101481:   Parse *pToplevel = sqlite3ParseToplevel(pParse);
101482:   sqlite3CodeVerifySchema(pParse, iDb);
101483:   DbMaskSet(pToplevel->writeMask, iDb);
101484:   pToplevel->isMultiWrite |= setStatement;
101485: }
101486: 
101487: /*
101488: ** Indicate that the statement currently under construction might write
101489: ** more than one entry (example: deleting one row then inserting another,
101490: ** inserting multiple rows in a table, or inserting a row and index entries.)
101491: ** If an abort occurs after some of these writes have completed, then it will
101492: ** be necessary to undo the completed writes.
101493: */
101494: SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
101495:   Parse *pToplevel = sqlite3ParseToplevel(pParse);
101496:   pToplevel->isMultiWrite = 1;
101497: }
101498: 
101499: /* 
101500: ** The code generator calls this routine if is discovers that it is
101501: ** possible to abort a statement prior to completion.  In order to 
101502: ** perform this abort without corrupting the database, we need to make
101503: ** sure that the statement is protected by a statement transaction.
101504: **
101505: ** Technically, we only need to set the mayAbort flag if the
101506: ** isMultiWrite flag was previously set.  There is a time dependency
101507: ** such that the abort must occur after the multiwrite.  This makes
101508: ** some statements involving the REPLACE conflict resolution algorithm
101509: ** go a little faster.  But taking advantage of this time dependency
101510: ** makes it more difficult to prove that the code is correct (in 
101511: ** particular, it prevents us from writing an effective
101512: ** implementation of sqlite3AssertMayAbort()) and so we have chosen
101513: ** to take the safe route and skip the optimization.
101514: */
101515: SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
101516:   Parse *pToplevel = sqlite3ParseToplevel(pParse);
101517:   pToplevel->mayAbort = 1;
101518: }
101519: 
101520: /*
101521: ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
101522: ** error. The onError parameter determines which (if any) of the statement
101523: ** and/or current transaction is rolled back.
101524: */
101525: SQLITE_PRIVATE void sqlite3HaltConstraint(
101526:   Parse *pParse,    /* Parsing context */
101527:   int errCode,      /* extended error code */
101528:   int onError,      /* Constraint type */
101529:   char *p4,         /* Error message */
101530:   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
101531:   u8 p5Errmsg       /* P5_ErrMsg type */
101532: ){
101533:   Vdbe *v = sqlite3GetVdbe(pParse);
101534:   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
101535:   if( onError==OE_Abort ){
101536:     sqlite3MayAbort(pParse);
101537:   }
101538:   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
101539:   sqlite3VdbeChangeP5(v, p5Errmsg);
101540: }
101541: 
101542: /*
101543: ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
101544: */
101545: SQLITE_PRIVATE void sqlite3UniqueConstraint(
101546:   Parse *pParse,    /* Parsing context */
101547:   int onError,      /* Constraint type */
101548:   Index *pIdx       /* The index that triggers the constraint */
101549: ){
101550:   char *zErr;
101551:   int j;
101552:   StrAccum errMsg;
101553:   Table *pTab = pIdx->pTable;
101554: 
101555:   sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
101556:   if( pIdx->aColExpr ){
101557:     sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
101558:   }else{
101559:     for(j=0; j<pIdx->nKeyCol; j++){
101560:       char *zCol;
101561:       assert( pIdx->aiColumn[j]>=0 );
101562:       zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
101563:       if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
101564:       sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
101565:     }
101566:   }
101567:   zErr = sqlite3StrAccumFinish(&errMsg);
101568:   sqlite3HaltConstraint(pParse, 
101569:     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
101570:                             : SQLITE_CONSTRAINT_UNIQUE,
101571:     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
101572: }
101573: 
101574: 
101575: /*
101576: ** Code an OP_Halt due to non-unique rowid.
101577: */
101578: SQLITE_PRIVATE void sqlite3RowidConstraint(
101579:   Parse *pParse,    /* Parsing context */
101580:   int onError,      /* Conflict resolution algorithm */
101581:   Table *pTab       /* The table with the non-unique rowid */ 
101582: ){
101583:   char *zMsg;
101584:   int rc;
101585:   if( pTab->iPKey>=0 ){
101586:     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
101587:                           pTab->aCol[pTab->iPKey].zName);
101588:     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
101589:   }else{
101590:     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
101591:     rc = SQLITE_CONSTRAINT_ROWID;
101592:   }
101593:   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
101594:                         P5_ConstraintUnique);
101595: }
101596: 
101597: /*
101598: ** Check to see if pIndex uses the collating sequence pColl.  Return
101599: ** true if it does and false if it does not.
101600: */
101601: #ifndef SQLITE_OMIT_REINDEX
101602: static int collationMatch(const char *zColl, Index *pIndex){
101603:   int i;
101604:   assert( zColl!=0 );
101605:   for(i=0; i<pIndex->nColumn; i++){
101606:     const char *z = pIndex->azColl[i];
101607:     assert( z!=0 || pIndex->aiColumn[i]<0 );
101608:     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
101609:       return 1;
101610:     }
101611:   }
101612:   return 0;
101613: }
101614: #endif
101615: 
101616: /*
101617: ** Recompute all indices of pTab that use the collating sequence pColl.
101618: ** If pColl==0 then recompute all indices of pTab.
101619: */
101620: #ifndef SQLITE_OMIT_REINDEX
101621: static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
101622:   Index *pIndex;              /* An index associated with pTab */
101623: 
101624:   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
101625:     if( zColl==0 || collationMatch(zColl, pIndex) ){
101626:       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
101627:       sqlite3BeginWriteOperation(pParse, 0, iDb);
101628:       sqlite3RefillIndex(pParse, pIndex, -1);
101629:     }
101630:   }
101631: }
101632: #endif
101633: 
101634: /*
101635: ** Recompute all indices of all tables in all databases where the
101636: ** indices use the collating sequence pColl.  If pColl==0 then recompute
101637: ** all indices everywhere.
101638: */
101639: #ifndef SQLITE_OMIT_REINDEX
101640: static void reindexDatabases(Parse *pParse, char const *zColl){
101641:   Db *pDb;                    /* A single database */
101642:   int iDb;                    /* The database index number */
101643:   sqlite3 *db = pParse->db;   /* The database connection */
101644:   HashElem *k;                /* For looping over tables in pDb */
101645:   Table *pTab;                /* A table in the database */
101646: 
101647:   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
101648:   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
101649:     assert( pDb!=0 );
101650:     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
101651:       pTab = (Table*)sqliteHashData(k);
101652:       reindexTable(pParse, pTab, zColl);
101653:     }
101654:   }
101655: }
101656: #endif
101657: 
101658: /*
101659: ** Generate code for the REINDEX command.
101660: **
101661: **        REINDEX                            -- 1
101662: **        REINDEX  <collation>               -- 2
101663: **        REINDEX  ?<database>.?<tablename>  -- 3
101664: **        REINDEX  ?<database>.?<indexname>  -- 4
101665: **
101666: ** Form 1 causes all indices in all attached databases to be rebuilt.
101667: ** Form 2 rebuilds all indices in all databases that use the named
101668: ** collating function.  Forms 3 and 4 rebuild the named index or all
101669: ** indices associated with the named table.
101670: */
101671: #ifndef SQLITE_OMIT_REINDEX
101672: SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
101673:   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
101674:   char *z;                    /* Name of a table or index */
101675:   const char *zDb;            /* Name of the database */
101676:   Table *pTab;                /* A table in the database */
101677:   Index *pIndex;              /* An index associated with pTab */
101678:   int iDb;                    /* The database index number */
101679:   sqlite3 *db = pParse->db;   /* The database connection */
101680:   Token *pObjName;            /* Name of the table or index to be reindexed */
101681: 
101682:   /* Read the database schema. If an error occurs, leave an error message
101683:   ** and code in pParse and return NULL. */
101684:   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101685:     return;
101686:   }
101687: 
101688:   if( pName1==0 ){
101689:     reindexDatabases(pParse, 0);
101690:     return;
101691:   }else if( NEVER(pName2==0) || pName2->z==0 ){
101692:     char *zColl;
101693:     assert( pName1->z );
101694:     zColl = sqlite3NameFromToken(pParse->db, pName1);
101695:     if( !zColl ) return;
101696:     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
101697:     if( pColl ){
101698:       reindexDatabases(pParse, zColl);
101699:       sqlite3DbFree(db, zColl);
101700:       return;
101701:     }
101702:     sqlite3DbFree(db, zColl);
101703:   }
101704:   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
101705:   if( iDb<0 ) return;
101706:   z = sqlite3NameFromToken(db, pObjName);
101707:   if( z==0 ) return;
101708:   zDb = db->aDb[iDb].zName;
101709:   pTab = sqlite3FindTable(db, z, zDb);
101710:   if( pTab ){
101711:     reindexTable(pParse, pTab, 0);
101712:     sqlite3DbFree(db, z);
101713:     return;
101714:   }
101715:   pIndex = sqlite3FindIndex(db, z, zDb);
101716:   sqlite3DbFree(db, z);
101717:   if( pIndex ){
101718:     sqlite3BeginWriteOperation(pParse, 0, iDb);
101719:     sqlite3RefillIndex(pParse, pIndex, -1);
101720:     return;
101721:   }
101722:   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
101723: }
101724: #endif
101725: 
101726: /*
101727: ** Return a KeyInfo structure that is appropriate for the given Index.
101728: **
101729: ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
101730: ** when it has finished using it.
101731: */
101732: SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
101733:   int i;
101734:   int nCol = pIdx->nColumn;
101735:   int nKey = pIdx->nKeyCol;
101736:   KeyInfo *pKey;
101737:   if( pParse->nErr ) return 0;
101738:   if( pIdx->uniqNotNull ){
101739:     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
101740:   }else{
101741:     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
101742:   }
101743:   if( pKey ){
101744:     assert( sqlite3KeyInfoIsWriteable(pKey) );
101745:     for(i=0; i<nCol; i++){
101746:       const char *zColl = pIdx->azColl[i];
101747:       pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
101748:                         sqlite3LocateCollSeq(pParse, zColl);
101749:       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
101750:     }
101751:     if( pParse->nErr ){
101752:       sqlite3KeyInfoUnref(pKey);
101753:       pKey = 0;
101754:     }
101755:   }
101756:   return pKey;
101757: }
101758: 
101759: #ifndef SQLITE_OMIT_CTE
101760: /* 
101761: ** This routine is invoked once per CTE by the parser while parsing a 
101762: ** WITH clause. 
101763: */
101764: SQLITE_PRIVATE With *sqlite3WithAdd(
101765:   Parse *pParse,          /* Parsing context */
101766:   With *pWith,            /* Existing WITH clause, or NULL */
101767:   Token *pName,           /* Name of the common-table */
101768:   ExprList *pArglist,     /* Optional column name list for the table */
101769:   Select *pQuery          /* Query used to initialize the table */
101770: ){
101771:   sqlite3 *db = pParse->db;
101772:   With *pNew;
101773:   char *zName;
101774: 
101775:   /* Check that the CTE name is unique within this WITH clause. If
101776:   ** not, store an error in the Parse structure. */
101777:   zName = sqlite3NameFromToken(pParse->db, pName);
101778:   if( zName && pWith ){
101779:     int i;
101780:     for(i=0; i<pWith->nCte; i++){
101781:       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
101782:         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
101783:       }
101784:     }
101785:   }
101786: 
101787:   if( pWith ){
101788:     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
101789:     pNew = sqlite3DbRealloc(db, pWith, nByte);
101790:   }else{
101791:     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
101792:   }
101793:   assert( (pNew!=0 && zName!=0) || db->mallocFailed );
101794: 
101795:   if( db->mallocFailed ){
101796:     sqlite3ExprListDelete(db, pArglist);
101797:     sqlite3SelectDelete(db, pQuery);
101798:     sqlite3DbFree(db, zName);
101799:     pNew = pWith;
101800:   }else{
101801:     pNew->a[pNew->nCte].pSelect = pQuery;
101802:     pNew->a[pNew->nCte].pCols = pArglist;
101803:     pNew->a[pNew->nCte].zName = zName;
101804:     pNew->a[pNew->nCte].zCteErr = 0;
101805:     pNew->nCte++;
101806:   }
101807: 
101808:   return pNew;
101809: }
101810: 
101811: /*
101812: ** Free the contents of the With object passed as the second argument.
101813: */
101814: SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
101815:   if( pWith ){
101816:     int i;
101817:     for(i=0; i<pWith->nCte; i++){
101818:       struct Cte *pCte = &pWith->a[i];
101819:       sqlite3ExprListDelete(db, pCte->pCols);
101820:       sqlite3SelectDelete(db, pCte->pSelect);
101821:       sqlite3DbFree(db, pCte->zName);
101822:     }
101823:     sqlite3DbFree(db, pWith);
101824:   }
101825: }
101826: #endif /* !defined(SQLITE_OMIT_CTE) */
101827: 
101828: /************** End of build.c ***********************************************/
101829: /************** Begin file callback.c ****************************************/
101830: /*
101831: ** 2005 May 23 
101832: **
101833: ** The author disclaims copyright to this source code.  In place of
101834: ** a legal notice, here is a blessing:
101835: **
101836: **    May you do good and not evil.
101837: **    May you find forgiveness for yourself and forgive others.
101838: **    May you share freely, never taking more than you give.
101839: **
101840: *************************************************************************
101841: **
101842: ** This file contains functions used to access the internal hash tables
101843: ** of user defined functions and collation sequences.
101844: */
101845: 
101846: /* #include "sqliteInt.h" */
101847: 
101848: /*
101849: ** Invoke the 'collation needed' callback to request a collation sequence
101850: ** in the encoding enc of name zName, length nName.
101851: */
101852: static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
101853:   assert( !db->xCollNeeded || !db->xCollNeeded16 );
101854:   if( db->xCollNeeded ){
101855:     char *zExternal = sqlite3DbStrDup(db, zName);
101856:     if( !zExternal ) return;
101857:     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
101858:     sqlite3DbFree(db, zExternal);
101859:   }
101860: #ifndef SQLITE_OMIT_UTF16
101861:   if( db->xCollNeeded16 ){
101862:     char const *zExternal;
101863:     sqlite3_value *pTmp = sqlite3ValueNew(db);
101864:     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
101865:     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
101866:     if( zExternal ){
101867:       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
101868:     }
101869:     sqlite3ValueFree(pTmp);
101870:   }
101871: #endif
101872: }
101873: 
101874: /*
101875: ** This routine is called if the collation factory fails to deliver a
101876: ** collation function in the best encoding but there may be other versions
101877: ** of this collation function (for other text encodings) available. Use one
101878: ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
101879: ** possible.
101880: */
101881: static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
101882:   CollSeq *pColl2;
101883:   char *z = pColl->zName;
101884:   int i;
101885:   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
101886:   for(i=0; i<3; i++){
101887:     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
101888:     if( pColl2->xCmp!=0 ){
101889:       memcpy(pColl, pColl2, sizeof(CollSeq));
101890:       pColl->xDel = 0;         /* Do not copy the destructor */
101891:       return SQLITE_OK;
101892:     }
101893:   }
101894:   return SQLITE_ERROR;
101895: }
101896: 
101897: /*
101898: ** This function is responsible for invoking the collation factory callback
101899: ** or substituting a collation sequence of a different encoding when the
101900: ** requested collation sequence is not available in the desired encoding.
101901: ** 
101902: ** If it is not NULL, then pColl must point to the database native encoding 
101903: ** collation sequence with name zName, length nName.
101904: **
101905: ** The return value is either the collation sequence to be used in database
101906: ** db for collation type name zName, length nName, or NULL, if no collation
101907: ** sequence can be found.  If no collation is found, leave an error message.
101908: **
101909: ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
101910: */
101911: SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
101912:   Parse *pParse,        /* Parsing context */
101913:   u8 enc,               /* The desired encoding for the collating sequence */
101914:   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
101915:   const char *zName     /* Collating sequence name */
101916: ){
101917:   CollSeq *p;
101918:   sqlite3 *db = pParse->db;
101919: 
101920:   p = pColl;
101921:   if( !p ){
101922:     p = sqlite3FindCollSeq(db, enc, zName, 0);
101923:   }
101924:   if( !p || !p->xCmp ){
101925:     /* No collation sequence of this type for this encoding is registered.
101926:     ** Call the collation factory to see if it can supply us with one.
101927:     */
101928:     callCollNeeded(db, enc, zName);
101929:     p = sqlite3FindCollSeq(db, enc, zName, 0);
101930:   }
101931:   if( p && !p->xCmp && synthCollSeq(db, p) ){
101932:     p = 0;
101933:   }
101934:   assert( !p || p->xCmp );
101935:   if( p==0 ){
101936:     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
101937:   }
101938:   return p;
101939: }
101940: 
101941: /*
101942: ** This routine is called on a collation sequence before it is used to
101943: ** check that it is defined. An undefined collation sequence exists when
101944: ** a database is loaded that contains references to collation sequences
101945: ** that have not been defined by sqlite3_create_collation() etc.
101946: **
101947: ** If required, this routine calls the 'collation needed' callback to
101948: ** request a definition of the collating sequence. If this doesn't work, 
101949: ** an equivalent collating sequence that uses a text encoding different
101950: ** from the main database is substituted, if one is available.
101951: */
101952: SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
101953:   if( pColl ){
101954:     const char *zName = pColl->zName;
101955:     sqlite3 *db = pParse->db;
101956:     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
101957:     if( !p ){
101958:       return SQLITE_ERROR;
101959:     }
101960:     assert( p==pColl );
101961:   }
101962:   return SQLITE_OK;
101963: }
101964: 
101965: 
101966: 
101967: /*
101968: ** Locate and return an entry from the db.aCollSeq hash table. If the entry
101969: ** specified by zName and nName is not found and parameter 'create' is
101970: ** true, then create a new entry. Otherwise return NULL.
101971: **
101972: ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
101973: ** array of three CollSeq structures. The first is the collation sequence
101974: ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
101975: **
101976: ** Stored immediately after the three collation sequences is a copy of
101977: ** the collation sequence name. A pointer to this string is stored in
101978: ** each collation sequence structure.
101979: */
101980: static CollSeq *findCollSeqEntry(
101981:   sqlite3 *db,          /* Database connection */
101982:   const char *zName,    /* Name of the collating sequence */
101983:   int create            /* Create a new entry if true */
101984: ){
101985:   CollSeq *pColl;
101986:   pColl = sqlite3HashFind(&db->aCollSeq, zName);
101987: 
101988:   if( 0==pColl && create ){
101989:     int nName = sqlite3Strlen30(zName);
101990:     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
101991:     if( pColl ){
101992:       CollSeq *pDel = 0;
101993:       pColl[0].zName = (char*)&pColl[3];
101994:       pColl[0].enc = SQLITE_UTF8;
101995:       pColl[1].zName = (char*)&pColl[3];
101996:       pColl[1].enc = SQLITE_UTF16LE;
101997:       pColl[2].zName = (char*)&pColl[3];
101998:       pColl[2].enc = SQLITE_UTF16BE;
101999:       memcpy(pColl[0].zName, zName, nName);
102000:       pColl[0].zName[nName] = 0;
102001:       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
102002: 
102003:       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
102004:       ** return the pColl pointer to be deleted (because it wasn't added
102005:       ** to the hash table).
102006:       */
102007:       assert( pDel==0 || pDel==pColl );
102008:       if( pDel!=0 ){
102009:         sqlite3OomFault(db);
102010:         sqlite3DbFree(db, pDel);
102011:         pColl = 0;
102012:       }
102013:     }
102014:   }
102015:   return pColl;
102016: }
102017: 
102018: /*
102019: ** Parameter zName points to a UTF-8 encoded string nName bytes long.
102020: ** Return the CollSeq* pointer for the collation sequence named zName
102021: ** for the encoding 'enc' from the database 'db'.
102022: **
102023: ** If the entry specified is not found and 'create' is true, then create a
102024: ** new entry.  Otherwise return NULL.
102025: **
102026: ** A separate function sqlite3LocateCollSeq() is a wrapper around
102027: ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
102028: ** if necessary and generates an error message if the collating sequence
102029: ** cannot be found.
102030: **
102031: ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
102032: */
102033: SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
102034:   sqlite3 *db,
102035:   u8 enc,
102036:   const char *zName,
102037:   int create
102038: ){
102039:   CollSeq *pColl;
102040:   if( zName ){
102041:     pColl = findCollSeqEntry(db, zName, create);
102042:   }else{
102043:     pColl = db->pDfltColl;
102044:   }
102045:   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
102046:   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
102047:   if( pColl ) pColl += enc-1;
102048:   return pColl;
102049: }
102050: 
102051: /* During the search for the best function definition, this procedure
102052: ** is called to test how well the function passed as the first argument
102053: ** matches the request for a function with nArg arguments in a system
102054: ** that uses encoding enc. The value returned indicates how well the
102055: ** request is matched. A higher value indicates a better match.
102056: **
102057: ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
102058: ** is also -1.  In other words, we are searching for a function that
102059: ** takes a variable number of arguments.
102060: **
102061: ** If nArg is -2 that means that we are searching for any function 
102062: ** regardless of the number of arguments it uses, so return a positive
102063: ** match score for any
102064: **
102065: ** The returned value is always between 0 and 6, as follows:
102066: **
102067: ** 0: Not a match.
102068: ** 1: UTF8/16 conversion required and function takes any number of arguments.
102069: ** 2: UTF16 byte order change required and function takes any number of args.
102070: ** 3: encoding matches and function takes any number of arguments
102071: ** 4: UTF8/16 conversion required - argument count matches exactly
102072: ** 5: UTF16 byte order conversion required - argument count matches exactly
102073: ** 6: Perfect match:  encoding and argument count match exactly.
102074: **
102075: ** If nArg==(-2) then any function with a non-null xSFunc is
102076: ** a perfect match and any function with xSFunc NULL is
102077: ** a non-match.
102078: */
102079: #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
102080: static int matchQuality(
102081:   FuncDef *p,     /* The function we are evaluating for match quality */
102082:   int nArg,       /* Desired number of arguments.  (-1)==any */
102083:   u8 enc          /* Desired text encoding */
102084: ){
102085:   int match;
102086: 
102087:   /* nArg of -2 is a special case */
102088:   if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
102089: 
102090:   /* Wrong number of arguments means "no match" */
102091:   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
102092: 
102093:   /* Give a better score to a function with a specific number of arguments
102094:   ** than to function that accepts any number of arguments. */
102095:   if( p->nArg==nArg ){
102096:     match = 4;
102097:   }else{
102098:     match = 1;
102099:   }
102100: 
102101:   /* Bonus points if the text encoding matches */
102102:   if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
102103:     match += 2;  /* Exact encoding match */
102104:   }else if( (enc & p->funcFlags & 2)!=0 ){
102105:     match += 1;  /* Both are UTF16, but with different byte orders */
102106:   }
102107: 
102108:   return match;
102109: }
102110: 
102111: /*
102112: ** Search a FuncDefHash for a function with the given name.  Return
102113: ** a pointer to the matching FuncDef if found, or 0 if there is no match.
102114: */
102115: static FuncDef *functionSearch(
102116:   int h,               /* Hash of the name */
102117:   const char *zFunc    /* Name of function */
102118: ){
102119:   FuncDef *p;
102120:   for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
102121:     if( sqlite3StrICmp(p->zName, zFunc)==0 ){
102122:       return p;
102123:     }
102124:   }
102125:   return 0;
102126: }
102127: 
102128: /*
102129: ** Insert a new FuncDef into a FuncDefHash hash table.
102130: */
102131: SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
102132:   FuncDef *aDef,      /* List of global functions to be inserted */
102133:   int nDef            /* Length of the apDef[] list */
102134: ){
102135:   int i;
102136:   for(i=0; i<nDef; i++){
102137:     FuncDef *pOther;
102138:     const char *zName = aDef[i].zName;
102139:     int nName = sqlite3Strlen30(zName);
102140:     int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
102141:     pOther = functionSearch(h, zName);
102142:     if( pOther ){
102143:       assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
102144:       aDef[i].pNext = pOther->pNext;
102145:       pOther->pNext = &aDef[i];
102146:     }else{
102147:       aDef[i].pNext = 0;
102148:       aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
102149:       sqlite3BuiltinFunctions.a[h] = &aDef[i];
102150:     }
102151:   }
102152: }
102153:   
102154:   
102155: 
102156: /*
102157: ** Locate a user function given a name, a number of arguments and a flag
102158: ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
102159: ** pointer to the FuncDef structure that defines that function, or return
102160: ** NULL if the function does not exist.
102161: **
102162: ** If the createFlag argument is true, then a new (blank) FuncDef
102163: ** structure is created and liked into the "db" structure if a
102164: ** no matching function previously existed.
102165: **
102166: ** If nArg is -2, then the first valid function found is returned.  A
102167: ** function is valid if xSFunc is non-zero.  The nArg==(-2)
102168: ** case is used to see if zName is a valid function name for some number
102169: ** of arguments.  If nArg is -2, then createFlag must be 0.
102170: **
102171: ** If createFlag is false, then a function with the required name and
102172: ** number of arguments may be returned even if the eTextRep flag does not
102173: ** match that requested.
102174: */
102175: SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
102176:   sqlite3 *db,       /* An open database */
102177:   const char *zName, /* Name of the function.  zero-terminated */
102178:   int nArg,          /* Number of arguments.  -1 means any number */
102179:   u8 enc,            /* Preferred text encoding */
102180:   u8 createFlag      /* Create new entry if true and does not otherwise exist */
102181: ){
102182:   FuncDef *p;         /* Iterator variable */
102183:   FuncDef *pBest = 0; /* Best match found so far */
102184:   int bestScore = 0;  /* Score of best match */
102185:   int h;              /* Hash value */
102186:   int nName;          /* Length of the name */
102187: 
102188:   assert( nArg>=(-2) );
102189:   assert( nArg>=(-1) || createFlag==0 );
102190:   nName = sqlite3Strlen30(zName);
102191: 
102192:   /* First search for a match amongst the application-defined functions.
102193:   */
102194:   p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
102195:   while( p ){
102196:     int score = matchQuality(p, nArg, enc);
102197:     if( score>bestScore ){
102198:       pBest = p;
102199:       bestScore = score;
102200:     }
102201:     p = p->pNext;
102202:   }
102203: 
102204:   /* If no match is found, search the built-in functions.
102205:   **
102206:   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
102207:   ** functions even if a prior app-defined function was found.  And give
102208:   ** priority to built-in functions.
102209:   **
102210:   ** Except, if createFlag is true, that means that we are trying to
102211:   ** install a new function.  Whatever FuncDef structure is returned it will
102212:   ** have fields overwritten with new information appropriate for the
102213:   ** new function.  But the FuncDefs for built-in functions are read-only.
102214:   ** So we must not search for built-ins when creating a new function.
102215:   */ 
102216:   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
102217:     bestScore = 0;
102218:     h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
102219:     p = functionSearch(h, zName);
102220:     while( p ){
102221:       int score = matchQuality(p, nArg, enc);
102222:       if( score>bestScore ){
102223:         pBest = p;
102224:         bestScore = score;
102225:       }
102226:       p = p->pNext;
102227:     }
102228:   }
102229: 
102230:   /* If the createFlag parameter is true and the search did not reveal an
102231:   ** exact match for the name, number of arguments and encoding, then add a
102232:   ** new entry to the hash table and return it.
102233:   */
102234:   if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
102235:       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
102236:     FuncDef *pOther;
102237:     pBest->zName = (const char*)&pBest[1];
102238:     pBest->nArg = (u16)nArg;
102239:     pBest->funcFlags = enc;
102240:     memcpy((char*)&pBest[1], zName, nName+1);
102241:     pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
102242:     if( pOther==pBest ){
102243:       sqlite3DbFree(db, pBest);
102244:       sqlite3OomFault(db);
102245:       return 0;
102246:     }else{
102247:       pBest->pNext = pOther;
102248:     }
102249:   }
102250: 
102251:   if( pBest && (pBest->xSFunc || createFlag) ){
102252:     return pBest;
102253:   }
102254:   return 0;
102255: }
102256: 
102257: /*
102258: ** Free all resources held by the schema structure. The void* argument points
102259: ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
102260: ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
102261: ** of the schema hash tables).
102262: **
102263: ** The Schema.cache_size variable is not cleared.
102264: */
102265: SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
102266:   Hash temp1;
102267:   Hash temp2;
102268:   HashElem *pElem;
102269:   Schema *pSchema = (Schema *)p;
102270: 
102271:   temp1 = pSchema->tblHash;
102272:   temp2 = pSchema->trigHash;
102273:   sqlite3HashInit(&pSchema->trigHash);
102274:   sqlite3HashClear(&pSchema->idxHash);
102275:   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
102276:     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
102277:   }
102278:   sqlite3HashClear(&temp2);
102279:   sqlite3HashInit(&pSchema->tblHash);
102280:   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
102281:     Table *pTab = sqliteHashData(pElem);
102282:     sqlite3DeleteTable(0, pTab);
102283:   }
102284:   sqlite3HashClear(&temp1);
102285:   sqlite3HashClear(&pSchema->fkeyHash);
102286:   pSchema->pSeqTab = 0;
102287:   if( pSchema->schemaFlags & DB_SchemaLoaded ){
102288:     pSchema->iGeneration++;
102289:     pSchema->schemaFlags &= ~DB_SchemaLoaded;
102290:   }
102291: }
102292: 
102293: /*
102294: ** Find and return the schema associated with a BTree.  Create
102295: ** a new one if necessary.
102296: */
102297: SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
102298:   Schema * p;
102299:   if( pBt ){
102300:     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
102301:   }else{
102302:     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
102303:   }
102304:   if( !p ){
102305:     sqlite3OomFault(db);
102306:   }else if ( 0==p->file_format ){
102307:     sqlite3HashInit(&p->tblHash);
102308:     sqlite3HashInit(&p->idxHash);
102309:     sqlite3HashInit(&p->trigHash);
102310:     sqlite3HashInit(&p->fkeyHash);
102311:     p->enc = SQLITE_UTF8;
102312:   }
102313:   return p;
102314: }
102315: 
102316: /************** End of callback.c ********************************************/
102317: /************** Begin file delete.c ******************************************/
102318: /*
102319: ** 2001 September 15
102320: **
102321: ** The author disclaims copyright to this source code.  In place of
102322: ** a legal notice, here is a blessing:
102323: **
102324: **    May you do good and not evil.
102325: **    May you find forgiveness for yourself and forgive others.
102326: **    May you share freely, never taking more than you give.
102327: **
102328: *************************************************************************
102329: ** This file contains C code routines that are called by the parser
102330: ** in order to generate code for DELETE FROM statements.
102331: */
102332: /* #include "sqliteInt.h" */
102333: 
102334: /*
102335: ** While a SrcList can in general represent multiple tables and subqueries
102336: ** (as in the FROM clause of a SELECT statement) in this case it contains
102337: ** the name of a single table, as one might find in an INSERT, DELETE,
102338: ** or UPDATE statement.  Look up that table in the symbol table and
102339: ** return a pointer.  Set an error message and return NULL if the table 
102340: ** name is not found or if any other error occurs.
102341: **
102342: ** The following fields are initialized appropriate in pSrc:
102343: **
102344: **    pSrc->a[0].pTab       Pointer to the Table object
102345: **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
102346: **
102347: */
102348: SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
102349:   struct SrcList_item *pItem = pSrc->a;
102350:   Table *pTab;
102351:   assert( pItem && pSrc->nSrc==1 );
102352:   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
102353:   sqlite3DeleteTable(pParse->db, pItem->pTab);
102354:   pItem->pTab = pTab;
102355:   if( pTab ){
102356:     pTab->nRef++;
102357:   }
102358:   if( sqlite3IndexedByLookup(pParse, pItem) ){
102359:     pTab = 0;
102360:   }
102361:   return pTab;
102362: }
102363: 
102364: /*
102365: ** Check to make sure the given table is writable.  If it is not
102366: ** writable, generate an error message and return 1.  If it is
102367: ** writable return 0;
102368: */
102369: SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
102370:   /* A table is not writable under the following circumstances:
102371:   **
102372:   **   1) It is a virtual table and no implementation of the xUpdate method
102373:   **      has been provided, or
102374:   **   2) It is a system table (i.e. sqlite_master), this call is not
102375:   **      part of a nested parse and writable_schema pragma has not 
102376:   **      been specified.
102377:   **
102378:   ** In either case leave an error message in pParse and return non-zero.
102379:   */
102380:   if( ( IsVirtual(pTab) 
102381:      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
102382:    || ( (pTab->tabFlags & TF_Readonly)!=0
102383:      && (pParse->db->flags & SQLITE_WriteSchema)==0
102384:      && pParse->nested==0 )
102385:   ){
102386:     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
102387:     return 1;
102388:   }
102389: 
102390: #ifndef SQLITE_OMIT_VIEW
102391:   if( !viewOk && pTab->pSelect ){
102392:     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
102393:     return 1;
102394:   }
102395: #endif
102396:   return 0;
102397: }
102398: 
102399: 
102400: #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102401: /*
102402: ** Evaluate a view and store its result in an ephemeral table.  The
102403: ** pWhere argument is an optional WHERE clause that restricts the
102404: ** set of rows in the view that are to be added to the ephemeral table.
102405: */
102406: SQLITE_PRIVATE void sqlite3MaterializeView(
102407:   Parse *pParse,       /* Parsing context */
102408:   Table *pView,        /* View definition */
102409:   Expr *pWhere,        /* Optional WHERE clause to be added */
102410:   int iCur             /* Cursor number for ephemeral table */
102411: ){
102412:   SelectDest dest;
102413:   Select *pSel;
102414:   SrcList *pFrom;
102415:   sqlite3 *db = pParse->db;
102416:   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
102417:   pWhere = sqlite3ExprDup(db, pWhere, 0);
102418:   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
102419:   if( pFrom ){
102420:     assert( pFrom->nSrc==1 );
102421:     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
102422:     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
102423:     assert( pFrom->a[0].pOn==0 );
102424:     assert( pFrom->a[0].pUsing==0 );
102425:   }
102426:   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 
102427:                           SF_IncludeHidden, 0, 0);
102428:   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
102429:   sqlite3Select(pParse, pSel, &dest);
102430:   sqlite3SelectDelete(db, pSel);
102431: }
102432: #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
102433: 
102434: #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
102435: /*
102436: ** Generate an expression tree to implement the WHERE, ORDER BY,
102437: ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
102438: **
102439: **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
102440: **                            \__________________________/
102441: **                               pLimitWhere (pInClause)
102442: */
102443: SQLITE_PRIVATE Expr *sqlite3LimitWhere(
102444:   Parse *pParse,               /* The parser context */
102445:   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
102446:   Expr *pWhere,                /* The WHERE clause.  May be null */
102447:   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
102448:   Expr *pLimit,                /* The LIMIT clause.  May be null */
102449:   Expr *pOffset,               /* The OFFSET clause.  May be null */
102450:   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
102451: ){
102452:   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
102453:   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
102454:   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
102455:   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
102456:   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
102457:   Select *pSelect = NULL;      /* Complete SELECT tree */
102458: 
102459:   /* Check that there isn't an ORDER BY without a LIMIT clause.
102460:   */
102461:   if( pOrderBy && (pLimit == 0) ) {
102462:     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
102463:     goto limit_where_cleanup;
102464:   }
102465: 
102466:   /* We only need to generate a select expression if there
102467:   ** is a limit/offset term to enforce.
102468:   */
102469:   if( pLimit == 0 ) {
102470:     /* if pLimit is null, pOffset will always be null as well. */
102471:     assert( pOffset == 0 );
102472:     return pWhere;
102473:   }
102474: 
102475:   /* Generate a select expression tree to enforce the limit/offset 
102476:   ** term for the DELETE or UPDATE statement.  For example:
102477:   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
102478:   ** becomes:
102479:   **   DELETE FROM table_a WHERE rowid IN ( 
102480:   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
102481:   **   );
102482:   */
102483: 
102484:   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
102485:   if( pSelectRowid == 0 ) goto limit_where_cleanup;
102486:   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
102487:   if( pEList == 0 ) goto limit_where_cleanup;
102488: 
102489:   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
102490:   ** and the SELECT subtree. */
102491:   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
102492:   if( pSelectSrc == 0 ) {
102493:     sqlite3ExprListDelete(pParse->db, pEList);
102494:     goto limit_where_cleanup;
102495:   }
102496: 
102497:   /* generate the SELECT expression tree. */
102498:   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
102499:                              pOrderBy,0,pLimit,pOffset);
102500:   if( pSelect == 0 ) return 0;
102501: 
102502:   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
102503:   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
102504:   pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
102505:   sqlite3PExprAddSelect(pParse, pInClause, pSelect);
102506:   return pInClause;
102507: 
102508: limit_where_cleanup:
102509:   sqlite3ExprDelete(pParse->db, pWhere);
102510:   sqlite3ExprListDelete(pParse->db, pOrderBy);
102511:   sqlite3ExprDelete(pParse->db, pLimit);
102512:   sqlite3ExprDelete(pParse->db, pOffset);
102513:   return 0;
102514: }
102515: #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
102516:        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
102517: 
102518: /*
102519: ** Generate code for a DELETE FROM statement.
102520: **
102521: **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
102522: **                 \________/       \________________/
102523: **                  pTabList              pWhere
102524: */
102525: SQLITE_PRIVATE void sqlite3DeleteFrom(
102526:   Parse *pParse,         /* The parser context */
102527:   SrcList *pTabList,     /* The table from which we should delete things */
102528:   Expr *pWhere           /* The WHERE clause.  May be null */
102529: ){
102530:   Vdbe *v;               /* The virtual database engine */
102531:   Table *pTab;           /* The table from which records will be deleted */
102532:   const char *zDb;       /* Name of database holding pTab */
102533:   int i;                 /* Loop counter */
102534:   WhereInfo *pWInfo;     /* Information about the WHERE clause */
102535:   Index *pIdx;           /* For looping over indices of the table */
102536:   int iTabCur;           /* Cursor number for the table */
102537:   int iDataCur = 0;      /* VDBE cursor for the canonical data source */
102538:   int iIdxCur = 0;       /* Cursor number of the first index */
102539:   int nIdx;              /* Number of indices */
102540:   sqlite3 *db;           /* Main database structure */
102541:   AuthContext sContext;  /* Authorization context */
102542:   NameContext sNC;       /* Name context to resolve expressions in */
102543:   int iDb;               /* Database number */
102544:   int memCnt = -1;       /* Memory cell used for change counting */
102545:   int rcauth;            /* Value returned by authorization callback */
102546:   int eOnePass;          /* ONEPASS_OFF or _SINGLE or _MULTI */
102547:   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
102548:   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
102549:   Index *pPk;            /* The PRIMARY KEY index on the table */
102550:   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
102551:   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
102552:   int iKey;              /* Memory cell holding key of row to be deleted */
102553:   i16 nKey;              /* Number of memory cells in the row key */
102554:   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
102555:   int iRowSet = 0;       /* Register for rowset of rows to delete */
102556:   int addrBypass = 0;    /* Address of jump over the delete logic */
102557:   int addrLoop = 0;      /* Top of the delete loop */
102558:   int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
102559:   int bComplex;          /* True if there are triggers or FKs or
102560:                          ** subqueries in the WHERE clause */
102561:  
102562: #ifndef SQLITE_OMIT_TRIGGER
102563:   int isView;                  /* True if attempting to delete from a view */
102564:   Trigger *pTrigger;           /* List of table triggers, if required */
102565: #endif
102566: 
102567:   memset(&sContext, 0, sizeof(sContext));
102568:   db = pParse->db;
102569:   if( pParse->nErr || db->mallocFailed ){
102570:     goto delete_from_cleanup;
102571:   }
102572:   assert( pTabList->nSrc==1 );
102573: 
102574:   /* Locate the table which we want to delete.  This table has to be
102575:   ** put in an SrcList structure because some of the subroutines we
102576:   ** will be calling are designed to work with multiple tables and expect
102577:   ** an SrcList* parameter instead of just a Table* parameter.
102578:   */
102579:   pTab = sqlite3SrcListLookup(pParse, pTabList);
102580:   if( pTab==0 )  goto delete_from_cleanup;
102581: 
102582:   /* Figure out if we have any triggers and if the table being
102583:   ** deleted from is a view
102584:   */
102585: #ifndef SQLITE_OMIT_TRIGGER
102586:   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
102587:   isView = pTab->pSelect!=0;
102588:   bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
102589: #else
102590: # define pTrigger 0
102591: # define isView 0
102592: #endif
102593: #ifdef SQLITE_OMIT_VIEW
102594: # undef isView
102595: # define isView 0
102596: #endif
102597: 
102598:   /* If pTab is really a view, make sure it has been initialized.
102599:   */
102600:   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102601:     goto delete_from_cleanup;
102602:   }
102603: 
102604:   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
102605:     goto delete_from_cleanup;
102606:   }
102607:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
102608:   assert( iDb<db->nDb );
102609:   zDb = db->aDb[iDb].zName;
102610:   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
102611:   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
102612:   if( rcauth==SQLITE_DENY ){
102613:     goto delete_from_cleanup;
102614:   }
102615:   assert(!isView || pTrigger);
102616: 
102617:   /* Assign cursor numbers to the table and all its indices.
102618:   */
102619:   assert( pTabList->nSrc==1 );
102620:   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
102621:   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
102622:     pParse->nTab++;
102623:   }
102624: 
102625:   /* Start the view context
102626:   */
102627:   if( isView ){
102628:     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
102629:   }
102630: 
102631:   /* Begin generating code.
102632:   */
102633:   v = sqlite3GetVdbe(pParse);
102634:   if( v==0 ){
102635:     goto delete_from_cleanup;
102636:   }
102637:   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102638:   sqlite3BeginWriteOperation(pParse, 1, iDb);
102639: 
102640:   /* If we are trying to delete from a view, realize that view into
102641:   ** an ephemeral table.
102642:   */
102643: #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102644:   if( isView ){
102645:     sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
102646:     iDataCur = iIdxCur = iTabCur;
102647:   }
102648: #endif
102649: 
102650:   /* Resolve the column names in the WHERE clause.
102651:   */
102652:   memset(&sNC, 0, sizeof(sNC));
102653:   sNC.pParse = pParse;
102654:   sNC.pSrcList = pTabList;
102655:   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102656:     goto delete_from_cleanup;
102657:   }
102658: 
102659:   /* Initialize the counter of the number of rows deleted, if
102660:   ** we are counting rows.
102661:   */
102662:   if( db->flags & SQLITE_CountRows ){
102663:     memCnt = ++pParse->nMem;
102664:     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
102665:   }
102666: 
102667: #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
102668:   /* Special case: A DELETE without a WHERE clause deletes everything.
102669:   ** It is easier just to erase the whole table. Prior to version 3.6.5,
102670:   ** this optimization caused the row change count (the value returned by 
102671:   ** API function sqlite3_count_changes) to be set incorrectly.  */
102672:   if( rcauth==SQLITE_OK
102673:    && pWhere==0
102674:    && !bComplex
102675:    && !IsVirtual(pTab)
102676: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
102677:    && db->xPreUpdateCallback==0
102678: #endif
102679:   ){
102680:     assert( !isView );
102681:     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
102682:     if( HasRowid(pTab) ){
102683:       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
102684:                         pTab->zName, P4_STATIC);
102685:     }
102686:     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102687:       assert( pIdx->pSchema==pTab->pSchema );
102688:       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
102689:     }
102690:   }else
102691: #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
102692:   {
102693:     u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
102694:     if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
102695:     wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
102696:     if( HasRowid(pTab) ){
102697:       /* For a rowid table, initialize the RowSet to an empty set */
102698:       pPk = 0;
102699:       nPk = 1;
102700:       iRowSet = ++pParse->nMem;
102701:       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
102702:     }else{
102703:       /* For a WITHOUT ROWID table, create an ephemeral table used to
102704:       ** hold all primary keys for rows to be deleted. */
102705:       pPk = sqlite3PrimaryKeyIndex(pTab);
102706:       assert( pPk!=0 );
102707:       nPk = pPk->nKeyCol;
102708:       iPk = pParse->nMem+1;
102709:       pParse->nMem += nPk;
102710:       iEphCur = pParse->nTab++;
102711:       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
102712:       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
102713:     }
102714:   
102715:     /* Construct a query to find the rowid or primary key for every row
102716:     ** to be deleted, based on the WHERE clause. Set variable eOnePass
102717:     ** to indicate the strategy used to implement this delete:
102718:     **
102719:     **  ONEPASS_OFF:    Two-pass approach - use a FIFO for rowids/PK values.
102720:     **  ONEPASS_SINGLE: One-pass approach - at most one row deleted.
102721:     **  ONEPASS_MULTI:  One-pass approach - any number of rows may be deleted.
102722:     */
102723:     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
102724:     if( pWInfo==0 ) goto delete_from_cleanup;
102725:     eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
102726:     assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
102727:     assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
102728:   
102729:     /* Keep track of the number of rows to be deleted */
102730:     if( db->flags & SQLITE_CountRows ){
102731:       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
102732:     }
102733:   
102734:     /* Extract the rowid or primary key for the current row */
102735:     if( pPk ){
102736:       for(i=0; i<nPk; i++){
102737:         assert( pPk->aiColumn[i]>=0 );
102738:         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
102739:                                         pPk->aiColumn[i], iPk+i);
102740:       }
102741:       iKey = iPk;
102742:     }else{
102743:       iKey = pParse->nMem + 1;
102744:       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
102745:       if( iKey>pParse->nMem ) pParse->nMem = iKey;
102746:     }
102747:   
102748:     if( eOnePass!=ONEPASS_OFF ){
102749:       /* For ONEPASS, no need to store the rowid/primary-key. There is only
102750:       ** one, so just keep it in its register(s) and fall through to the
102751:       ** delete code.  */
102752:       nKey = nPk; /* OP_Found will use an unpacked key */
102753:       aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
102754:       if( aToOpen==0 ){
102755:         sqlite3WhereEnd(pWInfo);
102756:         goto delete_from_cleanup;
102757:       }
102758:       memset(aToOpen, 1, nIdx+1);
102759:       aToOpen[nIdx+1] = 0;
102760:       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
102761:       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
102762:       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
102763:     }else{
102764:       if( pPk ){
102765:         /* Add the PK key for this row to the temporary table */
102766:         iKey = ++pParse->nMem;
102767:         nKey = 0;   /* Zero tells OP_Found to use a composite key */
102768:         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
102769:             sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
102770:         sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
102771:       }else{
102772:         /* Add the rowid of the row to be deleted to the RowSet */
102773:         nKey = 1;  /* OP_Seek always uses a single rowid */
102774:         sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
102775:       }
102776:     }
102777:   
102778:     /* If this DELETE cannot use the ONEPASS strategy, this is the 
102779:     ** end of the WHERE loop */
102780:     if( eOnePass!=ONEPASS_OFF ){
102781:       addrBypass = sqlite3VdbeMakeLabel(v);
102782:     }else{
102783:       sqlite3WhereEnd(pWInfo);
102784:     }
102785:   
102786:     /* Unless this is a view, open cursors for the table we are 
102787:     ** deleting from and all its indices. If this is a view, then the
102788:     ** only effect this statement has is to fire the INSTEAD OF 
102789:     ** triggers.
102790:     */
102791:     if( !isView ){
102792:       int iAddrOnce = 0;
102793:       if( eOnePass==ONEPASS_MULTI ){
102794:         iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
102795:       }
102796:       testcase( IsVirtual(pTab) );
102797:       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
102798:                                  iTabCur, aToOpen, &iDataCur, &iIdxCur);
102799:       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
102800:       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
102801:       if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
102802:     }
102803:   
102804:     /* Set up a loop over the rowids/primary-keys that were found in the
102805:     ** where-clause loop above.
102806:     */
102807:     if( eOnePass!=ONEPASS_OFF ){
102808:       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
102809:       if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
102810:         assert( pPk!=0 || pTab->pSelect!=0 );
102811:         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
102812:         VdbeCoverage(v);
102813:       }
102814:     }else if( pPk ){
102815:       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
102816:       sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
102817:       assert( nKey==0 );  /* OP_Found will use a composite key */
102818:     }else{
102819:       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
102820:       VdbeCoverage(v);
102821:       assert( nKey==1 );
102822:     }  
102823:   
102824:     /* Delete the row */
102825: #ifndef SQLITE_OMIT_VIRTUALTABLE
102826:     if( IsVirtual(pTab) ){
102827:       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102828:       sqlite3VtabMakeWritable(pParse, pTab);
102829:       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
102830:       sqlite3VdbeChangeP5(v, OE_Abort);
102831:       assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
102832:       sqlite3MayAbort(pParse);
102833:       if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
102834:         pParse->isMultiWrite = 0;
102835:       }
102836:     }else
102837: #endif
102838:     {
102839:       int count = (pParse->nested==0);    /* True to count changes */
102840:       int iIdxNoSeek = -1;
102841:       if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
102842:         iIdxNoSeek = aiCurOnePass[1];
102843:       }
102844:       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
102845:           iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
102846:     }
102847:   
102848:     /* End of the loop over all rowids/primary-keys. */
102849:     if( eOnePass!=ONEPASS_OFF ){
102850:       sqlite3VdbeResolveLabel(v, addrBypass);
102851:       sqlite3WhereEnd(pWInfo);
102852:     }else if( pPk ){
102853:       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
102854:       sqlite3VdbeJumpHere(v, addrLoop);
102855:     }else{
102856:       sqlite3VdbeGoto(v, addrLoop);
102857:       sqlite3VdbeJumpHere(v, addrLoop);
102858:     }     
102859:   
102860:     /* Close the cursors open on the table and its indexes. */
102861:     if( !isView && !IsVirtual(pTab) ){
102862:       if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
102863:       for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
102864:         sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
102865:       }
102866:     }
102867:   } /* End non-truncate path */
102868: 
102869:   /* Update the sqlite_sequence table by storing the content of the
102870:   ** maximum rowid counter values recorded while inserting into
102871:   ** autoincrement tables.
102872:   */
102873:   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102874:     sqlite3AutoincrementEnd(pParse);
102875:   }
102876: 
102877:   /* Return the number of rows that were deleted. If this routine is 
102878:   ** generating code because of a call to sqlite3NestedParse(), do not
102879:   ** invoke the callback function.
102880:   */
102881:   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
102882:     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
102883:     sqlite3VdbeSetNumCols(v, 1);
102884:     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
102885:   }
102886: 
102887: delete_from_cleanup:
102888:   sqlite3AuthContextPop(&sContext);
102889:   sqlite3SrcListDelete(db, pTabList);
102890:   sqlite3ExprDelete(db, pWhere);
102891:   sqlite3DbFree(db, aToOpen);
102892:   return;
102893: }
102894: /* Make sure "isView" and other macros defined above are undefined. Otherwise
102895: ** they may interfere with compilation of other functions in this file
102896: ** (or in another file, if this file becomes part of the amalgamation).  */
102897: #ifdef isView
102898:  #undef isView
102899: #endif
102900: #ifdef pTrigger
102901:  #undef pTrigger
102902: #endif
102903: 
102904: /*
102905: ** This routine generates VDBE code that causes a single row of a
102906: ** single table to be deleted.  Both the original table entry and
102907: ** all indices are removed.
102908: **
102909: ** Preconditions:
102910: **
102911: **   1.  iDataCur is an open cursor on the btree that is the canonical data
102912: **       store for the table.  (This will be either the table itself,
102913: **       in the case of a rowid table, or the PRIMARY KEY index in the case
102914: **       of a WITHOUT ROWID table.)
102915: **
102916: **   2.  Read/write cursors for all indices of pTab must be open as
102917: **       cursor number iIdxCur+i for the i-th index.
102918: **
102919: **   3.  The primary key for the row to be deleted must be stored in a
102920: **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
102921: **       that a search record formed from OP_MakeRecord is contained in the
102922: **       single memory location iPk.
102923: **
102924: ** eMode:
102925: **   Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
102926: **   ONEPASS_MULTI.  If eMode is not ONEPASS_OFF, then the cursor
102927: **   iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
102928: **   then this function must seek iDataCur to the entry identified by iPk
102929: **   and nPk before reading from it.
102930: **
102931: **   If eMode is ONEPASS_MULTI, then this call is being made as part
102932: **   of a ONEPASS delete that affects multiple rows. In this case, if 
102933: **   iIdxNoSeek is a valid cursor number (>=0), then its position should
102934: **   be preserved following the delete operation. Or, if iIdxNoSeek is not
102935: **   a valid cursor number, the position of iDataCur should be preserved
102936: **   instead.
102937: **
102938: ** iIdxNoSeek:
102939: **   If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
102940: **   index cursor (from within array of cursors starting at iIdxCur) that
102941: **   already points to the index entry to be deleted.
102942: */
102943: SQLITE_PRIVATE void sqlite3GenerateRowDelete(
102944:   Parse *pParse,     /* Parsing context */
102945:   Table *pTab,       /* Table containing the row to be deleted */
102946:   Trigger *pTrigger, /* List of triggers to (potentially) fire */
102947:   int iDataCur,      /* Cursor from which column data is extracted */
102948:   int iIdxCur,       /* First index cursor */
102949:   int iPk,           /* First memory cell containing the PRIMARY KEY */
102950:   i16 nPk,           /* Number of PRIMARY KEY memory cells */
102951:   u8 count,          /* If non-zero, increment the row change counter */
102952:   u8 onconf,         /* Default ON CONFLICT policy for triggers */
102953:   u8 eMode,          /* ONEPASS_OFF, _SINGLE, or _MULTI.  See above */
102954:   int iIdxNoSeek     /* Cursor number of cursor that does not need seeking */
102955: ){
102956:   Vdbe *v = pParse->pVdbe;        /* Vdbe */
102957:   int iOld = 0;                   /* First register in OLD.* array */
102958:   int iLabel;                     /* Label resolved to end of generated code */
102959:   u8 opSeek;                      /* Seek opcode */
102960: 
102961:   /* Vdbe is guaranteed to have been allocated by this stage. */
102962:   assert( v );
102963:   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
102964:                          iDataCur, iIdxCur, iPk, (int)nPk));
102965: 
102966:   /* Seek cursor iCur to the row to delete. If this row no longer exists 
102967:   ** (this can happen if a trigger program has already deleted it), do
102968:   ** not attempt to delete it or fire any DELETE triggers.  */
102969:   iLabel = sqlite3VdbeMakeLabel(v);
102970:   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
102971:   if( eMode==ONEPASS_OFF ){
102972:     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
102973:     VdbeCoverageIf(v, opSeek==OP_NotExists);
102974:     VdbeCoverageIf(v, opSeek==OP_NotFound);
102975:   }
102976:  
102977:   /* If there are any triggers to fire, allocate a range of registers to
102978:   ** use for the old.* references in the triggers.  */
102979:   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
102980:     u32 mask;                     /* Mask of OLD.* columns in use */
102981:     int iCol;                     /* Iterator used while populating OLD.* */
102982:     int addrStart;                /* Start of BEFORE trigger programs */
102983: 
102984:     /* TODO: Could use temporary registers here. Also could attempt to
102985:     ** avoid copying the contents of the rowid register.  */
102986:     mask = sqlite3TriggerColmask(
102987:         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
102988:     );
102989:     mask |= sqlite3FkOldmask(pParse, pTab);
102990:     iOld = pParse->nMem+1;
102991:     pParse->nMem += (1 + pTab->nCol);
102992: 
102993:     /* Populate the OLD.* pseudo-table register array. These values will be 
102994:     ** used by any BEFORE and AFTER triggers that exist.  */
102995:     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
102996:     for(iCol=0; iCol<pTab->nCol; iCol++){
102997:       testcase( mask!=0xffffffff && iCol==31 );
102998:       testcase( mask!=0xffffffff && iCol==32 );
102999:       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
103000:         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
103001:       }
103002:     }
103003: 
103004:     /* Invoke BEFORE DELETE trigger programs. */
103005:     addrStart = sqlite3VdbeCurrentAddr(v);
103006:     sqlite3CodeRowTrigger(pParse, pTrigger, 
103007:         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
103008:     );
103009: 
103010:     /* If any BEFORE triggers were coded, then seek the cursor to the 
103011:     ** row to be deleted again. It may be that the BEFORE triggers moved
103012:     ** the cursor or of already deleted the row that the cursor was
103013:     ** pointing to.
103014:     */
103015:     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
103016:       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
103017:       VdbeCoverageIf(v, opSeek==OP_NotExists);
103018:       VdbeCoverageIf(v, opSeek==OP_NotFound);
103019:     }
103020: 
103021:     /* Do FK processing. This call checks that any FK constraints that
103022:     ** refer to this table (i.e. constraints attached to other tables) 
103023:     ** are not violated by deleting this row.  */
103024:     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
103025:   }
103026: 
103027:   /* Delete the index and table entries. Skip this step if pTab is really
103028:   ** a view (in which case the only effect of the DELETE statement is to
103029:   ** fire the INSTEAD OF triggers).  
103030:   **
103031:   ** If variable 'count' is non-zero, then this OP_Delete instruction should
103032:   ** invoke the update-hook. The pre-update-hook, on the other hand should
103033:   ** be invoked unless table pTab is a system table. The difference is that
103034:   ** the update-hook is not invoked for rows removed by REPLACE, but the 
103035:   ** pre-update-hook is.
103036:   */ 
103037:   if( pTab->pSelect==0 ){
103038:     u8 p5 = 0;
103039:     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
103040:     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
103041:     sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
103042:     if( eMode!=ONEPASS_OFF ){
103043:       sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
103044:     }
103045:     if( iIdxNoSeek>=0 ){
103046:       sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
103047:     }
103048:     if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
103049:     sqlite3VdbeChangeP5(v, p5);
103050:   }
103051: 
103052:   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
103053:   ** handle rows (possibly in other tables) that refer via a foreign key
103054:   ** to the row just deleted. */ 
103055:   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
103056: 
103057:   /* Invoke AFTER DELETE trigger programs. */
103058:   sqlite3CodeRowTrigger(pParse, pTrigger, 
103059:       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
103060:   );
103061: 
103062:   /* Jump here if the row had already been deleted before any BEFORE
103063:   ** trigger programs were invoked. Or if a trigger program throws a 
103064:   ** RAISE(IGNORE) exception.  */
103065:   sqlite3VdbeResolveLabel(v, iLabel);
103066:   VdbeModuleComment((v, "END: GenRowDel()"));
103067: }
103068: 
103069: /*
103070: ** This routine generates VDBE code that causes the deletion of all
103071: ** index entries associated with a single row of a single table, pTab
103072: **
103073: ** Preconditions:
103074: **
103075: **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
103076: **       btree for the table pTab.  (This will be either the table itself
103077: **       for rowid tables or to the primary key index for WITHOUT ROWID
103078: **       tables.)
103079: **
103080: **   2.  Read/write cursors for all indices of pTab must be open as
103081: **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
103082: **       index is the 0-th index.)
103083: **
103084: **   3.  The "iDataCur" cursor must be already be positioned on the row
103085: **       that is to be deleted.
103086: */
103087: SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
103088:   Parse *pParse,     /* Parsing and code generating context */
103089:   Table *pTab,       /* Table containing the row to be deleted */
103090:   int iDataCur,      /* Cursor of table holding data. */
103091:   int iIdxCur,       /* First index cursor */
103092:   int *aRegIdx,      /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
103093:   int iIdxNoSeek     /* Do not delete from this cursor */
103094: ){
103095:   int i;             /* Index loop counter */
103096:   int r1 = -1;       /* Register holding an index key */
103097:   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
103098:   Index *pIdx;       /* Current index */
103099:   Index *pPrior = 0; /* Prior index */
103100:   Vdbe *v;           /* The prepared statement under construction */
103101:   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
103102: 
103103:   v = pParse->pVdbe;
103104:   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
103105:   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
103106:     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
103107:     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
103108:     if( pIdx==pPk ) continue;
103109:     if( iIdxCur+i==iIdxNoSeek ) continue;
103110:     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
103111:     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
103112:         &iPartIdxLabel, pPrior, r1);
103113:     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
103114:         pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
103115:     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
103116:     pPrior = pIdx;
103117:   }
103118: }
103119: 
103120: /*
103121: ** Generate code that will assemble an index key and stores it in register
103122: ** regOut.  The key with be for index pIdx which is an index on pTab.
103123: ** iCur is the index of a cursor open on the pTab table and pointing to
103124: ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
103125: ** iCur must be the cursor of the PRIMARY KEY index.
103126: **
103127: ** Return a register number which is the first in a block of
103128: ** registers that holds the elements of the index key.  The
103129: ** block of registers has already been deallocated by the time
103130: ** this routine returns.
103131: **
103132: ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
103133: ** to that label if pIdx is a partial index that should be skipped.
103134: ** The label should be resolved using sqlite3ResolvePartIdxLabel().
103135: ** A partial index should be skipped if its WHERE clause evaluates
103136: ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
103137: ** will be set to zero which is an empty label that is ignored by
103138: ** sqlite3ResolvePartIdxLabel().
103139: **
103140: ** The pPrior and regPrior parameters are used to implement a cache to
103141: ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
103142: ** a pointer to a different index for which an index key has just been
103143: ** computed into register regPrior.  If the current pIdx index is generating
103144: ** its key into the same sequence of registers and if pPrior and pIdx share
103145: ** a column in common, then the register corresponding to that column already
103146: ** holds the correct value and the loading of that register is skipped.
103147: ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 
103148: ** on a table with multiple indices, and especially with the ROWID or
103149: ** PRIMARY KEY columns of the index.
103150: */
103151: SQLITE_PRIVATE int sqlite3GenerateIndexKey(
103152:   Parse *pParse,       /* Parsing context */
103153:   Index *pIdx,         /* The index for which to generate a key */
103154:   int iDataCur,        /* Cursor number from which to take column data */
103155:   int regOut,          /* Put the new key into this register if not 0 */
103156:   int prefixOnly,      /* Compute only a unique prefix of the key */
103157:   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
103158:   Index *pPrior,       /* Previously generated index key */
103159:   int regPrior         /* Register holding previous generated key */
103160: ){
103161:   Vdbe *v = pParse->pVdbe;
103162:   int j;
103163:   int regBase;
103164:   int nCol;
103165: 
103166:   if( piPartIdxLabel ){
103167:     if( pIdx->pPartIdxWhere ){
103168:       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
103169:       pParse->iSelfTab = iDataCur;
103170:       sqlite3ExprCachePush(pParse);
103171:       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 
103172:                             SQLITE_JUMPIFNULL);
103173:     }else{
103174:       *piPartIdxLabel = 0;
103175:     }
103176:   }
103177:   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
103178:   regBase = sqlite3GetTempRange(pParse, nCol);
103179:   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
103180:   for(j=0; j<nCol; j++){
103181:     if( pPrior
103182:      && pPrior->aiColumn[j]==pIdx->aiColumn[j]
103183:      && pPrior->aiColumn[j]!=XN_EXPR
103184:     ){
103185:       /* This column was already computed by the previous index */
103186:       continue;
103187:     }
103188:     sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
103189:     /* If the column affinity is REAL but the number is an integer, then it
103190:     ** might be stored in the table as an integer (using a compact
103191:     ** representation) then converted to REAL by an OP_RealAffinity opcode.
103192:     ** But we are getting ready to store this value back into an index, where
103193:     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
103194:     ** opcode if it is present */
103195:     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
103196:   }
103197:   if( regOut ){
103198:     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
103199:   }
103200:   sqlite3ReleaseTempRange(pParse, regBase, nCol);
103201:   return regBase;
103202: }
103203: 
103204: /*
103205: ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
103206: ** because it was a partial index, then this routine should be called to
103207: ** resolve that label.
103208: */
103209: SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
103210:   if( iLabel ){
103211:     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
103212:     sqlite3ExprCachePop(pParse);
103213:   }
103214: }
103215: 
103216: /************** End of delete.c **********************************************/
103217: /************** Begin file func.c ********************************************/
103218: /*
103219: ** 2002 February 23
103220: **
103221: ** The author disclaims copyright to this source code.  In place of
103222: ** a legal notice, here is a blessing:
103223: **
103224: **    May you do good and not evil.
103225: **    May you find forgiveness for yourself and forgive others.
103226: **    May you share freely, never taking more than you give.
103227: **
103228: *************************************************************************
103229: ** This file contains the C-language implementations for many of the SQL
103230: ** functions of SQLite.  (Some function, and in particular the date and
103231: ** time functions, are implemented separately.)
103232: */
103233: /* #include "sqliteInt.h" */
103234: /* #include <stdlib.h> */
103235: /* #include <assert.h> */
103236: /* #include "vdbeInt.h" */
103237: 
103238: /*
103239: ** Return the collating function associated with a function.
103240: */
103241: static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
103242:   VdbeOp *pOp;
103243:   assert( context->pVdbe!=0 );
103244:   pOp = &context->pVdbe->aOp[context->iOp-1];
103245:   assert( pOp->opcode==OP_CollSeq );
103246:   assert( pOp->p4type==P4_COLLSEQ );
103247:   return pOp->p4.pColl;
103248: }
103249: 
103250: /*
103251: ** Indicate that the accumulator load should be skipped on this
103252: ** iteration of the aggregate loop.
103253: */
103254: static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
103255:   context->skipFlag = 1;
103256: }
103257: 
103258: /*
103259: ** Implementation of the non-aggregate min() and max() functions
103260: */
103261: static void minmaxFunc(
103262:   sqlite3_context *context,
103263:   int argc,
103264:   sqlite3_value **argv
103265: ){
103266:   int i;
103267:   int mask;    /* 0 for min() or 0xffffffff for max() */
103268:   int iBest;
103269:   CollSeq *pColl;
103270: 
103271:   assert( argc>1 );
103272:   mask = sqlite3_user_data(context)==0 ? 0 : -1;
103273:   pColl = sqlite3GetFuncCollSeq(context);
103274:   assert( pColl );
103275:   assert( mask==-1 || mask==0 );
103276:   iBest = 0;
103277:   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
103278:   for(i=1; i<argc; i++){
103279:     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
103280:     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
103281:       testcase( mask==0 );
103282:       iBest = i;
103283:     }
103284:   }
103285:   sqlite3_result_value(context, argv[iBest]);
103286: }
103287: 
103288: /*
103289: ** Return the type of the argument.
103290: */
103291: static void typeofFunc(
103292:   sqlite3_context *context,
103293:   int NotUsed,
103294:   sqlite3_value **argv
103295: ){
103296:   const char *z = 0;
103297:   UNUSED_PARAMETER(NotUsed);
103298:   switch( sqlite3_value_type(argv[0]) ){
103299:     case SQLITE_INTEGER: z = "integer"; break;
103300:     case SQLITE_TEXT:    z = "text";    break;
103301:     case SQLITE_FLOAT:   z = "real";    break;
103302:     case SQLITE_BLOB:    z = "blob";    break;
103303:     default:             z = "null";    break;
103304:   }
103305:   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
103306: }
103307: 
103308: 
103309: /*
103310: ** Implementation of the length() function
103311: */
103312: static void lengthFunc(
103313:   sqlite3_context *context,
103314:   int argc,
103315:   sqlite3_value **argv
103316: ){
103317:   int len;
103318: 
103319:   assert( argc==1 );
103320:   UNUSED_PARAMETER(argc);
103321:   switch( sqlite3_value_type(argv[0]) ){
103322:     case SQLITE_BLOB:
103323:     case SQLITE_INTEGER:
103324:     case SQLITE_FLOAT: {
103325:       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
103326:       break;
103327:     }
103328:     case SQLITE_TEXT: {
103329:       const unsigned char *z = sqlite3_value_text(argv[0]);
103330:       if( z==0 ) return;
103331:       len = 0;
103332:       while( *z ){
103333:         len++;
103334:         SQLITE_SKIP_UTF8(z);
103335:       }
103336:       sqlite3_result_int(context, len);
103337:       break;
103338:     }
103339:     default: {
103340:       sqlite3_result_null(context);
103341:       break;
103342:     }
103343:   }
103344: }
103345: 
103346: /*
103347: ** Implementation of the abs() function.
103348: **
103349: ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
103350: ** the numeric argument X. 
103351: */
103352: static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103353:   assert( argc==1 );
103354:   UNUSED_PARAMETER(argc);
103355:   switch( sqlite3_value_type(argv[0]) ){
103356:     case SQLITE_INTEGER: {
103357:       i64 iVal = sqlite3_value_int64(argv[0]);
103358:       if( iVal<0 ){
103359:         if( iVal==SMALLEST_INT64 ){
103360:           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
103361:           ** then abs(X) throws an integer overflow error since there is no
103362:           ** equivalent positive 64-bit two complement value. */
103363:           sqlite3_result_error(context, "integer overflow", -1);
103364:           return;
103365:         }
103366:         iVal = -iVal;
103367:       } 
103368:       sqlite3_result_int64(context, iVal);
103369:       break;
103370:     }
103371:     case SQLITE_NULL: {
103372:       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
103373:       sqlite3_result_null(context);
103374:       break;
103375:     }
103376:     default: {
103377:       /* Because sqlite3_value_double() returns 0.0 if the argument is not
103378:       ** something that can be converted into a number, we have:
103379:       ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
103380:       ** that cannot be converted to a numeric value.
103381:       */
103382:       double rVal = sqlite3_value_double(argv[0]);
103383:       if( rVal<0 ) rVal = -rVal;
103384:       sqlite3_result_double(context, rVal);
103385:       break;
103386:     }
103387:   }
103388: }
103389: 
103390: /*
103391: ** Implementation of the instr() function.
103392: **
103393: ** instr(haystack,needle) finds the first occurrence of needle
103394: ** in haystack and returns the number of previous characters plus 1,
103395: ** or 0 if needle does not occur within haystack.
103396: **
103397: ** If both haystack and needle are BLOBs, then the result is one more than
103398: ** the number of bytes in haystack prior to the first occurrence of needle,
103399: ** or 0 if needle never occurs in haystack.
103400: */
103401: static void instrFunc(
103402:   sqlite3_context *context,
103403:   int argc,
103404:   sqlite3_value **argv
103405: ){
103406:   const unsigned char *zHaystack;
103407:   const unsigned char *zNeedle;
103408:   int nHaystack;
103409:   int nNeedle;
103410:   int typeHaystack, typeNeedle;
103411:   int N = 1;
103412:   int isText;
103413: 
103414:   UNUSED_PARAMETER(argc);
103415:   typeHaystack = sqlite3_value_type(argv[0]);
103416:   typeNeedle = sqlite3_value_type(argv[1]);
103417:   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
103418:   nHaystack = sqlite3_value_bytes(argv[0]);
103419:   nNeedle = sqlite3_value_bytes(argv[1]);
103420:   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
103421:     zHaystack = sqlite3_value_blob(argv[0]);
103422:     zNeedle = sqlite3_value_blob(argv[1]);
103423:     isText = 0;
103424:   }else{
103425:     zHaystack = sqlite3_value_text(argv[0]);
103426:     zNeedle = sqlite3_value_text(argv[1]);
103427:     isText = 1;
103428:   }
103429:   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
103430:     N++;
103431:     do{
103432:       nHaystack--;
103433:       zHaystack++;
103434:     }while( isText && (zHaystack[0]&0xc0)==0x80 );
103435:   }
103436:   if( nNeedle>nHaystack ) N = 0;
103437:   sqlite3_result_int(context, N);
103438: }
103439: 
103440: /*
103441: ** Implementation of the printf() function.
103442: */
103443: static void printfFunc(
103444:   sqlite3_context *context,
103445:   int argc,
103446:   sqlite3_value **argv
103447: ){
103448:   PrintfArguments x;
103449:   StrAccum str;
103450:   const char *zFormat;
103451:   int n;
103452:   sqlite3 *db = sqlite3_context_db_handle(context);
103453: 
103454:   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
103455:     x.nArg = argc-1;
103456:     x.nUsed = 0;
103457:     x.apArg = argv+1;
103458:     sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
103459:     str.printfFlags = SQLITE_PRINTF_SQLFUNC;
103460:     sqlite3XPrintf(&str, zFormat, &x);
103461:     n = str.nChar;
103462:     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
103463:                         SQLITE_DYNAMIC);
103464:   }
103465: }
103466: 
103467: /*
103468: ** Implementation of the substr() function.
103469: **
103470: ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
103471: ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
103472: ** of x.  If x is text, then we actually count UTF-8 characters.
103473: ** If x is a blob, then we count bytes.
103474: **
103475: ** If p1 is negative, then we begin abs(p1) from the end of x[].
103476: **
103477: ** If p2 is negative, return the p2 characters preceding p1.
103478: */
103479: static void substrFunc(
103480:   sqlite3_context *context,
103481:   int argc,
103482:   sqlite3_value **argv
103483: ){
103484:   const unsigned char *z;
103485:   const unsigned char *z2;
103486:   int len;
103487:   int p0type;
103488:   i64 p1, p2;
103489:   int negP2 = 0;
103490: 
103491:   assert( argc==3 || argc==2 );
103492:   if( sqlite3_value_type(argv[1])==SQLITE_NULL
103493:    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
103494:   ){
103495:     return;
103496:   }
103497:   p0type = sqlite3_value_type(argv[0]);
103498:   p1 = sqlite3_value_int(argv[1]);
103499:   if( p0type==SQLITE_BLOB ){
103500:     len = sqlite3_value_bytes(argv[0]);
103501:     z = sqlite3_value_blob(argv[0]);
103502:     if( z==0 ) return;
103503:     assert( len==sqlite3_value_bytes(argv[0]) );
103504:   }else{
103505:     z = sqlite3_value_text(argv[0]);
103506:     if( z==0 ) return;
103507:     len = 0;
103508:     if( p1<0 ){
103509:       for(z2=z; *z2; len++){
103510:         SQLITE_SKIP_UTF8(z2);
103511:       }
103512:     }
103513:   }
103514: #ifdef SQLITE_SUBSTR_COMPATIBILITY
103515:   /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
103516:   ** as substr(X,1,N) - it returns the first N characters of X.  This
103517:   ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
103518:   ** from 2009-02-02 for compatibility of applications that exploited the
103519:   ** old buggy behavior. */
103520:   if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
103521: #endif
103522:   if( argc==3 ){
103523:     p2 = sqlite3_value_int(argv[2]);
103524:     if( p2<0 ){
103525:       p2 = -p2;
103526:       negP2 = 1;
103527:     }
103528:   }else{
103529:     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
103530:   }
103531:   if( p1<0 ){
103532:     p1 += len;
103533:     if( p1<0 ){
103534:       p2 += p1;
103535:       if( p2<0 ) p2 = 0;
103536:       p1 = 0;
103537:     }
103538:   }else if( p1>0 ){
103539:     p1--;
103540:   }else if( p2>0 ){
103541:     p2--;
103542:   }
103543:   if( negP2 ){
103544:     p1 -= p2;
103545:     if( p1<0 ){
103546:       p2 += p1;
103547:       p1 = 0;
103548:     }
103549:   }
103550:   assert( p1>=0 && p2>=0 );
103551:   if( p0type!=SQLITE_BLOB ){
103552:     while( *z && p1 ){
103553:       SQLITE_SKIP_UTF8(z);
103554:       p1--;
103555:     }
103556:     for(z2=z; *z2 && p2; p2--){
103557:       SQLITE_SKIP_UTF8(z2);
103558:     }
103559:     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
103560:                           SQLITE_UTF8);
103561:   }else{
103562:     if( p1+p2>len ){
103563:       p2 = len-p1;
103564:       if( p2<0 ) p2 = 0;
103565:     }
103566:     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
103567:   }
103568: }
103569: 
103570: /*
103571: ** Implementation of the round() function
103572: */
103573: #ifndef SQLITE_OMIT_FLOATING_POINT
103574: static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103575:   int n = 0;
103576:   double r;
103577:   char *zBuf;
103578:   assert( argc==1 || argc==2 );
103579:   if( argc==2 ){
103580:     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
103581:     n = sqlite3_value_int(argv[1]);
103582:     if( n>30 ) n = 30;
103583:     if( n<0 ) n = 0;
103584:   }
103585:   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
103586:   r = sqlite3_value_double(argv[0]);
103587:   /* If Y==0 and X will fit in a 64-bit int,
103588:   ** handle the rounding directly,
103589:   ** otherwise use printf.
103590:   */
103591:   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
103592:     r = (double)((sqlite_int64)(r+0.5));
103593:   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
103594:     r = -(double)((sqlite_int64)((-r)+0.5));
103595:   }else{
103596:     zBuf = sqlite3_mprintf("%.*f",n,r);
103597:     if( zBuf==0 ){
103598:       sqlite3_result_error_nomem(context);
103599:       return;
103600:     }
103601:     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
103602:     sqlite3_free(zBuf);
103603:   }
103604:   sqlite3_result_double(context, r);
103605: }
103606: #endif
103607: 
103608: /*
103609: ** Allocate nByte bytes of space using sqlite3Malloc(). If the
103610: ** allocation fails, call sqlite3_result_error_nomem() to notify
103611: ** the database handle that malloc() has failed and return NULL.
103612: ** If nByte is larger than the maximum string or blob length, then
103613: ** raise an SQLITE_TOOBIG exception and return NULL.
103614: */
103615: static void *contextMalloc(sqlite3_context *context, i64 nByte){
103616:   char *z;
103617:   sqlite3 *db = sqlite3_context_db_handle(context);
103618:   assert( nByte>0 );
103619:   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
103620:   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
103621:   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
103622:     sqlite3_result_error_toobig(context);
103623:     z = 0;
103624:   }else{
103625:     z = sqlite3Malloc(nByte);
103626:     if( !z ){
103627:       sqlite3_result_error_nomem(context);
103628:     }
103629:   }
103630:   return z;
103631: }
103632: 
103633: /*
103634: ** Implementation of the upper() and lower() SQL functions.
103635: */
103636: static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103637:   char *z1;
103638:   const char *z2;
103639:   int i, n;
103640:   UNUSED_PARAMETER(argc);
103641:   z2 = (char*)sqlite3_value_text(argv[0]);
103642:   n = sqlite3_value_bytes(argv[0]);
103643:   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
103644:   assert( z2==(char*)sqlite3_value_text(argv[0]) );
103645:   if( z2 ){
103646:     z1 = contextMalloc(context, ((i64)n)+1);
103647:     if( z1 ){
103648:       for(i=0; i<n; i++){
103649:         z1[i] = (char)sqlite3Toupper(z2[i]);
103650:       }
103651:       sqlite3_result_text(context, z1, n, sqlite3_free);
103652:     }
103653:   }
103654: }
103655: static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103656:   char *z1;
103657:   const char *z2;
103658:   int i, n;
103659:   UNUSED_PARAMETER(argc);
103660:   z2 = (char*)sqlite3_value_text(argv[0]);
103661:   n = sqlite3_value_bytes(argv[0]);
103662:   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
103663:   assert( z2==(char*)sqlite3_value_text(argv[0]) );
103664:   if( z2 ){
103665:     z1 = contextMalloc(context, ((i64)n)+1);
103666:     if( z1 ){
103667:       for(i=0; i<n; i++){
103668:         z1[i] = sqlite3Tolower(z2[i]);
103669:       }
103670:       sqlite3_result_text(context, z1, n, sqlite3_free);
103671:     }
103672:   }
103673: }
103674: 
103675: /*
103676: ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
103677: ** as VDBE code so that unused argument values do not have to be computed.
103678: ** However, we still need some kind of function implementation for this
103679: ** routines in the function table.  The noopFunc macro provides this.
103680: ** noopFunc will never be called so it doesn't matter what the implementation
103681: ** is.  We might as well use the "version()" function as a substitute.
103682: */
103683: #define noopFunc versionFunc   /* Substitute function - never called */
103684: 
103685: /*
103686: ** Implementation of random().  Return a random integer.  
103687: */
103688: static void randomFunc(
103689:   sqlite3_context *context,
103690:   int NotUsed,
103691:   sqlite3_value **NotUsed2
103692: ){
103693:   sqlite_int64 r;
103694:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
103695:   sqlite3_randomness(sizeof(r), &r);
103696:   if( r<0 ){
103697:     /* We need to prevent a random number of 0x8000000000000000 
103698:     ** (or -9223372036854775808) since when you do abs() of that
103699:     ** number of you get the same value back again.  To do this
103700:     ** in a way that is testable, mask the sign bit off of negative
103701:     ** values, resulting in a positive value.  Then take the 
103702:     ** 2s complement of that positive value.  The end result can
103703:     ** therefore be no less than -9223372036854775807.
103704:     */
103705:     r = -(r & LARGEST_INT64);
103706:   }
103707:   sqlite3_result_int64(context, r);
103708: }
103709: 
103710: /*
103711: ** Implementation of randomblob(N).  Return a random blob
103712: ** that is N bytes long.
103713: */
103714: static void randomBlob(
103715:   sqlite3_context *context,
103716:   int argc,
103717:   sqlite3_value **argv
103718: ){
103719:   int n;
103720:   unsigned char *p;
103721:   assert( argc==1 );
103722:   UNUSED_PARAMETER(argc);
103723:   n = sqlite3_value_int(argv[0]);
103724:   if( n<1 ){
103725:     n = 1;
103726:   }
103727:   p = contextMalloc(context, n);
103728:   if( p ){
103729:     sqlite3_randomness(n, p);
103730:     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
103731:   }
103732: }
103733: 
103734: /*
103735: ** Implementation of the last_insert_rowid() SQL function.  The return
103736: ** value is the same as the sqlite3_last_insert_rowid() API function.
103737: */
103738: static void last_insert_rowid(
103739:   sqlite3_context *context, 
103740:   int NotUsed, 
103741:   sqlite3_value **NotUsed2
103742: ){
103743:   sqlite3 *db = sqlite3_context_db_handle(context);
103744:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
103745:   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
103746:   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
103747:   ** function. */
103748:   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
103749: }
103750: 
103751: /*
103752: ** Implementation of the changes() SQL function.
103753: **
103754: ** IMP: R-62073-11209 The changes() SQL function is a wrapper
103755: ** around the sqlite3_changes() C/C++ function and hence follows the same
103756: ** rules for counting changes.
103757: */
103758: static void changes(
103759:   sqlite3_context *context,
103760:   int NotUsed,
103761:   sqlite3_value **NotUsed2
103762: ){
103763:   sqlite3 *db = sqlite3_context_db_handle(context);
103764:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
103765:   sqlite3_result_int(context, sqlite3_changes(db));
103766: }
103767: 
103768: /*
103769: ** Implementation of the total_changes() SQL function.  The return value is
103770: ** the same as the sqlite3_total_changes() API function.
103771: */
103772: static void total_changes(
103773:   sqlite3_context *context,
103774:   int NotUsed,
103775:   sqlite3_value **NotUsed2
103776: ){
103777:   sqlite3 *db = sqlite3_context_db_handle(context);
103778:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
103779:   /* IMP: R-52756-41993 This function is a wrapper around the
103780:   ** sqlite3_total_changes() C/C++ interface. */
103781:   sqlite3_result_int(context, sqlite3_total_changes(db));
103782: }
103783: 
103784: /*
103785: ** A structure defining how to do GLOB-style comparisons.
103786: */
103787: struct compareInfo {
103788:   u8 matchAll;          /* "*" or "%" */
103789:   u8 matchOne;          /* "?" or "_" */
103790:   u8 matchSet;          /* "[" or 0 */
103791:   u8 noCase;            /* true to ignore case differences */
103792: };
103793: 
103794: /*
103795: ** For LIKE and GLOB matching on EBCDIC machines, assume that every
103796: ** character is exactly one byte in size.  Also, provde the Utf8Read()
103797: ** macro for fast reading of the next character in the common case where
103798: ** the next character is ASCII.
103799: */
103800: #if defined(SQLITE_EBCDIC)
103801: # define sqlite3Utf8Read(A)        (*((*A)++))
103802: # define Utf8Read(A)               (*(A++))
103803: #else
103804: # define Utf8Read(A)               (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
103805: #endif
103806: 
103807: static const struct compareInfo globInfo = { '*', '?', '[', 0 };
103808: /* The correct SQL-92 behavior is for the LIKE operator to ignore
103809: ** case.  Thus  'a' LIKE 'A' would be true. */
103810: static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
103811: /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
103812: ** is case sensitive causing 'a' LIKE 'A' to be false */
103813: static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
103814: 
103815: /*
103816: ** Compare two UTF-8 strings for equality where the first string can
103817: ** potentially be a "glob" or "like" expression.  Return true (1) if they
103818: ** are the same and false (0) if they are different.
103819: **
103820: ** Globbing rules:
103821: **
103822: **      '*'       Matches any sequence of zero or more characters.
103823: **
103824: **      '?'       Matches exactly one character.
103825: **
103826: **     [...]      Matches one character from the enclosed list of
103827: **                characters.
103828: **
103829: **     [^...]     Matches one character not in the enclosed list.
103830: **
103831: ** With the [...] and [^...] matching, a ']' character can be included
103832: ** in the list by making it the first character after '[' or '^'.  A
103833: ** range of characters can be specified using '-'.  Example:
103834: ** "[a-z]" matches any single lower-case letter.  To match a '-', make
103835: ** it the last character in the list.
103836: **
103837: ** Like matching rules:
103838: ** 
103839: **      '%'       Matches any sequence of zero or more characters
103840: **
103841: ***     '_'       Matches any one character
103842: **
103843: **      Ec        Where E is the "esc" character and c is any other
103844: **                character, including '%', '_', and esc, match exactly c.
103845: **
103846: ** The comments within this routine usually assume glob matching.
103847: **
103848: ** This routine is usually quick, but can be N**2 in the worst case.
103849: */
103850: static int patternCompare(
103851:   const u8 *zPattern,              /* The glob pattern */
103852:   const u8 *zString,               /* The string to compare against the glob */
103853:   const struct compareInfo *pInfo, /* Information about how to do the compare */
103854:   u32 matchOther                   /* The escape char (LIKE) or '[' (GLOB) */
103855: ){
103856:   u32 c, c2;                       /* Next pattern and input string chars */
103857:   u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
103858:   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
103859:   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
103860:   const u8 *zEscaped = 0;          /* One past the last escaped input char */
103861:   
103862:   while( (c = Utf8Read(zPattern))!=0 ){
103863:     if( c==matchAll ){  /* Match "*" */
103864:       /* Skip over multiple "*" characters in the pattern.  If there
103865:       ** are also "?" characters, skip those as well, but consume a
103866:       ** single character of the input string for each "?" skipped */
103867:       while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
103868:         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
103869:           return 0;
103870:         }
103871:       }
103872:       if( c==0 ){
103873:         return 1;   /* "*" at the end of the pattern matches */
103874:       }else if( c==matchOther ){
103875:         if( pInfo->matchSet==0 ){
103876:           c = sqlite3Utf8Read(&zPattern);
103877:           if( c==0 ) return 0;
103878:         }else{
103879:           /* "[...]" immediately follows the "*".  We have to do a slow
103880:           ** recursive search in this case, but it is an unusual case. */
103881:           assert( matchOther<0x80 );  /* '[' is a single-byte character */
103882:           while( *zString
103883:                  && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){
103884:             SQLITE_SKIP_UTF8(zString);
103885:           }
103886:           return *zString!=0;
103887:         }
103888:       }
103889: 
103890:       /* At this point variable c contains the first character of the
103891:       ** pattern string past the "*".  Search in the input string for the
103892:       ** first matching character and recursively contine the match from
103893:       ** that point.
103894:       **
103895:       ** For a case-insensitive search, set variable cx to be the same as
103896:       ** c but in the other case and search the input string for either
103897:       ** c or cx.
103898:       */
103899:       if( c<=0x80 ){
103900:         u32 cx;
103901:         if( noCase ){
103902:           cx = sqlite3Toupper(c);
103903:           c = sqlite3Tolower(c);
103904:         }else{
103905:           cx = c;
103906:         }
103907:         while( (c2 = *(zString++))!=0 ){
103908:           if( c2!=c && c2!=cx ) continue;
103909:           if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103910:         }
103911:       }else{
103912:         while( (c2 = Utf8Read(zString))!=0 ){
103913:           if( c2!=c ) continue;
103914:           if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103915:         }
103916:       }
103917:       return 0;
103918:     }
103919:     if( c==matchOther ){
103920:       if( pInfo->matchSet==0 ){
103921:         c = sqlite3Utf8Read(&zPattern);
103922:         if( c==0 ) return 0;
103923:         zEscaped = zPattern;
103924:       }else{
103925:         u32 prior_c = 0;
103926:         int seen = 0;
103927:         int invert = 0;
103928:         c = sqlite3Utf8Read(&zString);
103929:         if( c==0 ) return 0;
103930:         c2 = sqlite3Utf8Read(&zPattern);
103931:         if( c2=='^' ){
103932:           invert = 1;
103933:           c2 = sqlite3Utf8Read(&zPattern);
103934:         }
103935:         if( c2==']' ){
103936:           if( c==']' ) seen = 1;
103937:           c2 = sqlite3Utf8Read(&zPattern);
103938:         }
103939:         while( c2 && c2!=']' ){
103940:           if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
103941:             c2 = sqlite3Utf8Read(&zPattern);
103942:             if( c>=prior_c && c<=c2 ) seen = 1;
103943:             prior_c = 0;
103944:           }else{
103945:             if( c==c2 ){
103946:               seen = 1;
103947:             }
103948:             prior_c = c2;
103949:           }
103950:           c2 = sqlite3Utf8Read(&zPattern);
103951:         }
103952:         if( c2==0 || (seen ^ invert)==0 ){
103953:           return 0;
103954:         }
103955:         continue;
103956:       }
103957:     }
103958:     c2 = Utf8Read(zString);
103959:     if( c==c2 ) continue;
103960:     if( noCase  && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
103961:       continue;
103962:     }
103963:     if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
103964:     return 0;
103965:   }
103966:   return *zString==0;
103967: }
103968: 
103969: /*
103970: ** The sqlite3_strglob() interface.
103971: */
103972: SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
103973:   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0;
103974: }
103975: 
103976: /*
103977: ** The sqlite3_strlike() interface.
103978: */
103979: SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
103980:   return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
103981: }
103982: 
103983: /*
103984: ** Count the number of times that the LIKE operator (or GLOB which is
103985: ** just a variation of LIKE) gets called.  This is used for testing
103986: ** only.
103987: */
103988: #ifdef SQLITE_TEST
103989: SQLITE_API int sqlite3_like_count = 0;
103990: #endif
103991: 
103992: 
103993: /*
103994: ** Implementation of the like() SQL function.  This function implements
103995: ** the build-in LIKE operator.  The first argument to the function is the
103996: ** pattern and the second argument is the string.  So, the SQL statements:
103997: **
103998: **       A LIKE B
103999: **
104000: ** is implemented as like(B,A).
104001: **
104002: ** This same function (with a different compareInfo structure) computes
104003: ** the GLOB operator.
104004: */
104005: static void likeFunc(
104006:   sqlite3_context *context, 
104007:   int argc, 
104008:   sqlite3_value **argv
104009: ){
104010:   const unsigned char *zA, *zB;
104011:   u32 escape;
104012:   int nPat;
104013:   sqlite3 *db = sqlite3_context_db_handle(context);
104014:   struct compareInfo *pInfo = sqlite3_user_data(context);
104015: 
104016: #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
104017:   if( sqlite3_value_type(argv[0])==SQLITE_BLOB
104018:    || sqlite3_value_type(argv[1])==SQLITE_BLOB
104019:   ){
104020: #ifdef SQLITE_TEST
104021:     sqlite3_like_count++;
104022: #endif
104023:     sqlite3_result_int(context, 0);
104024:     return;
104025:   }
104026: #endif
104027:   zB = sqlite3_value_text(argv[0]);
104028:   zA = sqlite3_value_text(argv[1]);
104029: 
104030:   /* Limit the length of the LIKE or GLOB pattern to avoid problems
104031:   ** of deep recursion and N*N behavior in patternCompare().
104032:   */
104033:   nPat = sqlite3_value_bytes(argv[0]);
104034:   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
104035:   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
104036:   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
104037:     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
104038:     return;
104039:   }
104040:   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
104041: 
104042:   if( argc==3 ){
104043:     /* The escape character string must consist of a single UTF-8 character.
104044:     ** Otherwise, return an error.
104045:     */
104046:     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
104047:     if( zEsc==0 ) return;
104048:     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
104049:       sqlite3_result_error(context, 
104050:           "ESCAPE expression must be a single character", -1);
104051:       return;
104052:     }
104053:     escape = sqlite3Utf8Read(&zEsc);
104054:   }else{
104055:     escape = pInfo->matchSet;
104056:   }
104057:   if( zA && zB ){
104058: #ifdef SQLITE_TEST
104059:     sqlite3_like_count++;
104060: #endif
104061:     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
104062:   }
104063: }
104064: 
104065: /*
104066: ** Implementation of the NULLIF(x,y) function.  The result is the first
104067: ** argument if the arguments are different.  The result is NULL if the
104068: ** arguments are equal to each other.
104069: */
104070: static void nullifFunc(
104071:   sqlite3_context *context,
104072:   int NotUsed,
104073:   sqlite3_value **argv
104074: ){
104075:   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104076:   UNUSED_PARAMETER(NotUsed);
104077:   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
104078:     sqlite3_result_value(context, argv[0]);
104079:   }
104080: }
104081: 
104082: /*
104083: ** Implementation of the sqlite_version() function.  The result is the version
104084: ** of the SQLite library that is running.
104085: */
104086: static void versionFunc(
104087:   sqlite3_context *context,
104088:   int NotUsed,
104089:   sqlite3_value **NotUsed2
104090: ){
104091:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
104092:   /* IMP: R-48699-48617 This function is an SQL wrapper around the
104093:   ** sqlite3_libversion() C-interface. */
104094:   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
104095: }
104096: 
104097: /*
104098: ** Implementation of the sqlite_source_id() function. The result is a string
104099: ** that identifies the particular version of the source code used to build
104100: ** SQLite.
104101: */
104102: static void sourceidFunc(
104103:   sqlite3_context *context,
104104:   int NotUsed,
104105:   sqlite3_value **NotUsed2
104106: ){
104107:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
104108:   /* IMP: R-24470-31136 This function is an SQL wrapper around the
104109:   ** sqlite3_sourceid() C interface. */
104110:   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
104111: }
104112: 
104113: /*
104114: ** Implementation of the sqlite_log() function.  This is a wrapper around
104115: ** sqlite3_log().  The return value is NULL.  The function exists purely for
104116: ** its side-effects.
104117: */
104118: static void errlogFunc(
104119:   sqlite3_context *context,
104120:   int argc,
104121:   sqlite3_value **argv
104122: ){
104123:   UNUSED_PARAMETER(argc);
104124:   UNUSED_PARAMETER(context);
104125:   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
104126: }
104127: 
104128: /*
104129: ** Implementation of the sqlite_compileoption_used() function.
104130: ** The result is an integer that identifies if the compiler option
104131: ** was used to build SQLite.
104132: */
104133: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104134: static void compileoptionusedFunc(
104135:   sqlite3_context *context,
104136:   int argc,
104137:   sqlite3_value **argv
104138: ){
104139:   const char *zOptName;
104140:   assert( argc==1 );
104141:   UNUSED_PARAMETER(argc);
104142:   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
104143:   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
104144:   ** function.
104145:   */
104146:   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
104147:     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
104148:   }
104149: }
104150: #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104151: 
104152: /*
104153: ** Implementation of the sqlite_compileoption_get() function. 
104154: ** The result is a string that identifies the compiler options 
104155: ** used to build SQLite.
104156: */
104157: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104158: static void compileoptiongetFunc(
104159:   sqlite3_context *context,
104160:   int argc,
104161:   sqlite3_value **argv
104162: ){
104163:   int n;
104164:   assert( argc==1 );
104165:   UNUSED_PARAMETER(argc);
104166:   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
104167:   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
104168:   */
104169:   n = sqlite3_value_int(argv[0]);
104170:   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
104171: }
104172: #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104173: 
104174: /* Array for converting from half-bytes (nybbles) into ASCII hex
104175: ** digits. */
104176: static const char hexdigits[] = {
104177:   '0', '1', '2', '3', '4', '5', '6', '7',
104178:   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
104179: };
104180: 
104181: /*
104182: ** Implementation of the QUOTE() function.  This function takes a single
104183: ** argument.  If the argument is numeric, the return value is the same as
104184: ** the argument.  If the argument is NULL, the return value is the string
104185: ** "NULL".  Otherwise, the argument is enclosed in single quotes with
104186: ** single-quote escapes.
104187: */
104188: static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
104189:   assert( argc==1 );
104190:   UNUSED_PARAMETER(argc);
104191:   switch( sqlite3_value_type(argv[0]) ){
104192:     case SQLITE_FLOAT: {
104193:       double r1, r2;
104194:       char zBuf[50];
104195:       r1 = sqlite3_value_double(argv[0]);
104196:       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
104197:       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
104198:       if( r1!=r2 ){
104199:         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
104200:       }
104201:       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
104202:       break;
104203:     }
104204:     case SQLITE_INTEGER: {
104205:       sqlite3_result_value(context, argv[0]);
104206:       break;
104207:     }
104208:     case SQLITE_BLOB: {
104209:       char *zText = 0;
104210:       char const *zBlob = sqlite3_value_blob(argv[0]);
104211:       int nBlob = sqlite3_value_bytes(argv[0]);
104212:       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
104213:       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
104214:       if( zText ){
104215:         int i;
104216:         for(i=0; i<nBlob; i++){
104217:           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
104218:           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
104219:         }
104220:         zText[(nBlob*2)+2] = '\'';
104221:         zText[(nBlob*2)+3] = '\0';
104222:         zText[0] = 'X';
104223:         zText[1] = '\'';
104224:         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
104225:         sqlite3_free(zText);
104226:       }
104227:       break;
104228:     }
104229:     case SQLITE_TEXT: {
104230:       int i,j;
104231:       u64 n;
104232:       const unsigned char *zArg = sqlite3_value_text(argv[0]);
104233:       char *z;
104234: 
104235:       if( zArg==0 ) return;
104236:       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
104237:       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
104238:       if( z ){
104239:         z[0] = '\'';
104240:         for(i=0, j=1; zArg[i]; i++){
104241:           z[j++] = zArg[i];
104242:           if( zArg[i]=='\'' ){
104243:             z[j++] = '\'';
104244:           }
104245:         }
104246:         z[j++] = '\'';
104247:         z[j] = 0;
104248:         sqlite3_result_text(context, z, j, sqlite3_free);
104249:       }
104250:       break;
104251:     }
104252:     default: {
104253:       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
104254:       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
104255:       break;
104256:     }
104257:   }
104258: }
104259: 
104260: /*
104261: ** The unicode() function.  Return the integer unicode code-point value
104262: ** for the first character of the input string. 
104263: */
104264: static void unicodeFunc(
104265:   sqlite3_context *context,
104266:   int argc,
104267:   sqlite3_value **argv
104268: ){
104269:   const unsigned char *z = sqlite3_value_text(argv[0]);
104270:   (void)argc;
104271:   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
104272: }
104273: 
104274: /*
104275: ** The char() function takes zero or more arguments, each of which is
104276: ** an integer.  It constructs a string where each character of the string
104277: ** is the unicode character for the corresponding integer argument.
104278: */
104279: static void charFunc(
104280:   sqlite3_context *context,
104281:   int argc,
104282:   sqlite3_value **argv
104283: ){
104284:   unsigned char *z, *zOut;
104285:   int i;
104286:   zOut = z = sqlite3_malloc64( argc*4+1 );
104287:   if( z==0 ){
104288:     sqlite3_result_error_nomem(context);
104289:     return;
104290:   }
104291:   for(i=0; i<argc; i++){
104292:     sqlite3_int64 x;
104293:     unsigned c;
104294:     x = sqlite3_value_int64(argv[i]);
104295:     if( x<0 || x>0x10ffff ) x = 0xfffd;
104296:     c = (unsigned)(x & 0x1fffff);
104297:     if( c<0x00080 ){
104298:       *zOut++ = (u8)(c&0xFF);
104299:     }else if( c<0x00800 ){
104300:       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
104301:       *zOut++ = 0x80 + (u8)(c & 0x3F);
104302:     }else if( c<0x10000 ){
104303:       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
104304:       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
104305:       *zOut++ = 0x80 + (u8)(c & 0x3F);
104306:     }else{
104307:       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
104308:       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
104309:       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
104310:       *zOut++ = 0x80 + (u8)(c & 0x3F);
104311:     }                                                    \
104312:   }
104313:   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
104314: }
104315: 
104316: /*
104317: ** The hex() function.  Interpret the argument as a blob.  Return
104318: ** a hexadecimal rendering as text.
104319: */
104320: static void hexFunc(
104321:   sqlite3_context *context,
104322:   int argc,
104323:   sqlite3_value **argv
104324: ){
104325:   int i, n;
104326:   const unsigned char *pBlob;
104327:   char *zHex, *z;
104328:   assert( argc==1 );
104329:   UNUSED_PARAMETER(argc);
104330:   pBlob = sqlite3_value_blob(argv[0]);
104331:   n = sqlite3_value_bytes(argv[0]);
104332:   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
104333:   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
104334:   if( zHex ){
104335:     for(i=0; i<n; i++, pBlob++){
104336:       unsigned char c = *pBlob;
104337:       *(z++) = hexdigits[(c>>4)&0xf];
104338:       *(z++) = hexdigits[c&0xf];
104339:     }
104340:     *z = 0;
104341:     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
104342:   }
104343: }
104344: 
104345: /*
104346: ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
104347: */
104348: static void zeroblobFunc(
104349:   sqlite3_context *context,
104350:   int argc,
104351:   sqlite3_value **argv
104352: ){
104353:   i64 n;
104354:   int rc;
104355:   assert( argc==1 );
104356:   UNUSED_PARAMETER(argc);
104357:   n = sqlite3_value_int64(argv[0]);
104358:   if( n<0 ) n = 0;
104359:   rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
104360:   if( rc ){
104361:     sqlite3_result_error_code(context, rc);
104362:   }
104363: }
104364: 
104365: /*
104366: ** The replace() function.  Three arguments are all strings: call
104367: ** them A, B, and C. The result is also a string which is derived
104368: ** from A by replacing every occurrence of B with C.  The match
104369: ** must be exact.  Collating sequences are not used.
104370: */
104371: static void replaceFunc(
104372:   sqlite3_context *context,
104373:   int argc,
104374:   sqlite3_value **argv
104375: ){
104376:   const unsigned char *zStr;        /* The input string A */
104377:   const unsigned char *zPattern;    /* The pattern string B */
104378:   const unsigned char *zRep;        /* The replacement string C */
104379:   unsigned char *zOut;              /* The output */
104380:   int nStr;                /* Size of zStr */
104381:   int nPattern;            /* Size of zPattern */
104382:   int nRep;                /* Size of zRep */
104383:   i64 nOut;                /* Maximum size of zOut */
104384:   int loopLimit;           /* Last zStr[] that might match zPattern[] */
104385:   int i, j;                /* Loop counters */
104386: 
104387:   assert( argc==3 );
104388:   UNUSED_PARAMETER(argc);
104389:   zStr = sqlite3_value_text(argv[0]);
104390:   if( zStr==0 ) return;
104391:   nStr = sqlite3_value_bytes(argv[0]);
104392:   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
104393:   zPattern = sqlite3_value_text(argv[1]);
104394:   if( zPattern==0 ){
104395:     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
104396:             || sqlite3_context_db_handle(context)->mallocFailed );
104397:     return;
104398:   }
104399:   if( zPattern[0]==0 ){
104400:     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
104401:     sqlite3_result_value(context, argv[0]);
104402:     return;
104403:   }
104404:   nPattern = sqlite3_value_bytes(argv[1]);
104405:   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
104406:   zRep = sqlite3_value_text(argv[2]);
104407:   if( zRep==0 ) return;
104408:   nRep = sqlite3_value_bytes(argv[2]);
104409:   assert( zRep==sqlite3_value_text(argv[2]) );
104410:   nOut = nStr + 1;
104411:   assert( nOut<SQLITE_MAX_LENGTH );
104412:   zOut = contextMalloc(context, (i64)nOut);
104413:   if( zOut==0 ){
104414:     return;
104415:   }
104416:   loopLimit = nStr - nPattern;  
104417:   for(i=j=0; i<=loopLimit; i++){
104418:     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
104419:       zOut[j++] = zStr[i];
104420:     }else{
104421:       u8 *zOld;
104422:       sqlite3 *db = sqlite3_context_db_handle(context);
104423:       nOut += nRep - nPattern;
104424:       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
104425:       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
104426:       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
104427:         sqlite3_result_error_toobig(context);
104428:         sqlite3_free(zOut);
104429:         return;
104430:       }
104431:       zOld = zOut;
104432:       zOut = sqlite3_realloc64(zOut, (int)nOut);
104433:       if( zOut==0 ){
104434:         sqlite3_result_error_nomem(context);
104435:         sqlite3_free(zOld);
104436:         return;
104437:       }
104438:       memcpy(&zOut[j], zRep, nRep);
104439:       j += nRep;
104440:       i += nPattern-1;
104441:     }
104442:   }
104443:   assert( j+nStr-i+1==nOut );
104444:   memcpy(&zOut[j], &zStr[i], nStr-i);
104445:   j += nStr - i;
104446:   assert( j<=nOut );
104447:   zOut[j] = 0;
104448:   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
104449: }
104450: 
104451: /*
104452: ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
104453: ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
104454: */
104455: static void trimFunc(
104456:   sqlite3_context *context,
104457:   int argc,
104458:   sqlite3_value **argv
104459: ){
104460:   const unsigned char *zIn;         /* Input string */
104461:   const unsigned char *zCharSet;    /* Set of characters to trim */
104462:   int nIn;                          /* Number of bytes in input */
104463:   int flags;                        /* 1: trimleft  2: trimright  3: trim */
104464:   int i;                            /* Loop counter */
104465:   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
104466:   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
104467:   int nChar;                        /* Number of characters in zCharSet */
104468: 
104469:   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
104470:     return;
104471:   }
104472:   zIn = sqlite3_value_text(argv[0]);
104473:   if( zIn==0 ) return;
104474:   nIn = sqlite3_value_bytes(argv[0]);
104475:   assert( zIn==sqlite3_value_text(argv[0]) );
104476:   if( argc==1 ){
104477:     static const unsigned char lenOne[] = { 1 };
104478:     static unsigned char * const azOne[] = { (u8*)" " };
104479:     nChar = 1;
104480:     aLen = (u8*)lenOne;
104481:     azChar = (unsigned char **)azOne;
104482:     zCharSet = 0;
104483:   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
104484:     return;
104485:   }else{
104486:     const unsigned char *z;
104487:     for(z=zCharSet, nChar=0; *z; nChar++){
104488:       SQLITE_SKIP_UTF8(z);
104489:     }
104490:     if( nChar>0 ){
104491:       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
104492:       if( azChar==0 ){
104493:         return;
104494:       }
104495:       aLen = (unsigned char*)&azChar[nChar];
104496:       for(z=zCharSet, nChar=0; *z; nChar++){
104497:         azChar[nChar] = (unsigned char *)z;
104498:         SQLITE_SKIP_UTF8(z);
104499:         aLen[nChar] = (u8)(z - azChar[nChar]);
104500:       }
104501:     }
104502:   }
104503:   if( nChar>0 ){
104504:     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
104505:     if( flags & 1 ){
104506:       while( nIn>0 ){
104507:         int len = 0;
104508:         for(i=0; i<nChar; i++){
104509:           len = aLen[i];
104510:           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
104511:         }
104512:         if( i>=nChar ) break;
104513:         zIn += len;
104514:         nIn -= len;
104515:       }
104516:     }
104517:     if( flags & 2 ){
104518:       while( nIn>0 ){
104519:         int len = 0;
104520:         for(i=0; i<nChar; i++){
104521:           len = aLen[i];
104522:           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
104523:         }
104524:         if( i>=nChar ) break;
104525:         nIn -= len;
104526:       }
104527:     }
104528:     if( zCharSet ){
104529:       sqlite3_free(azChar);
104530:     }
104531:   }
104532:   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
104533: }
104534: 
104535: 
104536: #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
104537: /*
104538: ** The "unknown" function is automatically substituted in place of
104539: ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
104540: ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
104541: ** When the "sqlite3" command-line shell is built using this functionality,
104542: ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
104543: ** involving application-defined functions to be examined in a generic
104544: ** sqlite3 shell.
104545: */
104546: static void unknownFunc(
104547:   sqlite3_context *context,
104548:   int argc,
104549:   sqlite3_value **argv
104550: ){
104551:   /* no-op */
104552: }
104553: #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
104554: 
104555: 
104556: /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
104557: ** is only available if the SQLITE_SOUNDEX compile-time option is used
104558: ** when SQLite is built.
104559: */
104560: #ifdef SQLITE_SOUNDEX
104561: /*
104562: ** Compute the soundex encoding of a word.
104563: **
104564: ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
104565: ** soundex encoding of the string X. 
104566: */
104567: static void soundexFunc(
104568:   sqlite3_context *context,
104569:   int argc,
104570:   sqlite3_value **argv
104571: ){
104572:   char zResult[8];
104573:   const u8 *zIn;
104574:   int i, j;
104575:   static const unsigned char iCode[] = {
104576:     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104577:     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104578:     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104579:     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
104580:     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
104581:     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
104582:     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
104583:     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
104584:   };
104585:   assert( argc==1 );
104586:   zIn = (u8*)sqlite3_value_text(argv[0]);
104587:   if( zIn==0 ) zIn = (u8*)"";
104588:   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
104589:   if( zIn[i] ){
104590:     u8 prevcode = iCode[zIn[i]&0x7f];
104591:     zResult[0] = sqlite3Toupper(zIn[i]);
104592:     for(j=1; j<4 && zIn[i]; i++){
104593:       int code = iCode[zIn[i]&0x7f];
104594:       if( code>0 ){
104595:         if( code!=prevcode ){
104596:           prevcode = code;
104597:           zResult[j++] = code + '0';
104598:         }
104599:       }else{
104600:         prevcode = 0;
104601:       }
104602:     }
104603:     while( j<4 ){
104604:       zResult[j++] = '0';
104605:     }
104606:     zResult[j] = 0;
104607:     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
104608:   }else{
104609:     /* IMP: R-64894-50321 The string "?000" is returned if the argument
104610:     ** is NULL or contains no ASCII alphabetic characters. */
104611:     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
104612:   }
104613: }
104614: #endif /* SQLITE_SOUNDEX */
104615: 
104616: #ifndef SQLITE_OMIT_LOAD_EXTENSION
104617: /*
104618: ** A function that loads a shared-library extension then returns NULL.
104619: */
104620: static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
104621:   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
104622:   const char *zProc;
104623:   sqlite3 *db = sqlite3_context_db_handle(context);
104624:   char *zErrMsg = 0;
104625: 
104626:   /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
104627:   ** flag is set.  See the sqlite3_enable_load_extension() API.
104628:   */
104629:   if( (db->flags & SQLITE_LoadExtFunc)==0 ){
104630:     sqlite3_result_error(context, "not authorized", -1);
104631:     return;
104632:   }
104633: 
104634:   if( argc==2 ){
104635:     zProc = (const char *)sqlite3_value_text(argv[1]);
104636:   }else{
104637:     zProc = 0;
104638:   }
104639:   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
104640:     sqlite3_result_error(context, zErrMsg, -1);
104641:     sqlite3_free(zErrMsg);
104642:   }
104643: }
104644: #endif
104645: 
104646: 
104647: /*
104648: ** An instance of the following structure holds the context of a
104649: ** sum() or avg() aggregate computation.
104650: */
104651: typedef struct SumCtx SumCtx;
104652: struct SumCtx {
104653:   double rSum;      /* Floating point sum */
104654:   i64 iSum;         /* Integer sum */   
104655:   i64 cnt;          /* Number of elements summed */
104656:   u8 overflow;      /* True if integer overflow seen */
104657:   u8 approx;        /* True if non-integer value was input to the sum */
104658: };
104659: 
104660: /*
104661: ** Routines used to compute the sum, average, and total.
104662: **
104663: ** The SUM() function follows the (broken) SQL standard which means
104664: ** that it returns NULL if it sums over no inputs.  TOTAL returns
104665: ** 0.0 in that case.  In addition, TOTAL always returns a float where
104666: ** SUM might return an integer if it never encounters a floating point
104667: ** value.  TOTAL never fails, but SUM might through an exception if
104668: ** it overflows an integer.
104669: */
104670: static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104671:   SumCtx *p;
104672:   int type;
104673:   assert( argc==1 );
104674:   UNUSED_PARAMETER(argc);
104675:   p = sqlite3_aggregate_context(context, sizeof(*p));
104676:   type = sqlite3_value_numeric_type(argv[0]);
104677:   if( p && type!=SQLITE_NULL ){
104678:     p->cnt++;
104679:     if( type==SQLITE_INTEGER ){
104680:       i64 v = sqlite3_value_int64(argv[0]);
104681:       p->rSum += v;
104682:       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
104683:         p->overflow = 1;
104684:       }
104685:     }else{
104686:       p->rSum += sqlite3_value_double(argv[0]);
104687:       p->approx = 1;
104688:     }
104689:   }
104690: }
104691: static void sumFinalize(sqlite3_context *context){
104692:   SumCtx *p;
104693:   p = sqlite3_aggregate_context(context, 0);
104694:   if( p && p->cnt>0 ){
104695:     if( p->overflow ){
104696:       sqlite3_result_error(context,"integer overflow",-1);
104697:     }else if( p->approx ){
104698:       sqlite3_result_double(context, p->rSum);
104699:     }else{
104700:       sqlite3_result_int64(context, p->iSum);
104701:     }
104702:   }
104703: }
104704: static void avgFinalize(sqlite3_context *context){
104705:   SumCtx *p;
104706:   p = sqlite3_aggregate_context(context, 0);
104707:   if( p && p->cnt>0 ){
104708:     sqlite3_result_double(context, p->rSum/(double)p->cnt);
104709:   }
104710: }
104711: static void totalFinalize(sqlite3_context *context){
104712:   SumCtx *p;
104713:   p = sqlite3_aggregate_context(context, 0);
104714:   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
104715:   sqlite3_result_double(context, p ? p->rSum : (double)0);
104716: }
104717: 
104718: /*
104719: ** The following structure keeps track of state information for the
104720: ** count() aggregate function.
104721: */
104722: typedef struct CountCtx CountCtx;
104723: struct CountCtx {
104724:   i64 n;
104725: };
104726: 
104727: /*
104728: ** Routines to implement the count() aggregate function.
104729: */
104730: static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104731:   CountCtx *p;
104732:   p = sqlite3_aggregate_context(context, sizeof(*p));
104733:   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
104734:     p->n++;
104735:   }
104736: 
104737: #ifndef SQLITE_OMIT_DEPRECATED
104738:   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
104739:   ** sure it still operates correctly, verify that its count agrees with our 
104740:   ** internal count when using count(*) and when the total count can be
104741:   ** expressed as a 32-bit integer. */
104742:   assert( argc==1 || p==0 || p->n>0x7fffffff
104743:           || p->n==sqlite3_aggregate_count(context) );
104744: #endif
104745: }   
104746: static void countFinalize(sqlite3_context *context){
104747:   CountCtx *p;
104748:   p = sqlite3_aggregate_context(context, 0);
104749:   sqlite3_result_int64(context, p ? p->n : 0);
104750: }
104751: 
104752: /*
104753: ** Routines to implement min() and max() aggregate functions.
104754: */
104755: static void minmaxStep(
104756:   sqlite3_context *context, 
104757:   int NotUsed, 
104758:   sqlite3_value **argv
104759: ){
104760:   Mem *pArg  = (Mem *)argv[0];
104761:   Mem *pBest;
104762:   UNUSED_PARAMETER(NotUsed);
104763: 
104764:   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
104765:   if( !pBest ) return;
104766: 
104767:   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
104768:     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
104769:   }else if( pBest->flags ){
104770:     int max;
104771:     int cmp;
104772:     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104773:     /* This step function is used for both the min() and max() aggregates,
104774:     ** the only difference between the two being that the sense of the
104775:     ** comparison is inverted. For the max() aggregate, the
104776:     ** sqlite3_user_data() function returns (void *)-1. For min() it
104777:     ** returns (void *)db, where db is the sqlite3* database pointer.
104778:     ** Therefore the next statement sets variable 'max' to 1 for the max()
104779:     ** aggregate, or 0 for min().
104780:     */
104781:     max = sqlite3_user_data(context)!=0;
104782:     cmp = sqlite3MemCompare(pBest, pArg, pColl);
104783:     if( (max && cmp<0) || (!max && cmp>0) ){
104784:       sqlite3VdbeMemCopy(pBest, pArg);
104785:     }else{
104786:       sqlite3SkipAccumulatorLoad(context);
104787:     }
104788:   }else{
104789:     pBest->db = sqlite3_context_db_handle(context);
104790:     sqlite3VdbeMemCopy(pBest, pArg);
104791:   }
104792: }
104793: static void minMaxFinalize(sqlite3_context *context){
104794:   sqlite3_value *pRes;
104795:   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
104796:   if( pRes ){
104797:     if( pRes->flags ){
104798:       sqlite3_result_value(context, pRes);
104799:     }
104800:     sqlite3VdbeMemRelease(pRes);
104801:   }
104802: }
104803: 
104804: /*
104805: ** group_concat(EXPR, ?SEPARATOR?)
104806: */
104807: static void groupConcatStep(
104808:   sqlite3_context *context,
104809:   int argc,
104810:   sqlite3_value **argv
104811: ){
104812:   const char *zVal;
104813:   StrAccum *pAccum;
104814:   const char *zSep;
104815:   int nVal, nSep;
104816:   assert( argc==1 || argc==2 );
104817:   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104818:   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
104819: 
104820:   if( pAccum ){
104821:     sqlite3 *db = sqlite3_context_db_handle(context);
104822:     int firstTerm = pAccum->mxAlloc==0;
104823:     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
104824:     if( !firstTerm ){
104825:       if( argc==2 ){
104826:         zSep = (char*)sqlite3_value_text(argv[1]);
104827:         nSep = sqlite3_value_bytes(argv[1]);
104828:       }else{
104829:         zSep = ",";
104830:         nSep = 1;
104831:       }
104832:       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
104833:     }
104834:     zVal = (char*)sqlite3_value_text(argv[0]);
104835:     nVal = sqlite3_value_bytes(argv[0]);
104836:     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
104837:   }
104838: }
104839: static void groupConcatFinalize(sqlite3_context *context){
104840:   StrAccum *pAccum;
104841:   pAccum = sqlite3_aggregate_context(context, 0);
104842:   if( pAccum ){
104843:     if( pAccum->accError==STRACCUM_TOOBIG ){
104844:       sqlite3_result_error_toobig(context);
104845:     }else if( pAccum->accError==STRACCUM_NOMEM ){
104846:       sqlite3_result_error_nomem(context);
104847:     }else{    
104848:       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
104849:                           sqlite3_free);
104850:     }
104851:   }
104852: }
104853: 
104854: /*
104855: ** This routine does per-connection function registration.  Most
104856: ** of the built-in functions above are part of the global function set.
104857: ** This routine only deals with those that are not global.
104858: */
104859: SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
104860:   int rc = sqlite3_overload_function(db, "MATCH", 2);
104861:   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
104862:   if( rc==SQLITE_NOMEM ){
104863:     sqlite3OomFault(db);
104864:   }
104865: }
104866: 
104867: /*
104868: ** Set the LIKEOPT flag on the 2-argument function with the given name.
104869: */
104870: static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
104871:   FuncDef *pDef;
104872:   pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
104873:   if( ALWAYS(pDef) ){
104874:     pDef->funcFlags |= flagVal;
104875:   }
104876: }
104877: 
104878: /*
104879: ** Register the built-in LIKE and GLOB functions.  The caseSensitive
104880: ** parameter determines whether or not the LIKE operator is case
104881: ** sensitive.  GLOB is always case sensitive.
104882: */
104883: SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
104884:   struct compareInfo *pInfo;
104885:   if( caseSensitive ){
104886:     pInfo = (struct compareInfo*)&likeInfoAlt;
104887:   }else{
104888:     pInfo = (struct compareInfo*)&likeInfoNorm;
104889:   }
104890:   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104891:   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104892:   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
104893:       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
104894:   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
104895:   setLikeOptFlag(db, "like", 
104896:       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
104897: }
104898: 
104899: /*
104900: ** pExpr points to an expression which implements a function.  If
104901: ** it is appropriate to apply the LIKE optimization to that function
104902: ** then set aWc[0] through aWc[2] to the wildcard characters and
104903: ** return TRUE.  If the function is not a LIKE-style function then
104904: ** return FALSE.
104905: **
104906: ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
104907: ** the function (default for LIKE).  If the function makes the distinction
104908: ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
104909: ** false.
104910: */
104911: SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
104912:   FuncDef *pDef;
104913:   if( pExpr->op!=TK_FUNCTION 
104914:    || !pExpr->x.pList 
104915:    || pExpr->x.pList->nExpr!=2
104916:   ){
104917:     return 0;
104918:   }
104919:   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
104920:   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
104921:   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
104922:     return 0;
104923:   }
104924: 
104925:   /* The memcpy() statement assumes that the wildcard characters are
104926:   ** the first three statements in the compareInfo structure.  The
104927:   ** asserts() that follow verify that assumption
104928:   */
104929:   memcpy(aWc, pDef->pUserData, 3);
104930:   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
104931:   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
104932:   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
104933:   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
104934:   return 1;
104935: }
104936: 
104937: /*
104938: ** All of the FuncDef structures in the aBuiltinFunc[] array above
104939: ** to the global function hash table.  This occurs at start-time (as
104940: ** a consequence of calling sqlite3_initialize()).
104941: **
104942: ** After this routine runs
104943: */
104944: SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
104945:   /*
104946:   ** The following array holds FuncDef structures for all of the functions
104947:   ** defined in this file.
104948:   **
104949:   ** The array cannot be constant since changes are made to the
104950:   ** FuncDef.pHash elements at start-time.  The elements of this array
104951:   ** are read-only after initialization is complete.
104952:   **
104953:   ** For peak efficiency, put the most frequently used function last.
104954:   */
104955:   static FuncDef aBuiltinFunc[] = {
104956: #ifdef SQLITE_SOUNDEX
104957:     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
104958: #endif
104959: #ifndef SQLITE_OMIT_LOAD_EXTENSION
104960:     VFUNCTION(load_extension,    1, 0, 0, loadExt          ),
104961:     VFUNCTION(load_extension,    2, 0, 0, loadExt          ),
104962: #endif
104963: #if SQLITE_USER_AUTHENTICATION
104964:     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
104965: #endif
104966: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104967:     DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
104968:     DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
104969: #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104970:     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104971:     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104972:     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
104973:     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
104974:     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
104975:     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
104976:     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
104977:     FUNCTION(trim,               1, 3, 0, trimFunc         ),
104978:     FUNCTION(trim,               2, 3, 0, trimFunc         ),
104979:     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
104980:     FUNCTION(min,                0, 0, 1, 0                ),
104981:     AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
104982:                                           SQLITE_FUNC_MINMAX ),
104983:     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
104984:     FUNCTION(max,                0, 1, 1, 0                ),
104985:     AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
104986:                                           SQLITE_FUNC_MINMAX ),
104987:     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
104988:     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
104989:     FUNCTION(instr,              2, 0, 0, instrFunc        ),
104990:     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
104991:     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
104992:     FUNCTION(char,              -1, 0, 0, charFunc         ),
104993:     FUNCTION(abs,                1, 0, 0, absFunc          ),
104994: #ifndef SQLITE_OMIT_FLOATING_POINT
104995:     FUNCTION(round,              1, 0, 0, roundFunc        ),
104996:     FUNCTION(round,              2, 0, 0, roundFunc        ),
104997: #endif
104998:     FUNCTION(upper,              1, 0, 0, upperFunc        ),
104999:     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
105000:     FUNCTION(hex,                1, 0, 0, hexFunc          ),
105001:     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
105002:     VFUNCTION(random,            0, 0, 0, randomFunc       ),
105003:     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
105004:     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
105005:     DFUNCTION(sqlite_version,    0, 0, 0, versionFunc      ),
105006:     DFUNCTION(sqlite_source_id,  0, 0, 0, sourceidFunc     ),
105007:     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
105008:     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
105009:     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
105010:     VFUNCTION(changes,           0, 0, 0, changes          ),
105011:     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
105012:     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
105013:     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
105014:     FUNCTION(substr,             2, 0, 0, substrFunc       ),
105015:     FUNCTION(substr,             3, 0, 0, substrFunc       ),
105016:     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
105017:     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
105018:     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
105019:     AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
105020:                SQLITE_FUNC_COUNT  ),
105021:     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
105022:     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
105023:     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
105024:   
105025:     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105026: #ifdef SQLITE_CASE_SENSITIVE_LIKE
105027:     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105028:     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
105029: #else
105030:     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
105031:     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
105032: #endif
105033: #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
105034:     FUNCTION(unknown,           -1, 0, 0, unknownFunc      ),
105035: #endif
105036:     FUNCTION(coalesce,           1, 0, 0, 0                ),
105037:     FUNCTION(coalesce,           0, 0, 0, 0                ),
105038:     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
105039:   };
105040: #ifndef SQLITE_OMIT_ALTERTABLE
105041:   sqlite3AlterFunctions();
105042: #endif
105043: #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
105044:   sqlite3AnalyzeFunctions();
105045: #endif
105046:   sqlite3RegisterDateTimeFunctions();
105047:   sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
105048: 
105049: #if 0  /* Enable to print out how the built-in functions are hashed */
105050:   {
105051:     int i;
105052:     FuncDef *p;
105053:     for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
105054:       printf("FUNC-HASH %02d:", i);
105055:       for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
105056:         int n = sqlite3Strlen30(p->zName);
105057:         int h = p->zName[0] + n;
105058:         printf(" %s(%d)", p->zName, h);
105059:       }
105060:       printf("\n");
105061:     }
105062:   }
105063: #endif
105064: }
105065: 
105066: /************** End of func.c ************************************************/
105067: /************** Begin file fkey.c ********************************************/
105068: /*
105069: **
105070: ** The author disclaims copyright to this source code.  In place of
105071: ** a legal notice, here is a blessing:
105072: **
105073: **    May you do good and not evil.
105074: **    May you find forgiveness for yourself and forgive others.
105075: **    May you share freely, never taking more than you give.
105076: **
105077: *************************************************************************
105078: ** This file contains code used by the compiler to add foreign key
105079: ** support to compiled SQL statements.
105080: */
105081: /* #include "sqliteInt.h" */
105082: 
105083: #ifndef SQLITE_OMIT_FOREIGN_KEY
105084: #ifndef SQLITE_OMIT_TRIGGER
105085: 
105086: /*
105087: ** Deferred and Immediate FKs
105088: ** --------------------------
105089: **
105090: ** Foreign keys in SQLite come in two flavours: deferred and immediate.
105091: ** If an immediate foreign key constraint is violated,
105092: ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
105093: ** statement transaction rolled back. If a 
105094: ** deferred foreign key constraint is violated, no action is taken 
105095: ** immediately. However if the application attempts to commit the 
105096: ** transaction before fixing the constraint violation, the attempt fails.
105097: **
105098: ** Deferred constraints are implemented using a simple counter associated
105099: ** with the database handle. The counter is set to zero each time a 
105100: ** database transaction is opened. Each time a statement is executed 
105101: ** that causes a foreign key violation, the counter is incremented. Each
105102: ** time a statement is executed that removes an existing violation from
105103: ** the database, the counter is decremented. When the transaction is
105104: ** committed, the commit fails if the current value of the counter is
105105: ** greater than zero. This scheme has two big drawbacks:
105106: **
105107: **   * When a commit fails due to a deferred foreign key constraint, 
105108: **     there is no way to tell which foreign constraint is not satisfied,
105109: **     or which row it is not satisfied for.
105110: **
105111: **   * If the database contains foreign key violations when the 
105112: **     transaction is opened, this may cause the mechanism to malfunction.
105113: **
105114: ** Despite these problems, this approach is adopted as it seems simpler
105115: ** than the alternatives.
105116: **
105117: ** INSERT operations:
105118: **
105119: **   I.1) For each FK for which the table is the child table, search
105120: **        the parent table for a match. If none is found increment the
105121: **        constraint counter.
105122: **
105123: **   I.2) For each FK for which the table is the parent table, 
105124: **        search the child table for rows that correspond to the new
105125: **        row in the parent table. Decrement the counter for each row
105126: **        found (as the constraint is now satisfied).
105127: **
105128: ** DELETE operations:
105129: **
105130: **   D.1) For each FK for which the table is the child table, 
105131: **        search the parent table for a row that corresponds to the 
105132: **        deleted row in the child table. If such a row is not found, 
105133: **        decrement the counter.
105134: **
105135: **   D.2) For each FK for which the table is the parent table, search 
105136: **        the child table for rows that correspond to the deleted row 
105137: **        in the parent table. For each found increment the counter.
105138: **
105139: ** UPDATE operations:
105140: **
105141: **   An UPDATE command requires that all 4 steps above are taken, but only
105142: **   for FK constraints for which the affected columns are actually 
105143: **   modified (values must be compared at runtime).
105144: **
105145: ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
105146: ** This simplifies the implementation a bit.
105147: **
105148: ** For the purposes of immediate FK constraints, the OR REPLACE conflict
105149: ** resolution is considered to delete rows before the new row is inserted.
105150: ** If a delete caused by OR REPLACE violates an FK constraint, an exception
105151: ** is thrown, even if the FK constraint would be satisfied after the new 
105152: ** row is inserted.
105153: **
105154: ** Immediate constraints are usually handled similarly. The only difference 
105155: ** is that the counter used is stored as part of each individual statement
105156: ** object (struct Vdbe). If, after the statement has run, its immediate
105157: ** constraint counter is greater than zero,
105158: ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
105159: ** and the statement transaction is rolled back. An exception is an INSERT
105160: ** statement that inserts a single row only (no triggers). In this case,
105161: ** instead of using a counter, an exception is thrown immediately if the
105162: ** INSERT violates a foreign key constraint. This is necessary as such
105163: ** an INSERT does not open a statement transaction.
105164: **
105165: ** TODO: How should dropping a table be handled? How should renaming a 
105166: ** table be handled?
105167: **
105168: **
105169: ** Query API Notes
105170: ** ---------------
105171: **
105172: ** Before coding an UPDATE or DELETE row operation, the code-generator
105173: ** for those two operations needs to know whether or not the operation
105174: ** requires any FK processing and, if so, which columns of the original
105175: ** row are required by the FK processing VDBE code (i.e. if FKs were
105176: ** implemented using triggers, which of the old.* columns would be 
105177: ** accessed). No information is required by the code-generator before
105178: ** coding an INSERT operation. The functions used by the UPDATE/DELETE
105179: ** generation code to query for this information are:
105180: **
105181: **   sqlite3FkRequired() - Test to see if FK processing is required.
105182: **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
105183: **
105184: **
105185: ** Externally accessible module functions
105186: ** --------------------------------------
105187: **
105188: **   sqlite3FkCheck()    - Check for foreign key violations.
105189: **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
105190: **   sqlite3FkDelete()   - Delete an FKey structure.
105191: */
105192: 
105193: /*
105194: ** VDBE Calling Convention
105195: ** -----------------------
105196: **
105197: ** Example:
105198: **
105199: **   For the following INSERT statement:
105200: **
105201: **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
105202: **     INSERT INTO t1 VALUES(1, 2, 3.1);
105203: **
105204: **   Register (x):        2    (type integer)
105205: **   Register (x+1):      1    (type integer)
105206: **   Register (x+2):      NULL (type NULL)
105207: **   Register (x+3):      3.1  (type real)
105208: */
105209: 
105210: /*
105211: ** A foreign key constraint requires that the key columns in the parent
105212: ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
105213: ** Given that pParent is the parent table for foreign key constraint pFKey, 
105214: ** search the schema for a unique index on the parent key columns. 
105215: **
105216: ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
105217: ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
105218: ** is set to point to the unique index. 
105219: ** 
105220: ** If the parent key consists of a single column (the foreign key constraint
105221: ** is not a composite foreign key), output variable *paiCol is set to NULL.
105222: ** Otherwise, it is set to point to an allocated array of size N, where
105223: ** N is the number of columns in the parent key. The first element of the
105224: ** array is the index of the child table column that is mapped by the FK
105225: ** constraint to the parent table column stored in the left-most column
105226: ** of index *ppIdx. The second element of the array is the index of the
105227: ** child table column that corresponds to the second left-most column of
105228: ** *ppIdx, and so on.
105229: **
105230: ** If the required index cannot be found, either because:
105231: **
105232: **   1) The named parent key columns do not exist, or
105233: **
105234: **   2) The named parent key columns do exist, but are not subject to a
105235: **      UNIQUE or PRIMARY KEY constraint, or
105236: **
105237: **   3) No parent key columns were provided explicitly as part of the
105238: **      foreign key definition, and the parent table does not have a
105239: **      PRIMARY KEY, or
105240: **
105241: **   4) No parent key columns were provided explicitly as part of the
105242: **      foreign key definition, and the PRIMARY KEY of the parent table 
105243: **      consists of a different number of columns to the child key in 
105244: **      the child table.
105245: **
105246: ** then non-zero is returned, and a "foreign key mismatch" error loaded
105247: ** into pParse. If an OOM error occurs, non-zero is returned and the
105248: ** pParse->db->mallocFailed flag is set.
105249: */
105250: SQLITE_PRIVATE int sqlite3FkLocateIndex(
105251:   Parse *pParse,                  /* Parse context to store any error in */
105252:   Table *pParent,                 /* Parent table of FK constraint pFKey */
105253:   FKey *pFKey,                    /* Foreign key to find index for */
105254:   Index **ppIdx,                  /* OUT: Unique index on parent table */
105255:   int **paiCol                    /* OUT: Map of index columns in pFKey */
105256: ){
105257:   Index *pIdx = 0;                    /* Value to return via *ppIdx */
105258:   int *aiCol = 0;                     /* Value to return via *paiCol */
105259:   int nCol = pFKey->nCol;             /* Number of columns in parent key */
105260:   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
105261: 
105262:   /* The caller is responsible for zeroing output parameters. */
105263:   assert( ppIdx && *ppIdx==0 );
105264:   assert( !paiCol || *paiCol==0 );
105265:   assert( pParse );
105266: 
105267:   /* If this is a non-composite (single column) foreign key, check if it 
105268:   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
105269:   ** and *paiCol set to zero and return early. 
105270:   **
105271:   ** Otherwise, for a composite foreign key (more than one column), allocate
105272:   ** space for the aiCol array (returned via output parameter *paiCol).
105273:   ** Non-composite foreign keys do not require the aiCol array.
105274:   */
105275:   if( nCol==1 ){
105276:     /* The FK maps to the IPK if any of the following are true:
105277:     **
105278:     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
105279:     **      mapped to the primary key of table pParent, or
105280:     **   2) The FK is explicitly mapped to a column declared as INTEGER
105281:     **      PRIMARY KEY.
105282:     */
105283:     if( pParent->iPKey>=0 ){
105284:       if( !zKey ) return 0;
105285:       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
105286:     }
105287:   }else if( paiCol ){
105288:     assert( nCol>1 );
105289:     aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
105290:     if( !aiCol ) return 1;
105291:     *paiCol = aiCol;
105292:   }
105293: 
105294:   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
105295:     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){ 
105296:       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
105297:       ** of columns. If each indexed column corresponds to a foreign key
105298:       ** column of pFKey, then this index is a winner.  */
105299: 
105300:       if( zKey==0 ){
105301:         /* If zKey is NULL, then this foreign key is implicitly mapped to 
105302:         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
105303:         ** identified by the test.  */
105304:         if( IsPrimaryKeyIndex(pIdx) ){
105305:           if( aiCol ){
105306:             int i;
105307:             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
105308:           }
105309:           break;
105310:         }
105311:       }else{
105312:         /* If zKey is non-NULL, then this foreign key was declared to
105313:         ** map to an explicit list of columns in table pParent. Check if this
105314:         ** index matches those columns. Also, check that the index uses
105315:         ** the default collation sequences for each column. */
105316:         int i, j;
105317:         for(i=0; i<nCol; i++){
105318:           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
105319:           const char *zDfltColl;            /* Def. collation for column */
105320:           char *zIdxCol;                    /* Name of indexed column */
105321: 
105322:           if( iCol<0 ) break; /* No foreign keys against expression indexes */
105323: 
105324:           /* If the index uses a collation sequence that is different from
105325:           ** the default collation sequence for the column, this index is
105326:           ** unusable. Bail out early in this case.  */
105327:           zDfltColl = pParent->aCol[iCol].zColl;
105328:           if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
105329:           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
105330: 
105331:           zIdxCol = pParent->aCol[iCol].zName;
105332:           for(j=0; j<nCol; j++){
105333:             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
105334:               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
105335:               break;
105336:             }
105337:           }
105338:           if( j==nCol ) break;
105339:         }
105340:         if( i==nCol ) break;      /* pIdx is usable */
105341:       }
105342:     }
105343:   }
105344: 
105345:   if( !pIdx ){
105346:     if( !pParse->disableTriggers ){
105347:       sqlite3ErrorMsg(pParse,
105348:            "foreign key mismatch - \"%w\" referencing \"%w\"",
105349:            pFKey->pFrom->zName, pFKey->zTo);
105350:     }
105351:     sqlite3DbFree(pParse->db, aiCol);
105352:     return 1;
105353:   }
105354: 
105355:   *ppIdx = pIdx;
105356:   return 0;
105357: }
105358: 
105359: /*
105360: ** This function is called when a row is inserted into or deleted from the 
105361: ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
105362: ** on the child table of pFKey, this function is invoked twice for each row
105363: ** affected - once to "delete" the old row, and then again to "insert" the
105364: ** new row.
105365: **
105366: ** Each time it is called, this function generates VDBE code to locate the
105367: ** row in the parent table that corresponds to the row being inserted into 
105368: ** or deleted from the child table. If the parent row can be found, no 
105369: ** special action is taken. Otherwise, if the parent row can *not* be
105370: ** found in the parent table:
105371: **
105372: **   Operation | FK type   | Action taken
105373: **   --------------------------------------------------------------------------
105374: **   INSERT      immediate   Increment the "immediate constraint counter".
105375: **
105376: **   DELETE      immediate   Decrement the "immediate constraint counter".
105377: **
105378: **   INSERT      deferred    Increment the "deferred constraint counter".
105379: **
105380: **   DELETE      deferred    Decrement the "deferred constraint counter".
105381: **
105382: ** These operations are identified in the comment at the top of this file 
105383: ** (fkey.c) as "I.1" and "D.1".
105384: */
105385: static void fkLookupParent(
105386:   Parse *pParse,        /* Parse context */
105387:   int iDb,              /* Index of database housing pTab */
105388:   Table *pTab,          /* Parent table of FK pFKey */
105389:   Index *pIdx,          /* Unique index on parent key columns in pTab */
105390:   FKey *pFKey,          /* Foreign key constraint */
105391:   int *aiCol,           /* Map from parent key columns to child table columns */
105392:   int regData,          /* Address of array containing child table row */
105393:   int nIncr,            /* Increment constraint counter by this */
105394:   int isIgnore          /* If true, pretend pTab contains all NULL values */
105395: ){
105396:   int i;                                    /* Iterator variable */
105397:   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
105398:   int iCur = pParse->nTab - 1;              /* Cursor number to use */
105399:   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
105400: 
105401:   /* If nIncr is less than zero, then check at runtime if there are any
105402:   ** outstanding constraints to resolve. If there are not, there is no need
105403:   ** to check if deleting this row resolves any outstanding violations.
105404:   **
105405:   ** Check if any of the key columns in the child table row are NULL. If 
105406:   ** any are, then the constraint is considered satisfied. No need to 
105407:   ** search for a matching row in the parent table.  */
105408:   if( nIncr<0 ){
105409:     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
105410:     VdbeCoverage(v);
105411:   }
105412:   for(i=0; i<pFKey->nCol; i++){
105413:     int iReg = aiCol[i] + regData + 1;
105414:     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
105415:   }
105416: 
105417:   if( isIgnore==0 ){
105418:     if( pIdx==0 ){
105419:       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
105420:       ** column of the parent table (table pTab).  */
105421:       int iMustBeInt;               /* Address of MustBeInt instruction */
105422:       int regTemp = sqlite3GetTempReg(pParse);
105423:   
105424:       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
105425:       ** apply the affinity of the parent key). If this fails, then there
105426:       ** is no matching parent key. Before using MustBeInt, make a copy of
105427:       ** the value. Otherwise, the value inserted into the child key column
105428:       ** will have INTEGER affinity applied to it, which may not be correct.  */
105429:       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
105430:       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
105431:       VdbeCoverage(v);
105432:   
105433:       /* If the parent table is the same as the child table, and we are about
105434:       ** to increment the constraint-counter (i.e. this is an INSERT operation),
105435:       ** then check if the row being inserted matches itself. If so, do not
105436:       ** increment the constraint-counter.  */
105437:       if( pTab==pFKey->pFrom && nIncr==1 ){
105438:         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
105439:         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
105440:       }
105441:   
105442:       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
105443:       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
105444:       sqlite3VdbeGoto(v, iOk);
105445:       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
105446:       sqlite3VdbeJumpHere(v, iMustBeInt);
105447:       sqlite3ReleaseTempReg(pParse, regTemp);
105448:     }else{
105449:       int nCol = pFKey->nCol;
105450:       int regTemp = sqlite3GetTempRange(pParse, nCol);
105451:       int regRec = sqlite3GetTempReg(pParse);
105452:   
105453:       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
105454:       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
105455:       for(i=0; i<nCol; i++){
105456:         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
105457:       }
105458:   
105459:       /* If the parent table is the same as the child table, and we are about
105460:       ** to increment the constraint-counter (i.e. this is an INSERT operation),
105461:       ** then check if the row being inserted matches itself. If so, do not
105462:       ** increment the constraint-counter. 
105463:       **
105464:       ** If any of the parent-key values are NULL, then the row cannot match 
105465:       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
105466:       ** of the parent-key values are NULL (at this point it is known that
105467:       ** none of the child key values are).
105468:       */
105469:       if( pTab==pFKey->pFrom && nIncr==1 ){
105470:         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
105471:         for(i=0; i<nCol; i++){
105472:           int iChild = aiCol[i]+1+regData;
105473:           int iParent = pIdx->aiColumn[i]+1+regData;
105474:           assert( pIdx->aiColumn[i]>=0 );
105475:           assert( aiCol[i]!=pTab->iPKey );
105476:           if( pIdx->aiColumn[i]==pTab->iPKey ){
105477:             /* The parent key is a composite key that includes the IPK column */
105478:             iParent = regData;
105479:           }
105480:           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
105481:           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
105482:         }
105483:         sqlite3VdbeGoto(v, iOk);
105484:       }
105485:   
105486:       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
105487:                         sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
105488:       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
105489:   
105490:       sqlite3ReleaseTempReg(pParse, regRec);
105491:       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
105492:     }
105493:   }
105494: 
105495:   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
105496:    && !pParse->pToplevel 
105497:    && !pParse->isMultiWrite 
105498:   ){
105499:     /* Special case: If this is an INSERT statement that will insert exactly
105500:     ** one row into the table, raise a constraint immediately instead of
105501:     ** incrementing a counter. This is necessary as the VM code is being
105502:     ** generated for will not open a statement transaction.  */
105503:     assert( nIncr==1 );
105504:     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
105505:         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
105506:   }else{
105507:     if( nIncr>0 && pFKey->isDeferred==0 ){
105508:       sqlite3MayAbort(pParse);
105509:     }
105510:     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
105511:   }
105512: 
105513:   sqlite3VdbeResolveLabel(v, iOk);
105514:   sqlite3VdbeAddOp1(v, OP_Close, iCur);
105515: }
105516: 
105517: 
105518: /*
105519: ** Return an Expr object that refers to a memory register corresponding
105520: ** to column iCol of table pTab.
105521: **
105522: ** regBase is the first of an array of register that contains the data
105523: ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
105524: ** column.  regBase+2 holds the second column, and so forth.
105525: */
105526: static Expr *exprTableRegister(
105527:   Parse *pParse,     /* Parsing and code generating context */
105528:   Table *pTab,       /* The table whose content is at r[regBase]... */
105529:   int regBase,       /* Contents of table pTab */
105530:   i16 iCol           /* Which column of pTab is desired */
105531: ){
105532:   Expr *pExpr;
105533:   Column *pCol;
105534:   const char *zColl;
105535:   sqlite3 *db = pParse->db;
105536: 
105537:   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
105538:   if( pExpr ){
105539:     if( iCol>=0 && iCol!=pTab->iPKey ){
105540:       pCol = &pTab->aCol[iCol];
105541:       pExpr->iTable = regBase + iCol + 1;
105542:       pExpr->affinity = pCol->affinity;
105543:       zColl = pCol->zColl;
105544:       if( zColl==0 ) zColl = db->pDfltColl->zName;
105545:       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
105546:     }else{
105547:       pExpr->iTable = regBase;
105548:       pExpr->affinity = SQLITE_AFF_INTEGER;
105549:     }
105550:   }
105551:   return pExpr;
105552: }
105553: 
105554: /*
105555: ** Return an Expr object that refers to column iCol of table pTab which
105556: ** has cursor iCur.
105557: */
105558: static Expr *exprTableColumn(
105559:   sqlite3 *db,      /* The database connection */
105560:   Table *pTab,      /* The table whose column is desired */
105561:   int iCursor,      /* The open cursor on the table */
105562:   i16 iCol          /* The column that is wanted */
105563: ){
105564:   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
105565:   if( pExpr ){
105566:     pExpr->pTab = pTab;
105567:     pExpr->iTable = iCursor;
105568:     pExpr->iColumn = iCol;
105569:   }
105570:   return pExpr;
105571: }
105572: 
105573: /*
105574: ** This function is called to generate code executed when a row is deleted
105575: ** from the parent table of foreign key constraint pFKey and, if pFKey is 
105576: ** deferred, when a row is inserted into the same table. When generating
105577: ** code for an SQL UPDATE operation, this function may be called twice -
105578: ** once to "delete" the old row and once to "insert" the new row.
105579: **
105580: ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
105581: ** the number of FK violations in the db) or +1 when deleting one (as this
105582: ** may increase the number of FK constraint problems).
105583: **
105584: ** The code generated by this function scans through the rows in the child
105585: ** table that correspond to the parent table row being deleted or inserted.
105586: ** For each child row found, one of the following actions is taken:
105587: **
105588: **   Operation | FK type   | Action taken
105589: **   --------------------------------------------------------------------------
105590: **   DELETE      immediate   Increment the "immediate constraint counter".
105591: **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
105592: **                           throw a "FOREIGN KEY constraint failed" exception.
105593: **
105594: **   INSERT      immediate   Decrement the "immediate constraint counter".
105595: **
105596: **   DELETE      deferred    Increment the "deferred constraint counter".
105597: **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
105598: **                           throw a "FOREIGN KEY constraint failed" exception.
105599: **
105600: **   INSERT      deferred    Decrement the "deferred constraint counter".
105601: **
105602: ** These operations are identified in the comment at the top of this file 
105603: ** (fkey.c) as "I.2" and "D.2".
105604: */
105605: static void fkScanChildren(
105606:   Parse *pParse,                  /* Parse context */
105607:   SrcList *pSrc,                  /* The child table to be scanned */
105608:   Table *pTab,                    /* The parent table */
105609:   Index *pIdx,                    /* Index on parent covering the foreign key */
105610:   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
105611:   int *aiCol,                     /* Map from pIdx cols to child table cols */
105612:   int regData,                    /* Parent row data starts here */
105613:   int nIncr                       /* Amount to increment deferred counter by */
105614: ){
105615:   sqlite3 *db = pParse->db;       /* Database handle */
105616:   int i;                          /* Iterator variable */
105617:   Expr *pWhere = 0;               /* WHERE clause to scan with */
105618:   NameContext sNameContext;       /* Context used to resolve WHERE clause */
105619:   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
105620:   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
105621:   Vdbe *v = sqlite3GetVdbe(pParse);
105622: 
105623:   assert( pIdx==0 || pIdx->pTable==pTab );
105624:   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
105625:   assert( pIdx!=0 || pFKey->nCol==1 );
105626:   assert( pIdx!=0 || HasRowid(pTab) );
105627: 
105628:   if( nIncr<0 ){
105629:     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
105630:     VdbeCoverage(v);
105631:   }
105632: 
105633:   /* Create an Expr object representing an SQL expression like:
105634:   **
105635:   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
105636:   **
105637:   ** The collation sequence used for the comparison should be that of
105638:   ** the parent key columns. The affinity of the parent key column should
105639:   ** be applied to each child key value before the comparison takes place.
105640:   */
105641:   for(i=0; i<pFKey->nCol; i++){
105642:     Expr *pLeft;                  /* Value from parent table row */
105643:     Expr *pRight;                 /* Column ref to child table */
105644:     Expr *pEq;                    /* Expression (pLeft = pRight) */
105645:     i16 iCol;                     /* Index of column in child table */ 
105646:     const char *zCol;             /* Name of column in child table */
105647: 
105648:     iCol = pIdx ? pIdx->aiColumn[i] : -1;
105649:     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
105650:     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
105651:     assert( iCol>=0 );
105652:     zCol = pFKey->pFrom->aCol[iCol].zName;
105653:     pRight = sqlite3Expr(db, TK_ID, zCol);
105654:     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
105655:     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
105656:   }
105657: 
105658:   /* If the child table is the same as the parent table, then add terms
105659:   ** to the WHERE clause that prevent this entry from being scanned.
105660:   ** The added WHERE clause terms are like this:
105661:   **
105662:   **     $current_rowid!=rowid
105663:   **     NOT( $current_a==a AND $current_b==b AND ... )
105664:   **
105665:   ** The first form is used for rowid tables.  The second form is used
105666:   ** for WITHOUT ROWID tables.  In the second form, the primary key is
105667:   ** (a,b,...)
105668:   */
105669:   if( pTab==pFKey->pFrom && nIncr>0 ){
105670:     Expr *pNe;                    /* Expression (pLeft != pRight) */
105671:     Expr *pLeft;                  /* Value from parent table row */
105672:     Expr *pRight;                 /* Column ref to child table */
105673:     if( HasRowid(pTab) ){
105674:       pLeft = exprTableRegister(pParse, pTab, regData, -1);
105675:       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
105676:       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
105677:     }else{
105678:       Expr *pEq, *pAll = 0;
105679:       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
105680:       assert( pIdx!=0 );
105681:       for(i=0; i<pPk->nKeyCol; i++){
105682:         i16 iCol = pIdx->aiColumn[i];
105683:         assert( iCol>=0 );
105684:         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
105685:         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
105686:         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
105687:         pAll = sqlite3ExprAnd(db, pAll, pEq);
105688:       }
105689:       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
105690:     }
105691:     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
105692:   }
105693: 
105694:   /* Resolve the references in the WHERE clause. */
105695:   memset(&sNameContext, 0, sizeof(NameContext));
105696:   sNameContext.pSrcList = pSrc;
105697:   sNameContext.pParse = pParse;
105698:   sqlite3ResolveExprNames(&sNameContext, pWhere);
105699: 
105700:   /* Create VDBE to loop through the entries in pSrc that match the WHERE
105701:   ** clause. For each row found, increment either the deferred or immediate
105702:   ** foreign key constraint counter. */
105703:   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
105704:   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
105705:   if( pWInfo ){
105706:     sqlite3WhereEnd(pWInfo);
105707:   }
105708: 
105709:   /* Clean up the WHERE clause constructed above. */
105710:   sqlite3ExprDelete(db, pWhere);
105711:   if( iFkIfZero ){
105712:     sqlite3VdbeJumpHere(v, iFkIfZero);
105713:   }
105714: }
105715: 
105716: /*
105717: ** This function returns a linked list of FKey objects (connected by
105718: ** FKey.pNextTo) holding all children of table pTab.  For example,
105719: ** given the following schema:
105720: **
105721: **   CREATE TABLE t1(a PRIMARY KEY);
105722: **   CREATE TABLE t2(b REFERENCES t1(a);
105723: **
105724: ** Calling this function with table "t1" as an argument returns a pointer
105725: ** to the FKey structure representing the foreign key constraint on table
105726: ** "t2". Calling this function with "t2" as the argument would return a
105727: ** NULL pointer (as there are no FK constraints for which t2 is the parent
105728: ** table).
105729: */
105730: SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
105731:   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
105732: }
105733: 
105734: /*
105735: ** The second argument is a Trigger structure allocated by the 
105736: ** fkActionTrigger() routine. This function deletes the Trigger structure
105737: ** and all of its sub-components.
105738: **
105739: ** The Trigger structure or any of its sub-components may be allocated from
105740: ** the lookaside buffer belonging to database handle dbMem.
105741: */
105742: static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
105743:   if( p ){
105744:     TriggerStep *pStep = p->step_list;
105745:     sqlite3ExprDelete(dbMem, pStep->pWhere);
105746:     sqlite3ExprListDelete(dbMem, pStep->pExprList);
105747:     sqlite3SelectDelete(dbMem, pStep->pSelect);
105748:     sqlite3ExprDelete(dbMem, p->pWhen);
105749:     sqlite3DbFree(dbMem, p);
105750:   }
105751: }
105752: 
105753: /*
105754: ** This function is called to generate code that runs when table pTab is
105755: ** being dropped from the database. The SrcList passed as the second argument
105756: ** to this function contains a single entry guaranteed to resolve to
105757: ** table pTab.
105758: **
105759: ** Normally, no code is required. However, if either
105760: **
105761: **   (a) The table is the parent table of a FK constraint, or
105762: **   (b) The table is the child table of a deferred FK constraint and it is
105763: **       determined at runtime that there are outstanding deferred FK 
105764: **       constraint violations in the database,
105765: **
105766: ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
105767: ** the table from the database. Triggers are disabled while running this
105768: ** DELETE, but foreign key actions are not.
105769: */
105770: SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
105771:   sqlite3 *db = pParse->db;
105772:   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
105773:     int iSkip = 0;
105774:     Vdbe *v = sqlite3GetVdbe(pParse);
105775: 
105776:     assert( v );                  /* VDBE has already been allocated */
105777:     if( sqlite3FkReferences(pTab)==0 ){
105778:       /* Search for a deferred foreign key constraint for which this table
105779:       ** is the child table. If one cannot be found, return without 
105780:       ** generating any VDBE code. If one can be found, then jump over
105781:       ** the entire DELETE if there are no outstanding deferred constraints
105782:       ** when this statement is run.  */
105783:       FKey *p;
105784:       for(p=pTab->pFKey; p; p=p->pNextFrom){
105785:         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
105786:       }
105787:       if( !p ) return;
105788:       iSkip = sqlite3VdbeMakeLabel(v);
105789:       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
105790:     }
105791: 
105792:     pParse->disableTriggers = 1;
105793:     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
105794:     pParse->disableTriggers = 0;
105795: 
105796:     /* If the DELETE has generated immediate foreign key constraint 
105797:     ** violations, halt the VDBE and return an error at this point, before
105798:     ** any modifications to the schema are made. This is because statement
105799:     ** transactions are not able to rollback schema changes.  
105800:     **
105801:     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
105802:     ** the statement transaction will not be rolled back even if FK
105803:     ** constraints are violated.
105804:     */
105805:     if( (db->flags & SQLITE_DeferFKs)==0 ){
105806:       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
105807:       VdbeCoverage(v);
105808:       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
105809:           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
105810:     }
105811: 
105812:     if( iSkip ){
105813:       sqlite3VdbeResolveLabel(v, iSkip);
105814:     }
105815:   }
105816: }
105817: 
105818: 
105819: /*
105820: ** The second argument points to an FKey object representing a foreign key
105821: ** for which pTab is the child table. An UPDATE statement against pTab
105822: ** is currently being processed. For each column of the table that is 
105823: ** actually updated, the corresponding element in the aChange[] array
105824: ** is zero or greater (if a column is unmodified the corresponding element
105825: ** is set to -1). If the rowid column is modified by the UPDATE statement
105826: ** the bChngRowid argument is non-zero.
105827: **
105828: ** This function returns true if any of the columns that are part of the
105829: ** child key for FK constraint *p are modified.
105830: */
105831: static int fkChildIsModified(
105832:   Table *pTab,                    /* Table being updated */
105833:   FKey *p,                        /* Foreign key for which pTab is the child */
105834:   int *aChange,                   /* Array indicating modified columns */
105835:   int bChngRowid                  /* True if rowid is modified by this update */
105836: ){
105837:   int i;
105838:   for(i=0; i<p->nCol; i++){
105839:     int iChildKey = p->aCol[i].iFrom;
105840:     if( aChange[iChildKey]>=0 ) return 1;
105841:     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
105842:   }
105843:   return 0;
105844: }
105845: 
105846: /*
105847: ** The second argument points to an FKey object representing a foreign key
105848: ** for which pTab is the parent table. An UPDATE statement against pTab
105849: ** is currently being processed. For each column of the table that is 
105850: ** actually updated, the corresponding element in the aChange[] array
105851: ** is zero or greater (if a column is unmodified the corresponding element
105852: ** is set to -1). If the rowid column is modified by the UPDATE statement
105853: ** the bChngRowid argument is non-zero.
105854: **
105855: ** This function returns true if any of the columns that are part of the
105856: ** parent key for FK constraint *p are modified.
105857: */
105858: static int fkParentIsModified(
105859:   Table *pTab, 
105860:   FKey *p, 
105861:   int *aChange, 
105862:   int bChngRowid
105863: ){
105864:   int i;
105865:   for(i=0; i<p->nCol; i++){
105866:     char *zKey = p->aCol[i].zCol;
105867:     int iKey;
105868:     for(iKey=0; iKey<pTab->nCol; iKey++){
105869:       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
105870:         Column *pCol = &pTab->aCol[iKey];
105871:         if( zKey ){
105872:           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
105873:         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
105874:           return 1;
105875:         }
105876:       }
105877:     }
105878:   }
105879:   return 0;
105880: }
105881: 
105882: /*
105883: ** Return true if the parser passed as the first argument is being
105884: ** used to code a trigger that is really a "SET NULL" action belonging
105885: ** to trigger pFKey.
105886: */
105887: static int isSetNullAction(Parse *pParse, FKey *pFKey){
105888:   Parse *pTop = sqlite3ParseToplevel(pParse);
105889:   if( pTop->pTriggerPrg ){
105890:     Trigger *p = pTop->pTriggerPrg->pTrigger;
105891:     if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
105892:      || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
105893:     ){
105894:       return 1;
105895:     }
105896:   }
105897:   return 0;
105898: }
105899: 
105900: /*
105901: ** This function is called when inserting, deleting or updating a row of
105902: ** table pTab to generate VDBE code to perform foreign key constraint 
105903: ** processing for the operation.
105904: **
105905: ** For a DELETE operation, parameter regOld is passed the index of the
105906: ** first register in an array of (pTab->nCol+1) registers containing the
105907: ** rowid of the row being deleted, followed by each of the column values
105908: ** of the row being deleted, from left to right. Parameter regNew is passed
105909: ** zero in this case.
105910: **
105911: ** For an INSERT operation, regOld is passed zero and regNew is passed the
105912: ** first register of an array of (pTab->nCol+1) registers containing the new
105913: ** row data.
105914: **
105915: ** For an UPDATE operation, this function is called twice. Once before
105916: ** the original record is deleted from the table using the calling convention
105917: ** described for DELETE. Then again after the original record is deleted
105918: ** but before the new record is inserted using the INSERT convention. 
105919: */
105920: SQLITE_PRIVATE void sqlite3FkCheck(
105921:   Parse *pParse,                  /* Parse context */
105922:   Table *pTab,                    /* Row is being deleted from this table */ 
105923:   int regOld,                     /* Previous row data is stored here */
105924:   int regNew,                     /* New row data is stored here */
105925:   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
105926:   int bChngRowid                  /* True if rowid is UPDATEd */
105927: ){
105928:   sqlite3 *db = pParse->db;       /* Database handle */
105929:   FKey *pFKey;                    /* Used to iterate through FKs */
105930:   int iDb;                        /* Index of database containing pTab */
105931:   const char *zDb;                /* Name of database containing pTab */
105932:   int isIgnoreErrors = pParse->disableTriggers;
105933: 
105934:   /* Exactly one of regOld and regNew should be non-zero. */
105935:   assert( (regOld==0)!=(regNew==0) );
105936: 
105937:   /* If foreign-keys are disabled, this function is a no-op. */
105938:   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
105939: 
105940:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105941:   zDb = db->aDb[iDb].zName;
105942: 
105943:   /* Loop through all the foreign key constraints for which pTab is the
105944:   ** child table (the table that the foreign key definition is part of).  */
105945:   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
105946:     Table *pTo;                   /* Parent table of foreign key pFKey */
105947:     Index *pIdx = 0;              /* Index on key columns in pTo */
105948:     int *aiFree = 0;
105949:     int *aiCol;
105950:     int iCol;
105951:     int i;
105952:     int bIgnore = 0;
105953: 
105954:     if( aChange 
105955:      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
105956:      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 
105957:     ){
105958:       continue;
105959:     }
105960: 
105961:     /* Find the parent table of this foreign key. Also find a unique index 
105962:     ** on the parent key columns in the parent table. If either of these 
105963:     ** schema items cannot be located, set an error in pParse and return 
105964:     ** early.  */
105965:     if( pParse->disableTriggers ){
105966:       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
105967:     }else{
105968:       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
105969:     }
105970:     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
105971:       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
105972:       if( !isIgnoreErrors || db->mallocFailed ) return;
105973:       if( pTo==0 ){
105974:         /* If isIgnoreErrors is true, then a table is being dropped. In this
105975:         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
105976:         ** before actually dropping it in order to check FK constraints.
105977:         ** If the parent table of an FK constraint on the current table is
105978:         ** missing, behave as if it is empty. i.e. decrement the relevant
105979:         ** FK counter for each row of the current table with non-NULL keys.
105980:         */
105981:         Vdbe *v = sqlite3GetVdbe(pParse);
105982:         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
105983:         for(i=0; i<pFKey->nCol; i++){
105984:           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
105985:           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
105986:         }
105987:         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
105988:       }
105989:       continue;
105990:     }
105991:     assert( pFKey->nCol==1 || (aiFree && pIdx) );
105992: 
105993:     if( aiFree ){
105994:       aiCol = aiFree;
105995:     }else{
105996:       iCol = pFKey->aCol[0].iFrom;
105997:       aiCol = &iCol;
105998:     }
105999:     for(i=0; i<pFKey->nCol; i++){
106000:       if( aiCol[i]==pTab->iPKey ){
106001:         aiCol[i] = -1;
106002:       }
106003:       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
106004: #ifndef SQLITE_OMIT_AUTHORIZATION
106005:       /* Request permission to read the parent key columns. If the 
106006:       ** authorization callback returns SQLITE_IGNORE, behave as if any
106007:       ** values read from the parent table are NULL. */
106008:       if( db->xAuth ){
106009:         int rcauth;
106010:         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
106011:         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
106012:         bIgnore = (rcauth==SQLITE_IGNORE);
106013:       }
106014: #endif
106015:     }
106016: 
106017:     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
106018:     ** a cursor to use to search the unique index on the parent key columns 
106019:     ** in the parent table.  */
106020:     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
106021:     pParse->nTab++;
106022: 
106023:     if( regOld!=0 ){
106024:       /* A row is being removed from the child table. Search for the parent.
106025:       ** If the parent does not exist, removing the child row resolves an 
106026:       ** outstanding foreign key constraint violation. */
106027:       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
106028:     }
106029:     if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
106030:       /* A row is being added to the child table. If a parent row cannot
106031:       ** be found, adding the child row has violated the FK constraint. 
106032:       **
106033:       ** If this operation is being performed as part of a trigger program
106034:       ** that is actually a "SET NULL" action belonging to this very 
106035:       ** foreign key, then omit this scan altogether. As all child key
106036:       ** values are guaranteed to be NULL, it is not possible for adding
106037:       ** this row to cause an FK violation.  */
106038:       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
106039:     }
106040: 
106041:     sqlite3DbFree(db, aiFree);
106042:   }
106043: 
106044:   /* Loop through all the foreign key constraints that refer to this table.
106045:   ** (the "child" constraints) */
106046:   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106047:     Index *pIdx = 0;              /* Foreign key index for pFKey */
106048:     SrcList *pSrc;
106049:     int *aiCol = 0;
106050: 
106051:     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
106052:       continue;
106053:     }
106054: 
106055:     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) 
106056:      && !pParse->pToplevel && !pParse->isMultiWrite 
106057:     ){
106058:       assert( regOld==0 && regNew!=0 );
106059:       /* Inserting a single row into a parent table cannot cause (or fix)
106060:       ** an immediate foreign key violation. So do nothing in this case.  */
106061:       continue;
106062:     }
106063: 
106064:     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
106065:       if( !isIgnoreErrors || db->mallocFailed ) return;
106066:       continue;
106067:     }
106068:     assert( aiCol || pFKey->nCol==1 );
106069: 
106070:     /* Create a SrcList structure containing the child table.  We need the
106071:     ** child table as a SrcList for sqlite3WhereBegin() */
106072:     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
106073:     if( pSrc ){
106074:       struct SrcList_item *pItem = pSrc->a;
106075:       pItem->pTab = pFKey->pFrom;
106076:       pItem->zName = pFKey->pFrom->zName;
106077:       pItem->pTab->nRef++;
106078:       pItem->iCursor = pParse->nTab++;
106079:   
106080:       if( regNew!=0 ){
106081:         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
106082:       }
106083:       if( regOld!=0 ){
106084:         int eAction = pFKey->aAction[aChange!=0];
106085:         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
106086:         /* If this is a deferred FK constraint, or a CASCADE or SET NULL
106087:         ** action applies, then any foreign key violations caused by
106088:         ** removing the parent key will be rectified by the action trigger.
106089:         ** So do not set the "may-abort" flag in this case.
106090:         **
106091:         ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
106092:         ** may-abort flag will eventually be set on this statement anyway
106093:         ** (when this function is called as part of processing the UPDATE
106094:         ** within the action trigger).
106095:         **
106096:         ** Note 2: At first glance it may seem like SQLite could simply omit
106097:         ** all OP_FkCounter related scans when either CASCADE or SET NULL
106098:         ** applies. The trouble starts if the CASCADE or SET NULL action 
106099:         ** trigger causes other triggers or action rules attached to the 
106100:         ** child table to fire. In these cases the fk constraint counters
106101:         ** might be set incorrectly if any OP_FkCounter related scans are 
106102:         ** omitted.  */
106103:         if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
106104:           sqlite3MayAbort(pParse);
106105:         }
106106:       }
106107:       pItem->zName = 0;
106108:       sqlite3SrcListDelete(db, pSrc);
106109:     }
106110:     sqlite3DbFree(db, aiCol);
106111:   }
106112: }
106113: 
106114: #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
106115: 
106116: /*
106117: ** This function is called before generating code to update or delete a 
106118: ** row contained in table pTab.
106119: */
106120: SQLITE_PRIVATE u32 sqlite3FkOldmask(
106121:   Parse *pParse,                  /* Parse context */
106122:   Table *pTab                     /* Table being modified */
106123: ){
106124:   u32 mask = 0;
106125:   if( pParse->db->flags&SQLITE_ForeignKeys ){
106126:     FKey *p;
106127:     int i;
106128:     for(p=pTab->pFKey; p; p=p->pNextFrom){
106129:       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
106130:     }
106131:     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
106132:       Index *pIdx = 0;
106133:       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
106134:       if( pIdx ){
106135:         for(i=0; i<pIdx->nKeyCol; i++){
106136:           assert( pIdx->aiColumn[i]>=0 );
106137:           mask |= COLUMN_MASK(pIdx->aiColumn[i]);
106138:         }
106139:       }
106140:     }
106141:   }
106142:   return mask;
106143: }
106144: 
106145: 
106146: /*
106147: ** This function is called before generating code to update or delete a 
106148: ** row contained in table pTab. If the operation is a DELETE, then
106149: ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
106150: ** to an array of size N, where N is the number of columns in table pTab.
106151: ** If the i'th column is not modified by the UPDATE, then the corresponding 
106152: ** entry in the aChange[] array is set to -1. If the column is modified,
106153: ** the value is 0 or greater. Parameter chngRowid is set to true if the
106154: ** UPDATE statement modifies the rowid fields of the table.
106155: **
106156: ** If any foreign key processing will be required, this function returns
106157: ** true. If there is no foreign key related processing, this function 
106158: ** returns false.
106159: */
106160: SQLITE_PRIVATE int sqlite3FkRequired(
106161:   Parse *pParse,                  /* Parse context */
106162:   Table *pTab,                    /* Table being modified */
106163:   int *aChange,                   /* Non-NULL for UPDATE operations */
106164:   int chngRowid                   /* True for UPDATE that affects rowid */
106165: ){
106166:   if( pParse->db->flags&SQLITE_ForeignKeys ){
106167:     if( !aChange ){
106168:       /* A DELETE operation. Foreign key processing is required if the 
106169:       ** table in question is either the child or parent table for any 
106170:       ** foreign key constraint.  */
106171:       return (sqlite3FkReferences(pTab) || pTab->pFKey);
106172:     }else{
106173:       /* This is an UPDATE. Foreign key processing is only required if the
106174:       ** operation modifies one or more child or parent key columns. */
106175:       FKey *p;
106176: 
106177:       /* Check if any child key columns are being modified. */
106178:       for(p=pTab->pFKey; p; p=p->pNextFrom){
106179:         if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
106180:       }
106181: 
106182:       /* Check if any parent key columns are being modified. */
106183:       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
106184:         if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
106185:       }
106186:     }
106187:   }
106188:   return 0;
106189: }
106190: 
106191: /*
106192: ** This function is called when an UPDATE or DELETE operation is being 
106193: ** compiled on table pTab, which is the parent table of foreign-key pFKey.
106194: ** If the current operation is an UPDATE, then the pChanges parameter is
106195: ** passed a pointer to the list of columns being modified. If it is a
106196: ** DELETE, pChanges is passed a NULL pointer.
106197: **
106198: ** It returns a pointer to a Trigger structure containing a trigger
106199: ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
106200: ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
106201: ** returned (these actions require no special handling by the triggers
106202: ** sub-system, code for them is created by fkScanChildren()).
106203: **
106204: ** For example, if pFKey is the foreign key and pTab is table "p" in 
106205: ** the following schema:
106206: **
106207: **   CREATE TABLE p(pk PRIMARY KEY);
106208: **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
106209: **
106210: ** then the returned trigger structure is equivalent to:
106211: **
106212: **   CREATE TRIGGER ... DELETE ON p BEGIN
106213: **     DELETE FROM c WHERE ck = old.pk;
106214: **   END;
106215: **
106216: ** The returned pointer is cached as part of the foreign key object. It
106217: ** is eventually freed along with the rest of the foreign key object by 
106218: ** sqlite3FkDelete().
106219: */
106220: static Trigger *fkActionTrigger(
106221:   Parse *pParse,                  /* Parse context */
106222:   Table *pTab,                    /* Table being updated or deleted from */
106223:   FKey *pFKey,                    /* Foreign key to get action for */
106224:   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
106225: ){
106226:   sqlite3 *db = pParse->db;       /* Database handle */
106227:   int action;                     /* One of OE_None, OE_Cascade etc. */
106228:   Trigger *pTrigger;              /* Trigger definition to return */
106229:   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
106230: 
106231:   action = pFKey->aAction[iAction];
106232:   if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
106233:     return 0;
106234:   }
106235:   pTrigger = pFKey->apTrigger[iAction];
106236: 
106237:   if( action!=OE_None && !pTrigger ){
106238:     char const *zFrom;            /* Name of child table */
106239:     int nFrom;                    /* Length in bytes of zFrom */
106240:     Index *pIdx = 0;              /* Parent key index for this FK */
106241:     int *aiCol = 0;               /* child table cols -> parent key cols */
106242:     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
106243:     Expr *pWhere = 0;             /* WHERE clause of trigger step */
106244:     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
106245:     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
106246:     int i;                        /* Iterator variable */
106247:     Expr *pWhen = 0;              /* WHEN clause for the trigger */
106248: 
106249:     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
106250:     assert( aiCol || pFKey->nCol==1 );
106251: 
106252:     for(i=0; i<pFKey->nCol; i++){
106253:       Token tOld = { "old", 3 };  /* Literal "old" token */
106254:       Token tNew = { "new", 3 };  /* Literal "new" token */
106255:       Token tFromCol;             /* Name of column in child table */
106256:       Token tToCol;               /* Name of column in parent table */
106257:       int iFromCol;               /* Idx of column in child table */
106258:       Expr *pEq;                  /* tFromCol = OLD.tToCol */
106259: 
106260:       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
106261:       assert( iFromCol>=0 );
106262:       assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
106263:       assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
106264:       sqlite3TokenInit(&tToCol,
106265:                    pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
106266:       sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
106267: 
106268:       /* Create the expression "OLD.zToCol = zFromCol". It is important
106269:       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
106270:       ** that the affinity and collation sequence associated with the
106271:       ** parent table are used for the comparison. */
106272:       pEq = sqlite3PExpr(pParse, TK_EQ,
106273:           sqlite3PExpr(pParse, TK_DOT, 
106274:             sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
106275:             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
106276:           , 0),
106277:           sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
106278:       , 0);
106279:       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
106280: 
106281:       /* For ON UPDATE, construct the next term of the WHEN clause.
106282:       ** The final WHEN clause will be like this:
106283:       **
106284:       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
106285:       */
106286:       if( pChanges ){
106287:         pEq = sqlite3PExpr(pParse, TK_IS,
106288:             sqlite3PExpr(pParse, TK_DOT, 
106289:               sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
106290:               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
106291:               0),
106292:             sqlite3PExpr(pParse, TK_DOT, 
106293:               sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
106294:               sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
106295:               0),
106296:             0);
106297:         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
106298:       }
106299:   
106300:       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
106301:         Expr *pNew;
106302:         if( action==OE_Cascade ){
106303:           pNew = sqlite3PExpr(pParse, TK_DOT, 
106304:             sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
106305:             sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
106306:           , 0);
106307:         }else if( action==OE_SetDflt ){
106308:           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
106309:           if( pDflt ){
106310:             pNew = sqlite3ExprDup(db, pDflt, 0);
106311:           }else{
106312:             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
106313:           }
106314:         }else{
106315:           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
106316:         }
106317:         pList = sqlite3ExprListAppend(pParse, pList, pNew);
106318:         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
106319:       }
106320:     }
106321:     sqlite3DbFree(db, aiCol);
106322: 
106323:     zFrom = pFKey->pFrom->zName;
106324:     nFrom = sqlite3Strlen30(zFrom);
106325: 
106326:     if( action==OE_Restrict ){
106327:       Token tFrom;
106328:       Expr *pRaise; 
106329: 
106330:       tFrom.z = zFrom;
106331:       tFrom.n = nFrom;
106332:       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
106333:       if( pRaise ){
106334:         pRaise->affinity = OE_Abort;
106335:       }
106336:       pSelect = sqlite3SelectNew(pParse, 
106337:           sqlite3ExprListAppend(pParse, 0, pRaise),
106338:           sqlite3SrcListAppend(db, 0, &tFrom, 0),
106339:           pWhere,
106340:           0, 0, 0, 0, 0, 0
106341:       );
106342:       pWhere = 0;
106343:     }
106344: 
106345:     /* Disable lookaside memory allocation */
106346:     db->lookaside.bDisable++;
106347: 
106348:     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
106349:         sizeof(Trigger) +         /* struct Trigger */
106350:         sizeof(TriggerStep) +     /* Single step in trigger program */
106351:         nFrom + 1                 /* Space for pStep->zTarget */
106352:     );
106353:     if( pTrigger ){
106354:       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
106355:       pStep->zTarget = (char *)&pStep[1];
106356:       memcpy((char *)pStep->zTarget, zFrom, nFrom);
106357:   
106358:       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
106359:       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
106360:       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
106361:       if( pWhen ){
106362:         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
106363:         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
106364:       }
106365:     }
106366: 
106367:     /* Re-enable the lookaside buffer, if it was disabled earlier. */
106368:     db->lookaside.bDisable--;
106369: 
106370:     sqlite3ExprDelete(db, pWhere);
106371:     sqlite3ExprDelete(db, pWhen);
106372:     sqlite3ExprListDelete(db, pList);
106373:     sqlite3SelectDelete(db, pSelect);
106374:     if( db->mallocFailed==1 ){
106375:       fkTriggerDelete(db, pTrigger);
106376:       return 0;
106377:     }
106378:     assert( pStep!=0 );
106379: 
106380:     switch( action ){
106381:       case OE_Restrict:
106382:         pStep->op = TK_SELECT; 
106383:         break;
106384:       case OE_Cascade: 
106385:         if( !pChanges ){ 
106386:           pStep->op = TK_DELETE; 
106387:           break; 
106388:         }
106389:       default:
106390:         pStep->op = TK_UPDATE;
106391:     }
106392:     pStep->pTrig = pTrigger;
106393:     pTrigger->pSchema = pTab->pSchema;
106394:     pTrigger->pTabSchema = pTab->pSchema;
106395:     pFKey->apTrigger[iAction] = pTrigger;
106396:     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
106397:   }
106398: 
106399:   return pTrigger;
106400: }
106401: 
106402: /*
106403: ** This function is called when deleting or updating a row to implement
106404: ** any required CASCADE, SET NULL or SET DEFAULT actions.
106405: */
106406: SQLITE_PRIVATE void sqlite3FkActions(
106407:   Parse *pParse,                  /* Parse context */
106408:   Table *pTab,                    /* Table being updated or deleted from */
106409:   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
106410:   int regOld,                     /* Address of array containing old row */
106411:   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
106412:   int bChngRowid                  /* True if rowid is UPDATEd */
106413: ){
106414:   /* If foreign-key support is enabled, iterate through all FKs that 
106415:   ** refer to table pTab. If there is an action associated with the FK 
106416:   ** for this operation (either update or delete), invoke the associated 
106417:   ** trigger sub-program.  */
106418:   if( pParse->db->flags&SQLITE_ForeignKeys ){
106419:     FKey *pFKey;                  /* Iterator variable */
106420:     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
106421:       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
106422:         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
106423:         if( pAct ){
106424:           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
106425:         }
106426:       }
106427:     }
106428:   }
106429: }
106430: 
106431: #endif /* ifndef SQLITE_OMIT_TRIGGER */
106432: 
106433: /*
106434: ** Free all memory associated with foreign key definitions attached to
106435: ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
106436: ** hash table.
106437: */
106438: SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
106439:   FKey *pFKey;                    /* Iterator variable */
106440:   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
106441: 
106442:   assert( db==0 || IsVirtual(pTab)
106443:          || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
106444:   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
106445: 
106446:     /* Remove the FK from the fkeyHash hash table. */
106447:     if( !db || db->pnBytesFreed==0 ){
106448:       if( pFKey->pPrevTo ){
106449:         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
106450:       }else{
106451:         void *p = (void *)pFKey->pNextTo;
106452:         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
106453:         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
106454:       }
106455:       if( pFKey->pNextTo ){
106456:         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
106457:       }
106458:     }
106459: 
106460:     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
106461:     ** classified as either immediate or deferred.
106462:     */
106463:     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
106464: 
106465:     /* Delete any triggers created to implement actions for this FK. */
106466: #ifndef SQLITE_OMIT_TRIGGER
106467:     fkTriggerDelete(db, pFKey->apTrigger[0]);
106468:     fkTriggerDelete(db, pFKey->apTrigger[1]);
106469: #endif
106470: 
106471:     pNext = pFKey->pNextFrom;
106472:     sqlite3DbFree(db, pFKey);
106473:   }
106474: }
106475: #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
106476: 
106477: /************** End of fkey.c ************************************************/
106478: /************** Begin file insert.c ******************************************/
106479: /*
106480: ** 2001 September 15
106481: **
106482: ** The author disclaims copyright to this source code.  In place of
106483: ** a legal notice, here is a blessing:
106484: **
106485: **    May you do good and not evil.
106486: **    May you find forgiveness for yourself and forgive others.
106487: **    May you share freely, never taking more than you give.
106488: **
106489: *************************************************************************
106490: ** This file contains C code routines that are called by the parser
106491: ** to handle INSERT statements in SQLite.
106492: */
106493: /* #include "sqliteInt.h" */
106494: 
106495: /*
106496: ** Generate code that will 
106497: **
106498: **   (1) acquire a lock for table pTab then
106499: **   (2) open pTab as cursor iCur.
106500: **
106501: ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
106502: ** for that table that is actually opened.
106503: */
106504: SQLITE_PRIVATE void sqlite3OpenTable(
106505:   Parse *pParse,  /* Generate code into this VDBE */
106506:   int iCur,       /* The cursor number of the table */
106507:   int iDb,        /* The database index in sqlite3.aDb[] */
106508:   Table *pTab,    /* The table to be opened */
106509:   int opcode      /* OP_OpenRead or OP_OpenWrite */
106510: ){
106511:   Vdbe *v;
106512:   assert( !IsVirtual(pTab) );
106513:   v = sqlite3GetVdbe(pParse);
106514:   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
106515:   sqlite3TableLock(pParse, iDb, pTab->tnum, 
106516:                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
106517:   if( HasRowid(pTab) ){
106518:     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
106519:     VdbeComment((v, "%s", pTab->zName));
106520:   }else{
106521:     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
106522:     assert( pPk!=0 );
106523:     assert( pPk->tnum==pTab->tnum );
106524:     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
106525:     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
106526:     VdbeComment((v, "%s", pTab->zName));
106527:   }
106528: }
106529: 
106530: /*
106531: ** Return a pointer to the column affinity string associated with index
106532: ** pIdx. A column affinity string has one character for each column in 
106533: ** the table, according to the affinity of the column:
106534: **
106535: **  Character      Column affinity
106536: **  ------------------------------
106537: **  'A'            BLOB
106538: **  'B'            TEXT
106539: **  'C'            NUMERIC
106540: **  'D'            INTEGER
106541: **  'F'            REAL
106542: **
106543: ** An extra 'D' is appended to the end of the string to cover the
106544: ** rowid that appears as the last column in every index.
106545: **
106546: ** Memory for the buffer containing the column index affinity string
106547: ** is managed along with the rest of the Index structure. It will be
106548: ** released when sqlite3DeleteIndex() is called.
106549: */
106550: SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
106551:   if( !pIdx->zColAff ){
106552:     /* The first time a column affinity string for a particular index is
106553:     ** required, it is allocated and populated here. It is then stored as
106554:     ** a member of the Index structure for subsequent use.
106555:     **
106556:     ** The column affinity string will eventually be deleted by
106557:     ** sqliteDeleteIndex() when the Index structure itself is cleaned
106558:     ** up.
106559:     */
106560:     int n;
106561:     Table *pTab = pIdx->pTable;
106562:     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
106563:     if( !pIdx->zColAff ){
106564:       sqlite3OomFault(db);
106565:       return 0;
106566:     }
106567:     for(n=0; n<pIdx->nColumn; n++){
106568:       i16 x = pIdx->aiColumn[n];
106569:       if( x>=0 ){
106570:         pIdx->zColAff[n] = pTab->aCol[x].affinity;
106571:       }else if( x==XN_ROWID ){
106572:         pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
106573:       }else{
106574:         char aff;
106575:         assert( x==XN_EXPR );
106576:         assert( pIdx->aColExpr!=0 );
106577:         aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
106578:         if( aff==0 ) aff = SQLITE_AFF_BLOB;
106579:         pIdx->zColAff[n] = aff;
106580:       }
106581:     }
106582:     pIdx->zColAff[n] = 0;
106583:   }
106584:  
106585:   return pIdx->zColAff;
106586: }
106587: 
106588: /*
106589: ** Compute the affinity string for table pTab, if it has not already been
106590: ** computed.  As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
106591: **
106592: ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
106593: ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
106594: ** for register iReg and following.  Or if affinities exists and iReg==0,
106595: ** then just set the P4 operand of the previous opcode (which should  be
106596: ** an OP_MakeRecord) to the affinity string.
106597: **
106598: ** A column affinity string has one character per column:
106599: **
106600: **  Character      Column affinity
106601: **  ------------------------------
106602: **  'A'            BLOB
106603: **  'B'            TEXT
106604: **  'C'            NUMERIC
106605: **  'D'            INTEGER
106606: **  'E'            REAL
106607: */
106608: SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
106609:   int i;
106610:   char *zColAff = pTab->zColAff;
106611:   if( zColAff==0 ){
106612:     sqlite3 *db = sqlite3VdbeDb(v);
106613:     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
106614:     if( !zColAff ){
106615:       sqlite3OomFault(db);
106616:       return;
106617:     }
106618: 
106619:     for(i=0; i<pTab->nCol; i++){
106620:       zColAff[i] = pTab->aCol[i].affinity;
106621:     }
106622:     do{
106623:       zColAff[i--] = 0;
106624:     }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
106625:     pTab->zColAff = zColAff;
106626:   }
106627:   i = sqlite3Strlen30(zColAff);
106628:   if( i ){
106629:     if( iReg ){
106630:       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
106631:     }else{
106632:       sqlite3VdbeChangeP4(v, -1, zColAff, i);
106633:     }
106634:   }
106635: }
106636: 
106637: /*
106638: ** Return non-zero if the table pTab in database iDb or any of its indices
106639: ** have been opened at any point in the VDBE program. This is used to see if 
106640: ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
106641: ** run without using a temporary table for the results of the SELECT. 
106642: */
106643: static int readsTable(Parse *p, int iDb, Table *pTab){
106644:   Vdbe *v = sqlite3GetVdbe(p);
106645:   int i;
106646:   int iEnd = sqlite3VdbeCurrentAddr(v);
106647: #ifndef SQLITE_OMIT_VIRTUALTABLE
106648:   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
106649: #endif
106650: 
106651:   for(i=1; i<iEnd; i++){
106652:     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
106653:     assert( pOp!=0 );
106654:     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
106655:       Index *pIndex;
106656:       int tnum = pOp->p2;
106657:       if( tnum==pTab->tnum ){
106658:         return 1;
106659:       }
106660:       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
106661:         if( tnum==pIndex->tnum ){
106662:           return 1;
106663:         }
106664:       }
106665:     }
106666: #ifndef SQLITE_OMIT_VIRTUALTABLE
106667:     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
106668:       assert( pOp->p4.pVtab!=0 );
106669:       assert( pOp->p4type==P4_VTAB );
106670:       return 1;
106671:     }
106672: #endif
106673:   }
106674:   return 0;
106675: }
106676: 
106677: #ifndef SQLITE_OMIT_AUTOINCREMENT
106678: /*
106679: ** Locate or create an AutoincInfo structure associated with table pTab
106680: ** which is in database iDb.  Return the register number for the register
106681: ** that holds the maximum rowid.
106682: **
106683: ** There is at most one AutoincInfo structure per table even if the
106684: ** same table is autoincremented multiple times due to inserts within
106685: ** triggers.  A new AutoincInfo structure is created if this is the
106686: ** first use of table pTab.  On 2nd and subsequent uses, the original
106687: ** AutoincInfo structure is used.
106688: **
106689: ** Three memory locations are allocated:
106690: **
106691: **   (1)  Register to hold the name of the pTab table.
106692: **   (2)  Register to hold the maximum ROWID of pTab.
106693: **   (3)  Register to hold the rowid in sqlite_sequence of pTab
106694: **
106695: ** The 2nd register is the one that is returned.  That is all the
106696: ** insert routine needs to know about.
106697: */
106698: static int autoIncBegin(
106699:   Parse *pParse,      /* Parsing context */
106700:   int iDb,            /* Index of the database holding pTab */
106701:   Table *pTab         /* The table we are writing to */
106702: ){
106703:   int memId = 0;      /* Register holding maximum rowid */
106704:   if( pTab->tabFlags & TF_Autoincrement ){
106705:     Parse *pToplevel = sqlite3ParseToplevel(pParse);
106706:     AutoincInfo *pInfo;
106707: 
106708:     pInfo = pToplevel->pAinc;
106709:     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
106710:     if( pInfo==0 ){
106711:       pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
106712:       if( pInfo==0 ) return 0;
106713:       pInfo->pNext = pToplevel->pAinc;
106714:       pToplevel->pAinc = pInfo;
106715:       pInfo->pTab = pTab;
106716:       pInfo->iDb = iDb;
106717:       pToplevel->nMem++;                  /* Register to hold name of table */
106718:       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
106719:       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
106720:     }
106721:     memId = pInfo->regCtr;
106722:   }
106723:   return memId;
106724: }
106725: 
106726: /*
106727: ** This routine generates code that will initialize all of the
106728: ** register used by the autoincrement tracker.  
106729: */
106730: SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
106731:   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
106732:   sqlite3 *db = pParse->db;  /* The database connection */
106733:   Db *pDb;                   /* Database only autoinc table */
106734:   int memId;                 /* Register holding max rowid */
106735:   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
106736: 
106737:   /* This routine is never called during trigger-generation.  It is
106738:   ** only called from the top-level */
106739:   assert( pParse->pTriggerTab==0 );
106740:   assert( sqlite3IsToplevel(pParse) );
106741: 
106742:   assert( v );   /* We failed long ago if this is not so */
106743:   for(p = pParse->pAinc; p; p = p->pNext){
106744:     static const int iLn = VDBE_OFFSET_LINENO(2);
106745:     static const VdbeOpList autoInc[] = {
106746:       /* 0  */ {OP_Null,    0,  0, 0},
106747:       /* 1  */ {OP_Rewind,  0,  9, 0},
106748:       /* 2  */ {OP_Column,  0,  0, 0},
106749:       /* 3  */ {OP_Ne,      0,  7, 0},
106750:       /* 4  */ {OP_Rowid,   0,  0, 0},
106751:       /* 5  */ {OP_Column,  0,  1, 0},
106752:       /* 6  */ {OP_Goto,    0,  9, 0},
106753:       /* 7  */ {OP_Next,    0,  2, 0},
106754:       /* 8  */ {OP_Integer, 0,  0, 0},
106755:       /* 9  */ {OP_Close,   0,  0, 0} 
106756:     };
106757:     VdbeOp *aOp;
106758:     pDb = &db->aDb[p->iDb];
106759:     memId = p->regCtr;
106760:     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106761:     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
106762:     sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
106763:     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
106764:     if( aOp==0 ) break;
106765:     aOp[0].p2 = memId;
106766:     aOp[0].p3 = memId+1;
106767:     aOp[2].p3 = memId;
106768:     aOp[3].p1 = memId-1;
106769:     aOp[3].p3 = memId;
106770:     aOp[3].p5 = SQLITE_JUMPIFNULL;
106771:     aOp[4].p2 = memId+1;
106772:     aOp[5].p3 = memId;
106773:     aOp[8].p2 = memId;
106774:   }
106775: }
106776: 
106777: /*
106778: ** Update the maximum rowid for an autoincrement calculation.
106779: **
106780: ** This routine should be called when the regRowid register holds a
106781: ** new rowid that is about to be inserted.  If that new rowid is
106782: ** larger than the maximum rowid in the memId memory cell, then the
106783: ** memory cell is updated.
106784: */
106785: static void autoIncStep(Parse *pParse, int memId, int regRowid){
106786:   if( memId>0 ){
106787:     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
106788:   }
106789: }
106790: 
106791: /*
106792: ** This routine generates the code needed to write autoincrement
106793: ** maximum rowid values back into the sqlite_sequence register.
106794: ** Every statement that might do an INSERT into an autoincrement
106795: ** table (either directly or through triggers) needs to call this
106796: ** routine just before the "exit" code.
106797: */
106798: static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
106799:   AutoincInfo *p;
106800:   Vdbe *v = pParse->pVdbe;
106801:   sqlite3 *db = pParse->db;
106802: 
106803:   assert( v );
106804:   for(p = pParse->pAinc; p; p = p->pNext){
106805:     static const int iLn = VDBE_OFFSET_LINENO(2);
106806:     static const VdbeOpList autoIncEnd[] = {
106807:       /* 0 */ {OP_NotNull,     0, 2, 0},
106808:       /* 1 */ {OP_NewRowid,    0, 0, 0},
106809:       /* 2 */ {OP_MakeRecord,  0, 2, 0},
106810:       /* 3 */ {OP_Insert,      0, 0, 0},
106811:       /* 4 */ {OP_Close,       0, 0, 0}
106812:     };
106813:     VdbeOp *aOp;
106814:     Db *pDb = &db->aDb[p->iDb];
106815:     int iRec;
106816:     int memId = p->regCtr;
106817: 
106818:     iRec = sqlite3GetTempReg(pParse);
106819:     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106820:     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
106821:     aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
106822:     if( aOp==0 ) break;
106823:     aOp[0].p1 = memId+1;
106824:     aOp[1].p2 = memId+1;
106825:     aOp[2].p1 = memId-1;
106826:     aOp[2].p3 = iRec;
106827:     aOp[3].p2 = iRec;
106828:     aOp[3].p3 = memId+1;
106829:     aOp[3].p5 = OPFLAG_APPEND;
106830:     sqlite3ReleaseTempReg(pParse, iRec);
106831:   }
106832: }
106833: SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
106834:   if( pParse->pAinc ) autoIncrementEnd(pParse);
106835: }
106836: #else
106837: /*
106838: ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
106839: ** above are all no-ops
106840: */
106841: # define autoIncBegin(A,B,C) (0)
106842: # define autoIncStep(A,B,C)
106843: #endif /* SQLITE_OMIT_AUTOINCREMENT */
106844: 
106845: 
106846: /* Forward declaration */
106847: static int xferOptimization(
106848:   Parse *pParse,        /* Parser context */
106849:   Table *pDest,         /* The table we are inserting into */
106850:   Select *pSelect,      /* A SELECT statement to use as the data source */
106851:   int onError,          /* How to handle constraint errors */
106852:   int iDbDest           /* The database of pDest */
106853: );
106854: 
106855: /*
106856: ** This routine is called to handle SQL of the following forms:
106857: **
106858: **    insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
106859: **    insert into TABLE (IDLIST) select
106860: **    insert into TABLE (IDLIST) default values
106861: **
106862: ** The IDLIST following the table name is always optional.  If omitted,
106863: ** then a list of all (non-hidden) columns for the table is substituted.
106864: ** The IDLIST appears in the pColumn parameter.  pColumn is NULL if IDLIST
106865: ** is omitted.
106866: **
106867: ** For the pSelect parameter holds the values to be inserted for the
106868: ** first two forms shown above.  A VALUES clause is really just short-hand
106869: ** for a SELECT statement that omits the FROM clause and everything else
106870: ** that follows.  If the pSelect parameter is NULL, that means that the
106871: ** DEFAULT VALUES form of the INSERT statement is intended.
106872: **
106873: ** The code generated follows one of four templates.  For a simple
106874: ** insert with data coming from a single-row VALUES clause, the code executes
106875: ** once straight down through.  Pseudo-code follows (we call this
106876: ** the "1st template"):
106877: **
106878: **         open write cursor to <table> and its indices
106879: **         put VALUES clause expressions into registers
106880: **         write the resulting record into <table>
106881: **         cleanup
106882: **
106883: ** The three remaining templates assume the statement is of the form
106884: **
106885: **   INSERT INTO <table> SELECT ...
106886: **
106887: ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
106888: ** in other words if the SELECT pulls all columns from a single table
106889: ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
106890: ** if <table2> and <table1> are distinct tables but have identical
106891: ** schemas, including all the same indices, then a special optimization
106892: ** is invoked that copies raw records from <table2> over to <table1>.
106893: ** See the xferOptimization() function for the implementation of this
106894: ** template.  This is the 2nd template.
106895: **
106896: **         open a write cursor to <table>
106897: **         open read cursor on <table2>
106898: **         transfer all records in <table2> over to <table>
106899: **         close cursors
106900: **         foreach index on <table>
106901: **           open a write cursor on the <table> index
106902: **           open a read cursor on the corresponding <table2> index
106903: **           transfer all records from the read to the write cursors
106904: **           close cursors
106905: **         end foreach
106906: **
106907: ** The 3rd template is for when the second template does not apply
106908: ** and the SELECT clause does not read from <table> at any time.
106909: ** The generated code follows this template:
106910: **
106911: **         X <- A
106912: **         goto B
106913: **      A: setup for the SELECT
106914: **         loop over the rows in the SELECT
106915: **           load values into registers R..R+n
106916: **           yield X
106917: **         end loop
106918: **         cleanup after the SELECT
106919: **         end-coroutine X
106920: **      B: open write cursor to <table> and its indices
106921: **      C: yield X, at EOF goto D
106922: **         insert the select result into <table> from R..R+n
106923: **         goto C
106924: **      D: cleanup
106925: **
106926: ** The 4th template is used if the insert statement takes its
106927: ** values from a SELECT but the data is being inserted into a table
106928: ** that is also read as part of the SELECT.  In the third form,
106929: ** we have to use an intermediate table to store the results of
106930: ** the select.  The template is like this:
106931: **
106932: **         X <- A
106933: **         goto B
106934: **      A: setup for the SELECT
106935: **         loop over the tables in the SELECT
106936: **           load value into register R..R+n
106937: **           yield X
106938: **         end loop
106939: **         cleanup after the SELECT
106940: **         end co-routine R
106941: **      B: open temp table
106942: **      L: yield X, at EOF goto M
106943: **         insert row from R..R+n into temp table
106944: **         goto L
106945: **      M: open write cursor to <table> and its indices
106946: **         rewind temp table
106947: **      C: loop over rows of intermediate table
106948: **           transfer values form intermediate table into <table>
106949: **         end loop
106950: **      D: cleanup
106951: */
106952: SQLITE_PRIVATE void sqlite3Insert(
106953:   Parse *pParse,        /* Parser context */
106954:   SrcList *pTabList,    /* Name of table into which we are inserting */
106955:   Select *pSelect,      /* A SELECT statement to use as the data source */
106956:   IdList *pColumn,      /* Column names corresponding to IDLIST. */
106957:   int onError           /* How to handle constraint errors */
106958: ){
106959:   sqlite3 *db;          /* The main database structure */
106960:   Table *pTab;          /* The table to insert into.  aka TABLE */
106961:   char *zTab;           /* Name of the table into which we are inserting */
106962:   const char *zDb;      /* Name of the database holding this table */
106963:   int i, j, idx;        /* Loop counters */
106964:   Vdbe *v;              /* Generate code into this virtual machine */
106965:   Index *pIdx;          /* For looping over indices of the table */
106966:   int nColumn;          /* Number of columns in the data */
106967:   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
106968:   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
106969:   int iIdxCur = 0;      /* First index cursor */
106970:   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
106971:   int endOfLoop;        /* Label for the end of the insertion loop */
106972:   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
106973:   int addrInsTop = 0;   /* Jump to label "D" */
106974:   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
106975:   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
106976:   int iDb;              /* Index of database holding TABLE */
106977:   Db *pDb;              /* The database containing table being inserted into */
106978:   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
106979:   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
106980:   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
106981:   u8 bIdListInOrder;    /* True if IDLIST is in table order */
106982:   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
106983: 
106984:   /* Register allocations */
106985:   int regFromSelect = 0;/* Base register for data coming from SELECT */
106986:   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
106987:   int regRowCount = 0;  /* Memory cell used for the row counter */
106988:   int regIns;           /* Block of regs holding rowid+data being inserted */
106989:   int regRowid;         /* registers holding insert rowid */
106990:   int regData;          /* register holding first column to insert */
106991:   int *aRegIdx = 0;     /* One register allocated to each index */
106992: 
106993: #ifndef SQLITE_OMIT_TRIGGER
106994:   int isView;                 /* True if attempting to insert into a view */
106995:   Trigger *pTrigger;          /* List of triggers on pTab, if required */
106996:   int tmask;                  /* Mask of trigger times */
106997: #endif
106998: 
106999:   db = pParse->db;
107000:   memset(&dest, 0, sizeof(dest));
107001:   if( pParse->nErr || db->mallocFailed ){
107002:     goto insert_cleanup;
107003:   }
107004: 
107005:   /* If the Select object is really just a simple VALUES() list with a
107006:   ** single row (the common case) then keep that one row of values
107007:   ** and discard the other (unused) parts of the pSelect object
107008:   */
107009:   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
107010:     pList = pSelect->pEList;
107011:     pSelect->pEList = 0;
107012:     sqlite3SelectDelete(db, pSelect);
107013:     pSelect = 0;
107014:   }
107015: 
107016:   /* Locate the table into which we will be inserting new information.
107017:   */
107018:   assert( pTabList->nSrc==1 );
107019:   zTab = pTabList->a[0].zName;
107020:   if( NEVER(zTab==0) ) goto insert_cleanup;
107021:   pTab = sqlite3SrcListLookup(pParse, pTabList);
107022:   if( pTab==0 ){
107023:     goto insert_cleanup;
107024:   }
107025:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107026:   assert( iDb<db->nDb );
107027:   pDb = &db->aDb[iDb];
107028:   zDb = pDb->zName;
107029:   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
107030:     goto insert_cleanup;
107031:   }
107032:   withoutRowid = !HasRowid(pTab);
107033: 
107034:   /* Figure out if we have any triggers and if the table being
107035:   ** inserted into is a view
107036:   */
107037: #ifndef SQLITE_OMIT_TRIGGER
107038:   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
107039:   isView = pTab->pSelect!=0;
107040: #else
107041: # define pTrigger 0
107042: # define tmask 0
107043: # define isView 0
107044: #endif
107045: #ifdef SQLITE_OMIT_VIEW
107046: # undef isView
107047: # define isView 0
107048: #endif
107049:   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
107050: 
107051:   /* If pTab is really a view, make sure it has been initialized.
107052:   ** ViewGetColumnNames() is a no-op if pTab is not a view.
107053:   */
107054:   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
107055:     goto insert_cleanup;
107056:   }
107057: 
107058:   /* Cannot insert into a read-only table.
107059:   */
107060:   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
107061:     goto insert_cleanup;
107062:   }
107063: 
107064:   /* Allocate a VDBE
107065:   */
107066:   v = sqlite3GetVdbe(pParse);
107067:   if( v==0 ) goto insert_cleanup;
107068:   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
107069:   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
107070: 
107071: #ifndef SQLITE_OMIT_XFER_OPT
107072:   /* If the statement is of the form
107073:   **
107074:   **       INSERT INTO <table1> SELECT * FROM <table2>;
107075:   **
107076:   ** Then special optimizations can be applied that make the transfer
107077:   ** very fast and which reduce fragmentation of indices.
107078:   **
107079:   ** This is the 2nd template.
107080:   */
107081:   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
107082:     assert( !pTrigger );
107083:     assert( pList==0 );
107084:     goto insert_end;
107085:   }
107086: #endif /* SQLITE_OMIT_XFER_OPT */
107087: 
107088:   /* If this is an AUTOINCREMENT table, look up the sequence number in the
107089:   ** sqlite_sequence table and store it in memory cell regAutoinc.
107090:   */
107091:   regAutoinc = autoIncBegin(pParse, iDb, pTab);
107092: 
107093:   /* Allocate registers for holding the rowid of the new row,
107094:   ** the content of the new row, and the assembled row record.
107095:   */
107096:   regRowid = regIns = pParse->nMem+1;
107097:   pParse->nMem += pTab->nCol + 1;
107098:   if( IsVirtual(pTab) ){
107099:     regRowid++;
107100:     pParse->nMem++;
107101:   }
107102:   regData = regRowid+1;
107103: 
107104:   /* If the INSERT statement included an IDLIST term, then make sure
107105:   ** all elements of the IDLIST really are columns of the table and 
107106:   ** remember the column indices.
107107:   **
107108:   ** If the table has an INTEGER PRIMARY KEY column and that column
107109:   ** is named in the IDLIST, then record in the ipkColumn variable
107110:   ** the index into IDLIST of the primary key column.  ipkColumn is
107111:   ** the index of the primary key as it appears in IDLIST, not as
107112:   ** is appears in the original table.  (The index of the INTEGER
107113:   ** PRIMARY KEY in the original table is pTab->iPKey.)
107114:   */
107115:   bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
107116:   if( pColumn ){
107117:     for(i=0; i<pColumn->nId; i++){
107118:       pColumn->a[i].idx = -1;
107119:     }
107120:     for(i=0; i<pColumn->nId; i++){
107121:       for(j=0; j<pTab->nCol; j++){
107122:         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
107123:           pColumn->a[i].idx = j;
107124:           if( i!=j ) bIdListInOrder = 0;
107125:           if( j==pTab->iPKey ){
107126:             ipkColumn = i;  assert( !withoutRowid );
107127:           }
107128:           break;
107129:         }
107130:       }
107131:       if( j>=pTab->nCol ){
107132:         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
107133:           ipkColumn = i;
107134:           bIdListInOrder = 0;
107135:         }else{
107136:           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
107137:               pTabList, 0, pColumn->a[i].zName);
107138:           pParse->checkSchema = 1;
107139:           goto insert_cleanup;
107140:         }
107141:       }
107142:     }
107143:   }
107144: 
107145:   /* Figure out how many columns of data are supplied.  If the data
107146:   ** is coming from a SELECT statement, then generate a co-routine that
107147:   ** produces a single row of the SELECT on each invocation.  The
107148:   ** co-routine is the common header to the 3rd and 4th templates.
107149:   */
107150:   if( pSelect ){
107151:     /* Data is coming from a SELECT or from a multi-row VALUES clause.
107152:     ** Generate a co-routine to run the SELECT. */
107153:     int regYield;       /* Register holding co-routine entry-point */
107154:     int addrTop;        /* Top of the co-routine */
107155:     int rc;             /* Result code */
107156: 
107157:     regYield = ++pParse->nMem;
107158:     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
107159:     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
107160:     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
107161:     dest.iSdst = bIdListInOrder ? regData : 0;
107162:     dest.nSdst = pTab->nCol;
107163:     rc = sqlite3Select(pParse, pSelect, &dest);
107164:     regFromSelect = dest.iSdst;
107165:     if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
107166:     sqlite3VdbeEndCoroutine(v, regYield);
107167:     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
107168:     assert( pSelect->pEList );
107169:     nColumn = pSelect->pEList->nExpr;
107170: 
107171:     /* Set useTempTable to TRUE if the result of the SELECT statement
107172:     ** should be written into a temporary table (template 4).  Set to
107173:     ** FALSE if each output row of the SELECT can be written directly into
107174:     ** the destination table (template 3).
107175:     **
107176:     ** A temp table must be used if the table being updated is also one
107177:     ** of the tables being read by the SELECT statement.  Also use a 
107178:     ** temp table in the case of row triggers.
107179:     */
107180:     if( pTrigger || readsTable(pParse, iDb, pTab) ){
107181:       useTempTable = 1;
107182:     }
107183: 
107184:     if( useTempTable ){
107185:       /* Invoke the coroutine to extract information from the SELECT
107186:       ** and add it to a transient table srcTab.  The code generated
107187:       ** here is from the 4th template:
107188:       **
107189:       **      B: open temp table
107190:       **      L: yield X, goto M at EOF
107191:       **         insert row from R..R+n into temp table
107192:       **         goto L
107193:       **      M: ...
107194:       */
107195:       int regRec;          /* Register to hold packed record */
107196:       int regTempRowid;    /* Register to hold temp table ROWID */
107197:       int addrL;           /* Label "L" */
107198: 
107199:       srcTab = pParse->nTab++;
107200:       regRec = sqlite3GetTempReg(pParse);
107201:       regTempRowid = sqlite3GetTempReg(pParse);
107202:       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
107203:       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
107204:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
107205:       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
107206:       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
107207:       sqlite3VdbeGoto(v, addrL);
107208:       sqlite3VdbeJumpHere(v, addrL);
107209:       sqlite3ReleaseTempReg(pParse, regRec);
107210:       sqlite3ReleaseTempReg(pParse, regTempRowid);
107211:     }
107212:   }else{
107213:     /* This is the case if the data for the INSERT is coming from a 
107214:     ** single-row VALUES clause
107215:     */
107216:     NameContext sNC;
107217:     memset(&sNC, 0, sizeof(sNC));
107218:     sNC.pParse = pParse;
107219:     srcTab = -1;
107220:     assert( useTempTable==0 );
107221:     if( pList ){
107222:       nColumn = pList->nExpr;
107223:       if( sqlite3ResolveExprListNames(&sNC, pList) ){
107224:         goto insert_cleanup;
107225:       }
107226:     }else{
107227:       nColumn = 0;
107228:     }
107229:   }
107230: 
107231:   /* If there is no IDLIST term but the table has an integer primary
107232:   ** key, the set the ipkColumn variable to the integer primary key 
107233:   ** column index in the original table definition.
107234:   */
107235:   if( pColumn==0 && nColumn>0 ){
107236:     ipkColumn = pTab->iPKey;
107237:   }
107238: 
107239:   /* Make sure the number of columns in the source data matches the number
107240:   ** of columns to be inserted into the table.
107241:   */
107242:   for(i=0; i<pTab->nCol; i++){
107243:     nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
107244:   }
107245:   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
107246:     sqlite3ErrorMsg(pParse, 
107247:        "table %S has %d columns but %d values were supplied",
107248:        pTabList, 0, pTab->nCol-nHidden, nColumn);
107249:     goto insert_cleanup;
107250:   }
107251:   if( pColumn!=0 && nColumn!=pColumn->nId ){
107252:     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
107253:     goto insert_cleanup;
107254:   }
107255:     
107256:   /* Initialize the count of rows to be inserted
107257:   */
107258:   if( db->flags & SQLITE_CountRows ){
107259:     regRowCount = ++pParse->nMem;
107260:     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
107261:   }
107262: 
107263:   /* If this is not a view, open the table and and all indices */
107264:   if( !isView ){
107265:     int nIdx;
107266:     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
107267:                                       &iDataCur, &iIdxCur);
107268:     aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
107269:     if( aRegIdx==0 ){
107270:       goto insert_cleanup;
107271:     }
107272:     for(i=0; i<nIdx; i++){
107273:       aRegIdx[i] = ++pParse->nMem;
107274:     }
107275:   }
107276: 
107277:   /* This is the top of the main insertion loop */
107278:   if( useTempTable ){
107279:     /* This block codes the top of loop only.  The complete loop is the
107280:     ** following pseudocode (template 4):
107281:     **
107282:     **         rewind temp table, if empty goto D
107283:     **      C: loop over rows of intermediate table
107284:     **           transfer values form intermediate table into <table>
107285:     **         end loop
107286:     **      D: ...
107287:     */
107288:     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
107289:     addrCont = sqlite3VdbeCurrentAddr(v);
107290:   }else if( pSelect ){
107291:     /* This block codes the top of loop only.  The complete loop is the
107292:     ** following pseudocode (template 3):
107293:     **
107294:     **      C: yield X, at EOF goto D
107295:     **         insert the select result into <table> from R..R+n
107296:     **         goto C
107297:     **      D: ...
107298:     */
107299:     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
107300:     VdbeCoverage(v);
107301:   }
107302: 
107303:   /* Run the BEFORE and INSTEAD OF triggers, if there are any
107304:   */
107305:   endOfLoop = sqlite3VdbeMakeLabel(v);
107306:   if( tmask & TRIGGER_BEFORE ){
107307:     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
107308: 
107309:     /* build the NEW.* reference row.  Note that if there is an INTEGER
107310:     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
107311:     ** translated into a unique ID for the row.  But on a BEFORE trigger,
107312:     ** we do not know what the unique ID will be (because the insert has
107313:     ** not happened yet) so we substitute a rowid of -1
107314:     */
107315:     if( ipkColumn<0 ){
107316:       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
107317:     }else{
107318:       int addr1;
107319:       assert( !withoutRowid );
107320:       if( useTempTable ){
107321:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
107322:       }else{
107323:         assert( pSelect==0 );  /* Otherwise useTempTable is true */
107324:         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
107325:       }
107326:       addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
107327:       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
107328:       sqlite3VdbeJumpHere(v, addr1);
107329:       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
107330:     }
107331: 
107332:     /* Cannot have triggers on a virtual table. If it were possible,
107333:     ** this block would have to account for hidden column.
107334:     */
107335:     assert( !IsVirtual(pTab) );
107336: 
107337:     /* Create the new column data
107338:     */
107339:     for(i=j=0; i<pTab->nCol; i++){
107340:       if( pColumn ){
107341:         for(j=0; j<pColumn->nId; j++){
107342:           if( pColumn->a[j].idx==i ) break;
107343:         }
107344:       }
107345:       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
107346:             || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
107347:         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
107348:       }else if( useTempTable ){
107349:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
107350:       }else{
107351:         assert( pSelect==0 ); /* Otherwise useTempTable is true */
107352:         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
107353:       }
107354:       if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
107355:     }
107356: 
107357:     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
107358:     ** do not attempt any conversions before assembling the record.
107359:     ** If this is a real table, attempt conversions as required by the
107360:     ** table column affinities.
107361:     */
107362:     if( !isView ){
107363:       sqlite3TableAffinity(v, pTab, regCols+1);
107364:     }
107365: 
107366:     /* Fire BEFORE or INSTEAD OF triggers */
107367:     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
107368:         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
107369: 
107370:     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
107371:   }
107372: 
107373:   /* Compute the content of the next row to insert into a range of
107374:   ** registers beginning at regIns.
107375:   */
107376:   if( !isView ){
107377:     if( IsVirtual(pTab) ){
107378:       /* The row that the VUpdate opcode will delete: none */
107379:       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
107380:     }
107381:     if( ipkColumn>=0 ){
107382:       if( useTempTable ){
107383:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
107384:       }else if( pSelect ){
107385:         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
107386:       }else{
107387:         VdbeOp *pOp;
107388:         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
107389:         pOp = sqlite3VdbeGetOp(v, -1);
107390:         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
107391:           appendFlag = 1;
107392:           pOp->opcode = OP_NewRowid;
107393:           pOp->p1 = iDataCur;
107394:           pOp->p2 = regRowid;
107395:           pOp->p3 = regAutoinc;
107396:         }
107397:       }
107398:       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
107399:       ** to generate a unique primary key value.
107400:       */
107401:       if( !appendFlag ){
107402:         int addr1;
107403:         if( !IsVirtual(pTab) ){
107404:           addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
107405:           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
107406:           sqlite3VdbeJumpHere(v, addr1);
107407:         }else{
107408:           addr1 = sqlite3VdbeCurrentAddr(v);
107409:           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
107410:         }
107411:         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
107412:       }
107413:     }else if( IsVirtual(pTab) || withoutRowid ){
107414:       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
107415:     }else{
107416:       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
107417:       appendFlag = 1;
107418:     }
107419:     autoIncStep(pParse, regAutoinc, regRowid);
107420: 
107421:     /* Compute data for all columns of the new entry, beginning
107422:     ** with the first column.
107423:     */
107424:     nHidden = 0;
107425:     for(i=0; i<pTab->nCol; i++){
107426:       int iRegStore = regRowid+1+i;
107427:       if( i==pTab->iPKey ){
107428:         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
107429:         ** Whenever this column is read, the rowid will be substituted
107430:         ** in its place.  Hence, fill this column with a NULL to avoid
107431:         ** taking up data space with information that will never be used.
107432:         ** As there may be shallow copies of this value, make it a soft-NULL */
107433:         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
107434:         continue;
107435:       }
107436:       if( pColumn==0 ){
107437:         if( IsHiddenColumn(&pTab->aCol[i]) ){
107438:           j = -1;
107439:           nHidden++;
107440:         }else{
107441:           j = i - nHidden;
107442:         }
107443:       }else{
107444:         for(j=0; j<pColumn->nId; j++){
107445:           if( pColumn->a[j].idx==i ) break;
107446:         }
107447:       }
107448:       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
107449:         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
107450:       }else if( useTempTable ){
107451:         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
107452:       }else if( pSelect ){
107453:         if( regFromSelect!=regData ){
107454:           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
107455:         }
107456:       }else{
107457:         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
107458:       }
107459:     }
107460: 
107461:     /* Generate code to check constraints and generate index keys and
107462:     ** do the insertion.
107463:     */
107464: #ifndef SQLITE_OMIT_VIRTUALTABLE
107465:     if( IsVirtual(pTab) ){
107466:       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
107467:       sqlite3VtabMakeWritable(pParse, pTab);
107468:       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
107469:       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
107470:       sqlite3MayAbort(pParse);
107471:     }else
107472: #endif
107473:     {
107474:       int isReplace;    /* Set to true if constraints may cause a replace */
107475:       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
107476:           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
107477:       );
107478:       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
107479:       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
107480:                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
107481:     }
107482:   }
107483: 
107484:   /* Update the count of rows that are inserted
107485:   */
107486:   if( (db->flags & SQLITE_CountRows)!=0 ){
107487:     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
107488:   }
107489: 
107490:   if( pTrigger ){
107491:     /* Code AFTER triggers */
107492:     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
107493:         pTab, regData-2-pTab->nCol, onError, endOfLoop);
107494:   }
107495: 
107496:   /* The bottom of the main insertion loop, if the data source
107497:   ** is a SELECT statement.
107498:   */
107499:   sqlite3VdbeResolveLabel(v, endOfLoop);
107500:   if( useTempTable ){
107501:     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
107502:     sqlite3VdbeJumpHere(v, addrInsTop);
107503:     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
107504:   }else if( pSelect ){
107505:     sqlite3VdbeGoto(v, addrCont);
107506:     sqlite3VdbeJumpHere(v, addrInsTop);
107507:   }
107508: 
107509:   if( !IsVirtual(pTab) && !isView ){
107510:     /* Close all tables opened */
107511:     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
107512:     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
107513:       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
107514:     }
107515:   }
107516: 
107517: insert_end:
107518:   /* Update the sqlite_sequence table by storing the content of the
107519:   ** maximum rowid counter values recorded while inserting into
107520:   ** autoincrement tables.
107521:   */
107522:   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
107523:     sqlite3AutoincrementEnd(pParse);
107524:   }
107525: 
107526:   /*
107527:   ** Return the number of rows inserted. If this routine is 
107528:   ** generating code because of a call to sqlite3NestedParse(), do not
107529:   ** invoke the callback function.
107530:   */
107531:   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
107532:     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
107533:     sqlite3VdbeSetNumCols(v, 1);
107534:     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
107535:   }
107536: 
107537: insert_cleanup:
107538:   sqlite3SrcListDelete(db, pTabList);
107539:   sqlite3ExprListDelete(db, pList);
107540:   sqlite3SelectDelete(db, pSelect);
107541:   sqlite3IdListDelete(db, pColumn);
107542:   sqlite3DbFree(db, aRegIdx);
107543: }
107544: 
107545: /* Make sure "isView" and other macros defined above are undefined. Otherwise
107546: ** they may interfere with compilation of other functions in this file
107547: ** (or in another file, if this file becomes part of the amalgamation).  */
107548: #ifdef isView
107549:  #undef isView
107550: #endif
107551: #ifdef pTrigger
107552:  #undef pTrigger
107553: #endif
107554: #ifdef tmask
107555:  #undef tmask
107556: #endif
107557: 
107558: /*
107559: ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
107560: */
107561: #define CKCNSTRNT_COLUMN   0x01    /* CHECK constraint uses a changing column */
107562: #define CKCNSTRNT_ROWID    0x02    /* CHECK constraint references the ROWID */
107563: 
107564: /* This is the Walker callback from checkConstraintUnchanged().  Set
107565: ** bit 0x01 of pWalker->eCode if
107566: ** pWalker->eCode to 0 if this expression node references any of the
107567: ** columns that are being modifed by an UPDATE statement.
107568: */
107569: static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
107570:   if( pExpr->op==TK_COLUMN ){
107571:     assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
107572:     if( pExpr->iColumn>=0 ){
107573:       if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
107574:         pWalker->eCode |= CKCNSTRNT_COLUMN;
107575:       }
107576:     }else{
107577:       pWalker->eCode |= CKCNSTRNT_ROWID;
107578:     }
107579:   }
107580:   return WRC_Continue;
107581: }
107582: 
107583: /*
107584: ** pExpr is a CHECK constraint on a row that is being UPDATE-ed.  The
107585: ** only columns that are modified by the UPDATE are those for which
107586: ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
107587: **
107588: ** Return true if CHECK constraint pExpr does not use any of the
107589: ** changing columns (or the rowid if it is changing).  In other words,
107590: ** return true if this CHECK constraint can be skipped when validating
107591: ** the new row in the UPDATE statement.
107592: */
107593: static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
107594:   Walker w;
107595:   memset(&w, 0, sizeof(w));
107596:   w.eCode = 0;
107597:   w.xExprCallback = checkConstraintExprNode;
107598:   w.u.aiCol = aiChng;
107599:   sqlite3WalkExpr(&w, pExpr);
107600:   if( !chngRowid ){
107601:     testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
107602:     w.eCode &= ~CKCNSTRNT_ROWID;
107603:   }
107604:   testcase( w.eCode==0 );
107605:   testcase( w.eCode==CKCNSTRNT_COLUMN );
107606:   testcase( w.eCode==CKCNSTRNT_ROWID );
107607:   testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
107608:   return !w.eCode;
107609: }
107610: 
107611: /*
107612: ** Generate code to do constraint checks prior to an INSERT or an UPDATE
107613: ** on table pTab.
107614: **
107615: ** The regNewData parameter is the first register in a range that contains
107616: ** the data to be inserted or the data after the update.  There will be
107617: ** pTab->nCol+1 registers in this range.  The first register (the one
107618: ** that regNewData points to) will contain the new rowid, or NULL in the
107619: ** case of a WITHOUT ROWID table.  The second register in the range will
107620: ** contain the content of the first table column.  The third register will
107621: ** contain the content of the second table column.  And so forth.
107622: **
107623: ** The regOldData parameter is similar to regNewData except that it contains
107624: ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
107625: ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
107626: ** checking regOldData for zero.
107627: **
107628: ** For an UPDATE, the pkChng boolean is true if the true primary key (the
107629: ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
107630: ** might be modified by the UPDATE.  If pkChng is false, then the key of
107631: ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
107632: **
107633: ** For an INSERT, the pkChng boolean indicates whether or not the rowid
107634: ** was explicitly specified as part of the INSERT statement.  If pkChng
107635: ** is zero, it means that the either rowid is computed automatically or
107636: ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
107637: ** pkChng will only be true if the INSERT statement provides an integer
107638: ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
107639: **
107640: ** The code generated by this routine will store new index entries into
107641: ** registers identified by aRegIdx[].  No index entry is created for
107642: ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
107643: ** the same as the order of indices on the linked list of indices
107644: ** at pTab->pIndex.
107645: **
107646: ** The caller must have already opened writeable cursors on the main
107647: ** table and all applicable indices (that is to say, all indices for which
107648: ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
107649: ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
107650: ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
107651: ** for the first index in the pTab->pIndex list.  Cursors for other indices
107652: ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
107653: **
107654: ** This routine also generates code to check constraints.  NOT NULL,
107655: ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
107656: ** then the appropriate action is performed.  There are five possible
107657: ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
107658: **
107659: **  Constraint type  Action       What Happens
107660: **  ---------------  ----------   ----------------------------------------
107661: **  any              ROLLBACK     The current transaction is rolled back and
107662: **                                sqlite3_step() returns immediately with a
107663: **                                return code of SQLITE_CONSTRAINT.
107664: **
107665: **  any              ABORT        Back out changes from the current command
107666: **                                only (do not do a complete rollback) then
107667: **                                cause sqlite3_step() to return immediately
107668: **                                with SQLITE_CONSTRAINT.
107669: **
107670: **  any              FAIL         Sqlite3_step() returns immediately with a
107671: **                                return code of SQLITE_CONSTRAINT.  The
107672: **                                transaction is not rolled back and any
107673: **                                changes to prior rows are retained.
107674: **
107675: **  any              IGNORE       The attempt in insert or update the current
107676: **                                row is skipped, without throwing an error.
107677: **                                Processing continues with the next row.
107678: **                                (There is an immediate jump to ignoreDest.)
107679: **
107680: **  NOT NULL         REPLACE      The NULL value is replace by the default
107681: **                                value for that column.  If the default value
107682: **                                is NULL, the action is the same as ABORT.
107683: **
107684: **  UNIQUE           REPLACE      The other row that conflicts with the row
107685: **                                being inserted is removed.
107686: **
107687: **  CHECK            REPLACE      Illegal.  The results in an exception.
107688: **
107689: ** Which action to take is determined by the overrideError parameter.
107690: ** Or if overrideError==OE_Default, then the pParse->onError parameter
107691: ** is used.  Or if pParse->onError==OE_Default then the onError value
107692: ** for the constraint is used.
107693: */
107694: SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
107695:   Parse *pParse,       /* The parser context */
107696:   Table *pTab,         /* The table being inserted or updated */
107697:   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
107698:   int iDataCur,        /* Canonical data cursor (main table or PK index) */
107699:   int iIdxCur,         /* First index cursor */
107700:   int regNewData,      /* First register in a range holding values to insert */
107701:   int regOldData,      /* Previous content.  0 for INSERTs */
107702:   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
107703:   u8 overrideError,    /* Override onError to this if not OE_Default */
107704:   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
107705:   int *pbMayReplace,   /* OUT: Set to true if constraint may cause a replace */
107706:   int *aiChng          /* column i is unchanged if aiChng[i]<0 */
107707: ){
107708:   Vdbe *v;             /* VDBE under constrution */
107709:   Index *pIdx;         /* Pointer to one of the indices */
107710:   Index *pPk = 0;      /* The PRIMARY KEY index */
107711:   sqlite3 *db;         /* Database connection */
107712:   int i;               /* loop counter */
107713:   int ix;              /* Index loop counter */
107714:   int nCol;            /* Number of columns */
107715:   int onError;         /* Conflict resolution strategy */
107716:   int addr1;           /* Address of jump instruction */
107717:   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
107718:   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
107719:   int ipkTop = 0;      /* Top of the rowid change constraint check */
107720:   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
107721:   u8 isUpdate;         /* True if this is an UPDATE operation */
107722:   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
107723:   int regRowid = -1;   /* Register holding ROWID value */
107724: 
107725:   isUpdate = regOldData!=0;
107726:   db = pParse->db;
107727:   v = sqlite3GetVdbe(pParse);
107728:   assert( v!=0 );
107729:   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
107730:   nCol = pTab->nCol;
107731:   
107732:   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
107733:   ** normal rowid tables.  nPkField is the number of key fields in the 
107734:   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
107735:   ** number of fields in the true primary key of the table. */
107736:   if( HasRowid(pTab) ){
107737:     pPk = 0;
107738:     nPkField = 1;
107739:   }else{
107740:     pPk = sqlite3PrimaryKeyIndex(pTab);
107741:     nPkField = pPk->nKeyCol;
107742:   }
107743: 
107744:   /* Record that this module has started */
107745:   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
107746:                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
107747: 
107748:   /* Test all NOT NULL constraints.
107749:   */
107750:   for(i=0; i<nCol; i++){
107751:     if( i==pTab->iPKey ){
107752:       continue;        /* ROWID is never NULL */
107753:     }
107754:     if( aiChng && aiChng[i]<0 ){
107755:       /* Don't bother checking for NOT NULL on columns that do not change */
107756:       continue;
107757:     }
107758:     onError = pTab->aCol[i].notNull;
107759:     if( onError==OE_None ) continue;  /* This column is allowed to be NULL */
107760:     if( overrideError!=OE_Default ){
107761:       onError = overrideError;
107762:     }else if( onError==OE_Default ){
107763:       onError = OE_Abort;
107764:     }
107765:     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
107766:       onError = OE_Abort;
107767:     }
107768:     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
107769:         || onError==OE_Ignore || onError==OE_Replace );
107770:     switch( onError ){
107771:       case OE_Abort:
107772:         sqlite3MayAbort(pParse);
107773:         /* Fall through */
107774:       case OE_Rollback:
107775:       case OE_Fail: {
107776:         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
107777:                                     pTab->aCol[i].zName);
107778:         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
107779:                           regNewData+1+i, zMsg, P4_DYNAMIC);
107780:         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
107781:         VdbeCoverage(v);
107782:         break;
107783:       }
107784:       case OE_Ignore: {
107785:         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
107786:         VdbeCoverage(v);
107787:         break;
107788:       }
107789:       default: {
107790:         assert( onError==OE_Replace );
107791:         addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
107792:            VdbeCoverage(v);
107793:         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
107794:         sqlite3VdbeJumpHere(v, addr1);
107795:         break;
107796:       }
107797:     }
107798:   }
107799: 
107800:   /* Test all CHECK constraints
107801:   */
107802: #ifndef SQLITE_OMIT_CHECK
107803:   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
107804:     ExprList *pCheck = pTab->pCheck;
107805:     pParse->ckBase = regNewData+1;
107806:     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
107807:     for(i=0; i<pCheck->nExpr; i++){
107808:       int allOk;
107809:       Expr *pExpr = pCheck->a[i].pExpr;
107810:       if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
107811:       allOk = sqlite3VdbeMakeLabel(v);
107812:       sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
107813:       if( onError==OE_Ignore ){
107814:         sqlite3VdbeGoto(v, ignoreDest);
107815:       }else{
107816:         char *zName = pCheck->a[i].zName;
107817:         if( zName==0 ) zName = pTab->zName;
107818:         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
107819:         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
107820:                               onError, zName, P4_TRANSIENT,
107821:                               P5_ConstraintCheck);
107822:       }
107823:       sqlite3VdbeResolveLabel(v, allOk);
107824:     }
107825:   }
107826: #endif /* !defined(SQLITE_OMIT_CHECK) */
107827: 
107828:   /* If rowid is changing, make sure the new rowid does not previously
107829:   ** exist in the table.
107830:   */
107831:   if( pkChng && pPk==0 ){
107832:     int addrRowidOk = sqlite3VdbeMakeLabel(v);
107833: 
107834:     /* Figure out what action to take in case of a rowid collision */
107835:     onError = pTab->keyConf;
107836:     if( overrideError!=OE_Default ){
107837:       onError = overrideError;
107838:     }else if( onError==OE_Default ){
107839:       onError = OE_Abort;
107840:     }
107841: 
107842:     if( isUpdate ){
107843:       /* pkChng!=0 does not mean that the rowid has change, only that
107844:       ** it might have changed.  Skip the conflict logic below if the rowid
107845:       ** is unchanged. */
107846:       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
107847:       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
107848:       VdbeCoverage(v);
107849:     }
107850: 
107851:     /* If the response to a rowid conflict is REPLACE but the response
107852:     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
107853:     ** to defer the running of the rowid conflict checking until after
107854:     ** the UNIQUE constraints have run.
107855:     */
107856:     if( onError==OE_Replace && overrideError!=OE_Replace ){
107857:       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
107858:         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
107859:           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
107860:           break;
107861:         }
107862:       }
107863:     }
107864: 
107865:     /* Check to see if the new rowid already exists in the table.  Skip
107866:     ** the following conflict logic if it does not. */
107867:     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
107868:     VdbeCoverage(v);
107869: 
107870:     /* Generate code that deals with a rowid collision */
107871:     switch( onError ){
107872:       default: {
107873:         onError = OE_Abort;
107874:         /* Fall thru into the next case */
107875:       }
107876:       case OE_Rollback:
107877:       case OE_Abort:
107878:       case OE_Fail: {
107879:         sqlite3RowidConstraint(pParse, onError, pTab);
107880:         break;
107881:       }
107882:       case OE_Replace: {
107883:         /* If there are DELETE triggers on this table and the
107884:         ** recursive-triggers flag is set, call GenerateRowDelete() to
107885:         ** remove the conflicting row from the table. This will fire
107886:         ** the triggers and remove both the table and index b-tree entries.
107887:         **
107888:         ** Otherwise, if there are no triggers or the recursive-triggers
107889:         ** flag is not set, but the table has one or more indexes, call 
107890:         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
107891:         ** only. The table b-tree entry will be replaced by the new entry 
107892:         ** when it is inserted.  
107893:         **
107894:         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
107895:         ** also invoke MultiWrite() to indicate that this VDBE may require
107896:         ** statement rollback (if the statement is aborted after the delete
107897:         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
107898:         ** but being more selective here allows statements like:
107899:         **
107900:         **   REPLACE INTO t(rowid) VALUES($newrowid)
107901:         **
107902:         ** to run without a statement journal if there are no indexes on the
107903:         ** table.
107904:         */
107905:         Trigger *pTrigger = 0;
107906:         if( db->flags&SQLITE_RecTriggers ){
107907:           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
107908:         }
107909:         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
107910:           sqlite3MultiWrite(pParse);
107911:           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
107912:                                    regNewData, 1, 0, OE_Replace, 1, -1);
107913:         }else{
107914: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
107915:           if( HasRowid(pTab) ){
107916:             /* This OP_Delete opcode fires the pre-update-hook only. It does
107917:             ** not modify the b-tree. It is more efficient to let the coming
107918:             ** OP_Insert replace the existing entry than it is to delete the
107919:             ** existing entry and then insert a new one. */
107920:             sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
107921:             sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107922:           }
107923: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
107924:           if( pTab->pIndex ){
107925:             sqlite3MultiWrite(pParse);
107926:             sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
107927:           }
107928:         }
107929:         seenReplace = 1;
107930:         break;
107931:       }
107932:       case OE_Ignore: {
107933:         /*assert( seenReplace==0 );*/
107934:         sqlite3VdbeGoto(v, ignoreDest);
107935:         break;
107936:       }
107937:     }
107938:     sqlite3VdbeResolveLabel(v, addrRowidOk);
107939:     if( ipkTop ){
107940:       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
107941:       sqlite3VdbeJumpHere(v, ipkTop);
107942:     }
107943:   }
107944: 
107945:   /* Test all UNIQUE constraints by creating entries for each UNIQUE
107946:   ** index and making sure that duplicate entries do not already exist.
107947:   ** Compute the revised record entries for indices as we go.
107948:   **
107949:   ** This loop also handles the case of the PRIMARY KEY index for a
107950:   ** WITHOUT ROWID table.
107951:   */
107952:   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
107953:     int regIdx;          /* Range of registers hold conent for pIdx */
107954:     int regR;            /* Range of registers holding conflicting PK */
107955:     int iThisCur;        /* Cursor for this UNIQUE index */
107956:     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
107957: 
107958:     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
107959:     if( bAffinityDone==0 ){
107960:       sqlite3TableAffinity(v, pTab, regNewData+1);
107961:       bAffinityDone = 1;
107962:     }
107963:     iThisCur = iIdxCur+ix;
107964:     addrUniqueOk = sqlite3VdbeMakeLabel(v);
107965: 
107966:     /* Skip partial indices for which the WHERE clause is not true */
107967:     if( pIdx->pPartIdxWhere ){
107968:       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
107969:       pParse->ckBase = regNewData+1;
107970:       sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
107971:                             SQLITE_JUMPIFNULL);
107972:       pParse->ckBase = 0;
107973:     }
107974: 
107975:     /* Create a record for this index entry as it should appear after
107976:     ** the insert or update.  Store that record in the aRegIdx[ix] register
107977:     */
107978:     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
107979:     for(i=0; i<pIdx->nColumn; i++){
107980:       int iField = pIdx->aiColumn[i];
107981:       int x;
107982:       if( iField==XN_EXPR ){
107983:         pParse->ckBase = regNewData+1;
107984:         sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
107985:         pParse->ckBase = 0;
107986:         VdbeComment((v, "%s column %d", pIdx->zName, i));
107987:       }else{
107988:         if( iField==XN_ROWID || iField==pTab->iPKey ){
107989:           if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
107990:           x = regNewData;
107991:           regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
107992:         }else{
107993:           x = iField + regNewData + 1;
107994:         }
107995:         sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
107996:         VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
107997:       }
107998:     }
107999:     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
108000:     VdbeComment((v, "for %s", pIdx->zName));
108001:     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
108002: 
108003:     /* In an UPDATE operation, if this index is the PRIMARY KEY index 
108004:     ** of a WITHOUT ROWID table and there has been no change the
108005:     ** primary key, then no collision is possible.  The collision detection
108006:     ** logic below can all be skipped. */
108007:     if( isUpdate && pPk==pIdx && pkChng==0 ){
108008:       sqlite3VdbeResolveLabel(v, addrUniqueOk);
108009:       continue;
108010:     }
108011: 
108012:     /* Find out what action to take in case there is a uniqueness conflict */
108013:     onError = pIdx->onError;
108014:     if( onError==OE_None ){ 
108015:       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
108016:       sqlite3VdbeResolveLabel(v, addrUniqueOk);
108017:       continue;  /* pIdx is not a UNIQUE index */
108018:     }
108019:     if( overrideError!=OE_Default ){
108020:       onError = overrideError;
108021:     }else if( onError==OE_Default ){
108022:       onError = OE_Abort;
108023:     }
108024:     
108025:     /* Check to see if the new index entry will be unique */
108026:     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
108027:                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
108028: 
108029:     /* Generate code to handle collisions */
108030:     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
108031:     if( isUpdate || onError==OE_Replace ){
108032:       if( HasRowid(pTab) ){
108033:         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
108034:         /* Conflict only if the rowid of the existing index entry
108035:         ** is different from old-rowid */
108036:         if( isUpdate ){
108037:           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
108038:           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108039:           VdbeCoverage(v);
108040:         }
108041:       }else{
108042:         int x;
108043:         /* Extract the PRIMARY KEY from the end of the index entry and
108044:         ** store it in registers regR..regR+nPk-1 */
108045:         if( pIdx!=pPk ){
108046:           for(i=0; i<pPk->nKeyCol; i++){
108047:             assert( pPk->aiColumn[i]>=0 );
108048:             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
108049:             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
108050:             VdbeComment((v, "%s.%s", pTab->zName,
108051:                          pTab->aCol[pPk->aiColumn[i]].zName));
108052:           }
108053:         }
108054:         if( isUpdate ){
108055:           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 
108056:           ** table, only conflict if the new PRIMARY KEY values are actually
108057:           ** different from the old.
108058:           **
108059:           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
108060:           ** of the matched index row are different from the original PRIMARY
108061:           ** KEY values of this row before the update.  */
108062:           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
108063:           int op = OP_Ne;
108064:           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
108065:   
108066:           for(i=0; i<pPk->nKeyCol; i++){
108067:             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
108068:             x = pPk->aiColumn[i];
108069:             assert( x>=0 );
108070:             if( i==(pPk->nKeyCol-1) ){
108071:               addrJump = addrUniqueOk;
108072:               op = OP_Eq;
108073:             }
108074:             sqlite3VdbeAddOp4(v, op, 
108075:                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
108076:             );
108077:             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
108078:             VdbeCoverageIf(v, op==OP_Eq);
108079:             VdbeCoverageIf(v, op==OP_Ne);
108080:           }
108081:         }
108082:       }
108083:     }
108084: 
108085:     /* Generate code that executes if the new index entry is not unique */
108086:     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
108087:         || onError==OE_Ignore || onError==OE_Replace );
108088:     switch( onError ){
108089:       case OE_Rollback:
108090:       case OE_Abort:
108091:       case OE_Fail: {
108092:         sqlite3UniqueConstraint(pParse, onError, pIdx);
108093:         break;
108094:       }
108095:       case OE_Ignore: {
108096:         sqlite3VdbeGoto(v, ignoreDest);
108097:         break;
108098:       }
108099:       default: {
108100:         Trigger *pTrigger = 0;
108101:         assert( onError==OE_Replace );
108102:         sqlite3MultiWrite(pParse);
108103:         if( db->flags&SQLITE_RecTriggers ){
108104:           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
108105:         }
108106:         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
108107:             regR, nPkField, 0, OE_Replace,
108108:             (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
108109:         seenReplace = 1;
108110:         break;
108111:       }
108112:     }
108113:     sqlite3VdbeResolveLabel(v, addrUniqueOk);
108114:     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
108115:     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
108116:   }
108117:   if( ipkTop ){
108118:     sqlite3VdbeGoto(v, ipkTop+1);
108119:     sqlite3VdbeJumpHere(v, ipkBottom);
108120:   }
108121:   
108122:   *pbMayReplace = seenReplace;
108123:   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
108124: }
108125: 
108126: /*
108127: ** This routine generates code to finish the INSERT or UPDATE operation
108128: ** that was started by a prior call to sqlite3GenerateConstraintChecks.
108129: ** A consecutive range of registers starting at regNewData contains the
108130: ** rowid and the content to be inserted.
108131: **
108132: ** The arguments to this routine should be the same as the first six
108133: ** arguments to sqlite3GenerateConstraintChecks.
108134: */
108135: SQLITE_PRIVATE void sqlite3CompleteInsertion(
108136:   Parse *pParse,      /* The parser context */
108137:   Table *pTab,        /* the table into which we are inserting */
108138:   int iDataCur,       /* Cursor of the canonical data source */
108139:   int iIdxCur,        /* First index cursor */
108140:   int regNewData,     /* Range of content */
108141:   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
108142:   int isUpdate,       /* True for UPDATE, False for INSERT */
108143:   int appendBias,     /* True if this is likely to be an append */
108144:   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
108145: ){
108146:   Vdbe *v;            /* Prepared statements under construction */
108147:   Index *pIdx;        /* An index being inserted or updated */
108148:   u8 pik_flags;       /* flag values passed to the btree insert */
108149:   int regData;        /* Content registers (after the rowid) */
108150:   int regRec;         /* Register holding assembled record for the table */
108151:   int i;              /* Loop counter */
108152:   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
108153: 
108154:   v = sqlite3GetVdbe(pParse);
108155:   assert( v!=0 );
108156:   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
108157:   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
108158:     if( aRegIdx[i]==0 ) continue;
108159:     bAffinityDone = 1;
108160:     if( pIdx->pPartIdxWhere ){
108161:       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
108162:       VdbeCoverage(v);
108163:     }
108164:     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
108165:     pik_flags = 0;
108166:     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
108167:     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
108168:       assert( pParse->nested==0 );
108169:       pik_flags |= OPFLAG_NCHANGE;
108170:     }
108171:     sqlite3VdbeChangeP5(v, pik_flags);
108172:   }
108173:   if( !HasRowid(pTab) ) return;
108174:   regData = regNewData + 1;
108175:   regRec = sqlite3GetTempReg(pParse);
108176:   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
108177:   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
108178:   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
108179:   if( pParse->nested ){
108180:     pik_flags = 0;
108181:   }else{
108182:     pik_flags = OPFLAG_NCHANGE;
108183:     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
108184:   }
108185:   if( appendBias ){
108186:     pik_flags |= OPFLAG_APPEND;
108187:   }
108188:   if( useSeekResult ){
108189:     pik_flags |= OPFLAG_USESEEKRESULT;
108190:   }
108191:   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
108192:   if( !pParse->nested ){
108193:     sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
108194:   }
108195:   sqlite3VdbeChangeP5(v, pik_flags);
108196: }
108197: 
108198: /*
108199: ** Allocate cursors for the pTab table and all its indices and generate
108200: ** code to open and initialized those cursors.
108201: **
108202: ** The cursor for the object that contains the complete data (normally
108203: ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
108204: ** ROWID table) is returned in *piDataCur.  The first index cursor is
108205: ** returned in *piIdxCur.  The number of indices is returned.
108206: **
108207: ** Use iBase as the first cursor (either the *piDataCur for rowid tables
108208: ** or the first index for WITHOUT ROWID tables) if it is non-negative.
108209: ** If iBase is negative, then allocate the next available cursor.
108210: **
108211: ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
108212: ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
108213: ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
108214: ** pTab->pIndex list.
108215: **
108216: ** If pTab is a virtual table, then this routine is a no-op and the
108217: ** *piDataCur and *piIdxCur values are left uninitialized.
108218: */
108219: SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
108220:   Parse *pParse,   /* Parsing context */
108221:   Table *pTab,     /* Table to be opened */
108222:   int op,          /* OP_OpenRead or OP_OpenWrite */
108223:   u8 p5,           /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
108224:   int iBase,       /* Use this for the table cursor, if there is one */
108225:   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
108226:   int *piDataCur,  /* Write the database source cursor number here */
108227:   int *piIdxCur    /* Write the first index cursor number here */
108228: ){
108229:   int i;
108230:   int iDb;
108231:   int iDataCur;
108232:   Index *pIdx;
108233:   Vdbe *v;
108234: 
108235:   assert( op==OP_OpenRead || op==OP_OpenWrite );
108236:   assert( op==OP_OpenWrite || p5==0 );
108237:   if( IsVirtual(pTab) ){
108238:     /* This routine is a no-op for virtual tables. Leave the output
108239:     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
108240:     ** can detect if they are used by mistake in the caller. */
108241:     return 0;
108242:   }
108243:   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
108244:   v = sqlite3GetVdbe(pParse);
108245:   assert( v!=0 );
108246:   if( iBase<0 ) iBase = pParse->nTab;
108247:   iDataCur = iBase++;
108248:   if( piDataCur ) *piDataCur = iDataCur;
108249:   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
108250:     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
108251:   }else{
108252:     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
108253:   }
108254:   if( piIdxCur ) *piIdxCur = iBase;
108255:   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
108256:     int iIdxCur = iBase++;
108257:     assert( pIdx->pSchema==pTab->pSchema );
108258:     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
108259:       if( piDataCur ) *piDataCur = iIdxCur;
108260:       p5 = 0;
108261:     }
108262:     if( aToOpen==0 || aToOpen[i+1] ){
108263:       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
108264:       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
108265:       sqlite3VdbeChangeP5(v, p5);
108266:       VdbeComment((v, "%s", pIdx->zName));
108267:     }
108268:   }
108269:   if( iBase>pParse->nTab ) pParse->nTab = iBase;
108270:   return i;
108271: }
108272: 
108273: 
108274: #ifdef SQLITE_TEST
108275: /*
108276: ** The following global variable is incremented whenever the
108277: ** transfer optimization is used.  This is used for testing
108278: ** purposes only - to make sure the transfer optimization really
108279: ** is happening when it is supposed to.
108280: */
108281: SQLITE_API int sqlite3_xferopt_count;
108282: #endif /* SQLITE_TEST */
108283: 
108284: 
108285: #ifndef SQLITE_OMIT_XFER_OPT
108286: /*
108287: ** Check to see if index pSrc is compatible as a source of data
108288: ** for index pDest in an insert transfer optimization.  The rules
108289: ** for a compatible index:
108290: **
108291: **    *   The index is over the same set of columns
108292: **    *   The same DESC and ASC markings occurs on all columns
108293: **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
108294: **    *   The same collating sequence on each column
108295: **    *   The index has the exact same WHERE clause
108296: */
108297: static int xferCompatibleIndex(Index *pDest, Index *pSrc){
108298:   int i;
108299:   assert( pDest && pSrc );
108300:   assert( pDest->pTable!=pSrc->pTable );
108301:   if( pDest->nKeyCol!=pSrc->nKeyCol ){
108302:     return 0;   /* Different number of columns */
108303:   }
108304:   if( pDest->onError!=pSrc->onError ){
108305:     return 0;   /* Different conflict resolution strategies */
108306:   }
108307:   for(i=0; i<pSrc->nKeyCol; i++){
108308:     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
108309:       return 0;   /* Different columns indexed */
108310:     }
108311:     if( pSrc->aiColumn[i]==XN_EXPR ){
108312:       assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
108313:       if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
108314:                              pDest->aColExpr->a[i].pExpr, -1)!=0 ){
108315:         return 0;   /* Different expressions in the index */
108316:       }
108317:     }
108318:     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
108319:       return 0;   /* Different sort orders */
108320:     }
108321:     if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
108322:       return 0;   /* Different collating sequences */
108323:     }
108324:   }
108325:   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
108326:     return 0;     /* Different WHERE clauses */
108327:   }
108328: 
108329:   /* If no test above fails then the indices must be compatible */
108330:   return 1;
108331: }
108332: 
108333: /*
108334: ** Attempt the transfer optimization on INSERTs of the form
108335: **
108336: **     INSERT INTO tab1 SELECT * FROM tab2;
108337: **
108338: ** The xfer optimization transfers raw records from tab2 over to tab1.  
108339: ** Columns are not decoded and reassembled, which greatly improves
108340: ** performance.  Raw index records are transferred in the same way.
108341: **
108342: ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
108343: ** There are lots of rules for determining compatibility - see comments
108344: ** embedded in the code for details.
108345: **
108346: ** This routine returns TRUE if the optimization is guaranteed to be used.
108347: ** Sometimes the xfer optimization will only work if the destination table
108348: ** is empty - a factor that can only be determined at run-time.  In that
108349: ** case, this routine generates code for the xfer optimization but also
108350: ** does a test to see if the destination table is empty and jumps over the
108351: ** xfer optimization code if the test fails.  In that case, this routine
108352: ** returns FALSE so that the caller will know to go ahead and generate
108353: ** an unoptimized transfer.  This routine also returns FALSE if there
108354: ** is no chance that the xfer optimization can be applied.
108355: **
108356: ** This optimization is particularly useful at making VACUUM run faster.
108357: */
108358: static int xferOptimization(
108359:   Parse *pParse,        /* Parser context */
108360:   Table *pDest,         /* The table we are inserting into */
108361:   Select *pSelect,      /* A SELECT statement to use as the data source */
108362:   int onError,          /* How to handle constraint errors */
108363:   int iDbDest           /* The database of pDest */
108364: ){
108365:   sqlite3 *db = pParse->db;
108366:   ExprList *pEList;                /* The result set of the SELECT */
108367:   Table *pSrc;                     /* The table in the FROM clause of SELECT */
108368:   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
108369:   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
108370:   int i;                           /* Loop counter */
108371:   int iDbSrc;                      /* The database of pSrc */
108372:   int iSrc, iDest;                 /* Cursors from source and destination */
108373:   int addr1, addr2;                /* Loop addresses */
108374:   int emptyDestTest = 0;           /* Address of test for empty pDest */
108375:   int emptySrcTest = 0;            /* Address of test for empty pSrc */
108376:   Vdbe *v;                         /* The VDBE we are building */
108377:   int regAutoinc;                  /* Memory register used by AUTOINC */
108378:   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
108379:   int regData, regRowid;           /* Registers holding data and rowid */
108380: 
108381:   if( pSelect==0 ){
108382:     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
108383:   }
108384:   if( pParse->pWith || pSelect->pWith ){
108385:     /* Do not attempt to process this query if there are an WITH clauses
108386:     ** attached to it. Proceeding may generate a false "no such table: xxx"
108387:     ** error if pSelect reads from a CTE named "xxx".  */
108388:     return 0;
108389:   }
108390:   if( sqlite3TriggerList(pParse, pDest) ){
108391:     return 0;   /* tab1 must not have triggers */
108392:   }
108393: #ifndef SQLITE_OMIT_VIRTUALTABLE
108394:   if( pDest->tabFlags & TF_Virtual ){
108395:     return 0;   /* tab1 must not be a virtual table */
108396:   }
108397: #endif
108398:   if( onError==OE_Default ){
108399:     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
108400:     if( onError==OE_Default ) onError = OE_Abort;
108401:   }
108402:   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
108403:   if( pSelect->pSrc->nSrc!=1 ){
108404:     return 0;   /* FROM clause must have exactly one term */
108405:   }
108406:   if( pSelect->pSrc->a[0].pSelect ){
108407:     return 0;   /* FROM clause cannot contain a subquery */
108408:   }
108409:   if( pSelect->pWhere ){
108410:     return 0;   /* SELECT may not have a WHERE clause */
108411:   }
108412:   if( pSelect->pOrderBy ){
108413:     return 0;   /* SELECT may not have an ORDER BY clause */
108414:   }
108415:   /* Do not need to test for a HAVING clause.  If HAVING is present but
108416:   ** there is no ORDER BY, we will get an error. */
108417:   if( pSelect->pGroupBy ){
108418:     return 0;   /* SELECT may not have a GROUP BY clause */
108419:   }
108420:   if( pSelect->pLimit ){
108421:     return 0;   /* SELECT may not have a LIMIT clause */
108422:   }
108423:   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
108424:   if( pSelect->pPrior ){
108425:     return 0;   /* SELECT may not be a compound query */
108426:   }
108427:   if( pSelect->selFlags & SF_Distinct ){
108428:     return 0;   /* SELECT may not be DISTINCT */
108429:   }
108430:   pEList = pSelect->pEList;
108431:   assert( pEList!=0 );
108432:   if( pEList->nExpr!=1 ){
108433:     return 0;   /* The result set must have exactly one column */
108434:   }
108435:   assert( pEList->a[0].pExpr );
108436:   if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
108437:     return 0;   /* The result set must be the special operator "*" */
108438:   }
108439: 
108440:   /* At this point we have established that the statement is of the
108441:   ** correct syntactic form to participate in this optimization.  Now
108442:   ** we have to check the semantics.
108443:   */
108444:   pItem = pSelect->pSrc->a;
108445:   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
108446:   if( pSrc==0 ){
108447:     return 0;   /* FROM clause does not contain a real table */
108448:   }
108449:   if( pSrc==pDest ){
108450:     return 0;   /* tab1 and tab2 may not be the same table */
108451:   }
108452:   if( HasRowid(pDest)!=HasRowid(pSrc) ){
108453:     return 0;   /* source and destination must both be WITHOUT ROWID or not */
108454:   }
108455: #ifndef SQLITE_OMIT_VIRTUALTABLE
108456:   if( pSrc->tabFlags & TF_Virtual ){
108457:     return 0;   /* tab2 must not be a virtual table */
108458:   }
108459: #endif
108460:   if( pSrc->pSelect ){
108461:     return 0;   /* tab2 may not be a view */
108462:   }
108463:   if( pDest->nCol!=pSrc->nCol ){
108464:     return 0;   /* Number of columns must be the same in tab1 and tab2 */
108465:   }
108466:   if( pDest->iPKey!=pSrc->iPKey ){
108467:     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
108468:   }
108469:   for(i=0; i<pDest->nCol; i++){
108470:     Column *pDestCol = &pDest->aCol[i];
108471:     Column *pSrcCol = &pSrc->aCol[i];
108472: #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
108473:     if( (db->flags & SQLITE_Vacuum)==0 
108474:      && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN 
108475:     ){
108476:       return 0;    /* Neither table may have __hidden__ columns */
108477:     }
108478: #endif
108479:     if( pDestCol->affinity!=pSrcCol->affinity ){
108480:       return 0;    /* Affinity must be the same on all columns */
108481:     }
108482:     if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
108483:       return 0;    /* Collating sequence must be the same on all columns */
108484:     }
108485:     if( pDestCol->notNull && !pSrcCol->notNull ){
108486:       return 0;    /* tab2 must be NOT NULL if tab1 is */
108487:     }
108488:     /* Default values for second and subsequent columns need to match. */
108489:     if( i>0 ){
108490:       assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
108491:       assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
108492:       if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0) 
108493:        || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
108494:                                        pSrcCol->pDflt->u.zToken)!=0)
108495:       ){
108496:         return 0;    /* Default values must be the same for all columns */
108497:       }
108498:     }
108499:   }
108500:   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
108501:     if( IsUniqueIndex(pDestIdx) ){
108502:       destHasUniqueIdx = 1;
108503:     }
108504:     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
108505:       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
108506:     }
108507:     if( pSrcIdx==0 ){
108508:       return 0;    /* pDestIdx has no corresponding index in pSrc */
108509:     }
108510:   }
108511: #ifndef SQLITE_OMIT_CHECK
108512:   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
108513:     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
108514:   }
108515: #endif
108516: #ifndef SQLITE_OMIT_FOREIGN_KEY
108517:   /* Disallow the transfer optimization if the destination table constains
108518:   ** any foreign key constraints.  This is more restrictive than necessary.
108519:   ** But the main beneficiary of the transfer optimization is the VACUUM 
108520:   ** command, and the VACUUM command disables foreign key constraints.  So
108521:   ** the extra complication to make this rule less restrictive is probably
108522:   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
108523:   */
108524:   if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
108525:     return 0;
108526:   }
108527: #endif
108528:   if( (db->flags & SQLITE_CountRows)!=0 ){
108529:     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
108530:   }
108531: 
108532:   /* If we get this far, it means that the xfer optimization is at
108533:   ** least a possibility, though it might only work if the destination
108534:   ** table (tab1) is initially empty.
108535:   */
108536: #ifdef SQLITE_TEST
108537:   sqlite3_xferopt_count++;
108538: #endif
108539:   iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
108540:   v = sqlite3GetVdbe(pParse);
108541:   sqlite3CodeVerifySchema(pParse, iDbSrc);
108542:   iSrc = pParse->nTab++;
108543:   iDest = pParse->nTab++;
108544:   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
108545:   regData = sqlite3GetTempReg(pParse);
108546:   regRowid = sqlite3GetTempReg(pParse);
108547:   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
108548:   assert( HasRowid(pDest) || destHasUniqueIdx );
108549:   if( (db->flags & SQLITE_Vacuum)==0 && (
108550:       (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
108551:    || destHasUniqueIdx                              /* (2) */
108552:    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
108553:   )){
108554:     /* In some circumstances, we are able to run the xfer optimization
108555:     ** only if the destination table is initially empty. Unless the
108556:     ** SQLITE_Vacuum flag is set, this block generates code to make
108557:     ** that determination. If SQLITE_Vacuum is set, then the destination
108558:     ** table is always empty.
108559:     **
108560:     ** Conditions under which the destination must be empty:
108561:     **
108562:     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
108563:     **     (If the destination is not initially empty, the rowid fields
108564:     **     of index entries might need to change.)
108565:     **
108566:     ** (2) The destination has a unique index.  (The xfer optimization 
108567:     **     is unable to test uniqueness.)
108568:     **
108569:     ** (3) onError is something other than OE_Abort and OE_Rollback.
108570:     */
108571:     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
108572:     emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
108573:     sqlite3VdbeJumpHere(v, addr1);
108574:   }
108575:   if( HasRowid(pSrc) ){
108576:     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
108577:     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
108578:     if( pDest->iPKey>=0 ){
108579:       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
108580:       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
108581:       VdbeCoverage(v);
108582:       sqlite3RowidConstraint(pParse, onError, pDest);
108583:       sqlite3VdbeJumpHere(v, addr2);
108584:       autoIncStep(pParse, regAutoinc, regRowid);
108585:     }else if( pDest->pIndex==0 ){
108586:       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
108587:     }else{
108588:       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
108589:       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
108590:     }
108591:     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
108592:     sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
108593:                       (char*)pDest, P4_TABLE);
108594:     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
108595:     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
108596:     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
108597:     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108598:   }else{
108599:     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
108600:     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
108601:   }
108602:   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
108603:     u8 idxInsFlags = 0;
108604:     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
108605:       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
108606:     }
108607:     assert( pSrcIdx );
108608:     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
108609:     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
108610:     VdbeComment((v, "%s", pSrcIdx->zName));
108611:     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
108612:     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
108613:     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
108614:     VdbeComment((v, "%s", pDestIdx->zName));
108615:     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
108616:     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
108617:     if( db->flags & SQLITE_Vacuum ){
108618:       /* This INSERT command is part of a VACUUM operation, which guarantees
108619:       ** that the destination table is empty. If all indexed columns use
108620:       ** collation sequence BINARY, then it can also be assumed that the
108621:       ** index will be populated by inserting keys in strictly sorted 
108622:       ** order. In this case, instead of seeking within the b-tree as part
108623:       ** of every OP_IdxInsert opcode, an OP_Last is added before the
108624:       ** OP_IdxInsert to seek to the point within the b-tree where each key 
108625:       ** should be inserted. This is faster.
108626:       **
108627:       ** If any of the indexed columns use a collation sequence other than
108628:       ** BINARY, this optimization is disabled. This is because the user 
108629:       ** might change the definition of a collation sequence and then run
108630:       ** a VACUUM command. In that case keys may not be written in strictly
108631:       ** sorted order.  */
108632:       for(i=0; i<pSrcIdx->nColumn; i++){
108633:         const char *zColl = pSrcIdx->azColl[i];
108634:         assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
108635:                     || sqlite3StrBINARY==zColl );
108636:         if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
108637:       }
108638:       if( i==pSrcIdx->nColumn ){
108639:         idxInsFlags = OPFLAG_USESEEKRESULT;
108640:         sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
108641:       }
108642:     }
108643:     if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
108644:       idxInsFlags |= OPFLAG_NCHANGE;
108645:     }
108646:     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
108647:     sqlite3VdbeChangeP5(v, idxInsFlags);
108648:     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
108649:     sqlite3VdbeJumpHere(v, addr1);
108650:     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
108651:     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108652:   }
108653:   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
108654:   sqlite3ReleaseTempReg(pParse, regRowid);
108655:   sqlite3ReleaseTempReg(pParse, regData);
108656:   if( emptyDestTest ){
108657:     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
108658:     sqlite3VdbeJumpHere(v, emptyDestTest);
108659:     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
108660:     return 0;
108661:   }else{
108662:     return 1;
108663:   }
108664: }
108665: #endif /* SQLITE_OMIT_XFER_OPT */
108666: 
108667: /************** End of insert.c **********************************************/
108668: /************** Begin file legacy.c ******************************************/
108669: /*
108670: ** 2001 September 15
108671: **
108672: ** The author disclaims copyright to this source code.  In place of
108673: ** a legal notice, here is a blessing:
108674: **
108675: **    May you do good and not evil.
108676: **    May you find forgiveness for yourself and forgive others.
108677: **    May you share freely, never taking more than you give.
108678: **
108679: *************************************************************************
108680: ** Main file for the SQLite library.  The routines in this file
108681: ** implement the programmer interface to the library.  Routines in
108682: ** other files are for internal use by SQLite and should not be
108683: ** accessed by users of the library.
108684: */
108685: 
108686: /* #include "sqliteInt.h" */
108687: 
108688: /*
108689: ** Execute SQL code.  Return one of the SQLITE_ success/failure
108690: ** codes.  Also write an error message into memory obtained from
108691: ** malloc() and make *pzErrMsg point to that message.
108692: **
108693: ** If the SQL is a query, then for each row in the query result
108694: ** the xCallback() function is called.  pArg becomes the first
108695: ** argument to xCallback().  If xCallback=NULL then no callback
108696: ** is invoked, even for queries.
108697: */
108698: SQLITE_API int sqlite3_exec(
108699:   sqlite3 *db,                /* The database on which the SQL executes */
108700:   const char *zSql,           /* The SQL to be executed */
108701:   sqlite3_callback xCallback, /* Invoke this callback routine */
108702:   void *pArg,                 /* First argument to xCallback() */
108703:   char **pzErrMsg             /* Write error messages here */
108704: ){
108705:   int rc = SQLITE_OK;         /* Return code */
108706:   const char *zLeftover;      /* Tail of unprocessed SQL */
108707:   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
108708:   char **azCols = 0;          /* Names of result columns */
108709:   int callbackIsInit;         /* True if callback data is initialized */
108710: 
108711:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
108712:   if( zSql==0 ) zSql = "";
108713: 
108714:   sqlite3_mutex_enter(db->mutex);
108715:   sqlite3Error(db, SQLITE_OK);
108716:   while( rc==SQLITE_OK && zSql[0] ){
108717:     int nCol;
108718:     char **azVals = 0;
108719: 
108720:     pStmt = 0;
108721:     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
108722:     assert( rc==SQLITE_OK || pStmt==0 );
108723:     if( rc!=SQLITE_OK ){
108724:       continue;
108725:     }
108726:     if( !pStmt ){
108727:       /* this happens for a comment or white-space */
108728:       zSql = zLeftover;
108729:       continue;
108730:     }
108731: 
108732:     callbackIsInit = 0;
108733:     nCol = sqlite3_column_count(pStmt);
108734: 
108735:     while( 1 ){
108736:       int i;
108737:       rc = sqlite3_step(pStmt);
108738: 
108739:       /* Invoke the callback function if required */
108740:       if( xCallback && (SQLITE_ROW==rc || 
108741:           (SQLITE_DONE==rc && !callbackIsInit
108742:                            && db->flags&SQLITE_NullCallback)) ){
108743:         if( !callbackIsInit ){
108744:           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
108745:           if( azCols==0 ){
108746:             goto exec_out;
108747:           }
108748:           for(i=0; i<nCol; i++){
108749:             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
108750:             /* sqlite3VdbeSetColName() installs column names as UTF8
108751:             ** strings so there is no way for sqlite3_column_name() to fail. */
108752:             assert( azCols[i]!=0 );
108753:           }
108754:           callbackIsInit = 1;
108755:         }
108756:         if( rc==SQLITE_ROW ){
108757:           azVals = &azCols[nCol];
108758:           for(i=0; i<nCol; i++){
108759:             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
108760:             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
108761:               sqlite3OomFault(db);
108762:               goto exec_out;
108763:             }
108764:           }
108765:         }
108766:         if( xCallback(pArg, nCol, azVals, azCols) ){
108767:           /* EVIDENCE-OF: R-38229-40159 If the callback function to
108768:           ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
108769:           ** return SQLITE_ABORT. */
108770:           rc = SQLITE_ABORT;
108771:           sqlite3VdbeFinalize((Vdbe *)pStmt);
108772:           pStmt = 0;
108773:           sqlite3Error(db, SQLITE_ABORT);
108774:           goto exec_out;
108775:         }
108776:       }
108777: 
108778:       if( rc!=SQLITE_ROW ){
108779:         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
108780:         pStmt = 0;
108781:         zSql = zLeftover;
108782:         while( sqlite3Isspace(zSql[0]) ) zSql++;
108783:         break;
108784:       }
108785:     }
108786: 
108787:     sqlite3DbFree(db, azCols);
108788:     azCols = 0;
108789:   }
108790: 
108791: exec_out:
108792:   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
108793:   sqlite3DbFree(db, azCols);
108794: 
108795:   rc = sqlite3ApiExit(db, rc);
108796:   if( rc!=SQLITE_OK && pzErrMsg ){
108797:     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
108798:     *pzErrMsg = sqlite3Malloc(nErrMsg);
108799:     if( *pzErrMsg ){
108800:       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
108801:     }else{
108802:       rc = SQLITE_NOMEM_BKPT;
108803:       sqlite3Error(db, SQLITE_NOMEM);
108804:     }
108805:   }else if( pzErrMsg ){
108806:     *pzErrMsg = 0;
108807:   }
108808: 
108809:   assert( (rc&db->errMask)==rc );
108810:   sqlite3_mutex_leave(db->mutex);
108811:   return rc;
108812: }
108813: 
108814: /************** End of legacy.c **********************************************/
108815: /************** Begin file loadext.c *****************************************/
108816: /*
108817: ** 2006 June 7
108818: **
108819: ** The author disclaims copyright to this source code.  In place of
108820: ** a legal notice, here is a blessing:
108821: **
108822: **    May you do good and not evil.
108823: **    May you find forgiveness for yourself and forgive others.
108824: **    May you share freely, never taking more than you give.
108825: **
108826: *************************************************************************
108827: ** This file contains code used to dynamically load extensions into
108828: ** the SQLite library.
108829: */
108830: 
108831: #ifndef SQLITE_CORE
108832:   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
108833: #endif
108834: /************** Include sqlite3ext.h in the middle of loadext.c **************/
108835: /************** Begin file sqlite3ext.h **************************************/
108836: /*
108837: ** 2006 June 7
108838: **
108839: ** The author disclaims copyright to this source code.  In place of
108840: ** a legal notice, here is a blessing:
108841: **
108842: **    May you do good and not evil.
108843: **    May you find forgiveness for yourself and forgive others.
108844: **    May you share freely, never taking more than you give.
108845: **
108846: *************************************************************************
108847: ** This header file defines the SQLite interface for use by
108848: ** shared libraries that want to be imported as extensions into
108849: ** an SQLite instance.  Shared libraries that intend to be loaded
108850: ** as extensions by SQLite should #include this file instead of 
108851: ** sqlite3.h.
108852: */
108853: #ifndef SQLITE3EXT_H
108854: #define SQLITE3EXT_H
108855: /* #include "sqlite3.h" */
108856: 
108857: /*
108858: ** The following structure holds pointers to all of the SQLite API
108859: ** routines.
108860: **
108861: ** WARNING:  In order to maintain backwards compatibility, add new
108862: ** interfaces to the end of this structure only.  If you insert new
108863: ** interfaces in the middle of this structure, then older different
108864: ** versions of SQLite will not be able to load each other's shared
108865: ** libraries!
108866: */
108867: struct sqlite3_api_routines {
108868:   void * (*aggregate_context)(sqlite3_context*,int nBytes);
108869:   int  (*aggregate_count)(sqlite3_context*);
108870:   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
108871:   int  (*bind_double)(sqlite3_stmt*,int,double);
108872:   int  (*bind_int)(sqlite3_stmt*,int,int);
108873:   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
108874:   int  (*bind_null)(sqlite3_stmt*,int);
108875:   int  (*bind_parameter_count)(sqlite3_stmt*);
108876:   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
108877:   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
108878:   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
108879:   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
108880:   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
108881:   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
108882:   int  (*busy_timeout)(sqlite3*,int ms);
108883:   int  (*changes)(sqlite3*);
108884:   int  (*close)(sqlite3*);
108885:   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
108886:                            int eTextRep,const char*));
108887:   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
108888:                              int eTextRep,const void*));
108889:   const void * (*column_blob)(sqlite3_stmt*,int iCol);
108890:   int  (*column_bytes)(sqlite3_stmt*,int iCol);
108891:   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
108892:   int  (*column_count)(sqlite3_stmt*pStmt);
108893:   const char * (*column_database_name)(sqlite3_stmt*,int);
108894:   const void * (*column_database_name16)(sqlite3_stmt*,int);
108895:   const char * (*column_decltype)(sqlite3_stmt*,int i);
108896:   const void * (*column_decltype16)(sqlite3_stmt*,int);
108897:   double  (*column_double)(sqlite3_stmt*,int iCol);
108898:   int  (*column_int)(sqlite3_stmt*,int iCol);
108899:   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
108900:   const char * (*column_name)(sqlite3_stmt*,int);
108901:   const void * (*column_name16)(sqlite3_stmt*,int);
108902:   const char * (*column_origin_name)(sqlite3_stmt*,int);
108903:   const void * (*column_origin_name16)(sqlite3_stmt*,int);
108904:   const char * (*column_table_name)(sqlite3_stmt*,int);
108905:   const void * (*column_table_name16)(sqlite3_stmt*,int);
108906:   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
108907:   const void * (*column_text16)(sqlite3_stmt*,int iCol);
108908:   int  (*column_type)(sqlite3_stmt*,int iCol);
108909:   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
108910:   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
108911:   int  (*complete)(const char*sql);
108912:   int  (*complete16)(const void*sql);
108913:   int  (*create_collation)(sqlite3*,const char*,int,void*,
108914:                            int(*)(void*,int,const void*,int,const void*));
108915:   int  (*create_collation16)(sqlite3*,const void*,int,void*,
108916:                              int(*)(void*,int,const void*,int,const void*));
108917:   int  (*create_function)(sqlite3*,const char*,int,int,void*,
108918:                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108919:                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108920:                           void (*xFinal)(sqlite3_context*));
108921:   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
108922:                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108923:                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108924:                             void (*xFinal)(sqlite3_context*));
108925:   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
108926:   int  (*data_count)(sqlite3_stmt*pStmt);
108927:   sqlite3 * (*db_handle)(sqlite3_stmt*);
108928:   int (*declare_vtab)(sqlite3*,const char*);
108929:   int  (*enable_shared_cache)(int);
108930:   int  (*errcode)(sqlite3*db);
108931:   const char * (*errmsg)(sqlite3*);
108932:   const void * (*errmsg16)(sqlite3*);
108933:   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
108934:   int  (*expired)(sqlite3_stmt*);
108935:   int  (*finalize)(sqlite3_stmt*pStmt);
108936:   void  (*free)(void*);
108937:   void  (*free_table)(char**result);
108938:   int  (*get_autocommit)(sqlite3*);
108939:   void * (*get_auxdata)(sqlite3_context*,int);
108940:   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
108941:   int  (*global_recover)(void);
108942:   void  (*interruptx)(sqlite3*);
108943:   sqlite_int64  (*last_insert_rowid)(sqlite3*);
108944:   const char * (*libversion)(void);
108945:   int  (*libversion_number)(void);
108946:   void *(*malloc)(int);
108947:   char * (*mprintf)(const char*,...);
108948:   int  (*open)(const char*,sqlite3**);
108949:   int  (*open16)(const void*,sqlite3**);
108950:   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
108951:   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
108952:   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
108953:   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
108954:   void *(*realloc)(void*,int);
108955:   int  (*reset)(sqlite3_stmt*pStmt);
108956:   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
108957:   void  (*result_double)(sqlite3_context*,double);
108958:   void  (*result_error)(sqlite3_context*,const char*,int);
108959:   void  (*result_error16)(sqlite3_context*,const void*,int);
108960:   void  (*result_int)(sqlite3_context*,int);
108961:   void  (*result_int64)(sqlite3_context*,sqlite_int64);
108962:   void  (*result_null)(sqlite3_context*);
108963:   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
108964:   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
108965:   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
108966:   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
108967:   void  (*result_value)(sqlite3_context*,sqlite3_value*);
108968:   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
108969:   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
108970:                          const char*,const char*),void*);
108971:   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
108972:   char * (*snprintf)(int,char*,const char*,...);
108973:   int  (*step)(sqlite3_stmt*);
108974:   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
108975:                                 char const**,char const**,int*,int*,int*);
108976:   void  (*thread_cleanup)(void);
108977:   int  (*total_changes)(sqlite3*);
108978:   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
108979:   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
108980:   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
108981:                                          sqlite_int64),void*);
108982:   void * (*user_data)(sqlite3_context*);
108983:   const void * (*value_blob)(sqlite3_value*);
108984:   int  (*value_bytes)(sqlite3_value*);
108985:   int  (*value_bytes16)(sqlite3_value*);
108986:   double  (*value_double)(sqlite3_value*);
108987:   int  (*value_int)(sqlite3_value*);
108988:   sqlite_int64  (*value_int64)(sqlite3_value*);
108989:   int  (*value_numeric_type)(sqlite3_value*);
108990:   const unsigned char * (*value_text)(sqlite3_value*);
108991:   const void * (*value_text16)(sqlite3_value*);
108992:   const void * (*value_text16be)(sqlite3_value*);
108993:   const void * (*value_text16le)(sqlite3_value*);
108994:   int  (*value_type)(sqlite3_value*);
108995:   char *(*vmprintf)(const char*,va_list);
108996:   /* Added ??? */
108997:   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
108998:   /* Added by 3.3.13 */
108999:   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
109000:   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
109001:   int (*clear_bindings)(sqlite3_stmt*);
109002:   /* Added by 3.4.1 */
109003:   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
109004:                           void (*xDestroy)(void *));
109005:   /* Added by 3.5.0 */
109006:   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
109007:   int (*blob_bytes)(sqlite3_blob*);
109008:   int (*blob_close)(sqlite3_blob*);
109009:   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
109010:                    int,sqlite3_blob**);
109011:   int (*blob_read)(sqlite3_blob*,void*,int,int);
109012:   int (*blob_write)(sqlite3_blob*,const void*,int,int);
109013:   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
109014:                              int(*)(void*,int,const void*,int,const void*),
109015:                              void(*)(void*));
109016:   int (*file_control)(sqlite3*,const char*,int,void*);
109017:   sqlite3_int64 (*memory_highwater)(int);
109018:   sqlite3_int64 (*memory_used)(void);
109019:   sqlite3_mutex *(*mutex_alloc)(int);
109020:   void (*mutex_enter)(sqlite3_mutex*);
109021:   void (*mutex_free)(sqlite3_mutex*);
109022:   void (*mutex_leave)(sqlite3_mutex*);
109023:   int (*mutex_try)(sqlite3_mutex*);
109024:   int (*open_v2)(const char*,sqlite3**,int,const char*);
109025:   int (*release_memory)(int);
109026:   void (*result_error_nomem)(sqlite3_context*);
109027:   void (*result_error_toobig)(sqlite3_context*);
109028:   int (*sleep)(int);
109029:   void (*soft_heap_limit)(int);
109030:   sqlite3_vfs *(*vfs_find)(const char*);
109031:   int (*vfs_register)(sqlite3_vfs*,int);
109032:   int (*vfs_unregister)(sqlite3_vfs*);
109033:   int (*xthreadsafe)(void);
109034:   void (*result_zeroblob)(sqlite3_context*,int);
109035:   void (*result_error_code)(sqlite3_context*,int);
109036:   int (*test_control)(int, ...);
109037:   void (*randomness)(int,void*);
109038:   sqlite3 *(*context_db_handle)(sqlite3_context*);
109039:   int (*extended_result_codes)(sqlite3*,int);
109040:   int (*limit)(sqlite3*,int,int);
109041:   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
109042:   const char *(*sql)(sqlite3_stmt*);
109043:   int (*status)(int,int*,int*,int);
109044:   int (*backup_finish)(sqlite3_backup*);
109045:   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
109046:   int (*backup_pagecount)(sqlite3_backup*);
109047:   int (*backup_remaining)(sqlite3_backup*);
109048:   int (*backup_step)(sqlite3_backup*,int);
109049:   const char *(*compileoption_get)(int);
109050:   int (*compileoption_used)(const char*);
109051:   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
109052:                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
109053:                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
109054:                             void (*xFinal)(sqlite3_context*),
109055:                             void(*xDestroy)(void*));
109056:   int (*db_config)(sqlite3*,int,...);
109057:   sqlite3_mutex *(*db_mutex)(sqlite3*);
109058:   int (*db_status)(sqlite3*,int,int*,int*,int);
109059:   int (*extended_errcode)(sqlite3*);
109060:   void (*log)(int,const char*,...);
109061:   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
109062:   const char *(*sourceid)(void);
109063:   int (*stmt_status)(sqlite3_stmt*,int,int);
109064:   int (*strnicmp)(const char*,const char*,int);
109065:   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
109066:   int (*wal_autocheckpoint)(sqlite3*,int);
109067:   int (*wal_checkpoint)(sqlite3*,const char*);
109068:   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
109069:   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
109070:   int (*vtab_config)(sqlite3*,int op,...);
109071:   int (*vtab_on_conflict)(sqlite3*);
109072:   /* Version 3.7.16 and later */
109073:   int (*close_v2)(sqlite3*);
109074:   const char *(*db_filename)(sqlite3*,const char*);
109075:   int (*db_readonly)(sqlite3*,const char*);
109076:   int (*db_release_memory)(sqlite3*);
109077:   const char *(*errstr)(int);
109078:   int (*stmt_busy)(sqlite3_stmt*);
109079:   int (*stmt_readonly)(sqlite3_stmt*);
109080:   int (*stricmp)(const char*,const char*);
109081:   int (*uri_boolean)(const char*,const char*,int);
109082:   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
109083:   const char *(*uri_parameter)(const char*,const char*);
109084:   char *(*vsnprintf)(int,char*,const char*,va_list);
109085:   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
109086:   /* Version 3.8.7 and later */
109087:   int (*auto_extension)(void(*)(void));
109088:   int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
109089:                      void(*)(void*));
109090:   int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
109091:                       void(*)(void*),unsigned char);
109092:   int (*cancel_auto_extension)(void(*)(void));
109093:   int (*load_extension)(sqlite3*,const char*,const char*,char**);
109094:   void *(*malloc64)(sqlite3_uint64);
109095:   sqlite3_uint64 (*msize)(void*);
109096:   void *(*realloc64)(void*,sqlite3_uint64);
109097:   void (*reset_auto_extension)(void);
109098:   void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
109099:                         void(*)(void*));
109100:   void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
109101:                          void(*)(void*), unsigned char);
109102:   int (*strglob)(const char*,const char*);
109103:   /* Version 3.8.11 and later */
109104:   sqlite3_value *(*value_dup)(const sqlite3_value*);
109105:   void (*value_free)(sqlite3_value*);
109106:   int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
109107:   int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
109108:   /* Version 3.9.0 and later */
109109:   unsigned int (*value_subtype)(sqlite3_value*);
109110:   void (*result_subtype)(sqlite3_context*,unsigned int);
109111:   /* Version 3.10.0 and later */
109112:   int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
109113:   int (*strlike)(const char*,const char*,unsigned int);
109114:   int (*db_cacheflush)(sqlite3*);
109115:   /* Version 3.12.0 and later */
109116:   int (*system_errno)(sqlite3*);
109117:   /* Version 3.14.0 and later */
109118:   int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
109119:   char *(*expanded_sql)(sqlite3_stmt*);
109120: };
109121: 
109122: /*
109123: ** This is the function signature used for all extension entry points.  It
109124: ** is also defined in the file "loadext.c".
109125: */
109126: typedef int (*sqlite3_loadext_entry)(
109127:   sqlite3 *db,                       /* Handle to the database. */
109128:   char **pzErrMsg,                   /* Used to set error string on failure. */
109129:   const sqlite3_api_routines *pThunk /* Extension API function pointers. */
109130: );
109131: 
109132: /*
109133: ** The following macros redefine the API routines so that they are
109134: ** redirected through the global sqlite3_api structure.
109135: **
109136: ** This header file is also used by the loadext.c source file
109137: ** (part of the main SQLite library - not an extension) so that
109138: ** it can get access to the sqlite3_api_routines structure
109139: ** definition.  But the main library does not want to redefine
109140: ** the API.  So the redefinition macros are only valid if the
109141: ** SQLITE_CORE macros is undefined.
109142: */
109143: #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
109144: #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
109145: #ifndef SQLITE_OMIT_DEPRECATED
109146: #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
109147: #endif
109148: #define sqlite3_bind_blob              sqlite3_api->bind_blob
109149: #define sqlite3_bind_double            sqlite3_api->bind_double
109150: #define sqlite3_bind_int               sqlite3_api->bind_int
109151: #define sqlite3_bind_int64             sqlite3_api->bind_int64
109152: #define sqlite3_bind_null              sqlite3_api->bind_null
109153: #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
109154: #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
109155: #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
109156: #define sqlite3_bind_text              sqlite3_api->bind_text
109157: #define sqlite3_bind_text16            sqlite3_api->bind_text16
109158: #define sqlite3_bind_value             sqlite3_api->bind_value
109159: #define sqlite3_busy_handler           sqlite3_api->busy_handler
109160: #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
109161: #define sqlite3_changes                sqlite3_api->changes
109162: #define sqlite3_close                  sqlite3_api->close
109163: #define sqlite3_collation_needed       sqlite3_api->collation_needed
109164: #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
109165: #define sqlite3_column_blob            sqlite3_api->column_blob
109166: #define sqlite3_column_bytes           sqlite3_api->column_bytes
109167: #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
109168: #define sqlite3_column_count           sqlite3_api->column_count
109169: #define sqlite3_column_database_name   sqlite3_api->column_database_name
109170: #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
109171: #define sqlite3_column_decltype        sqlite3_api->column_decltype
109172: #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
109173: #define sqlite3_column_double          sqlite3_api->column_double
109174: #define sqlite3_column_int             sqlite3_api->column_int
109175: #define sqlite3_column_int64           sqlite3_api->column_int64
109176: #define sqlite3_column_name            sqlite3_api->column_name
109177: #define sqlite3_column_name16          sqlite3_api->column_name16
109178: #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
109179: #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
109180: #define sqlite3_column_table_name      sqlite3_api->column_table_name
109181: #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
109182: #define sqlite3_column_text            sqlite3_api->column_text
109183: #define sqlite3_column_text16          sqlite3_api->column_text16
109184: #define sqlite3_column_type            sqlite3_api->column_type
109185: #define sqlite3_column_value           sqlite3_api->column_value
109186: #define sqlite3_commit_hook            sqlite3_api->commit_hook
109187: #define sqlite3_complete               sqlite3_api->complete
109188: #define sqlite3_complete16             sqlite3_api->complete16
109189: #define sqlite3_create_collation       sqlite3_api->create_collation
109190: #define sqlite3_create_collation16     sqlite3_api->create_collation16
109191: #define sqlite3_create_function        sqlite3_api->create_function
109192: #define sqlite3_create_function16      sqlite3_api->create_function16
109193: #define sqlite3_create_module          sqlite3_api->create_module
109194: #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
109195: #define sqlite3_data_count             sqlite3_api->data_count
109196: #define sqlite3_db_handle              sqlite3_api->db_handle
109197: #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
109198: #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
109199: #define sqlite3_errcode                sqlite3_api->errcode
109200: #define sqlite3_errmsg                 sqlite3_api->errmsg
109201: #define sqlite3_errmsg16               sqlite3_api->errmsg16
109202: #define sqlite3_exec                   sqlite3_api->exec
109203: #ifndef SQLITE_OMIT_DEPRECATED
109204: #define sqlite3_expired                sqlite3_api->expired
109205: #endif
109206: #define sqlite3_finalize               sqlite3_api->finalize
109207: #define sqlite3_free                   sqlite3_api->free
109208: #define sqlite3_free_table             sqlite3_api->free_table
109209: #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
109210: #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
109211: #define sqlite3_get_table              sqlite3_api->get_table
109212: #ifndef SQLITE_OMIT_DEPRECATED
109213: #define sqlite3_global_recover         sqlite3_api->global_recover
109214: #endif
109215: #define sqlite3_interrupt              sqlite3_api->interruptx
109216: #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
109217: #define sqlite3_libversion             sqlite3_api->libversion
109218: #define sqlite3_libversion_number      sqlite3_api->libversion_number
109219: #define sqlite3_malloc                 sqlite3_api->malloc
109220: #define sqlite3_mprintf                sqlite3_api->mprintf
109221: #define sqlite3_open                   sqlite3_api->open
109222: #define sqlite3_open16                 sqlite3_api->open16
109223: #define sqlite3_prepare                sqlite3_api->prepare
109224: #define sqlite3_prepare16              sqlite3_api->prepare16
109225: #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
109226: #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
109227: #define sqlite3_profile                sqlite3_api->profile
109228: #define sqlite3_progress_handler       sqlite3_api->progress_handler
109229: #define sqlite3_realloc                sqlite3_api->realloc
109230: #define sqlite3_reset                  sqlite3_api->reset
109231: #define sqlite3_result_blob            sqlite3_api->result_blob
109232: #define sqlite3_result_double          sqlite3_api->result_double
109233: #define sqlite3_result_error           sqlite3_api->result_error
109234: #define sqlite3_result_error16         sqlite3_api->result_error16
109235: #define sqlite3_result_int             sqlite3_api->result_int
109236: #define sqlite3_result_int64           sqlite3_api->result_int64
109237: #define sqlite3_result_null            sqlite3_api->result_null
109238: #define sqlite3_result_text            sqlite3_api->result_text
109239: #define sqlite3_result_text16          sqlite3_api->result_text16
109240: #define sqlite3_result_text16be        sqlite3_api->result_text16be
109241: #define sqlite3_result_text16le        sqlite3_api->result_text16le
109242: #define sqlite3_result_value           sqlite3_api->result_value
109243: #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
109244: #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
109245: #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
109246: #define sqlite3_snprintf               sqlite3_api->snprintf
109247: #define sqlite3_step                   sqlite3_api->step
109248: #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
109249: #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
109250: #define sqlite3_total_changes          sqlite3_api->total_changes
109251: #define sqlite3_trace                  sqlite3_api->trace
109252: #ifndef SQLITE_OMIT_DEPRECATED
109253: #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
109254: #endif
109255: #define sqlite3_update_hook            sqlite3_api->update_hook
109256: #define sqlite3_user_data              sqlite3_api->user_data
109257: #define sqlite3_value_blob             sqlite3_api->value_blob
109258: #define sqlite3_value_bytes            sqlite3_api->value_bytes
109259: #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
109260: #define sqlite3_value_double           sqlite3_api->value_double
109261: #define sqlite3_value_int              sqlite3_api->value_int
109262: #define sqlite3_value_int64            sqlite3_api->value_int64
109263: #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
109264: #define sqlite3_value_text             sqlite3_api->value_text
109265: #define sqlite3_value_text16           sqlite3_api->value_text16
109266: #define sqlite3_value_text16be         sqlite3_api->value_text16be
109267: #define sqlite3_value_text16le         sqlite3_api->value_text16le
109268: #define sqlite3_value_type             sqlite3_api->value_type
109269: #define sqlite3_vmprintf               sqlite3_api->vmprintf
109270: #define sqlite3_vsnprintf              sqlite3_api->vsnprintf
109271: #define sqlite3_overload_function      sqlite3_api->overload_function
109272: #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
109273: #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
109274: #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
109275: #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
109276: #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
109277: #define sqlite3_blob_close             sqlite3_api->blob_close
109278: #define sqlite3_blob_open              sqlite3_api->blob_open
109279: #define sqlite3_blob_read              sqlite3_api->blob_read
109280: #define sqlite3_blob_write             sqlite3_api->blob_write
109281: #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
109282: #define sqlite3_file_control           sqlite3_api->file_control
109283: #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
109284: #define sqlite3_memory_used            sqlite3_api->memory_used
109285: #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
109286: #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
109287: #define sqlite3_mutex_free             sqlite3_api->mutex_free
109288: #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
109289: #define sqlite3_mutex_try              sqlite3_api->mutex_try
109290: #define sqlite3_open_v2                sqlite3_api->open_v2
109291: #define sqlite3_release_memory         sqlite3_api->release_memory
109292: #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
109293: #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
109294: #define sqlite3_sleep                  sqlite3_api->sleep
109295: #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
109296: #define sqlite3_vfs_find               sqlite3_api->vfs_find
109297: #define sqlite3_vfs_register           sqlite3_api->vfs_register
109298: #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
109299: #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
109300: #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
109301: #define sqlite3_result_error_code      sqlite3_api->result_error_code
109302: #define sqlite3_test_control           sqlite3_api->test_control
109303: #define sqlite3_randomness             sqlite3_api->randomness
109304: #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
109305: #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
109306: #define sqlite3_limit                  sqlite3_api->limit
109307: #define sqlite3_next_stmt              sqlite3_api->next_stmt
109308: #define sqlite3_sql                    sqlite3_api->sql
109309: #define sqlite3_status                 sqlite3_api->status
109310: #define sqlite3_backup_finish          sqlite3_api->backup_finish
109311: #define sqlite3_backup_init            sqlite3_api->backup_init
109312: #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
109313: #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
109314: #define sqlite3_backup_step            sqlite3_api->backup_step
109315: #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
109316: #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
109317: #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
109318: #define sqlite3_db_config              sqlite3_api->db_config
109319: #define sqlite3_db_mutex               sqlite3_api->db_mutex
109320: #define sqlite3_db_status              sqlite3_api->db_status
109321: #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
109322: #define sqlite3_log                    sqlite3_api->log
109323: #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
109324: #define sqlite3_sourceid               sqlite3_api->sourceid
109325: #define sqlite3_stmt_status            sqlite3_api->stmt_status
109326: #define sqlite3_strnicmp               sqlite3_api->strnicmp
109327: #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
109328: #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
109329: #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
109330: #define sqlite3_wal_hook               sqlite3_api->wal_hook
109331: #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
109332: #define sqlite3_vtab_config            sqlite3_api->vtab_config
109333: #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
109334: /* Version 3.7.16 and later */
109335: #define sqlite3_close_v2               sqlite3_api->close_v2
109336: #define sqlite3_db_filename            sqlite3_api->db_filename
109337: #define sqlite3_db_readonly            sqlite3_api->db_readonly
109338: #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
109339: #define sqlite3_errstr                 sqlite3_api->errstr
109340: #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
109341: #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
109342: #define sqlite3_stricmp                sqlite3_api->stricmp
109343: #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
109344: #define sqlite3_uri_int64              sqlite3_api->uri_int64
109345: #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
109346: #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
109347: #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
109348: /* Version 3.8.7 and later */
109349: #define sqlite3_auto_extension         sqlite3_api->auto_extension
109350: #define sqlite3_bind_blob64            sqlite3_api->bind_blob64
109351: #define sqlite3_bind_text64            sqlite3_api->bind_text64
109352: #define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
109353: #define sqlite3_load_extension         sqlite3_api->load_extension
109354: #define sqlite3_malloc64               sqlite3_api->malloc64
109355: #define sqlite3_msize                  sqlite3_api->msize
109356: #define sqlite3_realloc64              sqlite3_api->realloc64
109357: #define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
109358: #define sqlite3_result_blob64          sqlite3_api->result_blob64
109359: #define sqlite3_result_text64          sqlite3_api->result_text64
109360: #define sqlite3_strglob                sqlite3_api->strglob
109361: /* Version 3.8.11 and later */
109362: #define sqlite3_value_dup              sqlite3_api->value_dup
109363: #define sqlite3_value_free             sqlite3_api->value_free
109364: #define sqlite3_result_zeroblob64      sqlite3_api->result_zeroblob64
109365: #define sqlite3_bind_zeroblob64        sqlite3_api->bind_zeroblob64
109366: /* Version 3.9.0 and later */
109367: #define sqlite3_value_subtype          sqlite3_api->value_subtype
109368: #define sqlite3_result_subtype         sqlite3_api->result_subtype
109369: /* Version 3.10.0 and later */
109370: #define sqlite3_status64               sqlite3_api->status64
109371: #define sqlite3_strlike                sqlite3_api->strlike
109372: #define sqlite3_db_cacheflush          sqlite3_api->db_cacheflush
109373: /* Version 3.12.0 and later */
109374: #define sqlite3_system_errno           sqlite3_api->system_errno
109375: /* Version 3.14.0 and later */
109376: #define sqlite3_trace_v2               sqlite3_api->trace_v2
109377: #define sqlite3_expanded_sql           sqlite3_api->expanded_sql
109378: #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
109379: 
109380: #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
109381:   /* This case when the file really is being compiled as a loadable 
109382:   ** extension */
109383: # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
109384: # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
109385: # define SQLITE_EXTENSION_INIT3     \
109386:     extern const sqlite3_api_routines *sqlite3_api;
109387: #else
109388:   /* This case when the file is being statically linked into the 
109389:   ** application */
109390: # define SQLITE_EXTENSION_INIT1     /*no-op*/
109391: # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
109392: # define SQLITE_EXTENSION_INIT3     /*no-op*/
109393: #endif
109394: 
109395: #endif /* SQLITE3EXT_H */
109396: 
109397: /************** End of sqlite3ext.h ******************************************/
109398: /************** Continuing where we left off in loadext.c ********************/
109399: /* #include "sqliteInt.h" */
109400: /* #include <string.h> */
109401: 
109402: #ifndef SQLITE_OMIT_LOAD_EXTENSION
109403: /*
109404: ** Some API routines are omitted when various features are
109405: ** excluded from a build of SQLite.  Substitute a NULL pointer
109406: ** for any missing APIs.
109407: */
109408: #ifndef SQLITE_ENABLE_COLUMN_METADATA
109409: # define sqlite3_column_database_name   0
109410: # define sqlite3_column_database_name16 0
109411: # define sqlite3_column_table_name      0
109412: # define sqlite3_column_table_name16    0
109413: # define sqlite3_column_origin_name     0
109414: # define sqlite3_column_origin_name16   0
109415: #endif
109416: 
109417: #ifdef SQLITE_OMIT_AUTHORIZATION
109418: # define sqlite3_set_authorizer         0
109419: #endif
109420: 
109421: #ifdef SQLITE_OMIT_UTF16
109422: # define sqlite3_bind_text16            0
109423: # define sqlite3_collation_needed16     0
109424: # define sqlite3_column_decltype16      0
109425: # define sqlite3_column_name16          0
109426: # define sqlite3_column_text16          0
109427: # define sqlite3_complete16             0
109428: # define sqlite3_create_collation16     0
109429: # define sqlite3_create_function16      0
109430: # define sqlite3_errmsg16               0
109431: # define sqlite3_open16                 0
109432: # define sqlite3_prepare16              0
109433: # define sqlite3_prepare16_v2           0
109434: # define sqlite3_result_error16         0
109435: # define sqlite3_result_text16          0
109436: # define sqlite3_result_text16be        0
109437: # define sqlite3_result_text16le        0
109438: # define sqlite3_value_text16           0
109439: # define sqlite3_value_text16be         0
109440: # define sqlite3_value_text16le         0
109441: # define sqlite3_column_database_name16 0
109442: # define sqlite3_column_table_name16    0
109443: # define sqlite3_column_origin_name16   0
109444: #endif
109445: 
109446: #ifdef SQLITE_OMIT_COMPLETE
109447: # define sqlite3_complete 0
109448: # define sqlite3_complete16 0
109449: #endif
109450: 
109451: #ifdef SQLITE_OMIT_DECLTYPE
109452: # define sqlite3_column_decltype16      0
109453: # define sqlite3_column_decltype        0
109454: #endif
109455: 
109456: #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
109457: # define sqlite3_progress_handler 0
109458: #endif
109459: 
109460: #ifdef SQLITE_OMIT_VIRTUALTABLE
109461: # define sqlite3_create_module 0
109462: # define sqlite3_create_module_v2 0
109463: # define sqlite3_declare_vtab 0
109464: # define sqlite3_vtab_config 0
109465: # define sqlite3_vtab_on_conflict 0
109466: #endif
109467: 
109468: #ifdef SQLITE_OMIT_SHARED_CACHE
109469: # define sqlite3_enable_shared_cache 0
109470: #endif
109471: 
109472: #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
109473: # define sqlite3_profile       0
109474: # define sqlite3_trace         0
109475: #endif
109476: 
109477: #ifdef SQLITE_OMIT_GET_TABLE
109478: # define sqlite3_free_table    0
109479: # define sqlite3_get_table     0
109480: #endif
109481: 
109482: #ifdef SQLITE_OMIT_INCRBLOB
109483: #define sqlite3_bind_zeroblob  0
109484: #define sqlite3_blob_bytes     0
109485: #define sqlite3_blob_close     0
109486: #define sqlite3_blob_open      0
109487: #define sqlite3_blob_read      0
109488: #define sqlite3_blob_write     0
109489: #define sqlite3_blob_reopen    0
109490: #endif
109491: 
109492: #if defined(SQLITE_OMIT_TRACE)
109493: # define sqlite3_trace_v2      0
109494: #endif
109495: 
109496: /*
109497: ** The following structure contains pointers to all SQLite API routines.
109498: ** A pointer to this structure is passed into extensions when they are
109499: ** loaded so that the extension can make calls back into the SQLite
109500: ** library.
109501: **
109502: ** When adding new APIs, add them to the bottom of this structure
109503: ** in order to preserve backwards compatibility.
109504: **
109505: ** Extensions that use newer APIs should first call the
109506: ** sqlite3_libversion_number() to make sure that the API they
109507: ** intend to use is supported by the library.  Extensions should
109508: ** also check to make sure that the pointer to the function is
109509: ** not NULL before calling it.
109510: */
109511: static const sqlite3_api_routines sqlite3Apis = {
109512:   sqlite3_aggregate_context,
109513: #ifndef SQLITE_OMIT_DEPRECATED
109514:   sqlite3_aggregate_count,
109515: #else
109516:   0,
109517: #endif
109518:   sqlite3_bind_blob,
109519:   sqlite3_bind_double,
109520:   sqlite3_bind_int,
109521:   sqlite3_bind_int64,
109522:   sqlite3_bind_null,
109523:   sqlite3_bind_parameter_count,
109524:   sqlite3_bind_parameter_index,
109525:   sqlite3_bind_parameter_name,
109526:   sqlite3_bind_text,
109527:   sqlite3_bind_text16,
109528:   sqlite3_bind_value,
109529:   sqlite3_busy_handler,
109530:   sqlite3_busy_timeout,
109531:   sqlite3_changes,
109532:   sqlite3_close,
109533:   sqlite3_collation_needed,
109534:   sqlite3_collation_needed16,
109535:   sqlite3_column_blob,
109536:   sqlite3_column_bytes,
109537:   sqlite3_column_bytes16,
109538:   sqlite3_column_count,
109539:   sqlite3_column_database_name,
109540:   sqlite3_column_database_name16,
109541:   sqlite3_column_decltype,
109542:   sqlite3_column_decltype16,
109543:   sqlite3_column_double,
109544:   sqlite3_column_int,
109545:   sqlite3_column_int64,
109546:   sqlite3_column_name,
109547:   sqlite3_column_name16,
109548:   sqlite3_column_origin_name,
109549:   sqlite3_column_origin_name16,
109550:   sqlite3_column_table_name,
109551:   sqlite3_column_table_name16,
109552:   sqlite3_column_text,
109553:   sqlite3_column_text16,
109554:   sqlite3_column_type,
109555:   sqlite3_column_value,
109556:   sqlite3_commit_hook,
109557:   sqlite3_complete,
109558:   sqlite3_complete16,
109559:   sqlite3_create_collation,
109560:   sqlite3_create_collation16,
109561:   sqlite3_create_function,
109562:   sqlite3_create_function16,
109563:   sqlite3_create_module,
109564:   sqlite3_data_count,
109565:   sqlite3_db_handle,
109566:   sqlite3_declare_vtab,
109567:   sqlite3_enable_shared_cache,
109568:   sqlite3_errcode,
109569:   sqlite3_errmsg,
109570:   sqlite3_errmsg16,
109571:   sqlite3_exec,
109572: #ifndef SQLITE_OMIT_DEPRECATED
109573:   sqlite3_expired,
109574: #else
109575:   0,
109576: #endif
109577:   sqlite3_finalize,
109578:   sqlite3_free,
109579:   sqlite3_free_table,
109580:   sqlite3_get_autocommit,
109581:   sqlite3_get_auxdata,
109582:   sqlite3_get_table,
109583:   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
109584:   sqlite3_interrupt,
109585:   sqlite3_last_insert_rowid,
109586:   sqlite3_libversion,
109587:   sqlite3_libversion_number,
109588:   sqlite3_malloc,
109589:   sqlite3_mprintf,
109590:   sqlite3_open,
109591:   sqlite3_open16,
109592:   sqlite3_prepare,
109593:   sqlite3_prepare16,
109594:   sqlite3_profile,
109595:   sqlite3_progress_handler,
109596:   sqlite3_realloc,
109597:   sqlite3_reset,
109598:   sqlite3_result_blob,
109599:   sqlite3_result_double,
109600:   sqlite3_result_error,
109601:   sqlite3_result_error16,
109602:   sqlite3_result_int,
109603:   sqlite3_result_int64,
109604:   sqlite3_result_null,
109605:   sqlite3_result_text,
109606:   sqlite3_result_text16,
109607:   sqlite3_result_text16be,
109608:   sqlite3_result_text16le,
109609:   sqlite3_result_value,
109610:   sqlite3_rollback_hook,
109611:   sqlite3_set_authorizer,
109612:   sqlite3_set_auxdata,
109613:   sqlite3_snprintf,
109614:   sqlite3_step,
109615:   sqlite3_table_column_metadata,
109616: #ifndef SQLITE_OMIT_DEPRECATED
109617:   sqlite3_thread_cleanup,
109618: #else
109619:   0,
109620: #endif
109621:   sqlite3_total_changes,
109622:   sqlite3_trace,
109623: #ifndef SQLITE_OMIT_DEPRECATED
109624:   sqlite3_transfer_bindings,
109625: #else
109626:   0,
109627: #endif
109628:   sqlite3_update_hook,
109629:   sqlite3_user_data,
109630:   sqlite3_value_blob,
109631:   sqlite3_value_bytes,
109632:   sqlite3_value_bytes16,
109633:   sqlite3_value_double,
109634:   sqlite3_value_int,
109635:   sqlite3_value_int64,
109636:   sqlite3_value_numeric_type,
109637:   sqlite3_value_text,
109638:   sqlite3_value_text16,
109639:   sqlite3_value_text16be,
109640:   sqlite3_value_text16le,
109641:   sqlite3_value_type,
109642:   sqlite3_vmprintf,
109643:   /*
109644:   ** The original API set ends here.  All extensions can call any
109645:   ** of the APIs above provided that the pointer is not NULL.  But
109646:   ** before calling APIs that follow, extension should check the
109647:   ** sqlite3_libversion_number() to make sure they are dealing with
109648:   ** a library that is new enough to support that API.
109649:   *************************************************************************
109650:   */
109651:   sqlite3_overload_function,
109652: 
109653:   /*
109654:   ** Added after 3.3.13
109655:   */
109656:   sqlite3_prepare_v2,
109657:   sqlite3_prepare16_v2,
109658:   sqlite3_clear_bindings,
109659: 
109660:   /*
109661:   ** Added for 3.4.1
109662:   */
109663:   sqlite3_create_module_v2,
109664: 
109665:   /*
109666:   ** Added for 3.5.0
109667:   */
109668:   sqlite3_bind_zeroblob,
109669:   sqlite3_blob_bytes,
109670:   sqlite3_blob_close,
109671:   sqlite3_blob_open,
109672:   sqlite3_blob_read,
109673:   sqlite3_blob_write,
109674:   sqlite3_create_collation_v2,
109675:   sqlite3_file_control,
109676:   sqlite3_memory_highwater,
109677:   sqlite3_memory_used,
109678: #ifdef SQLITE_MUTEX_OMIT
109679:   0, 
109680:   0, 
109681:   0,
109682:   0,
109683:   0,
109684: #else
109685:   sqlite3_mutex_alloc,
109686:   sqlite3_mutex_enter,
109687:   sqlite3_mutex_free,
109688:   sqlite3_mutex_leave,
109689:   sqlite3_mutex_try,
109690: #endif
109691:   sqlite3_open_v2,
109692:   sqlite3_release_memory,
109693:   sqlite3_result_error_nomem,
109694:   sqlite3_result_error_toobig,
109695:   sqlite3_sleep,
109696:   sqlite3_soft_heap_limit,
109697:   sqlite3_vfs_find,
109698:   sqlite3_vfs_register,
109699:   sqlite3_vfs_unregister,
109700: 
109701:   /*
109702:   ** Added for 3.5.8
109703:   */
109704:   sqlite3_threadsafe,
109705:   sqlite3_result_zeroblob,
109706:   sqlite3_result_error_code,
109707:   sqlite3_test_control,
109708:   sqlite3_randomness,
109709:   sqlite3_context_db_handle,
109710: 
109711:   /*
109712:   ** Added for 3.6.0
109713:   */
109714:   sqlite3_extended_result_codes,
109715:   sqlite3_limit,
109716:   sqlite3_next_stmt,
109717:   sqlite3_sql,
109718:   sqlite3_status,
109719: 
109720:   /*
109721:   ** Added for 3.7.4
109722:   */
109723:   sqlite3_backup_finish,
109724:   sqlite3_backup_init,
109725:   sqlite3_backup_pagecount,
109726:   sqlite3_backup_remaining,
109727:   sqlite3_backup_step,
109728: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
109729:   sqlite3_compileoption_get,
109730:   sqlite3_compileoption_used,
109731: #else
109732:   0,
109733:   0,
109734: #endif
109735:   sqlite3_create_function_v2,
109736:   sqlite3_db_config,
109737:   sqlite3_db_mutex,
109738:   sqlite3_db_status,
109739:   sqlite3_extended_errcode,
109740:   sqlite3_log,
109741:   sqlite3_soft_heap_limit64,
109742:   sqlite3_sourceid,
109743:   sqlite3_stmt_status,
109744:   sqlite3_strnicmp,
109745: #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
109746:   sqlite3_unlock_notify,
109747: #else
109748:   0,
109749: #endif
109750: #ifndef SQLITE_OMIT_WAL
109751:   sqlite3_wal_autocheckpoint,
109752:   sqlite3_wal_checkpoint,
109753:   sqlite3_wal_hook,
109754: #else
109755:   0,
109756:   0,
109757:   0,
109758: #endif
109759:   sqlite3_blob_reopen,
109760:   sqlite3_vtab_config,
109761:   sqlite3_vtab_on_conflict,
109762:   sqlite3_close_v2,
109763:   sqlite3_db_filename,
109764:   sqlite3_db_readonly,
109765:   sqlite3_db_release_memory,
109766:   sqlite3_errstr,
109767:   sqlite3_stmt_busy,
109768:   sqlite3_stmt_readonly,
109769:   sqlite3_stricmp,
109770:   sqlite3_uri_boolean,
109771:   sqlite3_uri_int64,
109772:   sqlite3_uri_parameter,
109773:   sqlite3_vsnprintf,
109774:   sqlite3_wal_checkpoint_v2,
109775:   /* Version 3.8.7 and later */
109776:   sqlite3_auto_extension,
109777:   sqlite3_bind_blob64,
109778:   sqlite3_bind_text64,
109779:   sqlite3_cancel_auto_extension,
109780:   sqlite3_load_extension,
109781:   sqlite3_malloc64,
109782:   sqlite3_msize,
109783:   sqlite3_realloc64,
109784:   sqlite3_reset_auto_extension,
109785:   sqlite3_result_blob64,
109786:   sqlite3_result_text64,
109787:   sqlite3_strglob,
109788:   /* Version 3.8.11 and later */
109789:   (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
109790:   sqlite3_value_free,
109791:   sqlite3_result_zeroblob64,
109792:   sqlite3_bind_zeroblob64,
109793:   /* Version 3.9.0 and later */
109794:   sqlite3_value_subtype,
109795:   sqlite3_result_subtype,
109796:   /* Version 3.10.0 and later */
109797:   sqlite3_status64,
109798:   sqlite3_strlike,
109799:   sqlite3_db_cacheflush,
109800:   /* Version 3.12.0 and later */
109801:   sqlite3_system_errno,
109802:   /* Version 3.14.0 and later */
109803:   sqlite3_trace_v2,
109804:   sqlite3_expanded_sql
109805: };
109806: 
109807: /*
109808: ** Attempt to load an SQLite extension library contained in the file
109809: ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
109810: ** default entry point name (sqlite3_extension_init) is used.  Use
109811: ** of the default name is recommended.
109812: **
109813: ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
109814: **
109815: ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
109816: ** error message text.  The calling function should free this memory
109817: ** by calling sqlite3DbFree(db, ).
109818: */
109819: static int sqlite3LoadExtension(
109820:   sqlite3 *db,          /* Load the extension into this database connection */
109821:   const char *zFile,    /* Name of the shared library containing extension */
109822:   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
109823:   char **pzErrMsg       /* Put error message here if not 0 */
109824: ){
109825:   sqlite3_vfs *pVfs = db->pVfs;
109826:   void *handle;
109827:   sqlite3_loadext_entry xInit;
109828:   char *zErrmsg = 0;
109829:   const char *zEntry;
109830:   char *zAltEntry = 0;
109831:   void **aHandle;
109832:   u64 nMsg = 300 + sqlite3Strlen30(zFile);
109833:   int ii;
109834:   int rc;
109835: 
109836:   /* Shared library endings to try if zFile cannot be loaded as written */
109837:   static const char *azEndings[] = {
109838: #if SQLITE_OS_WIN
109839:      "dll"   
109840: #elif defined(__APPLE__)
109841:      "dylib"
109842: #else
109843:      "so"
109844: #endif
109845:   };
109846: 
109847: 
109848:   if( pzErrMsg ) *pzErrMsg = 0;
109849: 
109850:   /* Ticket #1863.  To avoid a creating security problems for older
109851:   ** applications that relink against newer versions of SQLite, the
109852:   ** ability to run load_extension is turned off by default.  One
109853:   ** must call either sqlite3_enable_load_extension(db) or
109854:   ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
109855:   ** to turn on extension loading.
109856:   */
109857:   if( (db->flags & SQLITE_LoadExtension)==0 ){
109858:     if( pzErrMsg ){
109859:       *pzErrMsg = sqlite3_mprintf("not authorized");
109860:     }
109861:     return SQLITE_ERROR;
109862:   }
109863: 
109864:   zEntry = zProc ? zProc : "sqlite3_extension_init";
109865: 
109866:   handle = sqlite3OsDlOpen(pVfs, zFile);
109867: #if SQLITE_OS_UNIX || SQLITE_OS_WIN
109868:   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
109869:     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
109870:     if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
109871:     handle = sqlite3OsDlOpen(pVfs, zAltFile);
109872:     sqlite3_free(zAltFile);
109873:   }
109874: #endif
109875:   if( handle==0 ){
109876:     if( pzErrMsg ){
109877:       *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109878:       if( zErrmsg ){
109879:         sqlite3_snprintf(nMsg, zErrmsg, 
109880:             "unable to open shared library [%s]", zFile);
109881:         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109882:       }
109883:     }
109884:     return SQLITE_ERROR;
109885:   }
109886:   xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
109887: 
109888:   /* If no entry point was specified and the default legacy
109889:   ** entry point name "sqlite3_extension_init" was not found, then
109890:   ** construct an entry point name "sqlite3_X_init" where the X is
109891:   ** replaced by the lowercase value of every ASCII alphabetic 
109892:   ** character in the filename after the last "/" upto the first ".",
109893:   ** and eliding the first three characters if they are "lib".  
109894:   ** Examples:
109895:   **
109896:   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
109897:   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
109898:   */
109899:   if( xInit==0 && zProc==0 ){
109900:     int iFile, iEntry, c;
109901:     int ncFile = sqlite3Strlen30(zFile);
109902:     zAltEntry = sqlite3_malloc64(ncFile+30);
109903:     if( zAltEntry==0 ){
109904:       sqlite3OsDlClose(pVfs, handle);
109905:       return SQLITE_NOMEM_BKPT;
109906:     }
109907:     memcpy(zAltEntry, "sqlite3_", 8);
109908:     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
109909:     iFile++;
109910:     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
109911:     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
109912:       if( sqlite3Isalpha(c) ){
109913:         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
109914:       }
109915:     }
109916:     memcpy(zAltEntry+iEntry, "_init", 6);
109917:     zEntry = zAltEntry;
109918:     xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
109919:   }
109920:   if( xInit==0 ){
109921:     if( pzErrMsg ){
109922:       nMsg += sqlite3Strlen30(zEntry);
109923:       *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109924:       if( zErrmsg ){
109925:         sqlite3_snprintf(nMsg, zErrmsg,
109926:             "no entry point [%s] in shared library [%s]", zEntry, zFile);
109927:         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109928:       }
109929:     }
109930:     sqlite3OsDlClose(pVfs, handle);
109931:     sqlite3_free(zAltEntry);
109932:     return SQLITE_ERROR;
109933:   }
109934:   sqlite3_free(zAltEntry);
109935:   rc = xInit(db, &zErrmsg, &sqlite3Apis);
109936:   if( rc ){
109937:     if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
109938:     if( pzErrMsg ){
109939:       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
109940:     }
109941:     sqlite3_free(zErrmsg);
109942:     sqlite3OsDlClose(pVfs, handle);
109943:     return SQLITE_ERROR;
109944:   }
109945: 
109946:   /* Append the new shared library handle to the db->aExtension array. */
109947:   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
109948:   if( aHandle==0 ){
109949:     return SQLITE_NOMEM_BKPT;
109950:   }
109951:   if( db->nExtension>0 ){
109952:     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
109953:   }
109954:   sqlite3DbFree(db, db->aExtension);
109955:   db->aExtension = aHandle;
109956: 
109957:   db->aExtension[db->nExtension++] = handle;
109958:   return SQLITE_OK;
109959: }
109960: SQLITE_API int sqlite3_load_extension(
109961:   sqlite3 *db,          /* Load the extension into this database connection */
109962:   const char *zFile,    /* Name of the shared library containing extension */
109963:   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
109964:   char **pzErrMsg       /* Put error message here if not 0 */
109965: ){
109966:   int rc;
109967:   sqlite3_mutex_enter(db->mutex);
109968:   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
109969:   rc = sqlite3ApiExit(db, rc);
109970:   sqlite3_mutex_leave(db->mutex);
109971:   return rc;
109972: }
109973: 
109974: /*
109975: ** Call this routine when the database connection is closing in order
109976: ** to clean up loaded extensions
109977: */
109978: SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
109979:   int i;
109980:   assert( sqlite3_mutex_held(db->mutex) );
109981:   for(i=0; i<db->nExtension; i++){
109982:     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
109983:   }
109984:   sqlite3DbFree(db, db->aExtension);
109985: }
109986: 
109987: /*
109988: ** Enable or disable extension loading.  Extension loading is disabled by
109989: ** default so as not to open security holes in older applications.
109990: */
109991: SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
109992:   sqlite3_mutex_enter(db->mutex);
109993:   if( onoff ){
109994:     db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
109995:   }else{
109996:     db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
109997:   }
109998:   sqlite3_mutex_leave(db->mutex);
109999:   return SQLITE_OK;
110000: }
110001: 
110002: #endif /* SQLITE_OMIT_LOAD_EXTENSION */
110003: 
110004: /*
110005: ** The auto-extension code added regardless of whether or not extension
110006: ** loading is supported.  We need a dummy sqlite3Apis pointer for that
110007: ** code if regular extension loading is not available.  This is that
110008: ** dummy pointer.
110009: */
110010: #ifdef SQLITE_OMIT_LOAD_EXTENSION
110011: static const sqlite3_api_routines sqlite3Apis = { 0 };
110012: #endif
110013: 
110014: 
110015: /*
110016: ** The following object holds the list of automatically loaded
110017: ** extensions.
110018: **
110019: ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
110020: ** mutex must be held while accessing this list.
110021: */
110022: typedef struct sqlite3AutoExtList sqlite3AutoExtList;
110023: static SQLITE_WSD struct sqlite3AutoExtList {
110024:   u32 nExt;              /* Number of entries in aExt[] */          
110025:   void (**aExt)(void);   /* Pointers to the extension init functions */
110026: } sqlite3Autoext = { 0, 0 };
110027: 
110028: /* The "wsdAutoext" macro will resolve to the autoextension
110029: ** state vector.  If writable static data is unsupported on the target,
110030: ** we have to locate the state vector at run-time.  In the more common
110031: ** case where writable static data is supported, wsdStat can refer directly
110032: ** to the "sqlite3Autoext" state vector declared above.
110033: */
110034: #ifdef SQLITE_OMIT_WSD
110035: # define wsdAutoextInit \
110036:   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
110037: # define wsdAutoext x[0]
110038: #else
110039: # define wsdAutoextInit
110040: # define wsdAutoext sqlite3Autoext
110041: #endif
110042: 
110043: 
110044: /*
110045: ** Register a statically linked extension that is automatically
110046: ** loaded by every new database connection.
110047: */
110048: SQLITE_API int sqlite3_auto_extension(
110049:   void (*xInit)(void)
110050: ){
110051:   int rc = SQLITE_OK;
110052: #ifndef SQLITE_OMIT_AUTOINIT
110053:   rc = sqlite3_initialize();
110054:   if( rc ){
110055:     return rc;
110056:   }else
110057: #endif
110058:   {
110059:     u32 i;
110060: #if SQLITE_THREADSAFE
110061:     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110062: #endif
110063:     wsdAutoextInit;
110064:     sqlite3_mutex_enter(mutex);
110065:     for(i=0; i<wsdAutoext.nExt; i++){
110066:       if( wsdAutoext.aExt[i]==xInit ) break;
110067:     }
110068:     if( i==wsdAutoext.nExt ){
110069:       u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
110070:       void (**aNew)(void);
110071:       aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
110072:       if( aNew==0 ){
110073:         rc = SQLITE_NOMEM_BKPT;
110074:       }else{
110075:         wsdAutoext.aExt = aNew;
110076:         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
110077:         wsdAutoext.nExt++;
110078:       }
110079:     }
110080:     sqlite3_mutex_leave(mutex);
110081:     assert( (rc&0xff)==rc );
110082:     return rc;
110083:   }
110084: }
110085: 
110086: /*
110087: ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
110088: ** set of routines that is invoked for each new database connection, if it
110089: ** is currently on the list.  If xInit is not on the list, then this
110090: ** routine is a no-op.
110091: **
110092: ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
110093: ** was not on the list.
110094: */
110095: SQLITE_API int sqlite3_cancel_auto_extension(
110096:   void (*xInit)(void)
110097: ){
110098: #if SQLITE_THREADSAFE
110099:   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110100: #endif
110101:   int i;
110102:   int n = 0;
110103:   wsdAutoextInit;
110104:   sqlite3_mutex_enter(mutex);
110105:   for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
110106:     if( wsdAutoext.aExt[i]==xInit ){
110107:       wsdAutoext.nExt--;
110108:       wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
110109:       n++;
110110:       break;
110111:     }
110112:   }
110113:   sqlite3_mutex_leave(mutex);
110114:   return n;
110115: }
110116: 
110117: /*
110118: ** Reset the automatic extension loading mechanism.
110119: */
110120: SQLITE_API void sqlite3_reset_auto_extension(void){
110121: #ifndef SQLITE_OMIT_AUTOINIT
110122:   if( sqlite3_initialize()==SQLITE_OK )
110123: #endif
110124:   {
110125: #if SQLITE_THREADSAFE
110126:     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110127: #endif
110128:     wsdAutoextInit;
110129:     sqlite3_mutex_enter(mutex);
110130:     sqlite3_free(wsdAutoext.aExt);
110131:     wsdAutoext.aExt = 0;
110132:     wsdAutoext.nExt = 0;
110133:     sqlite3_mutex_leave(mutex);
110134:   }
110135: }
110136: 
110137: /*
110138: ** Load all automatic extensions.
110139: **
110140: ** If anything goes wrong, set an error in the database connection.
110141: */
110142: SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
110143:   u32 i;
110144:   int go = 1;
110145:   int rc;
110146:   sqlite3_loadext_entry xInit;
110147: 
110148:   wsdAutoextInit;
110149:   if( wsdAutoext.nExt==0 ){
110150:     /* Common case: early out without every having to acquire a mutex */
110151:     return;
110152:   }
110153:   for(i=0; go; i++){
110154:     char *zErrmsg;
110155: #if SQLITE_THREADSAFE
110156:     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110157: #endif
110158:     sqlite3_mutex_enter(mutex);
110159:     if( i>=wsdAutoext.nExt ){
110160:       xInit = 0;
110161:       go = 0;
110162:     }else{
110163:       xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
110164:     }
110165:     sqlite3_mutex_leave(mutex);
110166:     zErrmsg = 0;
110167:     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
110168:       sqlite3ErrorWithMsg(db, rc,
110169:             "automatic extension loading failed: %s", zErrmsg);
110170:       go = 0;
110171:     }
110172:     sqlite3_free(zErrmsg);
110173:   }
110174: }
110175: 
110176: /************** End of loadext.c *********************************************/
110177: /************** Begin file pragma.c ******************************************/
110178: /*
110179: ** 2003 April 6
110180: **
110181: ** The author disclaims copyright to this source code.  In place of
110182: ** a legal notice, here is a blessing:
110183: **
110184: **    May you do good and not evil.
110185: **    May you find forgiveness for yourself and forgive others.
110186: **    May you share freely, never taking more than you give.
110187: **
110188: *************************************************************************
110189: ** This file contains code used to implement the PRAGMA command.
110190: */
110191: /* #include "sqliteInt.h" */
110192: 
110193: #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
110194: #  if defined(__APPLE__)
110195: #    define SQLITE_ENABLE_LOCKING_STYLE 1
110196: #  else
110197: #    define SQLITE_ENABLE_LOCKING_STYLE 0
110198: #  endif
110199: #endif
110200: 
110201: /***************************************************************************
110202: ** The "pragma.h" include file is an automatically generated file that
110203: ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
110204: ** object.  This ensures that the aPragmaName[] table is arranged in
110205: ** lexicographical order to facility a binary search of the pragma name.
110206: ** Do not edit pragma.h directly.  Edit and rerun the script in at 
110207: ** ../tool/mkpragmatab.tcl. */
110208: /************** Include pragma.h in the middle of pragma.c *******************/
110209: /************** Begin file pragma.h ******************************************/
110210: /* DO NOT EDIT!
110211: ** This file is automatically generated by the script at
110212: ** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
110213: ** that script and rerun it.
110214: */
110215: #define PragTyp_HEADER_VALUE                   0
110216: #define PragTyp_AUTO_VACUUM                    1
110217: #define PragTyp_FLAG                           2
110218: #define PragTyp_BUSY_TIMEOUT                   3
110219: #define PragTyp_CACHE_SIZE                     4
110220: #define PragTyp_CACHE_SPILL                    5
110221: #define PragTyp_CASE_SENSITIVE_LIKE            6
110222: #define PragTyp_COLLATION_LIST                 7
110223: #define PragTyp_COMPILE_OPTIONS                8
110224: #define PragTyp_DATA_STORE_DIRECTORY           9
110225: #define PragTyp_DATABASE_LIST                 10
110226: #define PragTyp_DEFAULT_CACHE_SIZE            11
110227: #define PragTyp_ENCODING                      12
110228: #define PragTyp_FOREIGN_KEY_CHECK             13
110229: #define PragTyp_FOREIGN_KEY_LIST              14
110230: #define PragTyp_INCREMENTAL_VACUUM            15
110231: #define PragTyp_INDEX_INFO                    16
110232: #define PragTyp_INDEX_LIST                    17
110233: #define PragTyp_INTEGRITY_CHECK               18
110234: #define PragTyp_JOURNAL_MODE                  19
110235: #define PragTyp_JOURNAL_SIZE_LIMIT            20
110236: #define PragTyp_LOCK_PROXY_FILE               21
110237: #define PragTyp_LOCKING_MODE                  22
110238: #define PragTyp_PAGE_COUNT                    23
110239: #define PragTyp_MMAP_SIZE                     24
110240: #define PragTyp_PAGE_SIZE                     25
110241: #define PragTyp_SECURE_DELETE                 26
110242: #define PragTyp_SHRINK_MEMORY                 27
110243: #define PragTyp_SOFT_HEAP_LIMIT               28
110244: #define PragTyp_STATS                         29
110245: #define PragTyp_SYNCHRONOUS                   30
110246: #define PragTyp_TABLE_INFO                    31
110247: #define PragTyp_TEMP_STORE                    32
110248: #define PragTyp_TEMP_STORE_DIRECTORY          33
110249: #define PragTyp_THREADS                       34
110250: #define PragTyp_WAL_AUTOCHECKPOINT            35
110251: #define PragTyp_WAL_CHECKPOINT                36
110252: #define PragTyp_ACTIVATE_EXTENSIONS           37
110253: #define PragTyp_HEXKEY                        38
110254: #define PragTyp_KEY                           39
110255: #define PragTyp_REKEY                         40
110256: #define PragTyp_LOCK_STATUS                   41
110257: #define PragTyp_PARSER_TRACE                  42
110258: #define PragFlag_NeedSchema           0x01
110259: #define PragFlag_ReadOnly             0x02
110260: static const struct sPragmaNames {
110261:   const char *const zName;  /* Name of pragma */
110262:   u8 ePragTyp;              /* PragTyp_XXX value */
110263:   u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
110264:   u32 iArg;                 /* Extra argument */
110265: } aPragmaNames[] = {
110266: #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
110267:   { /* zName:     */ "activate_extensions",
110268:     /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
110269:     /* ePragFlag: */ 0,
110270:     /* iArg:      */ 0 },
110271: #endif
110272: #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110273:   { /* zName:     */ "application_id",
110274:     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110275:     /* ePragFlag: */ 0,
110276:     /* iArg:      */ BTREE_APPLICATION_ID },
110277: #endif
110278: #if !defined(SQLITE_OMIT_AUTOVACUUM)
110279:   { /* zName:     */ "auto_vacuum",
110280:     /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
110281:     /* ePragFlag: */ PragFlag_NeedSchema,
110282:     /* iArg:      */ 0 },
110283: #endif
110284: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110285: #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
110286:   { /* zName:     */ "automatic_index",
110287:     /* ePragTyp:  */ PragTyp_FLAG,
110288:     /* ePragFlag: */ 0,
110289:     /* iArg:      */ SQLITE_AutoIndex },
110290: #endif
110291: #endif
110292:   { /* zName:     */ "busy_timeout",
110293:     /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
110294:     /* ePragFlag: */ 0,
110295:     /* iArg:      */ 0 },
110296: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110297:   { /* zName:     */ "cache_size",
110298:     /* ePragTyp:  */ PragTyp_CACHE_SIZE,
110299:     /* ePragFlag: */ PragFlag_NeedSchema,
110300:     /* iArg:      */ 0 },
110301: #endif
110302: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110303:   { /* zName:     */ "cache_spill",
110304:     /* ePragTyp:  */ PragTyp_CACHE_SPILL,
110305:     /* ePragFlag: */ 0,
110306:     /* iArg:      */ 0 },
110307: #endif
110308:   { /* zName:     */ "case_sensitive_like",
110309:     /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
110310:     /* ePragFlag: */ 0,
110311:     /* iArg:      */ 0 },
110312:   { /* zName:     */ "cell_size_check",
110313:     /* ePragTyp:  */ PragTyp_FLAG,
110314:     /* ePragFlag: */ 0,
110315:     /* iArg:      */ SQLITE_CellSizeCk },
110316: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110317:   { /* zName:     */ "checkpoint_fullfsync",
110318:     /* ePragTyp:  */ PragTyp_FLAG,
110319:     /* ePragFlag: */ 0,
110320:     /* iArg:      */ SQLITE_CkptFullFSync },
110321: #endif
110322: #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110323:   { /* zName:     */ "collation_list",
110324:     /* ePragTyp:  */ PragTyp_COLLATION_LIST,
110325:     /* ePragFlag: */ 0,
110326:     /* iArg:      */ 0 },
110327: #endif
110328: #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
110329:   { /* zName:     */ "compile_options",
110330:     /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
110331:     /* ePragFlag: */ 0,
110332:     /* iArg:      */ 0 },
110333: #endif
110334: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110335:   { /* zName:     */ "count_changes",
110336:     /* ePragTyp:  */ PragTyp_FLAG,
110337:     /* ePragFlag: */ 0,
110338:     /* iArg:      */ SQLITE_CountRows },
110339: #endif
110340: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
110341:   { /* zName:     */ "data_store_directory",
110342:     /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
110343:     /* ePragFlag: */ 0,
110344:     /* iArg:      */ 0 },
110345: #endif
110346: #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110347:   { /* zName:     */ "data_version",
110348:     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110349:     /* ePragFlag: */ PragFlag_ReadOnly,
110350:     /* iArg:      */ BTREE_DATA_VERSION },
110351: #endif
110352: #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110353:   { /* zName:     */ "database_list",
110354:     /* ePragTyp:  */ PragTyp_DATABASE_LIST,
110355:     /* ePragFlag: */ PragFlag_NeedSchema,
110356:     /* iArg:      */ 0 },
110357: #endif
110358: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
110359:   { /* zName:     */ "default_cache_size",
110360:     /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
110361:     /* ePragFlag: */ PragFlag_NeedSchema,
110362:     /* iArg:      */ 0 },
110363: #endif
110364: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110365: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110366:   { /* zName:     */ "defer_foreign_keys",
110367:     /* ePragTyp:  */ PragTyp_FLAG,
110368:     /* ePragFlag: */ 0,
110369:     /* iArg:      */ SQLITE_DeferFKs },
110370: #endif
110371: #endif
110372: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110373:   { /* zName:     */ "empty_result_callbacks",
110374:     /* ePragTyp:  */ PragTyp_FLAG,
110375:     /* ePragFlag: */ 0,
110376:     /* iArg:      */ SQLITE_NullCallback },
110377: #endif
110378: #if !defined(SQLITE_OMIT_UTF16)
110379:   { /* zName:     */ "encoding",
110380:     /* ePragTyp:  */ PragTyp_ENCODING,
110381:     /* ePragFlag: */ 0,
110382:     /* iArg:      */ 0 },
110383: #endif
110384: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110385:   { /* zName:     */ "foreign_key_check",
110386:     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
110387:     /* ePragFlag: */ PragFlag_NeedSchema,
110388:     /* iArg:      */ 0 },
110389: #endif
110390: #if !defined(SQLITE_OMIT_FOREIGN_KEY)
110391:   { /* zName:     */ "foreign_key_list",
110392:     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
110393:     /* ePragFlag: */ PragFlag_NeedSchema,
110394:     /* iArg:      */ 0 },
110395: #endif
110396: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110397: #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
110398:   { /* zName:     */ "foreign_keys",
110399:     /* ePragTyp:  */ PragTyp_FLAG,
110400:     /* ePragFlag: */ 0,
110401:     /* iArg:      */ SQLITE_ForeignKeys },
110402: #endif
110403: #endif
110404: #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110405:   { /* zName:     */ "freelist_count",
110406:     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110407:     /* ePragFlag: */ PragFlag_ReadOnly,
110408:     /* iArg:      */ BTREE_FREE_PAGE_COUNT },
110409: #endif
110410: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110411:   { /* zName:     */ "full_column_names",
110412:     /* ePragTyp:  */ PragTyp_FLAG,
110413:     /* ePragFlag: */ 0,
110414:     /* iArg:      */ SQLITE_FullColNames },
110415:   { /* zName:     */ "fullfsync",
110416:     /* ePragTyp:  */ PragTyp_FLAG,
110417:     /* ePragFlag: */ 0,
110418:     /* iArg:      */ SQLITE_FullFSync },
110419: #endif
110420: #if defined(SQLITE_HAS_CODEC)
110421:   { /* zName:     */ "hexkey",
110422:     /* ePragTyp:  */ PragTyp_HEXKEY,
110423:     /* ePragFlag: */ 0,
110424:     /* iArg:      */ 0 },
110425:   { /* zName:     */ "hexrekey",
110426:     /* ePragTyp:  */ PragTyp_HEXKEY,
110427:     /* ePragFlag: */ 0,
110428:     /* iArg:      */ 0 },
110429: #endif
110430: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110431: #if !defined(SQLITE_OMIT_CHECK)
110432:   { /* zName:     */ "ignore_check_constraints",
110433:     /* ePragTyp:  */ PragTyp_FLAG,
110434:     /* ePragFlag: */ 0,
110435:     /* iArg:      */ SQLITE_IgnoreChecks },
110436: #endif
110437: #endif
110438: #if !defined(SQLITE_OMIT_AUTOVACUUM)
110439:   { /* zName:     */ "incremental_vacuum",
110440:     /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
110441:     /* ePragFlag: */ PragFlag_NeedSchema,
110442:     /* iArg:      */ 0 },
110443: #endif
110444: #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110445:   { /* zName:     */ "index_info",
110446:     /* ePragTyp:  */ PragTyp_INDEX_INFO,
110447:     /* ePragFlag: */ PragFlag_NeedSchema,
110448:     /* iArg:      */ 0 },
110449:   { /* zName:     */ "index_list",
110450:     /* ePragTyp:  */ PragTyp_INDEX_LIST,
110451:     /* ePragFlag: */ PragFlag_NeedSchema,
110452:     /* iArg:      */ 0 },
110453:   { /* zName:     */ "index_xinfo",
110454:     /* ePragTyp:  */ PragTyp_INDEX_INFO,
110455:     /* ePragFlag: */ PragFlag_NeedSchema,
110456:     /* iArg:      */ 1 },
110457: #endif
110458: #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
110459:   { /* zName:     */ "integrity_check",
110460:     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
110461:     /* ePragFlag: */ PragFlag_NeedSchema,
110462:     /* iArg:      */ 0 },
110463: #endif
110464: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110465:   { /* zName:     */ "journal_mode",
110466:     /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
110467:     /* ePragFlag: */ PragFlag_NeedSchema,
110468:     /* iArg:      */ 0 },
110469:   { /* zName:     */ "journal_size_limit",
110470:     /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
110471:     /* ePragFlag: */ 0,
110472:     /* iArg:      */ 0 },
110473: #endif
110474: #if defined(SQLITE_HAS_CODEC)
110475:   { /* zName:     */ "key",
110476:     /* ePragTyp:  */ PragTyp_KEY,
110477:     /* ePragFlag: */ 0,
110478:     /* iArg:      */ 0 },
110479: #endif
110480: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110481:   { /* zName:     */ "legacy_file_format",
110482:     /* ePragTyp:  */ PragTyp_FLAG,
110483:     /* ePragFlag: */ 0,
110484:     /* iArg:      */ SQLITE_LegacyFileFmt },
110485: #endif
110486: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
110487:   { /* zName:     */ "lock_proxy_file",
110488:     /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
110489:     /* ePragFlag: */ 0,
110490:     /* iArg:      */ 0 },
110491: #endif
110492: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
110493:   { /* zName:     */ "lock_status",
110494:     /* ePragTyp:  */ PragTyp_LOCK_STATUS,
110495:     /* ePragFlag: */ 0,
110496:     /* iArg:      */ 0 },
110497: #endif
110498: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110499:   { /* zName:     */ "locking_mode",
110500:     /* ePragTyp:  */ PragTyp_LOCKING_MODE,
110501:     /* ePragFlag: */ 0,
110502:     /* iArg:      */ 0 },
110503:   { /* zName:     */ "max_page_count",
110504:     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
110505:     /* ePragFlag: */ PragFlag_NeedSchema,
110506:     /* iArg:      */ 0 },
110507:   { /* zName:     */ "mmap_size",
110508:     /* ePragTyp:  */ PragTyp_MMAP_SIZE,
110509:     /* ePragFlag: */ 0,
110510:     /* iArg:      */ 0 },
110511:   { /* zName:     */ "page_count",
110512:     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
110513:     /* ePragFlag: */ PragFlag_NeedSchema,
110514:     /* iArg:      */ 0 },
110515:   { /* zName:     */ "page_size",
110516:     /* ePragTyp:  */ PragTyp_PAGE_SIZE,
110517:     /* ePragFlag: */ 0,
110518:     /* iArg:      */ 0 },
110519: #endif
110520: #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
110521:   { /* zName:     */ "parser_trace",
110522:     /* ePragTyp:  */ PragTyp_PARSER_TRACE,
110523:     /* ePragFlag: */ 0,
110524:     /* iArg:      */ 0 },
110525: #endif
110526: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110527:   { /* zName:     */ "query_only",
110528:     /* ePragTyp:  */ PragTyp_FLAG,
110529:     /* ePragFlag: */ 0,
110530:     /* iArg:      */ SQLITE_QueryOnly },
110531: #endif
110532: #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
110533:   { /* zName:     */ "quick_check",
110534:     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
110535:     /* ePragFlag: */ PragFlag_NeedSchema,
110536:     /* iArg:      */ 0 },
110537: #endif
110538: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110539:   { /* zName:     */ "read_uncommitted",
110540:     /* ePragTyp:  */ PragTyp_FLAG,
110541:     /* ePragFlag: */ 0,
110542:     /* iArg:      */ SQLITE_ReadUncommitted },
110543:   { /* zName:     */ "recursive_triggers",
110544:     /* ePragTyp:  */ PragTyp_FLAG,
110545:     /* ePragFlag: */ 0,
110546:     /* iArg:      */ SQLITE_RecTriggers },
110547: #endif
110548: #if defined(SQLITE_HAS_CODEC)
110549:   { /* zName:     */ "rekey",
110550:     /* ePragTyp:  */ PragTyp_REKEY,
110551:     /* ePragFlag: */ 0,
110552:     /* iArg:      */ 0 },
110553: #endif
110554: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110555:   { /* zName:     */ "reverse_unordered_selects",
110556:     /* ePragTyp:  */ PragTyp_FLAG,
110557:     /* ePragFlag: */ 0,
110558:     /* iArg:      */ SQLITE_ReverseOrder },
110559: #endif
110560: #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110561:   { /* zName:     */ "schema_version",
110562:     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110563:     /* ePragFlag: */ 0,
110564:     /* iArg:      */ BTREE_SCHEMA_VERSION },
110565: #endif
110566: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110567:   { /* zName:     */ "secure_delete",
110568:     /* ePragTyp:  */ PragTyp_SECURE_DELETE,
110569:     /* ePragFlag: */ 0,
110570:     /* iArg:      */ 0 },
110571: #endif
110572: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110573:   { /* zName:     */ "short_column_names",
110574:     /* ePragTyp:  */ PragTyp_FLAG,
110575:     /* ePragFlag: */ 0,
110576:     /* iArg:      */ SQLITE_ShortColNames },
110577: #endif
110578:   { /* zName:     */ "shrink_memory",
110579:     /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
110580:     /* ePragFlag: */ 0,
110581:     /* iArg:      */ 0 },
110582:   { /* zName:     */ "soft_heap_limit",
110583:     /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
110584:     /* ePragFlag: */ 0,
110585:     /* iArg:      */ 0 },
110586: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110587: #if defined(SQLITE_DEBUG)
110588:   { /* zName:     */ "sql_trace",
110589:     /* ePragTyp:  */ PragTyp_FLAG,
110590:     /* ePragFlag: */ 0,
110591:     /* iArg:      */ SQLITE_SqlTrace },
110592: #endif
110593: #endif
110594: #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110595:   { /* zName:     */ "stats",
110596:     /* ePragTyp:  */ PragTyp_STATS,
110597:     /* ePragFlag: */ PragFlag_NeedSchema,
110598:     /* iArg:      */ 0 },
110599: #endif
110600: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110601:   { /* zName:     */ "synchronous",
110602:     /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
110603:     /* ePragFlag: */ PragFlag_NeedSchema,
110604:     /* iArg:      */ 0 },
110605: #endif
110606: #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
110607:   { /* zName:     */ "table_info",
110608:     /* ePragTyp:  */ PragTyp_TABLE_INFO,
110609:     /* ePragFlag: */ PragFlag_NeedSchema,
110610:     /* iArg:      */ 0 },
110611: #endif
110612: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110613:   { /* zName:     */ "temp_store",
110614:     /* ePragTyp:  */ PragTyp_TEMP_STORE,
110615:     /* ePragFlag: */ 0,
110616:     /* iArg:      */ 0 },
110617:   { /* zName:     */ "temp_store_directory",
110618:     /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
110619:     /* ePragFlag: */ 0,
110620:     /* iArg:      */ 0 },
110621: #endif
110622:   { /* zName:     */ "threads",
110623:     /* ePragTyp:  */ PragTyp_THREADS,
110624:     /* ePragFlag: */ 0,
110625:     /* iArg:      */ 0 },
110626: #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
110627:   { /* zName:     */ "user_version",
110628:     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
110629:     /* ePragFlag: */ 0,
110630:     /* iArg:      */ BTREE_USER_VERSION },
110631: #endif
110632: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110633: #if defined(SQLITE_DEBUG)
110634:   { /* zName:     */ "vdbe_addoptrace",
110635:     /* ePragTyp:  */ PragTyp_FLAG,
110636:     /* ePragFlag: */ 0,
110637:     /* iArg:      */ SQLITE_VdbeAddopTrace },
110638:   { /* zName:     */ "vdbe_debug",
110639:     /* ePragTyp:  */ PragTyp_FLAG,
110640:     /* ePragFlag: */ 0,
110641:     /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
110642:   { /* zName:     */ "vdbe_eqp",
110643:     /* ePragTyp:  */ PragTyp_FLAG,
110644:     /* ePragFlag: */ 0,
110645:     /* iArg:      */ SQLITE_VdbeEQP },
110646:   { /* zName:     */ "vdbe_listing",
110647:     /* ePragTyp:  */ PragTyp_FLAG,
110648:     /* ePragFlag: */ 0,
110649:     /* iArg:      */ SQLITE_VdbeListing },
110650:   { /* zName:     */ "vdbe_trace",
110651:     /* ePragTyp:  */ PragTyp_FLAG,
110652:     /* ePragFlag: */ 0,
110653:     /* iArg:      */ SQLITE_VdbeTrace },
110654: #endif
110655: #endif
110656: #if !defined(SQLITE_OMIT_WAL)
110657:   { /* zName:     */ "wal_autocheckpoint",
110658:     /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
110659:     /* ePragFlag: */ 0,
110660:     /* iArg:      */ 0 },
110661:   { /* zName:     */ "wal_checkpoint",
110662:     /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
110663:     /* ePragFlag: */ PragFlag_NeedSchema,
110664:     /* iArg:      */ 0 },
110665: #endif
110666: #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
110667:   { /* zName:     */ "writable_schema",
110668:     /* ePragTyp:  */ PragTyp_FLAG,
110669:     /* ePragFlag: */ 0,
110670:     /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
110671: #endif
110672: };
110673: /* Number of pragmas: 60 on by default, 73 total. */
110674: 
110675: /************** End of pragma.h **********************************************/
110676: /************** Continuing where we left off in pragma.c *********************/
110677: 
110678: /*
110679: ** Interpret the given string as a safety level.  Return 0 for OFF,
110680: ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA.  Return 1 for an empty or 
110681: ** unrecognized string argument.  The FULL and EXTRA option is disallowed
110682: ** if the omitFull parameter it 1.
110683: **
110684: ** Note that the values returned are one less that the values that
110685: ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
110686: ** to support legacy SQL code.  The safety level used to be boolean
110687: ** and older scripts may have used numbers 0 for OFF and 1 for ON.
110688: */
110689: static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
110690:                              /* 123456789 123456789 123 */
110691:   static const char zText[] = "onoffalseyestruextrafull";
110692:   static const u8 iOffset[] = {0, 1, 2,  4,    9,  12,  15,   20};
110693:   static const u8 iLength[] = {2, 2, 3,  5,    3,   4,   5,    4};
110694:   static const u8 iValue[] =  {1, 0, 0,  0,    1,   1,   3,    2};
110695:                             /* on no off false yes true extra full */
110696:   int i, n;
110697:   if( sqlite3Isdigit(*z) ){
110698:     return (u8)sqlite3Atoi(z);
110699:   }
110700:   n = sqlite3Strlen30(z);
110701:   for(i=0; i<ArraySize(iLength); i++){
110702:     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
110703:      && (!omitFull || iValue[i]<=1)
110704:     ){
110705:       return iValue[i];
110706:     }
110707:   }
110708:   return dflt;
110709: }
110710: 
110711: /*
110712: ** Interpret the given string as a boolean value.
110713: */
110714: SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
110715:   return getSafetyLevel(z,1,dflt)!=0;
110716: }
110717: 
110718: /* The sqlite3GetBoolean() function is used by other modules but the
110719: ** remainder of this file is specific to PRAGMA processing.  So omit
110720: ** the rest of the file if PRAGMAs are omitted from the build.
110721: */
110722: #if !defined(SQLITE_OMIT_PRAGMA)
110723: 
110724: /*
110725: ** Interpret the given string as a locking mode value.
110726: */
110727: static int getLockingMode(const char *z){
110728:   if( z ){
110729:     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
110730:     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
110731:   }
110732:   return PAGER_LOCKINGMODE_QUERY;
110733: }
110734: 
110735: #ifndef SQLITE_OMIT_AUTOVACUUM
110736: /*
110737: ** Interpret the given string as an auto-vacuum mode value.
110738: **
110739: ** The following strings, "none", "full" and "incremental" are 
110740: ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
110741: */
110742: static int getAutoVacuum(const char *z){
110743:   int i;
110744:   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
110745:   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
110746:   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
110747:   i = sqlite3Atoi(z);
110748:   return (u8)((i>=0&&i<=2)?i:0);
110749: }
110750: #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
110751: 
110752: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110753: /*
110754: ** Interpret the given string as a temp db location. Return 1 for file
110755: ** backed temporary databases, 2 for the Red-Black tree in memory database
110756: ** and 0 to use the compile-time default.
110757: */
110758: static int getTempStore(const char *z){
110759:   if( z[0]>='0' && z[0]<='2' ){
110760:     return z[0] - '0';
110761:   }else if( sqlite3StrICmp(z, "file")==0 ){
110762:     return 1;
110763:   }else if( sqlite3StrICmp(z, "memory")==0 ){
110764:     return 2;
110765:   }else{
110766:     return 0;
110767:   }
110768: }
110769: #endif /* SQLITE_PAGER_PRAGMAS */
110770: 
110771: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110772: /*
110773: ** Invalidate temp storage, either when the temp storage is changed
110774: ** from default, or when 'file' and the temp_store_directory has changed
110775: */
110776: static int invalidateTempStorage(Parse *pParse){
110777:   sqlite3 *db = pParse->db;
110778:   if( db->aDb[1].pBt!=0 ){
110779:     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
110780:       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
110781:         "from within a transaction");
110782:       return SQLITE_ERROR;
110783:     }
110784:     sqlite3BtreeClose(db->aDb[1].pBt);
110785:     db->aDb[1].pBt = 0;
110786:     sqlite3ResetAllSchemasOfConnection(db);
110787:   }
110788:   return SQLITE_OK;
110789: }
110790: #endif /* SQLITE_PAGER_PRAGMAS */
110791: 
110792: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110793: /*
110794: ** If the TEMP database is open, close it and mark the database schema
110795: ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
110796: ** or DEFAULT_TEMP_STORE pragmas.
110797: */
110798: static int changeTempStorage(Parse *pParse, const char *zStorageType){
110799:   int ts = getTempStore(zStorageType);
110800:   sqlite3 *db = pParse->db;
110801:   if( db->temp_store==ts ) return SQLITE_OK;
110802:   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
110803:     return SQLITE_ERROR;
110804:   }
110805:   db->temp_store = (u8)ts;
110806:   return SQLITE_OK;
110807: }
110808: #endif /* SQLITE_PAGER_PRAGMAS */
110809: 
110810: /*
110811: ** Set the names of the first N columns to the values in azCol[]
110812: */
110813: static void setAllColumnNames(
110814:   Vdbe *v,               /* The query under construction */
110815:   int N,                 /* Number of columns */
110816:   const char **azCol     /* Names of columns */
110817: ){
110818:   int i;
110819:   sqlite3VdbeSetNumCols(v, N);
110820:   for(i=0; i<N; i++){
110821:     sqlite3VdbeSetColName(v, i, COLNAME_NAME, azCol[i], SQLITE_STATIC);
110822:   }
110823: }
110824: static void setOneColumnName(Vdbe *v, const char *z){
110825:   setAllColumnNames(v, 1, &z);
110826: }
110827: 
110828: /*
110829: ** Generate code to return a single integer value.
110830: */
110831: static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
110832:   sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
110833:   setOneColumnName(v, zLabel);
110834:   sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110835: }
110836: 
110837: /*
110838: ** Generate code to return a single text value.
110839: */
110840: static void returnSingleText(
110841:   Vdbe *v,                /* Prepared statement under construction */
110842:   const char *zLabel,     /* Name of the result column */
110843:   const char *zValue      /* Value to be returned */
110844: ){
110845:   if( zValue ){
110846:     sqlite3VdbeLoadString(v, 1, (const char*)zValue);
110847:     setOneColumnName(v, zLabel);
110848:     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110849:   }
110850: }
110851: 
110852: 
110853: /*
110854: ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
110855: ** set these values for all pagers.
110856: */
110857: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110858: static void setAllPagerFlags(sqlite3 *db){
110859:   if( db->autoCommit ){
110860:     Db *pDb = db->aDb;
110861:     int n = db->nDb;
110862:     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
110863:     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
110864:     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
110865:     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
110866:              ==  PAGER_FLAGS_MASK );
110867:     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
110868:     while( (n--) > 0 ){
110869:       if( pDb->pBt ){
110870:         sqlite3BtreeSetPagerFlags(pDb->pBt,
110871:                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
110872:       }
110873:       pDb++;
110874:     }
110875:   }
110876: }
110877: #else
110878: # define setAllPagerFlags(X)  /* no-op */
110879: #endif
110880: 
110881: 
110882: /*
110883: ** Return a human-readable name for a constraint resolution action.
110884: */
110885: #ifndef SQLITE_OMIT_FOREIGN_KEY
110886: static const char *actionName(u8 action){
110887:   const char *zName;
110888:   switch( action ){
110889:     case OE_SetNull:  zName = "SET NULL";        break;
110890:     case OE_SetDflt:  zName = "SET DEFAULT";     break;
110891:     case OE_Cascade:  zName = "CASCADE";         break;
110892:     case OE_Restrict: zName = "RESTRICT";        break;
110893:     default:          zName = "NO ACTION";  
110894:                       assert( action==OE_None ); break;
110895:   }
110896:   return zName;
110897: }
110898: #endif
110899: 
110900: 
110901: /*
110902: ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
110903: ** defined in pager.h. This function returns the associated lowercase
110904: ** journal-mode name.
110905: */
110906: SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
110907:   static char * const azModeName[] = {
110908:     "delete", "persist", "off", "truncate", "memory"
110909: #ifndef SQLITE_OMIT_WAL
110910:      , "wal"
110911: #endif
110912:   };
110913:   assert( PAGER_JOURNALMODE_DELETE==0 );
110914:   assert( PAGER_JOURNALMODE_PERSIST==1 );
110915:   assert( PAGER_JOURNALMODE_OFF==2 );
110916:   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
110917:   assert( PAGER_JOURNALMODE_MEMORY==4 );
110918:   assert( PAGER_JOURNALMODE_WAL==5 );
110919:   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
110920: 
110921:   if( eMode==ArraySize(azModeName) ) return 0;
110922:   return azModeName[eMode];
110923: }
110924: 
110925: /*
110926: ** Process a pragma statement.  
110927: **
110928: ** Pragmas are of this form:
110929: **
110930: **      PRAGMA [schema.]id [= value]
110931: **
110932: ** The identifier might also be a string.  The value is a string, and
110933: ** identifier, or a number.  If minusFlag is true, then the value is
110934: ** a number that was preceded by a minus sign.
110935: **
110936: ** If the left side is "database.id" then pId1 is the database name
110937: ** and pId2 is the id.  If the left side is just "id" then pId1 is the
110938: ** id and pId2 is any empty string.
110939: */
110940: SQLITE_PRIVATE void sqlite3Pragma(
110941:   Parse *pParse, 
110942:   Token *pId1,        /* First part of [schema.]id field */
110943:   Token *pId2,        /* Second part of [schema.]id field, or NULL */
110944:   Token *pValue,      /* Token for <value>, or NULL */
110945:   int minusFlag       /* True if a '-' sign preceded <value> */
110946: ){
110947:   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
110948:   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
110949:   const char *zDb = 0;   /* The database name */
110950:   Token *pId;            /* Pointer to <id> token */
110951:   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
110952:   int iDb;               /* Database index for <database> */
110953:   int lwr, upr, mid = 0;       /* Binary search bounds */
110954:   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
110955:   sqlite3 *db = pParse->db;    /* The database connection */
110956:   Db *pDb;                     /* The specific database being pragmaed */
110957:   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
110958:   const struct sPragmaNames *pPragma;
110959: 
110960:   if( v==0 ) return;
110961:   sqlite3VdbeRunOnlyOnce(v);
110962:   pParse->nMem = 2;
110963: 
110964:   /* Interpret the [schema.] part of the pragma statement. iDb is the
110965:   ** index of the database this pragma is being applied to in db.aDb[]. */
110966:   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
110967:   if( iDb<0 ) return;
110968:   pDb = &db->aDb[iDb];
110969: 
110970:   /* If the temp database has been explicitly named as part of the 
110971:   ** pragma, make sure it is open. 
110972:   */
110973:   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
110974:     return;
110975:   }
110976: 
110977:   zLeft = sqlite3NameFromToken(db, pId);
110978:   if( !zLeft ) return;
110979:   if( minusFlag ){
110980:     zRight = sqlite3MPrintf(db, "-%T", pValue);
110981:   }else{
110982:     zRight = sqlite3NameFromToken(db, pValue);
110983:   }
110984: 
110985:   assert( pId2 );
110986:   zDb = pId2->n>0 ? pDb->zName : 0;
110987:   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
110988:     goto pragma_out;
110989:   }
110990: 
110991:   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
110992:   ** connection.  If it returns SQLITE_OK, then assume that the VFS
110993:   ** handled the pragma and generate a no-op prepared statement.
110994:   **
110995:   ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
110996:   ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
110997:   ** object corresponding to the database file to which the pragma
110998:   ** statement refers.
110999:   **
111000:   ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
111001:   ** file control is an array of pointers to strings (char**) in which the
111002:   ** second element of the array is the name of the pragma and the third
111003:   ** element is the argument to the pragma or NULL if the pragma has no
111004:   ** argument.
111005:   */
111006:   aFcntl[0] = 0;
111007:   aFcntl[1] = zLeft;
111008:   aFcntl[2] = zRight;
111009:   aFcntl[3] = 0;
111010:   db->busyHandler.nBusy = 0;
111011:   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
111012:   if( rc==SQLITE_OK ){
111013:     returnSingleText(v, "result", aFcntl[0]);
111014:     sqlite3_free(aFcntl[0]);
111015:     goto pragma_out;
111016:   }
111017:   if( rc!=SQLITE_NOTFOUND ){
111018:     if( aFcntl[0] ){
111019:       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
111020:       sqlite3_free(aFcntl[0]);
111021:     }
111022:     pParse->nErr++;
111023:     pParse->rc = rc;
111024:     goto pragma_out;
111025:   }
111026: 
111027:   /* Locate the pragma in the lookup table */
111028:   lwr = 0;
111029:   upr = ArraySize(aPragmaNames)-1;
111030:   while( lwr<=upr ){
111031:     mid = (lwr+upr)/2;
111032:     rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
111033:     if( rc==0 ) break;
111034:     if( rc<0 ){
111035:       upr = mid - 1;
111036:     }else{
111037:       lwr = mid + 1;
111038:     }
111039:   }
111040:   if( lwr>upr ) goto pragma_out;
111041:   pPragma = &aPragmaNames[mid];
111042: 
111043:   /* Make sure the database schema is loaded if the pragma requires that */
111044:   if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
111045:     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
111046:   }
111047: 
111048:   /* Jump to the appropriate pragma handler */
111049:   switch( pPragma->ePragTyp ){
111050:   
111051: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
111052:   /*
111053:   **  PRAGMA [schema.]default_cache_size
111054:   **  PRAGMA [schema.]default_cache_size=N
111055:   **
111056:   ** The first form reports the current persistent setting for the
111057:   ** page cache size.  The value returned is the maximum number of
111058:   ** pages in the page cache.  The second form sets both the current
111059:   ** page cache size value and the persistent page cache size value
111060:   ** stored in the database file.
111061:   **
111062:   ** Older versions of SQLite would set the default cache size to a
111063:   ** negative number to indicate synchronous=OFF.  These days, synchronous
111064:   ** is always on by default regardless of the sign of the default cache
111065:   ** size.  But continue to take the absolute value of the default cache
111066:   ** size of historical compatibility.
111067:   */
111068:   case PragTyp_DEFAULT_CACHE_SIZE: {
111069:     static const int iLn = VDBE_OFFSET_LINENO(2);
111070:     static const VdbeOpList getCacheSize[] = {
111071:       { OP_Transaction, 0, 0,        0},                         /* 0 */
111072:       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
111073:       { OP_IfPos,       1, 8,        0},
111074:       { OP_Integer,     0, 2,        0},
111075:       { OP_Subtract,    1, 2,        1},
111076:       { OP_IfPos,       1, 8,        0},
111077:       { OP_Integer,     0, 1,        0},                         /* 6 */
111078:       { OP_Noop,        0, 0,        0},
111079:       { OP_ResultRow,   1, 1,        0},
111080:     };
111081:     VdbeOp *aOp;
111082:     sqlite3VdbeUsesBtree(v, iDb);
111083:     if( !zRight ){
111084:       setOneColumnName(v, "cache_size");
111085:       pParse->nMem += 2;
111086:       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
111087:       aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
111088:       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111089:       aOp[0].p1 = iDb;
111090:       aOp[1].p1 = iDb;
111091:       aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
111092:     }else{
111093:       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
111094:       sqlite3BeginWriteOperation(pParse, 0, iDb);
111095:       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
111096:       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111097:       pDb->pSchema->cache_size = size;
111098:       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
111099:     }
111100:     break;
111101:   }
111102: #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
111103: 
111104: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
111105:   /*
111106:   **  PRAGMA [schema.]page_size
111107:   **  PRAGMA [schema.]page_size=N
111108:   **
111109:   ** The first form reports the current setting for the
111110:   ** database page size in bytes.  The second form sets the
111111:   ** database page size value.  The value can only be set if
111112:   ** the database has not yet been created.
111113:   */
111114:   case PragTyp_PAGE_SIZE: {
111115:     Btree *pBt = pDb->pBt;
111116:     assert( pBt!=0 );
111117:     if( !zRight ){
111118:       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
111119:       returnSingleInt(v, "page_size", size);
111120:     }else{
111121:       /* Malloc may fail when setting the page-size, as there is an internal
111122:       ** buffer that the pager module resizes using sqlite3_realloc().
111123:       */
111124:       db->nextPagesize = sqlite3Atoi(zRight);
111125:       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
111126:         sqlite3OomFault(db);
111127:       }
111128:     }
111129:     break;
111130:   }
111131: 
111132:   /*
111133:   **  PRAGMA [schema.]secure_delete
111134:   **  PRAGMA [schema.]secure_delete=ON/OFF
111135:   **
111136:   ** The first form reports the current setting for the
111137:   ** secure_delete flag.  The second form changes the secure_delete
111138:   ** flag setting and reports thenew value.
111139:   */
111140:   case PragTyp_SECURE_DELETE: {
111141:     Btree *pBt = pDb->pBt;
111142:     int b = -1;
111143:     assert( pBt!=0 );
111144:     if( zRight ){
111145:       b = sqlite3GetBoolean(zRight, 0);
111146:     }
111147:     if( pId2->n==0 && b>=0 ){
111148:       int ii;
111149:       for(ii=0; ii<db->nDb; ii++){
111150:         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
111151:       }
111152:     }
111153:     b = sqlite3BtreeSecureDelete(pBt, b);
111154:     returnSingleInt(v, "secure_delete", b);
111155:     break;
111156:   }
111157: 
111158:   /*
111159:   **  PRAGMA [schema.]max_page_count
111160:   **  PRAGMA [schema.]max_page_count=N
111161:   **
111162:   ** The first form reports the current setting for the
111163:   ** maximum number of pages in the database file.  The 
111164:   ** second form attempts to change this setting.  Both
111165:   ** forms return the current setting.
111166:   **
111167:   ** The absolute value of N is used.  This is undocumented and might
111168:   ** change.  The only purpose is to provide an easy way to test
111169:   ** the sqlite3AbsInt32() function.
111170:   **
111171:   **  PRAGMA [schema.]page_count
111172:   **
111173:   ** Return the number of pages in the specified database.
111174:   */
111175:   case PragTyp_PAGE_COUNT: {
111176:     int iReg;
111177:     sqlite3CodeVerifySchema(pParse, iDb);
111178:     iReg = ++pParse->nMem;
111179:     if( sqlite3Tolower(zLeft[0])=='p' ){
111180:       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
111181:     }else{
111182:       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
111183:                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
111184:     }
111185:     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
111186:     sqlite3VdbeSetNumCols(v, 1);
111187:     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
111188:     break;
111189:   }
111190: 
111191:   /*
111192:   **  PRAGMA [schema.]locking_mode
111193:   **  PRAGMA [schema.]locking_mode = (normal|exclusive)
111194:   */
111195:   case PragTyp_LOCKING_MODE: {
111196:     const char *zRet = "normal";
111197:     int eMode = getLockingMode(zRight);
111198: 
111199:     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
111200:       /* Simple "PRAGMA locking_mode;" statement. This is a query for
111201:       ** the current default locking mode (which may be different to
111202:       ** the locking-mode of the main database).
111203:       */
111204:       eMode = db->dfltLockMode;
111205:     }else{
111206:       Pager *pPager;
111207:       if( pId2->n==0 ){
111208:         /* This indicates that no database name was specified as part
111209:         ** of the PRAGMA command. In this case the locking-mode must be
111210:         ** set on all attached databases, as well as the main db file.
111211:         **
111212:         ** Also, the sqlite3.dfltLockMode variable is set so that
111213:         ** any subsequently attached databases also use the specified
111214:         ** locking mode.
111215:         */
111216:         int ii;
111217:         assert(pDb==&db->aDb[0]);
111218:         for(ii=2; ii<db->nDb; ii++){
111219:           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
111220:           sqlite3PagerLockingMode(pPager, eMode);
111221:         }
111222:         db->dfltLockMode = (u8)eMode;
111223:       }
111224:       pPager = sqlite3BtreePager(pDb->pBt);
111225:       eMode = sqlite3PagerLockingMode(pPager, eMode);
111226:     }
111227: 
111228:     assert( eMode==PAGER_LOCKINGMODE_NORMAL
111229:             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
111230:     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
111231:       zRet = "exclusive";
111232:     }
111233:     returnSingleText(v, "locking_mode", zRet);
111234:     break;
111235:   }
111236: 
111237:   /*
111238:   **  PRAGMA [schema.]journal_mode
111239:   **  PRAGMA [schema.]journal_mode =
111240:   **                      (delete|persist|off|truncate|memory|wal|off)
111241:   */
111242:   case PragTyp_JOURNAL_MODE: {
111243:     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
111244:     int ii;           /* Loop counter */
111245: 
111246:     setOneColumnName(v, "journal_mode");
111247:     if( zRight==0 ){
111248:       /* If there is no "=MODE" part of the pragma, do a query for the
111249:       ** current mode */
111250:       eMode = PAGER_JOURNALMODE_QUERY;
111251:     }else{
111252:       const char *zMode;
111253:       int n = sqlite3Strlen30(zRight);
111254:       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
111255:         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
111256:       }
111257:       if( !zMode ){
111258:         /* If the "=MODE" part does not match any known journal mode,
111259:         ** then do a query */
111260:         eMode = PAGER_JOURNALMODE_QUERY;
111261:       }
111262:     }
111263:     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
111264:       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
111265:       iDb = 0;
111266:       pId2->n = 1;
111267:     }
111268:     for(ii=db->nDb-1; ii>=0; ii--){
111269:       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
111270:         sqlite3VdbeUsesBtree(v, ii);
111271:         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
111272:       }
111273:     }
111274:     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111275:     break;
111276:   }
111277: 
111278:   /*
111279:   **  PRAGMA [schema.]journal_size_limit
111280:   **  PRAGMA [schema.]journal_size_limit=N
111281:   **
111282:   ** Get or set the size limit on rollback journal files.
111283:   */
111284:   case PragTyp_JOURNAL_SIZE_LIMIT: {
111285:     Pager *pPager = sqlite3BtreePager(pDb->pBt);
111286:     i64 iLimit = -2;
111287:     if( zRight ){
111288:       sqlite3DecOrHexToI64(zRight, &iLimit);
111289:       if( iLimit<-1 ) iLimit = -1;
111290:     }
111291:     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
111292:     returnSingleInt(v, "journal_size_limit", iLimit);
111293:     break;
111294:   }
111295: 
111296: #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
111297: 
111298:   /*
111299:   **  PRAGMA [schema.]auto_vacuum
111300:   **  PRAGMA [schema.]auto_vacuum=N
111301:   **
111302:   ** Get or set the value of the database 'auto-vacuum' parameter.
111303:   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
111304:   */
111305: #ifndef SQLITE_OMIT_AUTOVACUUM
111306:   case PragTyp_AUTO_VACUUM: {
111307:     Btree *pBt = pDb->pBt;
111308:     assert( pBt!=0 );
111309:     if( !zRight ){
111310:       returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
111311:     }else{
111312:       int eAuto = getAutoVacuum(zRight);
111313:       assert( eAuto>=0 && eAuto<=2 );
111314:       db->nextAutovac = (u8)eAuto;
111315:       /* Call SetAutoVacuum() to set initialize the internal auto and
111316:       ** incr-vacuum flags. This is required in case this connection
111317:       ** creates the database file. It is important that it is created
111318:       ** as an auto-vacuum capable db.
111319:       */
111320:       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
111321:       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
111322:         /* When setting the auto_vacuum mode to either "full" or 
111323:         ** "incremental", write the value of meta[6] in the database
111324:         ** file. Before writing to meta[6], check that meta[3] indicates
111325:         ** that this really is an auto-vacuum capable database.
111326:         */
111327:         static const int iLn = VDBE_OFFSET_LINENO(2);
111328:         static const VdbeOpList setMeta6[] = {
111329:           { OP_Transaction,    0,         1,                 0},    /* 0 */
111330:           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
111331:           { OP_If,             1,         0,                 0},    /* 2 */
111332:           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
111333:           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 0},    /* 4 */
111334:         };
111335:         VdbeOp *aOp;
111336:         int iAddr = sqlite3VdbeCurrentAddr(v);
111337:         sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
111338:         aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
111339:         if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111340:         aOp[0].p1 = iDb;
111341:         aOp[1].p1 = iDb;
111342:         aOp[2].p2 = iAddr+4;
111343:         aOp[4].p1 = iDb;
111344:         aOp[4].p3 = eAuto - 1;
111345:         sqlite3VdbeUsesBtree(v, iDb);
111346:       }
111347:     }
111348:     break;
111349:   }
111350: #endif
111351: 
111352:   /*
111353:   **  PRAGMA [schema.]incremental_vacuum(N)
111354:   **
111355:   ** Do N steps of incremental vacuuming on a database.
111356:   */
111357: #ifndef SQLITE_OMIT_AUTOVACUUM
111358:   case PragTyp_INCREMENTAL_VACUUM: {
111359:     int iLimit, addr;
111360:     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
111361:       iLimit = 0x7fffffff;
111362:     }
111363:     sqlite3BeginWriteOperation(pParse, 0, iDb);
111364:     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
111365:     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
111366:     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
111367:     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
111368:     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
111369:     sqlite3VdbeJumpHere(v, addr);
111370:     break;
111371:   }
111372: #endif
111373: 
111374: #ifndef SQLITE_OMIT_PAGER_PRAGMAS
111375:   /*
111376:   **  PRAGMA [schema.]cache_size
111377:   **  PRAGMA [schema.]cache_size=N
111378:   **
111379:   ** The first form reports the current local setting for the
111380:   ** page cache size. The second form sets the local
111381:   ** page cache size value.  If N is positive then that is the
111382:   ** number of pages in the cache.  If N is negative, then the
111383:   ** number of pages is adjusted so that the cache uses -N kibibytes
111384:   ** of memory.
111385:   */
111386:   case PragTyp_CACHE_SIZE: {
111387:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111388:     if( !zRight ){
111389:       returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
111390:     }else{
111391:       int size = sqlite3Atoi(zRight);
111392:       pDb->pSchema->cache_size = size;
111393:       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
111394:     }
111395:     break;
111396:   }
111397: 
111398:   /*
111399:   **  PRAGMA [schema.]cache_spill
111400:   **  PRAGMA cache_spill=BOOLEAN
111401:   **  PRAGMA [schema.]cache_spill=N
111402:   **
111403:   ** The first form reports the current local setting for the
111404:   ** page cache spill size. The second form turns cache spill on
111405:   ** or off.  When turnning cache spill on, the size is set to the
111406:   ** current cache_size.  The third form sets a spill size that
111407:   ** may be different form the cache size.
111408:   ** If N is positive then that is the
111409:   ** number of pages in the cache.  If N is negative, then the
111410:   ** number of pages is adjusted so that the cache uses -N kibibytes
111411:   ** of memory.
111412:   **
111413:   ** If the number of cache_spill pages is less then the number of
111414:   ** cache_size pages, no spilling occurs until the page count exceeds
111415:   ** the number of cache_size pages.
111416:   **
111417:   ** The cache_spill=BOOLEAN setting applies to all attached schemas,
111418:   ** not just the schema specified.
111419:   */
111420:   case PragTyp_CACHE_SPILL: {
111421:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111422:     if( !zRight ){
111423:       returnSingleInt(v, "cache_spill", 
111424:          (db->flags & SQLITE_CacheSpill)==0 ? 0 : 
111425:             sqlite3BtreeSetSpillSize(pDb->pBt,0));
111426:     }else{
111427:       int size = 1;
111428:       if( sqlite3GetInt32(zRight, &size) ){
111429:         sqlite3BtreeSetSpillSize(pDb->pBt, size);
111430:       }
111431:       if( sqlite3GetBoolean(zRight, size!=0) ){
111432:         db->flags |= SQLITE_CacheSpill;
111433:       }else{
111434:         db->flags &= ~SQLITE_CacheSpill;
111435:       }
111436:       setAllPagerFlags(db);
111437:     }
111438:     break;
111439:   }
111440: 
111441:   /*
111442:   **  PRAGMA [schema.]mmap_size(N)
111443:   **
111444:   ** Used to set mapping size limit. The mapping size limit is
111445:   ** used to limit the aggregate size of all memory mapped regions of the
111446:   ** database file. If this parameter is set to zero, then memory mapping
111447:   ** is not used at all.  If N is negative, then the default memory map
111448:   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
111449:   ** The parameter N is measured in bytes.
111450:   **
111451:   ** This value is advisory.  The underlying VFS is free to memory map
111452:   ** as little or as much as it wants.  Except, if N is set to 0 then the
111453:   ** upper layers will never invoke the xFetch interfaces to the VFS.
111454:   */
111455:   case PragTyp_MMAP_SIZE: {
111456:     sqlite3_int64 sz;
111457: #if SQLITE_MAX_MMAP_SIZE>0
111458:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
111459:     if( zRight ){
111460:       int ii;
111461:       sqlite3DecOrHexToI64(zRight, &sz);
111462:       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
111463:       if( pId2->n==0 ) db->szMmap = sz;
111464:       for(ii=db->nDb-1; ii>=0; ii--){
111465:         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
111466:           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
111467:         }
111468:       }
111469:     }
111470:     sz = -1;
111471:     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
111472: #else
111473:     sz = 0;
111474:     rc = SQLITE_OK;
111475: #endif
111476:     if( rc==SQLITE_OK ){
111477:       returnSingleInt(v, "mmap_size", sz);
111478:     }else if( rc!=SQLITE_NOTFOUND ){
111479:       pParse->nErr++;
111480:       pParse->rc = rc;
111481:     }
111482:     break;
111483:   }
111484: 
111485:   /*
111486:   **   PRAGMA temp_store
111487:   **   PRAGMA temp_store = "default"|"memory"|"file"
111488:   **
111489:   ** Return or set the local value of the temp_store flag.  Changing
111490:   ** the local value does not make changes to the disk file and the default
111491:   ** value will be restored the next time the database is opened.
111492:   **
111493:   ** Note that it is possible for the library compile-time options to
111494:   ** override this setting
111495:   */
111496:   case PragTyp_TEMP_STORE: {
111497:     if( !zRight ){
111498:       returnSingleInt(v, "temp_store", db->temp_store);
111499:     }else{
111500:       changeTempStorage(pParse, zRight);
111501:     }
111502:     break;
111503:   }
111504: 
111505:   /*
111506:   **   PRAGMA temp_store_directory
111507:   **   PRAGMA temp_store_directory = ""|"directory_name"
111508:   **
111509:   ** Return or set the local value of the temp_store_directory flag.  Changing
111510:   ** the value sets a specific directory to be used for temporary files.
111511:   ** Setting to a null string reverts to the default temporary directory search.
111512:   ** If temporary directory is changed, then invalidateTempStorage.
111513:   **
111514:   */
111515:   case PragTyp_TEMP_STORE_DIRECTORY: {
111516:     if( !zRight ){
111517:       returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
111518:     }else{
111519: #ifndef SQLITE_OMIT_WSD
111520:       if( zRight[0] ){
111521:         int res;
111522:         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
111523:         if( rc!=SQLITE_OK || res==0 ){
111524:           sqlite3ErrorMsg(pParse, "not a writable directory");
111525:           goto pragma_out;
111526:         }
111527:       }
111528:       if( SQLITE_TEMP_STORE==0
111529:        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
111530:        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
111531:       ){
111532:         invalidateTempStorage(pParse);
111533:       }
111534:       sqlite3_free(sqlite3_temp_directory);
111535:       if( zRight[0] ){
111536:         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
111537:       }else{
111538:         sqlite3_temp_directory = 0;
111539:       }
111540: #endif /* SQLITE_OMIT_WSD */
111541:     }
111542:     break;
111543:   }
111544: 
111545: #if SQLITE_OS_WIN
111546:   /*
111547:   **   PRAGMA data_store_directory
111548:   **   PRAGMA data_store_directory = ""|"directory_name"
111549:   **
111550:   ** Return or set the local value of the data_store_directory flag.  Changing
111551:   ** the value sets a specific directory to be used for database files that
111552:   ** were specified with a relative pathname.  Setting to a null string reverts
111553:   ** to the default database directory, which for database files specified with
111554:   ** a relative path will probably be based on the current directory for the
111555:   ** process.  Database file specified with an absolute path are not impacted
111556:   ** by this setting, regardless of its value.
111557:   **
111558:   */
111559:   case PragTyp_DATA_STORE_DIRECTORY: {
111560:     if( !zRight ){
111561:       returnSingleText(v, "data_store_directory", sqlite3_data_directory);
111562:     }else{
111563: #ifndef SQLITE_OMIT_WSD
111564:       if( zRight[0] ){
111565:         int res;
111566:         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
111567:         if( rc!=SQLITE_OK || res==0 ){
111568:           sqlite3ErrorMsg(pParse, "not a writable directory");
111569:           goto pragma_out;
111570:         }
111571:       }
111572:       sqlite3_free(sqlite3_data_directory);
111573:       if( zRight[0] ){
111574:         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
111575:       }else{
111576:         sqlite3_data_directory = 0;
111577:       }
111578: #endif /* SQLITE_OMIT_WSD */
111579:     }
111580:     break;
111581:   }
111582: #endif
111583: 
111584: #if SQLITE_ENABLE_LOCKING_STYLE
111585:   /*
111586:   **   PRAGMA [schema.]lock_proxy_file
111587:   **   PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
111588:   **
111589:   ** Return or set the value of the lock_proxy_file flag.  Changing
111590:   ** the value sets a specific file to be used for database access locks.
111591:   **
111592:   */
111593:   case PragTyp_LOCK_PROXY_FILE: {
111594:     if( !zRight ){
111595:       Pager *pPager = sqlite3BtreePager(pDb->pBt);
111596:       char *proxy_file_path = NULL;
111597:       sqlite3_file *pFile = sqlite3PagerFile(pPager);
111598:       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
111599:                            &proxy_file_path);
111600:       returnSingleText(v, "lock_proxy_file", proxy_file_path);
111601:     }else{
111602:       Pager *pPager = sqlite3BtreePager(pDb->pBt);
111603:       sqlite3_file *pFile = sqlite3PagerFile(pPager);
111604:       int res;
111605:       if( zRight[0] ){
111606:         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
111607:                                      zRight);
111608:       } else {
111609:         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
111610:                                      NULL);
111611:       }
111612:       if( res!=SQLITE_OK ){
111613:         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
111614:         goto pragma_out;
111615:       }
111616:     }
111617:     break;
111618:   }
111619: #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
111620:     
111621:   /*
111622:   **   PRAGMA [schema.]synchronous
111623:   **   PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
111624:   **
111625:   ** Return or set the local value of the synchronous flag.  Changing
111626:   ** the local value does not make changes to the disk file and the
111627:   ** default value will be restored the next time the database is
111628:   ** opened.
111629:   */
111630:   case PragTyp_SYNCHRONOUS: {
111631:     if( !zRight ){
111632:       returnSingleInt(v, "synchronous", pDb->safety_level-1);
111633:     }else{
111634:       if( !db->autoCommit ){
111635:         sqlite3ErrorMsg(pParse, 
111636:             "Safety level may not be changed inside a transaction");
111637:       }else{
111638:         int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
111639:         if( iLevel==0 ) iLevel = 1;
111640:         pDb->safety_level = iLevel;
111641:         pDb->bSyncSet = 1;
111642:         setAllPagerFlags(db);
111643:       }
111644:     }
111645:     break;
111646:   }
111647: #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
111648: 
111649: #ifndef SQLITE_OMIT_FLAG_PRAGMAS
111650:   case PragTyp_FLAG: {
111651:     if( zRight==0 ){
111652:       returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
111653:     }else{
111654:       int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
111655:       if( db->autoCommit==0 ){
111656:         /* Foreign key support may not be enabled or disabled while not
111657:         ** in auto-commit mode.  */
111658:         mask &= ~(SQLITE_ForeignKeys);
111659:       }
111660: #if SQLITE_USER_AUTHENTICATION
111661:       if( db->auth.authLevel==UAUTH_User ){
111662:         /* Do not allow non-admin users to modify the schema arbitrarily */
111663:         mask &= ~(SQLITE_WriteSchema);
111664:       }
111665: #endif
111666: 
111667:       if( sqlite3GetBoolean(zRight, 0) ){
111668:         db->flags |= mask;
111669:       }else{
111670:         db->flags &= ~mask;
111671:         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
111672:       }
111673: 
111674:       /* Many of the flag-pragmas modify the code generated by the SQL 
111675:       ** compiler (eg. count_changes). So add an opcode to expire all
111676:       ** compiled SQL statements after modifying a pragma value.
111677:       */
111678:       sqlite3VdbeAddOp0(v, OP_Expire);
111679:       setAllPagerFlags(db);
111680:     }
111681:     break;
111682:   }
111683: #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
111684: 
111685: #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
111686:   /*
111687:   **   PRAGMA table_info(<table>)
111688:   **
111689:   ** Return a single row for each column of the named table. The columns of
111690:   ** the returned data set are:
111691:   **
111692:   ** cid:        Column id (numbered from left to right, starting at 0)
111693:   ** name:       Column name
111694:   ** type:       Column declaration type.
111695:   ** notnull:    True if 'NOT NULL' is part of column declaration
111696:   ** dflt_value: The default value for the column, if any.
111697:   */
111698:   case PragTyp_TABLE_INFO: if( zRight ){
111699:     Table *pTab;
111700:     pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
111701:     if( pTab ){
111702:       static const char *azCol[] = {
111703:          "cid", "name", "type", "notnull", "dflt_value", "pk"
111704:       };
111705:       int i, k;
111706:       int nHidden = 0;
111707:       Column *pCol;
111708:       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
111709:       pParse->nMem = 6;
111710:       sqlite3CodeVerifySchema(pParse, iDb);
111711:       setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
111712:       sqlite3ViewGetColumnNames(pParse, pTab);
111713:       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
111714:         if( IsHiddenColumn(pCol) ){
111715:           nHidden++;
111716:           continue;
111717:         }
111718:         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
111719:           k = 0;
111720:         }else if( pPk==0 ){
111721:           k = 1;
111722:         }else{
111723:           for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
111724:         }
111725:         assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
111726:         sqlite3VdbeMultiLoad(v, 1, "issisi",
111727:                i-nHidden,
111728:                pCol->zName,
111729:                sqlite3ColumnType(pCol,""),
111730:                pCol->notNull ? 1 : 0,
111731:                pCol->pDflt ? pCol->pDflt->u.zToken : 0,
111732:                k);
111733:         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
111734:       }
111735:     }
111736:   }
111737:   break;
111738: 
111739:   case PragTyp_STATS: {
111740:     static const char *azCol[] = { "table", "index", "width", "height" };
111741:     Index *pIdx;
111742:     HashElem *i;
111743:     v = sqlite3GetVdbe(pParse);
111744:     pParse->nMem = 4;
111745:     sqlite3CodeVerifySchema(pParse, iDb);
111746:     setAllColumnNames(v, 4, azCol);  assert( 4==ArraySize(azCol) );
111747:     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
111748:       Table *pTab = sqliteHashData(i);
111749:       sqlite3VdbeMultiLoad(v, 1, "ssii",
111750:            pTab->zName,
111751:            0,
111752:            pTab->szTabRow,
111753:            pTab->nRowLogEst);
111754:       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111755:       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111756:         sqlite3VdbeMultiLoad(v, 2, "sii",
111757:            pIdx->zName,
111758:            pIdx->szIdxRow,
111759:            pIdx->aiRowLogEst[0]);
111760:         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111761:       }
111762:     }
111763:   }
111764:   break;
111765: 
111766:   case PragTyp_INDEX_INFO: if( zRight ){
111767:     Index *pIdx;
111768:     Table *pTab;
111769:     pIdx = sqlite3FindIndex(db, zRight, zDb);
111770:     if( pIdx ){
111771:       static const char *azCol[] = {
111772:          "seqno", "cid", "name", "desc", "coll", "key"
111773:       };
111774:       int i;
111775:       int mx;
111776:       if( pPragma->iArg ){
111777:         /* PRAGMA index_xinfo (newer version with more rows and columns) */
111778:         mx = pIdx->nColumn;
111779:         pParse->nMem = 6;
111780:       }else{
111781:         /* PRAGMA index_info (legacy version) */
111782:         mx = pIdx->nKeyCol;
111783:         pParse->nMem = 3;
111784:       }
111785:       pTab = pIdx->pTable;
111786:       sqlite3CodeVerifySchema(pParse, iDb);
111787:       assert( pParse->nMem<=ArraySize(azCol) );
111788:       setAllColumnNames(v, pParse->nMem, azCol);
111789:       for(i=0; i<mx; i++){
111790:         i16 cnum = pIdx->aiColumn[i];
111791:         sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
111792:                              cnum<0 ? 0 : pTab->aCol[cnum].zName);
111793:         if( pPragma->iArg ){
111794:           sqlite3VdbeMultiLoad(v, 4, "isi",
111795:             pIdx->aSortOrder[i],
111796:             pIdx->azColl[i],
111797:             i<pIdx->nKeyCol);
111798:         }
111799:         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
111800:       }
111801:     }
111802:   }
111803:   break;
111804: 
111805:   case PragTyp_INDEX_LIST: if( zRight ){
111806:     Index *pIdx;
111807:     Table *pTab;
111808:     int i;
111809:     pTab = sqlite3FindTable(db, zRight, zDb);
111810:     if( pTab ){
111811:       static const char *azCol[] = {
111812:         "seq", "name", "unique", "origin", "partial"
111813:       };
111814:       v = sqlite3GetVdbe(pParse);
111815:       pParse->nMem = 5;
111816:       sqlite3CodeVerifySchema(pParse, iDb);
111817:       setAllColumnNames(v, 5, azCol);  assert( 5==ArraySize(azCol) );
111818:       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
111819:         const char *azOrigin[] = { "c", "u", "pk" };
111820:         sqlite3VdbeMultiLoad(v, 1, "isisi",
111821:            i,
111822:            pIdx->zName,
111823:            IsUniqueIndex(pIdx),
111824:            azOrigin[pIdx->idxType],
111825:            pIdx->pPartIdxWhere!=0);
111826:         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
111827:       }
111828:     }
111829:   }
111830:   break;
111831: 
111832:   case PragTyp_DATABASE_LIST: {
111833:     static const char *azCol[] = { "seq", "name", "file" };
111834:     int i;
111835:     pParse->nMem = 3;
111836:     setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
111837:     for(i=0; i<db->nDb; i++){
111838:       if( db->aDb[i].pBt==0 ) continue;
111839:       assert( db->aDb[i].zName!=0 );
111840:       sqlite3VdbeMultiLoad(v, 1, "iss",
111841:          i,
111842:          db->aDb[i].zName,
111843:          sqlite3BtreeGetFilename(db->aDb[i].pBt));
111844:       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
111845:     }
111846:   }
111847:   break;
111848: 
111849:   case PragTyp_COLLATION_LIST: {
111850:     static const char *azCol[] = { "seq", "name" };
111851:     int i = 0;
111852:     HashElem *p;
111853:     pParse->nMem = 2;
111854:     setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
111855:     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
111856:       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
111857:       sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
111858:       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
111859:     }
111860:   }
111861:   break;
111862: #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
111863: 
111864: #ifndef SQLITE_OMIT_FOREIGN_KEY
111865:   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
111866:     FKey *pFK;
111867:     Table *pTab;
111868:     pTab = sqlite3FindTable(db, zRight, zDb);
111869:     if( pTab ){
111870:       v = sqlite3GetVdbe(pParse);
111871:       pFK = pTab->pFKey;
111872:       if( pFK ){
111873:         static const char *azCol[] = {
111874:            "id", "seq", "table", "from", "to", "on_update", "on_delete",
111875:            "match"
111876:         };
111877:         int i = 0; 
111878:         pParse->nMem = 8;
111879:         sqlite3CodeVerifySchema(pParse, iDb);
111880:         setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
111881:         while(pFK){
111882:           int j;
111883:           for(j=0; j<pFK->nCol; j++){
111884:             sqlite3VdbeMultiLoad(v, 1, "iissssss",
111885:                    i,
111886:                    j,
111887:                    pFK->zTo,
111888:                    pTab->aCol[pFK->aCol[j].iFrom].zName,
111889:                    pFK->aCol[j].zCol,
111890:                    actionName(pFK->aAction[1]),  /* ON UPDATE */
111891:                    actionName(pFK->aAction[0]),  /* ON DELETE */
111892:                    "NONE");
111893:             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
111894:           }
111895:           ++i;
111896:           pFK = pFK->pNextFrom;
111897:         }
111898:       }
111899:     }
111900:   }
111901:   break;
111902: #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
111903: 
111904: #ifndef SQLITE_OMIT_FOREIGN_KEY
111905: #ifndef SQLITE_OMIT_TRIGGER
111906:   case PragTyp_FOREIGN_KEY_CHECK: {
111907:     FKey *pFK;             /* A foreign key constraint */
111908:     Table *pTab;           /* Child table contain "REFERENCES" keyword */
111909:     Table *pParent;        /* Parent table that child points to */
111910:     Index *pIdx;           /* Index in the parent table */
111911:     int i;                 /* Loop counter:  Foreign key number for pTab */
111912:     int j;                 /* Loop counter:  Field of the foreign key */
111913:     HashElem *k;           /* Loop counter:  Next table in schema */
111914:     int x;                 /* result variable */
111915:     int regResult;         /* 3 registers to hold a result row */
111916:     int regKey;            /* Register to hold key for checking the FK */
111917:     int regRow;            /* Registers to hold a row from pTab */
111918:     int addrTop;           /* Top of a loop checking foreign keys */
111919:     int addrOk;            /* Jump here if the key is OK */
111920:     int *aiCols;           /* child to parent column mapping */
111921:     static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
111922: 
111923:     regResult = pParse->nMem+1;
111924:     pParse->nMem += 4;
111925:     regKey = ++pParse->nMem;
111926:     regRow = ++pParse->nMem;
111927:     v = sqlite3GetVdbe(pParse);
111928:     setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
111929:     sqlite3CodeVerifySchema(pParse, iDb);
111930:     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
111931:     while( k ){
111932:       if( zRight ){
111933:         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
111934:         k = 0;
111935:       }else{
111936:         pTab = (Table*)sqliteHashData(k);
111937:         k = sqliteHashNext(k);
111938:       }
111939:       if( pTab==0 || pTab->pFKey==0 ) continue;
111940:       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
111941:       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
111942:       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
111943:       sqlite3VdbeLoadString(v, regResult, pTab->zName);
111944:       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111945:         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111946:         if( pParent==0 ) continue;
111947:         pIdx = 0;
111948:         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
111949:         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
111950:         if( x==0 ){
111951:           if( pIdx==0 ){
111952:             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
111953:           }else{
111954:             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
111955:             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111956:           }
111957:         }else{
111958:           k = 0;
111959:           break;
111960:         }
111961:       }
111962:       assert( pParse->nErr>0 || pFK==0 );
111963:       if( pFK ) break;
111964:       if( pParse->nTab<i ) pParse->nTab = i;
111965:       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
111966:       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111967:         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111968:         pIdx = 0;
111969:         aiCols = 0;
111970:         if( pParent ){
111971:           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
111972:           assert( x==0 );
111973:         }
111974:         addrOk = sqlite3VdbeMakeLabel(v);
111975:         if( pParent && pIdx==0 ){
111976:           int iKey = pFK->aCol[0].iFrom;
111977:           assert( iKey>=0 && iKey<pTab->nCol );
111978:           if( iKey!=pTab->iPKey ){
111979:             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
111980:             sqlite3ColumnDefault(v, pTab, iKey, regRow);
111981:             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
111982:           }else{
111983:             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
111984:           }
111985:           sqlite3VdbeAddOp3(v, OP_SeekRowid, i, 0, regRow); VdbeCoverage(v);
111986:           sqlite3VdbeGoto(v, addrOk);
111987:           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
111988:         }else{
111989:           for(j=0; j<pFK->nCol; j++){
111990:             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
111991:                             aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
111992:             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
111993:           }
111994:           if( pParent ){
111995:             sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
111996:                               sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
111997:             sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
111998:             VdbeCoverage(v);
111999:           }
112000:         }
112001:         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
112002:         sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
112003:         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
112004:         sqlite3VdbeResolveLabel(v, addrOk);
112005:         sqlite3DbFree(db, aiCols);
112006:       }
112007:       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
112008:       sqlite3VdbeJumpHere(v, addrTop);
112009:     }
112010:   }
112011:   break;
112012: #endif /* !defined(SQLITE_OMIT_TRIGGER) */
112013: #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
112014: 
112015: #ifndef NDEBUG
112016:   case PragTyp_PARSER_TRACE: {
112017:     if( zRight ){
112018:       if( sqlite3GetBoolean(zRight, 0) ){
112019:         sqlite3ParserTrace(stdout, "parser: ");
112020:       }else{
112021:         sqlite3ParserTrace(0, 0);
112022:       }
112023:     }
112024:   }
112025:   break;
112026: #endif
112027: 
112028:   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
112029:   ** used will be case sensitive or not depending on the RHS.
112030:   */
112031:   case PragTyp_CASE_SENSITIVE_LIKE: {
112032:     if( zRight ){
112033:       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
112034:     }
112035:   }
112036:   break;
112037: 
112038: #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
112039: # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
112040: #endif
112041: 
112042: #ifndef SQLITE_OMIT_INTEGRITY_CHECK
112043:   /* Pragma "quick_check" is reduced version of 
112044:   ** integrity_check designed to detect most database corruption
112045:   ** without most of the overhead of a full integrity-check.
112046:   */
112047:   case PragTyp_INTEGRITY_CHECK: {
112048:     int i, j, addr, mxErr;
112049: 
112050:     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
112051: 
112052:     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
112053:     ** then iDb is set to the index of the database identified by <db>.
112054:     ** In this case, the integrity of database iDb only is verified by
112055:     ** the VDBE created below.
112056:     **
112057:     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
112058:     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
112059:     ** to -1 here, to indicate that the VDBE should verify the integrity
112060:     ** of all attached databases.  */
112061:     assert( iDb>=0 );
112062:     assert( iDb==0 || pId2->z );
112063:     if( pId2->z==0 ) iDb = -1;
112064: 
112065:     /* Initialize the VDBE program */
112066:     pParse->nMem = 6;
112067:     setOneColumnName(v, "integrity_check");
112068: 
112069:     /* Set the maximum error count */
112070:     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112071:     if( zRight ){
112072:       sqlite3GetInt32(zRight, &mxErr);
112073:       if( mxErr<=0 ){
112074:         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
112075:       }
112076:     }
112077:     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
112078: 
112079:     /* Do an integrity check on each database file */
112080:     for(i=0; i<db->nDb; i++){
112081:       HashElem *x;
112082:       Hash *pTbls;
112083:       int *aRoot;
112084:       int cnt = 0;
112085:       int mxIdx = 0;
112086:       int nIdx;
112087: 
112088:       if( OMIT_TEMPDB && i==1 ) continue;
112089:       if( iDb>=0 && i!=iDb ) continue;
112090: 
112091:       sqlite3CodeVerifySchema(pParse, i);
112092:       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
112093:       VdbeCoverage(v);
112094:       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112095:       sqlite3VdbeJumpHere(v, addr);
112096: 
112097:       /* Do an integrity check of the B-Tree
112098:       **
112099:       ** Begin by finding the root pages numbers
112100:       ** for all tables and indices in the database.
112101:       */
112102:       assert( sqlite3SchemaMutexHeld(db, i, 0) );
112103:       pTbls = &db->aDb[i].pSchema->tblHash;
112104:       for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
112105:         Table *pTab = sqliteHashData(x);
112106:         Index *pIdx;
112107:         if( HasRowid(pTab) ) cnt++;
112108:         for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
112109:         if( nIdx>mxIdx ) mxIdx = nIdx;
112110:       }
112111:       aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
112112:       if( aRoot==0 ) break;
112113:       for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
112114:         Table *pTab = sqliteHashData(x);
112115:         Index *pIdx;
112116:         if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
112117:         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
112118:           aRoot[cnt++] = pIdx->tnum;
112119:         }
112120:       }
112121:       aRoot[cnt] = 0;
112122: 
112123:       /* Make sure sufficient number of registers have been allocated */
112124:       pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
112125: 
112126:       /* Do the b-tree integrity checks */
112127:       sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
112128:       sqlite3VdbeChangeP5(v, (u8)i);
112129:       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
112130:       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
112131:          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
112132:          P4_DYNAMIC);
112133:       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
112134:       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
112135:       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
112136:       sqlite3VdbeJumpHere(v, addr);
112137: 
112138:       /* Make sure all the indices are constructed correctly.
112139:       */
112140:       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
112141:         Table *pTab = sqliteHashData(x);
112142:         Index *pIdx, *pPk;
112143:         Index *pPrior = 0;
112144:         int loopTop;
112145:         int iDataCur, iIdxCur;
112146:         int r1 = -1;
112147: 
112148:         if( pTab->pIndex==0 ) continue;
112149:         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
112150:         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
112151:         VdbeCoverage(v);
112152:         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112153:         sqlite3VdbeJumpHere(v, addr);
112154:         sqlite3ExprCacheClear(pParse);
112155:         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
112156:                                    1, 0, &iDataCur, &iIdxCur);
112157:         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
112158:         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112159:           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
112160:         }
112161:         assert( pParse->nMem>=8+j );
112162:         assert( sqlite3NoTempsInRange(pParse,1,7+j) );
112163:         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
112164:         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
112165:         /* Verify that all NOT NULL columns really are NOT NULL */
112166:         for(j=0; j<pTab->nCol; j++){
112167:           char *zErr;
112168:           int jmp2, jmp3;
112169:           if( j==pTab->iPKey ) continue;
112170:           if( pTab->aCol[j].notNull==0 ) continue;
112171:           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
112172:           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
112173:           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
112174:           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112175:           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
112176:                               pTab->aCol[j].zName);
112177:           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
112178:           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
112179:           jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
112180:           sqlite3VdbeAddOp0(v, OP_Halt);
112181:           sqlite3VdbeJumpHere(v, jmp2);
112182:           sqlite3VdbeJumpHere(v, jmp3);
112183:         }
112184:         /* Validate index entries for the current row */
112185:         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112186:           int jmp2, jmp3, jmp4, jmp5;
112187:           int ckUniq = sqlite3VdbeMakeLabel(v);
112188:           if( pPk==pIdx ) continue;
112189:           r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
112190:                                        pPrior, r1);
112191:           pPrior = pIdx;
112192:           sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
112193:           /* Verify that an index entry exists for the current table row */
112194:           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
112195:                                       pIdx->nColumn); VdbeCoverage(v);
112196:           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112197:           sqlite3VdbeLoadString(v, 3, "row ");
112198:           sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
112199:           sqlite3VdbeLoadString(v, 4, " missing from index ");
112200:           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
112201:           jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
112202:           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
112203:           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
112204:           jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
112205:           sqlite3VdbeAddOp0(v, OP_Halt);
112206:           sqlite3VdbeJumpHere(v, jmp2);
112207:           /* For UNIQUE indexes, verify that only one entry exists with the
112208:           ** current key.  The entry is unique if (1) any column is NULL
112209:           ** or (2) the next entry has a different key */
112210:           if( IsUniqueIndex(pIdx) ){
112211:             int uniqOk = sqlite3VdbeMakeLabel(v);
112212:             int jmp6;
112213:             int kk;
112214:             for(kk=0; kk<pIdx->nKeyCol; kk++){
112215:               int iCol = pIdx->aiColumn[kk];
112216:               assert( iCol!=XN_ROWID && iCol<pTab->nCol );
112217:               if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
112218:               sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
112219:               VdbeCoverage(v);
112220:             }
112221:             jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
112222:             sqlite3VdbeGoto(v, uniqOk);
112223:             sqlite3VdbeJumpHere(v, jmp6);
112224:             sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
112225:                                  pIdx->nKeyCol); VdbeCoverage(v);
112226:             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
112227:             sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
112228:             sqlite3VdbeGoto(v, jmp5);
112229:             sqlite3VdbeResolveLabel(v, uniqOk);
112230:           }
112231:           sqlite3VdbeJumpHere(v, jmp4);
112232:           sqlite3ResolvePartIdxLabel(pParse, jmp3);
112233:         }
112234:         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
112235:         sqlite3VdbeJumpHere(v, loopTop-1);
112236: #ifndef SQLITE_OMIT_BTREECOUNT
112237:         sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
112238:         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
112239:           if( pPk==pIdx ) continue;
112240:           addr = sqlite3VdbeCurrentAddr(v);
112241:           sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
112242:           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
112243:           sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
112244:           sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
112245:           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
112246:           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
112247:           sqlite3VdbeLoadString(v, 3, pIdx->zName);
112248:           sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
112249:           sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
112250:         }
112251: #endif /* SQLITE_OMIT_BTREECOUNT */
112252:       } 
112253:     }
112254:     {
112255:       static const int iLn = VDBE_OFFSET_LINENO(2);
112256:       static const VdbeOpList endCode[] = {
112257:         { OP_AddImm,      1, 0,        0},    /* 0 */
112258:         { OP_If,          1, 4,        0},    /* 1 */
112259:         { OP_String8,     0, 3,        0},    /* 2 */
112260:         { OP_ResultRow,   3, 1,        0},    /* 3 */
112261:       };
112262:       VdbeOp *aOp;
112263: 
112264:       aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
112265:       if( aOp ){
112266:         aOp[0].p2 = -mxErr;
112267:         aOp[2].p4type = P4_STATIC;
112268:         aOp[2].p4.z = "ok";
112269:       }
112270:     }
112271:   }
112272:   break;
112273: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
112274: 
112275: #ifndef SQLITE_OMIT_UTF16
112276:   /*
112277:   **   PRAGMA encoding
112278:   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
112279:   **
112280:   ** In its first form, this pragma returns the encoding of the main
112281:   ** database. If the database is not initialized, it is initialized now.
112282:   **
112283:   ** The second form of this pragma is a no-op if the main database file
112284:   ** has not already been initialized. In this case it sets the default
112285:   ** encoding that will be used for the main database file if a new file
112286:   ** is created. If an existing main database file is opened, then the
112287:   ** default text encoding for the existing database is used.
112288:   ** 
112289:   ** In all cases new databases created using the ATTACH command are
112290:   ** created to use the same default text encoding as the main database. If
112291:   ** the main database has not been initialized and/or created when ATTACH
112292:   ** is executed, this is done before the ATTACH operation.
112293:   **
112294:   ** In the second form this pragma sets the text encoding to be used in
112295:   ** new database files created using this database handle. It is only
112296:   ** useful if invoked immediately after the main database i
112297:   */
112298:   case PragTyp_ENCODING: {
112299:     static const struct EncName {
112300:       char *zName;
112301:       u8 enc;
112302:     } encnames[] = {
112303:       { "UTF8",     SQLITE_UTF8        },
112304:       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
112305:       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
112306:       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
112307:       { "UTF16le",  SQLITE_UTF16LE     },
112308:       { "UTF16be",  SQLITE_UTF16BE     },
112309:       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
112310:       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
112311:       { 0, 0 }
112312:     };
112313:     const struct EncName *pEnc;
112314:     if( !zRight ){    /* "PRAGMA encoding" */
112315:       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
112316:       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
112317:       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
112318:       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
112319:       returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
112320:     }else{                        /* "PRAGMA encoding = XXX" */
112321:       /* Only change the value of sqlite.enc if the database handle is not
112322:       ** initialized. If the main database exists, the new sqlite.enc value
112323:       ** will be overwritten when the schema is next loaded. If it does not
112324:       ** already exists, it will be created to use the new encoding value.
112325:       */
112326:       if( 
112327:         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
112328:         DbHasProperty(db, 0, DB_Empty) 
112329:       ){
112330:         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
112331:           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
112332:             SCHEMA_ENC(db) = ENC(db) =
112333:                 pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
112334:             break;
112335:           }
112336:         }
112337:         if( !pEnc->zName ){
112338:           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
112339:         }
112340:       }
112341:     }
112342:   }
112343:   break;
112344: #endif /* SQLITE_OMIT_UTF16 */
112345: 
112346: #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
112347:   /*
112348:   **   PRAGMA [schema.]schema_version
112349:   **   PRAGMA [schema.]schema_version = <integer>
112350:   **
112351:   **   PRAGMA [schema.]user_version
112352:   **   PRAGMA [schema.]user_version = <integer>
112353:   **
112354:   **   PRAGMA [schema.]freelist_count
112355:   **
112356:   **   PRAGMA [schema.]data_version
112357:   **
112358:   **   PRAGMA [schema.]application_id
112359:   **   PRAGMA [schema.]application_id = <integer>
112360:   **
112361:   ** The pragma's schema_version and user_version are used to set or get
112362:   ** the value of the schema-version and user-version, respectively. Both
112363:   ** the schema-version and the user-version are 32-bit signed integers
112364:   ** stored in the database header.
112365:   **
112366:   ** The schema-cookie is usually only manipulated internally by SQLite. It
112367:   ** is incremented by SQLite whenever the database schema is modified (by
112368:   ** creating or dropping a table or index). The schema version is used by
112369:   ** SQLite each time a query is executed to ensure that the internal cache
112370:   ** of the schema used when compiling the SQL query matches the schema of
112371:   ** the database against which the compiled query is actually executed.
112372:   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
112373:   ** the schema-version is potentially dangerous and may lead to program
112374:   ** crashes or database corruption. Use with caution!
112375:   **
112376:   ** The user-version is not used internally by SQLite. It may be used by
112377:   ** applications for any purpose.
112378:   */
112379:   case PragTyp_HEADER_VALUE: {
112380:     int iCookie = pPragma->iArg;  /* Which cookie to read or write */
112381:     sqlite3VdbeUsesBtree(v, iDb);
112382:     if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
112383:       /* Write the specified cookie value */
112384:       static const VdbeOpList setCookie[] = {
112385:         { OP_Transaction,    0,  1,  0},    /* 0 */
112386:         { OP_SetCookie,      0,  0,  0},    /* 1 */
112387:       };
112388:       VdbeOp *aOp;
112389:       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
112390:       aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
112391:       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112392:       aOp[0].p1 = iDb;
112393:       aOp[1].p1 = iDb;
112394:       aOp[1].p2 = iCookie;
112395:       aOp[1].p3 = sqlite3Atoi(zRight);
112396:     }else{
112397:       /* Read the specified cookie value */
112398:       static const VdbeOpList readCookie[] = {
112399:         { OP_Transaction,     0,  0,  0},    /* 0 */
112400:         { OP_ReadCookie,      0,  1,  0},    /* 1 */
112401:         { OP_ResultRow,       1,  1,  0}
112402:       };
112403:       VdbeOp *aOp;
112404:       sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
112405:       aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
112406:       if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
112407:       aOp[0].p1 = iDb;
112408:       aOp[1].p1 = iDb;
112409:       aOp[1].p3 = iCookie;
112410:       sqlite3VdbeSetNumCols(v, 1);
112411:       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
112412:       sqlite3VdbeReusable(v);
112413:     }
112414:   }
112415:   break;
112416: #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
112417: 
112418: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
112419:   /*
112420:   **   PRAGMA compile_options
112421:   **
112422:   ** Return the names of all compile-time options used in this build,
112423:   ** one option per row.
112424:   */
112425:   case PragTyp_COMPILE_OPTIONS: {
112426:     int i = 0;
112427:     const char *zOpt;
112428:     pParse->nMem = 1;
112429:     setOneColumnName(v, "compile_option");
112430:     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
112431:       sqlite3VdbeLoadString(v, 1, zOpt);
112432:       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
112433:     }
112434:     sqlite3VdbeReusable(v);
112435:   }
112436:   break;
112437: #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
112438: 
112439: #ifndef SQLITE_OMIT_WAL
112440:   /*
112441:   **   PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
112442:   **
112443:   ** Checkpoint the database.
112444:   */
112445:   case PragTyp_WAL_CHECKPOINT: {
112446:     static const char *azCol[] = { "busy", "log", "checkpointed" };
112447:     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
112448:     int eMode = SQLITE_CHECKPOINT_PASSIVE;
112449:     if( zRight ){
112450:       if( sqlite3StrICmp(zRight, "full")==0 ){
112451:         eMode = SQLITE_CHECKPOINT_FULL;
112452:       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
112453:         eMode = SQLITE_CHECKPOINT_RESTART;
112454:       }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
112455:         eMode = SQLITE_CHECKPOINT_TRUNCATE;
112456:       }
112457:     }
112458:     setAllColumnNames(v, 3, azCol);  assert( 3==ArraySize(azCol) );
112459:     pParse->nMem = 3;
112460:     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
112461:     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
112462:   }
112463:   break;
112464: 
112465:   /*
112466:   **   PRAGMA wal_autocheckpoint
112467:   **   PRAGMA wal_autocheckpoint = N
112468:   **
112469:   ** Configure a database connection to automatically checkpoint a database
112470:   ** after accumulating N frames in the log. Or query for the current value
112471:   ** of N.
112472:   */
112473:   case PragTyp_WAL_AUTOCHECKPOINT: {
112474:     if( zRight ){
112475:       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
112476:     }
112477:     returnSingleInt(v, "wal_autocheckpoint", 
112478:        db->xWalCallback==sqlite3WalDefaultHook ? 
112479:            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
112480:   }
112481:   break;
112482: #endif
112483: 
112484:   /*
112485:   **  PRAGMA shrink_memory
112486:   **
112487:   ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
112488:   ** connection on which it is invoked to free up as much memory as it
112489:   ** can, by calling sqlite3_db_release_memory().
112490:   */
112491:   case PragTyp_SHRINK_MEMORY: {
112492:     sqlite3_db_release_memory(db);
112493:     break;
112494:   }
112495: 
112496:   /*
112497:   **   PRAGMA busy_timeout
112498:   **   PRAGMA busy_timeout = N
112499:   **
112500:   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
112501:   ** if one is set.  If no busy handler or a different busy handler is set
112502:   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
112503:   ** disables the timeout.
112504:   */
112505:   /*case PragTyp_BUSY_TIMEOUT*/ default: {
112506:     assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
112507:     if( zRight ){
112508:       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
112509:     }
112510:     returnSingleInt(v, "timeout",  db->busyTimeout);
112511:     break;
112512:   }
112513: 
112514:   /*
112515:   **   PRAGMA soft_heap_limit
112516:   **   PRAGMA soft_heap_limit = N
112517:   **
112518:   ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
112519:   ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
112520:   ** specified and is a non-negative integer.
112521:   ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
112522:   ** returns the same integer that would be returned by the
112523:   ** sqlite3_soft_heap_limit64(-1) C-language function.
112524:   */
112525:   case PragTyp_SOFT_HEAP_LIMIT: {
112526:     sqlite3_int64 N;
112527:     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
112528:       sqlite3_soft_heap_limit64(N);
112529:     }
112530:     returnSingleInt(v, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
112531:     break;
112532:   }
112533: 
112534:   /*
112535:   **   PRAGMA threads
112536:   **   PRAGMA threads = N
112537:   **
112538:   ** Configure the maximum number of worker threads.  Return the new
112539:   ** maximum, which might be less than requested.
112540:   */
112541:   case PragTyp_THREADS: {
112542:     sqlite3_int64 N;
112543:     if( zRight
112544:      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
112545:      && N>=0
112546:     ){
112547:       sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
112548:     }
112549:     returnSingleInt(v, "threads",
112550:                     sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
112551:     break;
112552:   }
112553: 
112554: #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
112555:   /*
112556:   ** Report the current state of file logs for all databases
112557:   */
112558:   case PragTyp_LOCK_STATUS: {
112559:     static const char *const azLockName[] = {
112560:       "unlocked", "shared", "reserved", "pending", "exclusive"
112561:     };
112562:     static const char *azCol[] = { "database", "status" };
112563:     int i;
112564:     setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
112565:     pParse->nMem = 2;
112566:     for(i=0; i<db->nDb; i++){
112567:       Btree *pBt;
112568:       const char *zState = "unknown";
112569:       int j;
112570:       if( db->aDb[i].zName==0 ) continue;
112571:       pBt = db->aDb[i].pBt;
112572:       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
112573:         zState = "closed";
112574:       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
112575:                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
112576:          zState = azLockName[j];
112577:       }
112578:       sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
112579:       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
112580:     }
112581:     break;
112582:   }
112583: #endif
112584: 
112585: #ifdef SQLITE_HAS_CODEC
112586:   case PragTyp_KEY: {
112587:     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
112588:     break;
112589:   }
112590:   case PragTyp_REKEY: {
112591:     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
112592:     break;
112593:   }
112594:   case PragTyp_HEXKEY: {
112595:     if( zRight ){
112596:       u8 iByte;
112597:       int i;
112598:       char zKey[40];
112599:       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
112600:         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
112601:         if( (i&1)!=0 ) zKey[i/2] = iByte;
112602:       }
112603:       if( (zLeft[3] & 0xf)==0xb ){
112604:         sqlite3_key_v2(db, zDb, zKey, i/2);
112605:       }else{
112606:         sqlite3_rekey_v2(db, zDb, zKey, i/2);
112607:       }
112608:     }
112609:     break;
112610:   }
112611: #endif
112612: #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
112613:   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
112614: #ifdef SQLITE_HAS_CODEC
112615:     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
112616:       sqlite3_activate_see(&zRight[4]);
112617:     }
112618: #endif
112619: #ifdef SQLITE_ENABLE_CEROD
112620:     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
112621:       sqlite3_activate_cerod(&zRight[6]);
112622:     }
112623: #endif
112624:   }
112625:   break;
112626: #endif
112627: 
112628:   } /* End of the PRAGMA switch */
112629: 
112630: pragma_out:
112631:   sqlite3DbFree(db, zLeft);
112632:   sqlite3DbFree(db, zRight);
112633: }
112634: 
112635: #endif /* SQLITE_OMIT_PRAGMA */
112636: 
112637: /************** End of pragma.c **********************************************/
112638: /************** Begin file prepare.c *****************************************/
112639: /*
112640: ** 2005 May 25
112641: **
112642: ** The author disclaims copyright to this source code.  In place of
112643: ** a legal notice, here is a blessing:
112644: **
112645: **    May you do good and not evil.
112646: **    May you find forgiveness for yourself and forgive others.
112647: **    May you share freely, never taking more than you give.
112648: **
112649: *************************************************************************
112650: ** This file contains the implementation of the sqlite3_prepare()
112651: ** interface, and routines that contribute to loading the database schema
112652: ** from disk.
112653: */
112654: /* #include "sqliteInt.h" */
112655: 
112656: /*
112657: ** Fill the InitData structure with an error message that indicates
112658: ** that the database is corrupt.
112659: */
112660: static void corruptSchema(
112661:   InitData *pData,     /* Initialization context */
112662:   const char *zObj,    /* Object being parsed at the point of error */
112663:   const char *zExtra   /* Error information */
112664: ){
112665:   sqlite3 *db = pData->db;
112666:   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
112667:     char *z;
112668:     if( zObj==0 ) zObj = "?";
112669:     z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
112670:     if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
112671:     sqlite3DbFree(db, *pData->pzErrMsg);
112672:     *pData->pzErrMsg = z;
112673:   }
112674:   pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
112675: }
112676: 
112677: /*
112678: ** This is the callback routine for the code that initializes the
112679: ** database.  See sqlite3Init() below for additional information.
112680: ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
112681: **
112682: ** Each callback contains the following information:
112683: **
112684: **     argv[0] = name of thing being created
112685: **     argv[1] = root page number for table or index. 0 for trigger or view.
112686: **     argv[2] = SQL text for the CREATE statement.
112687: **
112688: */
112689: SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
112690:   InitData *pData = (InitData*)pInit;
112691:   sqlite3 *db = pData->db;
112692:   int iDb = pData->iDb;
112693: 
112694:   assert( argc==3 );
112695:   UNUSED_PARAMETER2(NotUsed, argc);
112696:   assert( sqlite3_mutex_held(db->mutex) );
112697:   DbClearProperty(db, iDb, DB_Empty);
112698:   if( db->mallocFailed ){
112699:     corruptSchema(pData, argv[0], 0);
112700:     return 1;
112701:   }
112702: 
112703:   assert( iDb>=0 && iDb<db->nDb );
112704:   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
112705:   if( argv[1]==0 ){
112706:     corruptSchema(pData, argv[0], 0);
112707:   }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
112708:     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
112709:     ** But because db->init.busy is set to 1, no VDBE code is generated
112710:     ** or executed.  All the parser does is build the internal data
112711:     ** structures that describe the table, index, or view.
112712:     */
112713:     int rc;
112714:     sqlite3_stmt *pStmt;
112715:     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
112716: 
112717:     assert( db->init.busy );
112718:     db->init.iDb = iDb;
112719:     db->init.newTnum = sqlite3Atoi(argv[1]);
112720:     db->init.orphanTrigger = 0;
112721:     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
112722:     rc = db->errCode;
112723:     assert( (rc&0xFF)==(rcp&0xFF) );
112724:     db->init.iDb = 0;
112725:     if( SQLITE_OK!=rc ){
112726:       if( db->init.orphanTrigger ){
112727:         assert( iDb==1 );
112728:       }else{
112729:         pData->rc = rc;
112730:         if( rc==SQLITE_NOMEM ){
112731:           sqlite3OomFault(db);
112732:         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
112733:           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
112734:         }
112735:       }
112736:     }
112737:     sqlite3_finalize(pStmt);
112738:   }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
112739:     corruptSchema(pData, argv[0], 0);
112740:   }else{
112741:     /* If the SQL column is blank it means this is an index that
112742:     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
112743:     ** constraint for a CREATE TABLE.  The index should have already
112744:     ** been created when we processed the CREATE TABLE.  All we have
112745:     ** to do here is record the root page number for that index.
112746:     */
112747:     Index *pIndex;
112748:     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
112749:     if( pIndex==0 ){
112750:       /* This can occur if there exists an index on a TEMP table which
112751:       ** has the same name as another index on a permanent index.  Since
112752:       ** the permanent table is hidden by the TEMP table, we can also
112753:       ** safely ignore the index on the permanent table.
112754:       */
112755:       /* Do Nothing */;
112756:     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
112757:       corruptSchema(pData, argv[0], "invalid rootpage");
112758:     }
112759:   }
112760:   return 0;
112761: }
112762: 
112763: /*
112764: ** Attempt to read the database schema and initialize internal
112765: ** data structures for a single database file.  The index of the
112766: ** database file is given by iDb.  iDb==0 is used for the main
112767: ** database.  iDb==1 should never be used.  iDb>=2 is used for
112768: ** auxiliary databases.  Return one of the SQLITE_ error codes to
112769: ** indicate success or failure.
112770: */
112771: static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
112772:   int rc;
112773:   int i;
112774: #ifndef SQLITE_OMIT_DEPRECATED
112775:   int size;
112776: #endif
112777:   Db *pDb;
112778:   char const *azArg[4];
112779:   int meta[5];
112780:   InitData initData;
112781:   const char *zMasterName;
112782:   int openedTransaction = 0;
112783: 
112784:   assert( iDb>=0 && iDb<db->nDb );
112785:   assert( db->aDb[iDb].pSchema );
112786:   assert( sqlite3_mutex_held(db->mutex) );
112787:   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
112788: 
112789:   /* Construct the in-memory representation schema tables (sqlite_master or
112790:   ** sqlite_temp_master) by invoking the parser directly.  The appropriate
112791:   ** table name will be inserted automatically by the parser so we can just
112792:   ** use the abbreviation "x" here.  The parser will also automatically tag
112793:   ** the schema table as read-only. */
112794:   azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
112795:   azArg[1] = "1";
112796:   azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
112797:                             "rootpage integer,sql text)";
112798:   azArg[3] = 0;
112799:   initData.db = db;
112800:   initData.iDb = iDb;
112801:   initData.rc = SQLITE_OK;
112802:   initData.pzErrMsg = pzErrMsg;
112803:   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
112804:   if( initData.rc ){
112805:     rc = initData.rc;
112806:     goto error_out;
112807:   }
112808: 
112809:   /* Create a cursor to hold the database open
112810:   */
112811:   pDb = &db->aDb[iDb];
112812:   if( pDb->pBt==0 ){
112813:     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
112814:       DbSetProperty(db, 1, DB_SchemaLoaded);
112815:     }
112816:     return SQLITE_OK;
112817:   }
112818: 
112819:   /* If there is not already a read-only (or read-write) transaction opened
112820:   ** on the b-tree database, open one now. If a transaction is opened, it 
112821:   ** will be closed before this function returns.  */
112822:   sqlite3BtreeEnter(pDb->pBt);
112823:   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
112824:     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
112825:     if( rc!=SQLITE_OK ){
112826:       sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
112827:       goto initone_error_out;
112828:     }
112829:     openedTransaction = 1;
112830:   }
112831: 
112832:   /* Get the database meta information.
112833:   **
112834:   ** Meta values are as follows:
112835:   **    meta[0]   Schema cookie.  Changes with each schema change.
112836:   **    meta[1]   File format of schema layer.
112837:   **    meta[2]   Size of the page cache.
112838:   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
112839:   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
112840:   **    meta[5]   User version
112841:   **    meta[6]   Incremental vacuum mode
112842:   **    meta[7]   unused
112843:   **    meta[8]   unused
112844:   **    meta[9]   unused
112845:   **
112846:   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
112847:   ** the possible values of meta[4].
112848:   */
112849:   for(i=0; i<ArraySize(meta); i++){
112850:     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
112851:   }
112852:   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
112853: 
112854:   /* If opening a non-empty database, check the text encoding. For the
112855:   ** main database, set sqlite3.enc to the encoding of the main database.
112856:   ** For an attached db, it is an error if the encoding is not the same
112857:   ** as sqlite3.enc.
112858:   */
112859:   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
112860:     if( iDb==0 ){
112861: #ifndef SQLITE_OMIT_UTF16
112862:       u8 encoding;
112863:       /* If opening the main database, set ENC(db). */
112864:       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
112865:       if( encoding==0 ) encoding = SQLITE_UTF8;
112866:       ENC(db) = encoding;
112867: #else
112868:       ENC(db) = SQLITE_UTF8;
112869: #endif
112870:     }else{
112871:       /* If opening an attached database, the encoding much match ENC(db) */
112872:       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
112873:         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
112874:             " text encoding as main database");
112875:         rc = SQLITE_ERROR;
112876:         goto initone_error_out;
112877:       }
112878:     }
112879:   }else{
112880:     DbSetProperty(db, iDb, DB_Empty);
112881:   }
112882:   pDb->pSchema->enc = ENC(db);
112883: 
112884:   if( pDb->pSchema->cache_size==0 ){
112885: #ifndef SQLITE_OMIT_DEPRECATED
112886:     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
112887:     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
112888:     pDb->pSchema->cache_size = size;
112889: #else
112890:     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
112891: #endif
112892:     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
112893:   }
112894: 
112895:   /*
112896:   ** file_format==1    Version 3.0.0.
112897:   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
112898:   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
112899:   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
112900:   */
112901:   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
112902:   if( pDb->pSchema->file_format==0 ){
112903:     pDb->pSchema->file_format = 1;
112904:   }
112905:   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
112906:     sqlite3SetString(pzErrMsg, db, "unsupported file format");
112907:     rc = SQLITE_ERROR;
112908:     goto initone_error_out;
112909:   }
112910: 
112911:   /* Ticket #2804:  When we open a database in the newer file format,
112912:   ** clear the legacy_file_format pragma flag so that a VACUUM will
112913:   ** not downgrade the database and thus invalidate any descending
112914:   ** indices that the user might have created.
112915:   */
112916:   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
112917:     db->flags &= ~SQLITE_LegacyFileFmt;
112918:   }
112919: 
112920:   /* Read the schema information out of the schema tables
112921:   */
112922:   assert( db->init.busy );
112923:   {
112924:     char *zSql;
112925:     zSql = sqlite3MPrintf(db, 
112926:         "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
112927:         db->aDb[iDb].zName, zMasterName);
112928: #ifndef SQLITE_OMIT_AUTHORIZATION
112929:     {
112930:       sqlite3_xauth xAuth;
112931:       xAuth = db->xAuth;
112932:       db->xAuth = 0;
112933: #endif
112934:       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
112935: #ifndef SQLITE_OMIT_AUTHORIZATION
112936:       db->xAuth = xAuth;
112937:     }
112938: #endif
112939:     if( rc==SQLITE_OK ) rc = initData.rc;
112940:     sqlite3DbFree(db, zSql);
112941: #ifndef SQLITE_OMIT_ANALYZE
112942:     if( rc==SQLITE_OK ){
112943:       sqlite3AnalysisLoad(db, iDb);
112944:     }
112945: #endif
112946:   }
112947:   if( db->mallocFailed ){
112948:     rc = SQLITE_NOMEM_BKPT;
112949:     sqlite3ResetAllSchemasOfConnection(db);
112950:   }
112951:   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
112952:     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
112953:     ** the schema loaded, even if errors occurred. In this situation the 
112954:     ** current sqlite3_prepare() operation will fail, but the following one
112955:     ** will attempt to compile the supplied statement against whatever subset
112956:     ** of the schema was loaded before the error occurred. The primary
112957:     ** purpose of this is to allow access to the sqlite_master table
112958:     ** even when its contents have been corrupted.
112959:     */
112960:     DbSetProperty(db, iDb, DB_SchemaLoaded);
112961:     rc = SQLITE_OK;
112962:   }
112963: 
112964:   /* Jump here for an error that occurs after successfully allocating
112965:   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
112966:   ** before that point, jump to error_out.
112967:   */
112968: initone_error_out:
112969:   if( openedTransaction ){
112970:     sqlite3BtreeCommit(pDb->pBt);
112971:   }
112972:   sqlite3BtreeLeave(pDb->pBt);
112973: 
112974: error_out:
112975:   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
112976:     sqlite3OomFault(db);
112977:   }
112978:   return rc;
112979: }
112980: 
112981: /*
112982: ** Initialize all database files - the main database file, the file
112983: ** used to store temporary tables, and any additional database files
112984: ** created using ATTACH statements.  Return a success code.  If an
112985: ** error occurs, write an error message into *pzErrMsg.
112986: **
112987: ** After a database is initialized, the DB_SchemaLoaded bit is set
112988: ** bit is set in the flags field of the Db structure. If the database
112989: ** file was of zero-length, then the DB_Empty flag is also set.
112990: */
112991: SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
112992:   int i, rc;
112993:   int commit_internal = !(db->flags&SQLITE_InternChanges);
112994:   
112995:   assert( sqlite3_mutex_held(db->mutex) );
112996:   assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
112997:   assert( db->init.busy==0 );
112998:   rc = SQLITE_OK;
112999:   db->init.busy = 1;
113000:   ENC(db) = SCHEMA_ENC(db);
113001:   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
113002:     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
113003:     rc = sqlite3InitOne(db, i, pzErrMsg);
113004:     if( rc ){
113005:       sqlite3ResetOneSchema(db, i);
113006:     }
113007:   }
113008: 
113009:   /* Once all the other databases have been initialized, load the schema
113010:   ** for the TEMP database. This is loaded last, as the TEMP database
113011:   ** schema may contain references to objects in other databases.
113012:   */
113013: #ifndef SQLITE_OMIT_TEMPDB
113014:   assert( db->nDb>1 );
113015:   if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
113016:     rc = sqlite3InitOne(db, 1, pzErrMsg);
113017:     if( rc ){
113018:       sqlite3ResetOneSchema(db, 1);
113019:     }
113020:   }
113021: #endif
113022: 
113023:   db->init.busy = 0;
113024:   if( rc==SQLITE_OK && commit_internal ){
113025:     sqlite3CommitInternalChanges(db);
113026:   }
113027: 
113028:   return rc; 
113029: }
113030: 
113031: /*
113032: ** This routine is a no-op if the database schema is already initialized.
113033: ** Otherwise, the schema is loaded. An error code is returned.
113034: */
113035: SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
113036:   int rc = SQLITE_OK;
113037:   sqlite3 *db = pParse->db;
113038:   assert( sqlite3_mutex_held(db->mutex) );
113039:   if( !db->init.busy ){
113040:     rc = sqlite3Init(db, &pParse->zErrMsg);
113041:   }
113042:   if( rc!=SQLITE_OK ){
113043:     pParse->rc = rc;
113044:     pParse->nErr++;
113045:   }
113046:   return rc;
113047: }
113048: 
113049: 
113050: /*
113051: ** Check schema cookies in all databases.  If any cookie is out
113052: ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
113053: ** make no changes to pParse->rc.
113054: */
113055: static void schemaIsValid(Parse *pParse){
113056:   sqlite3 *db = pParse->db;
113057:   int iDb;
113058:   int rc;
113059:   int cookie;
113060: 
113061:   assert( pParse->checkSchema );
113062:   assert( sqlite3_mutex_held(db->mutex) );
113063:   for(iDb=0; iDb<db->nDb; iDb++){
113064:     int openedTransaction = 0;         /* True if a transaction is opened */
113065:     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
113066:     if( pBt==0 ) continue;
113067: 
113068:     /* If there is not already a read-only (or read-write) transaction opened
113069:     ** on the b-tree database, open one now. If a transaction is opened, it 
113070:     ** will be closed immediately after reading the meta-value. */
113071:     if( !sqlite3BtreeIsInReadTrans(pBt) ){
113072:       rc = sqlite3BtreeBeginTrans(pBt, 0);
113073:       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
113074:         sqlite3OomFault(db);
113075:       }
113076:       if( rc!=SQLITE_OK ) return;
113077:       openedTransaction = 1;
113078:     }
113079: 
113080:     /* Read the schema cookie from the database. If it does not match the 
113081:     ** value stored as part of the in-memory schema representation,
113082:     ** set Parse.rc to SQLITE_SCHEMA. */
113083:     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
113084:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
113085:     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
113086:       sqlite3ResetOneSchema(db, iDb);
113087:       pParse->rc = SQLITE_SCHEMA;
113088:     }
113089: 
113090:     /* Close the transaction, if one was opened. */
113091:     if( openedTransaction ){
113092:       sqlite3BtreeCommit(pBt);
113093:     }
113094:   }
113095: }
113096: 
113097: /*
113098: ** Convert a schema pointer into the iDb index that indicates
113099: ** which database file in db->aDb[] the schema refers to.
113100: **
113101: ** If the same database is attached more than once, the first
113102: ** attached database is returned.
113103: */
113104: SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
113105:   int i = -1000000;
113106: 
113107:   /* If pSchema is NULL, then return -1000000. This happens when code in 
113108:   ** expr.c is trying to resolve a reference to a transient table (i.e. one
113109:   ** created by a sub-select). In this case the return value of this 
113110:   ** function should never be used.
113111:   **
113112:   ** We return -1000000 instead of the more usual -1 simply because using
113113:   ** -1000000 as the incorrect index into db->aDb[] is much 
113114:   ** more likely to cause a segfault than -1 (of course there are assert()
113115:   ** statements too, but it never hurts to play the odds).
113116:   */
113117:   assert( sqlite3_mutex_held(db->mutex) );
113118:   if( pSchema ){
113119:     for(i=0; ALWAYS(i<db->nDb); i++){
113120:       if( db->aDb[i].pSchema==pSchema ){
113121:         break;
113122:       }
113123:     }
113124:     assert( i>=0 && i<db->nDb );
113125:   }
113126:   return i;
113127: }
113128: 
113129: /*
113130: ** Free all memory allocations in the pParse object
113131: */
113132: SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
113133:   if( pParse ){
113134:     sqlite3 *db = pParse->db;
113135:     sqlite3DbFree(db, pParse->aLabel);
113136:     sqlite3ExprListDelete(db, pParse->pConstExpr);
113137:     if( db ){
113138:       assert( db->lookaside.bDisable >= pParse->disableLookaside );
113139:       db->lookaside.bDisable -= pParse->disableLookaside;
113140:     }
113141:     pParse->disableLookaside = 0;
113142:   }
113143: }
113144: 
113145: /*
113146: ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
113147: */
113148: static int sqlite3Prepare(
113149:   sqlite3 *db,              /* Database handle. */
113150:   const char *zSql,         /* UTF-8 encoded SQL statement. */
113151:   int nBytes,               /* Length of zSql in bytes. */
113152:   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
113153:   Vdbe *pReprepare,         /* VM being reprepared */
113154:   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113155:   const char **pzTail       /* OUT: End of parsed string */
113156: ){
113157:   Parse *pParse;            /* Parsing context */
113158:   char *zErrMsg = 0;        /* Error message */
113159:   int rc = SQLITE_OK;       /* Result code */
113160:   int i;                    /* Loop counter */
113161: 
113162:   /* Allocate the parsing context */
113163:   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
113164:   if( pParse==0 ){
113165:     rc = SQLITE_NOMEM_BKPT;
113166:     goto end_prepare;
113167:   }
113168:   pParse->pReprepare = pReprepare;
113169:   assert( ppStmt && *ppStmt==0 );
113170:   /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
113171:   assert( sqlite3_mutex_held(db->mutex) );
113172: 
113173:   /* Check to verify that it is possible to get a read lock on all
113174:   ** database schemas.  The inability to get a read lock indicates that
113175:   ** some other database connection is holding a write-lock, which in
113176:   ** turn means that the other connection has made uncommitted changes
113177:   ** to the schema.
113178:   **
113179:   ** Were we to proceed and prepare the statement against the uncommitted
113180:   ** schema changes and if those schema changes are subsequently rolled
113181:   ** back and different changes are made in their place, then when this
113182:   ** prepared statement goes to run the schema cookie would fail to detect
113183:   ** the schema change.  Disaster would follow.
113184:   **
113185:   ** This thread is currently holding mutexes on all Btrees (because
113186:   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
113187:   ** is not possible for another thread to start a new schema change
113188:   ** while this routine is running.  Hence, we do not need to hold 
113189:   ** locks on the schema, we just need to make sure nobody else is 
113190:   ** holding them.
113191:   **
113192:   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
113193:   ** but it does *not* override schema lock detection, so this all still
113194:   ** works even if READ_UNCOMMITTED is set.
113195:   */
113196:   for(i=0; i<db->nDb; i++) {
113197:     Btree *pBt = db->aDb[i].pBt;
113198:     if( pBt ){
113199:       assert( sqlite3BtreeHoldsMutex(pBt) );
113200:       rc = sqlite3BtreeSchemaLocked(pBt);
113201:       if( rc ){
113202:         const char *zDb = db->aDb[i].zName;
113203:         sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
113204:         testcase( db->flags & SQLITE_ReadUncommitted );
113205:         goto end_prepare;
113206:       }
113207:     }
113208:   }
113209: 
113210:   sqlite3VtabUnlockList(db);
113211: 
113212:   pParse->db = db;
113213:   pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
113214:   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
113215:     char *zSqlCopy;
113216:     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
113217:     testcase( nBytes==mxLen );
113218:     testcase( nBytes==mxLen+1 );
113219:     if( nBytes>mxLen ){
113220:       sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
113221:       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
113222:       goto end_prepare;
113223:     }
113224:     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
113225:     if( zSqlCopy ){
113226:       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
113227:       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
113228:       sqlite3DbFree(db, zSqlCopy);
113229:     }else{
113230:       pParse->zTail = &zSql[nBytes];
113231:     }
113232:   }else{
113233:     sqlite3RunParser(pParse, zSql, &zErrMsg);
113234:   }
113235:   assert( 0==pParse->nQueryLoop );
113236: 
113237:   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
113238:   if( pParse->checkSchema ){
113239:     schemaIsValid(pParse);
113240:   }
113241:   if( db->mallocFailed ){
113242:     pParse->rc = SQLITE_NOMEM_BKPT;
113243:   }
113244:   if( pzTail ){
113245:     *pzTail = pParse->zTail;
113246:   }
113247:   rc = pParse->rc;
113248: 
113249: #ifndef SQLITE_OMIT_EXPLAIN
113250:   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
113251:     static const char * const azColName[] = {
113252:        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
113253:        "selectid", "order", "from", "detail"
113254:     };
113255:     int iFirst, mx;
113256:     if( pParse->explain==2 ){
113257:       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
113258:       iFirst = 8;
113259:       mx = 12;
113260:     }else{
113261:       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
113262:       iFirst = 0;
113263:       mx = 8;
113264:     }
113265:     for(i=iFirst; i<mx; i++){
113266:       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
113267:                             azColName[i], SQLITE_STATIC);
113268:     }
113269:   }
113270: #endif
113271: 
113272:   if( db->init.busy==0 ){
113273:     Vdbe *pVdbe = pParse->pVdbe;
113274:     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
113275:   }
113276:   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
113277:     sqlite3VdbeFinalize(pParse->pVdbe);
113278:     assert(!(*ppStmt));
113279:   }else{
113280:     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
113281:   }
113282: 
113283:   if( zErrMsg ){
113284:     sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
113285:     sqlite3DbFree(db, zErrMsg);
113286:   }else{
113287:     sqlite3Error(db, rc);
113288:   }
113289: 
113290:   /* Delete any TriggerPrg structures allocated while parsing this statement. */
113291:   while( pParse->pTriggerPrg ){
113292:     TriggerPrg *pT = pParse->pTriggerPrg;
113293:     pParse->pTriggerPrg = pT->pNext;
113294:     sqlite3DbFree(db, pT);
113295:   }
113296: 
113297: end_prepare:
113298: 
113299:   sqlite3ParserReset(pParse);
113300:   sqlite3StackFree(db, pParse);
113301:   rc = sqlite3ApiExit(db, rc);
113302:   assert( (rc&db->errMask)==rc );
113303:   return rc;
113304: }
113305: static int sqlite3LockAndPrepare(
113306:   sqlite3 *db,              /* Database handle. */
113307:   const char *zSql,         /* UTF-8 encoded SQL statement. */
113308:   int nBytes,               /* Length of zSql in bytes. */
113309:   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
113310:   Vdbe *pOld,               /* VM being reprepared */
113311:   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113312:   const char **pzTail       /* OUT: End of parsed string */
113313: ){
113314:   int rc;
113315: 
113316: #ifdef SQLITE_ENABLE_API_ARMOR
113317:   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
113318: #endif
113319:   *ppStmt = 0;
113320:   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
113321:     return SQLITE_MISUSE_BKPT;
113322:   }
113323:   sqlite3_mutex_enter(db->mutex);
113324:   sqlite3BtreeEnterAll(db);
113325:   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
113326:   if( rc==SQLITE_SCHEMA ){
113327:     sqlite3_finalize(*ppStmt);
113328:     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
113329:   }
113330:   sqlite3BtreeLeaveAll(db);
113331:   sqlite3_mutex_leave(db->mutex);
113332:   assert( rc==SQLITE_OK || *ppStmt==0 );
113333:   return rc;
113334: }
113335: 
113336: /*
113337: ** Rerun the compilation of a statement after a schema change.
113338: **
113339: ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
113340: ** if the statement cannot be recompiled because another connection has
113341: ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
113342: ** occurs, return SQLITE_SCHEMA.
113343: */
113344: SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
113345:   int rc;
113346:   sqlite3_stmt *pNew;
113347:   const char *zSql;
113348:   sqlite3 *db;
113349: 
113350:   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
113351:   zSql = sqlite3_sql((sqlite3_stmt *)p);
113352:   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
113353:   db = sqlite3VdbeDb(p);
113354:   assert( sqlite3_mutex_held(db->mutex) );
113355:   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
113356:   if( rc ){
113357:     if( rc==SQLITE_NOMEM ){
113358:       sqlite3OomFault(db);
113359:     }
113360:     assert( pNew==0 );
113361:     return rc;
113362:   }else{
113363:     assert( pNew!=0 );
113364:   }
113365:   sqlite3VdbeSwap((Vdbe*)pNew, p);
113366:   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
113367:   sqlite3VdbeResetStepResult((Vdbe*)pNew);
113368:   sqlite3VdbeFinalize((Vdbe*)pNew);
113369:   return SQLITE_OK;
113370: }
113371: 
113372: 
113373: /*
113374: ** Two versions of the official API.  Legacy and new use.  In the legacy
113375: ** version, the original SQL text is not saved in the prepared statement
113376: ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
113377: ** sqlite3_step().  In the new version, the original SQL text is retained
113378: ** and the statement is automatically recompiled if an schema change
113379: ** occurs.
113380: */
113381: SQLITE_API int sqlite3_prepare(
113382:   sqlite3 *db,              /* Database handle. */
113383:   const char *zSql,         /* UTF-8 encoded SQL statement. */
113384:   int nBytes,               /* Length of zSql in bytes. */
113385:   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113386:   const char **pzTail       /* OUT: End of parsed string */
113387: ){
113388:   int rc;
113389:   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
113390:   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113391:   return rc;
113392: }
113393: SQLITE_API int sqlite3_prepare_v2(
113394:   sqlite3 *db,              /* Database handle. */
113395:   const char *zSql,         /* UTF-8 encoded SQL statement. */
113396:   int nBytes,               /* Length of zSql in bytes. */
113397:   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113398:   const char **pzTail       /* OUT: End of parsed string */
113399: ){
113400:   int rc;
113401:   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
113402:   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113403:   return rc;
113404: }
113405: 
113406: 
113407: #ifndef SQLITE_OMIT_UTF16
113408: /*
113409: ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
113410: */
113411: static int sqlite3Prepare16(
113412:   sqlite3 *db,              /* Database handle. */ 
113413:   const void *zSql,         /* UTF-16 encoded SQL statement. */
113414:   int nBytes,               /* Length of zSql in bytes. */
113415:   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
113416:   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113417:   const void **pzTail       /* OUT: End of parsed string */
113418: ){
113419:   /* This function currently works by first transforming the UTF-16
113420:   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
113421:   ** tricky bit is figuring out the pointer to return in *pzTail.
113422:   */
113423:   char *zSql8;
113424:   const char *zTail8 = 0;
113425:   int rc = SQLITE_OK;
113426: 
113427: #ifdef SQLITE_ENABLE_API_ARMOR
113428:   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
113429: #endif
113430:   *ppStmt = 0;
113431:   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
113432:     return SQLITE_MISUSE_BKPT;
113433:   }
113434:   if( nBytes>=0 ){
113435:     int sz;
113436:     const char *z = (const char*)zSql;
113437:     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
113438:     nBytes = sz;
113439:   }
113440:   sqlite3_mutex_enter(db->mutex);
113441:   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
113442:   if( zSql8 ){
113443:     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
113444:   }
113445: 
113446:   if( zTail8 && pzTail ){
113447:     /* If sqlite3_prepare returns a tail pointer, we calculate the
113448:     ** equivalent pointer into the UTF-16 string by counting the unicode
113449:     ** characters between zSql8 and zTail8, and then returning a pointer
113450:     ** the same number of characters into the UTF-16 string.
113451:     */
113452:     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
113453:     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
113454:   }
113455:   sqlite3DbFree(db, zSql8); 
113456:   rc = sqlite3ApiExit(db, rc);
113457:   sqlite3_mutex_leave(db->mutex);
113458:   return rc;
113459: }
113460: 
113461: /*
113462: ** Two versions of the official API.  Legacy and new use.  In the legacy
113463: ** version, the original SQL text is not saved in the prepared statement
113464: ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
113465: ** sqlite3_step().  In the new version, the original SQL text is retained
113466: ** and the statement is automatically recompiled if an schema change
113467: ** occurs.
113468: */
113469: SQLITE_API int sqlite3_prepare16(
113470:   sqlite3 *db,              /* Database handle. */ 
113471:   const void *zSql,         /* UTF-16 encoded SQL statement. */
113472:   int nBytes,               /* Length of zSql in bytes. */
113473:   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113474:   const void **pzTail       /* OUT: End of parsed string */
113475: ){
113476:   int rc;
113477:   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
113478:   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113479:   return rc;
113480: }
113481: SQLITE_API int sqlite3_prepare16_v2(
113482:   sqlite3 *db,              /* Database handle. */ 
113483:   const void *zSql,         /* UTF-16 encoded SQL statement. */
113484:   int nBytes,               /* Length of zSql in bytes. */
113485:   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
113486:   const void **pzTail       /* OUT: End of parsed string */
113487: ){
113488:   int rc;
113489:   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
113490:   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
113491:   return rc;
113492: }
113493: 
113494: #endif /* SQLITE_OMIT_UTF16 */
113495: 
113496: /************** End of prepare.c *********************************************/
113497: /************** Begin file select.c ******************************************/
113498: /*
113499: ** 2001 September 15
113500: **
113501: ** The author disclaims copyright to this source code.  In place of
113502: ** a legal notice, here is a blessing:
113503: **
113504: **    May you do good and not evil.
113505: **    May you find forgiveness for yourself and forgive others.
113506: **    May you share freely, never taking more than you give.
113507: **
113508: *************************************************************************
113509: ** This file contains C code routines that are called by the parser
113510: ** to handle SELECT statements in SQLite.
113511: */
113512: /* #include "sqliteInt.h" */
113513: 
113514: /*
113515: ** Trace output macros
113516: */
113517: #if SELECTTRACE_ENABLED
113518: /***/ int sqlite3SelectTrace = 0;
113519: # define SELECTTRACE(K,P,S,X)  \
113520:   if(sqlite3SelectTrace&(K))   \
113521:     sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
113522:         (S)->zSelName,(S)),\
113523:     sqlite3DebugPrintf X
113524: #else
113525: # define SELECTTRACE(K,P,S,X)
113526: #endif
113527: 
113528: 
113529: /*
113530: ** An instance of the following object is used to record information about
113531: ** how to process the DISTINCT keyword, to simplify passing that information
113532: ** into the selectInnerLoop() routine.
113533: */
113534: typedef struct DistinctCtx DistinctCtx;
113535: struct DistinctCtx {
113536:   u8 isTnct;      /* True if the DISTINCT keyword is present */
113537:   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
113538:   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
113539:   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
113540: };
113541: 
113542: /*
113543: ** An instance of the following object is used to record information about
113544: ** the ORDER BY (or GROUP BY) clause of query is being coded.
113545: */
113546: typedef struct SortCtx SortCtx;
113547: struct SortCtx {
113548:   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
113549:   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
113550:   int iECursor;         /* Cursor number for the sorter */
113551:   int regReturn;        /* Register holding block-output return address */
113552:   int labelBkOut;       /* Start label for the block-output subroutine */
113553:   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
113554:   int labelDone;        /* Jump here when done, ex: LIMIT reached */
113555:   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
113556:   u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
113557: };
113558: #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
113559: 
113560: /*
113561: ** Delete all the content of a Select structure.  Deallocate the structure
113562: ** itself only if bFree is true.
113563: */
113564: static void clearSelect(sqlite3 *db, Select *p, int bFree){
113565:   while( p ){
113566:     Select *pPrior = p->pPrior;
113567:     sqlite3ExprListDelete(db, p->pEList);
113568:     sqlite3SrcListDelete(db, p->pSrc);
113569:     sqlite3ExprDelete(db, p->pWhere);
113570:     sqlite3ExprListDelete(db, p->pGroupBy);
113571:     sqlite3ExprDelete(db, p->pHaving);
113572:     sqlite3ExprListDelete(db, p->pOrderBy);
113573:     sqlite3ExprDelete(db, p->pLimit);
113574:     sqlite3ExprDelete(db, p->pOffset);
113575:     if( p->pWith ) sqlite3WithDelete(db, p->pWith);
113576:     if( bFree ) sqlite3DbFree(db, p);
113577:     p = pPrior;
113578:     bFree = 1;
113579:   }
113580: }
113581: 
113582: /*
113583: ** Initialize a SelectDest structure.
113584: */
113585: SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
113586:   pDest->eDest = (u8)eDest;
113587:   pDest->iSDParm = iParm;
113588:   pDest->affSdst = 0;
113589:   pDest->iSdst = 0;
113590:   pDest->nSdst = 0;
113591: }
113592: 
113593: 
113594: /*
113595: ** Allocate a new Select structure and return a pointer to that
113596: ** structure.
113597: */
113598: SQLITE_PRIVATE Select *sqlite3SelectNew(
113599:   Parse *pParse,        /* Parsing context */
113600:   ExprList *pEList,     /* which columns to include in the result */
113601:   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
113602:   Expr *pWhere,         /* the WHERE clause */
113603:   ExprList *pGroupBy,   /* the GROUP BY clause */
113604:   Expr *pHaving,        /* the HAVING clause */
113605:   ExprList *pOrderBy,   /* the ORDER BY clause */
113606:   u32 selFlags,         /* Flag parameters, such as SF_Distinct */
113607:   Expr *pLimit,         /* LIMIT value.  NULL means not used */
113608:   Expr *pOffset         /* OFFSET value.  NULL means no offset */
113609: ){
113610:   Select *pNew;
113611:   Select standin;
113612:   sqlite3 *db = pParse->db;
113613:   pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
113614:   if( pNew==0 ){
113615:     assert( db->mallocFailed );
113616:     pNew = &standin;
113617:   }
113618:   if( pEList==0 ){
113619:     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
113620:   }
113621:   pNew->pEList = pEList;
113622:   pNew->op = TK_SELECT;
113623:   pNew->selFlags = selFlags;
113624:   pNew->iLimit = 0;
113625:   pNew->iOffset = 0;
113626: #if SELECTTRACE_ENABLED
113627:   pNew->zSelName[0] = 0;
113628: #endif
113629:   pNew->addrOpenEphm[0] = -1;
113630:   pNew->addrOpenEphm[1] = -1;
113631:   pNew->nSelectRow = 0;
113632:   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
113633:   pNew->pSrc = pSrc;
113634:   pNew->pWhere = pWhere;
113635:   pNew->pGroupBy = pGroupBy;
113636:   pNew->pHaving = pHaving;
113637:   pNew->pOrderBy = pOrderBy;
113638:   pNew->pPrior = 0;
113639:   pNew->pNext = 0;
113640:   pNew->pLimit = pLimit;
113641:   pNew->pOffset = pOffset;
113642:   pNew->pWith = 0;
113643:   assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
113644:   if( db->mallocFailed ) {
113645:     clearSelect(db, pNew, pNew!=&standin);
113646:     pNew = 0;
113647:   }else{
113648:     assert( pNew->pSrc!=0 || pParse->nErr>0 );
113649:   }
113650:   assert( pNew!=&standin );
113651:   return pNew;
113652: }
113653: 
113654: #if SELECTTRACE_ENABLED
113655: /*
113656: ** Set the name of a Select object
113657: */
113658: SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
113659:   if( p && zName ){
113660:     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
113661:   }
113662: }
113663: #endif
113664: 
113665: 
113666: /*
113667: ** Delete the given Select structure and all of its substructures.
113668: */
113669: SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
113670:   if( p ) clearSelect(db, p, 1);
113671: }
113672: 
113673: /*
113674: ** Return a pointer to the right-most SELECT statement in a compound.
113675: */
113676: static Select *findRightmost(Select *p){
113677:   while( p->pNext ) p = p->pNext;
113678:   return p;
113679: }
113680: 
113681: /*
113682: ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
113683: ** type of join.  Return an integer constant that expresses that type
113684: ** in terms of the following bit values:
113685: **
113686: **     JT_INNER
113687: **     JT_CROSS
113688: **     JT_OUTER
113689: **     JT_NATURAL
113690: **     JT_LEFT
113691: **     JT_RIGHT
113692: **
113693: ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
113694: **
113695: ** If an illegal or unsupported join type is seen, then still return
113696: ** a join type, but put an error in the pParse structure.
113697: */
113698: SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
113699:   int jointype = 0;
113700:   Token *apAll[3];
113701:   Token *p;
113702:                              /*   0123456789 123456789 123456789 123 */
113703:   static const char zKeyText[] = "naturaleftouterightfullinnercross";
113704:   static const struct {
113705:     u8 i;        /* Beginning of keyword text in zKeyText[] */
113706:     u8 nChar;    /* Length of the keyword in characters */
113707:     u8 code;     /* Join type mask */
113708:   } aKeyword[] = {
113709:     /* natural */ { 0,  7, JT_NATURAL                },
113710:     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
113711:     /* outer   */ { 10, 5, JT_OUTER                  },
113712:     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
113713:     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
113714:     /* inner   */ { 23, 5, JT_INNER                  },
113715:     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
113716:   };
113717:   int i, j;
113718:   apAll[0] = pA;
113719:   apAll[1] = pB;
113720:   apAll[2] = pC;
113721:   for(i=0; i<3 && apAll[i]; i++){
113722:     p = apAll[i];
113723:     for(j=0; j<ArraySize(aKeyword); j++){
113724:       if( p->n==aKeyword[j].nChar 
113725:           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
113726:         jointype |= aKeyword[j].code;
113727:         break;
113728:       }
113729:     }
113730:     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
113731:     if( j>=ArraySize(aKeyword) ){
113732:       jointype |= JT_ERROR;
113733:       break;
113734:     }
113735:   }
113736:   if(
113737:      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
113738:      (jointype & JT_ERROR)!=0
113739:   ){
113740:     const char *zSp = " ";
113741:     assert( pB!=0 );
113742:     if( pC==0 ){ zSp++; }
113743:     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
113744:        "%T %T%s%T", pA, pB, zSp, pC);
113745:     jointype = JT_INNER;
113746:   }else if( (jointype & JT_OUTER)!=0 
113747:          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
113748:     sqlite3ErrorMsg(pParse, 
113749:       "RIGHT and FULL OUTER JOINs are not currently supported");
113750:     jointype = JT_INNER;
113751:   }
113752:   return jointype;
113753: }
113754: 
113755: /*
113756: ** Return the index of a column in a table.  Return -1 if the column
113757: ** is not contained in the table.
113758: */
113759: static int columnIndex(Table *pTab, const char *zCol){
113760:   int i;
113761:   for(i=0; i<pTab->nCol; i++){
113762:     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
113763:   }
113764:   return -1;
113765: }
113766: 
113767: /*
113768: ** Search the first N tables in pSrc, from left to right, looking for a
113769: ** table that has a column named zCol.  
113770: **
113771: ** When found, set *piTab and *piCol to the table index and column index
113772: ** of the matching column and return TRUE.
113773: **
113774: ** If not found, return FALSE.
113775: */
113776: static int tableAndColumnIndex(
113777:   SrcList *pSrc,       /* Array of tables to search */
113778:   int N,               /* Number of tables in pSrc->a[] to search */
113779:   const char *zCol,    /* Name of the column we are looking for */
113780:   int *piTab,          /* Write index of pSrc->a[] here */
113781:   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
113782: ){
113783:   int i;               /* For looping over tables in pSrc */
113784:   int iCol;            /* Index of column matching zCol */
113785: 
113786:   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
113787:   for(i=0; i<N; i++){
113788:     iCol = columnIndex(pSrc->a[i].pTab, zCol);
113789:     if( iCol>=0 ){
113790:       if( piTab ){
113791:         *piTab = i;
113792:         *piCol = iCol;
113793:       }
113794:       return 1;
113795:     }
113796:   }
113797:   return 0;
113798: }
113799: 
113800: /*
113801: ** This function is used to add terms implied by JOIN syntax to the
113802: ** WHERE clause expression of a SELECT statement. The new term, which
113803: ** is ANDed with the existing WHERE clause, is of the form:
113804: **
113805: **    (tab1.col1 = tab2.col2)
113806: **
113807: ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
113808: ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
113809: ** column iColRight of tab2.
113810: */
113811: static void addWhereTerm(
113812:   Parse *pParse,                  /* Parsing context */
113813:   SrcList *pSrc,                  /* List of tables in FROM clause */
113814:   int iLeft,                      /* Index of first table to join in pSrc */
113815:   int iColLeft,                   /* Index of column in first table */
113816:   int iRight,                     /* Index of second table in pSrc */
113817:   int iColRight,                  /* Index of column in second table */
113818:   int isOuterJoin,                /* True if this is an OUTER join */
113819:   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
113820: ){
113821:   sqlite3 *db = pParse->db;
113822:   Expr *pE1;
113823:   Expr *pE2;
113824:   Expr *pEq;
113825: 
113826:   assert( iLeft<iRight );
113827:   assert( pSrc->nSrc>iRight );
113828:   assert( pSrc->a[iLeft].pTab );
113829:   assert( pSrc->a[iRight].pTab );
113830: 
113831:   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
113832:   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
113833: 
113834:   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
113835:   if( pEq && isOuterJoin ){
113836:     ExprSetProperty(pEq, EP_FromJoin);
113837:     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
113838:     ExprSetVVAProperty(pEq, EP_NoReduce);
113839:     pEq->iRightJoinTable = (i16)pE2->iTable;
113840:   }
113841:   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
113842: }
113843: 
113844: /*
113845: ** Set the EP_FromJoin property on all terms of the given expression.
113846: ** And set the Expr.iRightJoinTable to iTable for every term in the
113847: ** expression.
113848: **
113849: ** The EP_FromJoin property is used on terms of an expression to tell
113850: ** the LEFT OUTER JOIN processing logic that this term is part of the
113851: ** join restriction specified in the ON or USING clause and not a part
113852: ** of the more general WHERE clause.  These terms are moved over to the
113853: ** WHERE clause during join processing but we need to remember that they
113854: ** originated in the ON or USING clause.
113855: **
113856: ** The Expr.iRightJoinTable tells the WHERE clause processing that the
113857: ** expression depends on table iRightJoinTable even if that table is not
113858: ** explicitly mentioned in the expression.  That information is needed
113859: ** for cases like this:
113860: **
113861: **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
113862: **
113863: ** The where clause needs to defer the handling of the t1.x=5
113864: ** term until after the t2 loop of the join.  In that way, a
113865: ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
113866: ** defer the handling of t1.x=5, it will be processed immediately
113867: ** after the t1 loop and rows with t1.x!=5 will never appear in
113868: ** the output, which is incorrect.
113869: */
113870: static void setJoinExpr(Expr *p, int iTable){
113871:   while( p ){
113872:     ExprSetProperty(p, EP_FromJoin);
113873:     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
113874:     ExprSetVVAProperty(p, EP_NoReduce);
113875:     p->iRightJoinTable = (i16)iTable;
113876:     if( p->op==TK_FUNCTION && p->x.pList ){
113877:       int i;
113878:       for(i=0; i<p->x.pList->nExpr; i++){
113879:         setJoinExpr(p->x.pList->a[i].pExpr, iTable);
113880:       }
113881:     }
113882:     setJoinExpr(p->pLeft, iTable);
113883:     p = p->pRight;
113884:   } 
113885: }
113886: 
113887: /*
113888: ** This routine processes the join information for a SELECT statement.
113889: ** ON and USING clauses are converted into extra terms of the WHERE clause.
113890: ** NATURAL joins also create extra WHERE clause terms.
113891: **
113892: ** The terms of a FROM clause are contained in the Select.pSrc structure.
113893: ** The left most table is the first entry in Select.pSrc.  The right-most
113894: ** table is the last entry.  The join operator is held in the entry to
113895: ** the left.  Thus entry 0 contains the join operator for the join between
113896: ** entries 0 and 1.  Any ON or USING clauses associated with the join are
113897: ** also attached to the left entry.
113898: **
113899: ** This routine returns the number of errors encountered.
113900: */
113901: static int sqliteProcessJoin(Parse *pParse, Select *p){
113902:   SrcList *pSrc;                  /* All tables in the FROM clause */
113903:   int i, j;                       /* Loop counters */
113904:   struct SrcList_item *pLeft;     /* Left table being joined */
113905:   struct SrcList_item *pRight;    /* Right table being joined */
113906: 
113907:   pSrc = p->pSrc;
113908:   pLeft = &pSrc->a[0];
113909:   pRight = &pLeft[1];
113910:   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
113911:     Table *pLeftTab = pLeft->pTab;
113912:     Table *pRightTab = pRight->pTab;
113913:     int isOuter;
113914: 
113915:     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
113916:     isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
113917: 
113918:     /* When the NATURAL keyword is present, add WHERE clause terms for
113919:     ** every column that the two tables have in common.
113920:     */
113921:     if( pRight->fg.jointype & JT_NATURAL ){
113922:       if( pRight->pOn || pRight->pUsing ){
113923:         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
113924:            "an ON or USING clause", 0);
113925:         return 1;
113926:       }
113927:       for(j=0; j<pRightTab->nCol; j++){
113928:         char *zName;   /* Name of column in the right table */
113929:         int iLeft;     /* Matching left table */
113930:         int iLeftCol;  /* Matching column in the left table */
113931: 
113932:         zName = pRightTab->aCol[j].zName;
113933:         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
113934:           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
113935:                        isOuter, &p->pWhere);
113936:         }
113937:       }
113938:     }
113939: 
113940:     /* Disallow both ON and USING clauses in the same join
113941:     */
113942:     if( pRight->pOn && pRight->pUsing ){
113943:       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
113944:         "clauses in the same join");
113945:       return 1;
113946:     }
113947: 
113948:     /* Add the ON clause to the end of the WHERE clause, connected by
113949:     ** an AND operator.
113950:     */
113951:     if( pRight->pOn ){
113952:       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
113953:       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
113954:       pRight->pOn = 0;
113955:     }
113956: 
113957:     /* Create extra terms on the WHERE clause for each column named
113958:     ** in the USING clause.  Example: If the two tables to be joined are 
113959:     ** A and B and the USING clause names X, Y, and Z, then add this
113960:     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
113961:     ** Report an error if any column mentioned in the USING clause is
113962:     ** not contained in both tables to be joined.
113963:     */
113964:     if( pRight->pUsing ){
113965:       IdList *pList = pRight->pUsing;
113966:       for(j=0; j<pList->nId; j++){
113967:         char *zName;     /* Name of the term in the USING clause */
113968:         int iLeft;       /* Table on the left with matching column name */
113969:         int iLeftCol;    /* Column number of matching column on the left */
113970:         int iRightCol;   /* Column number of matching column on the right */
113971: 
113972:         zName = pList->a[j].zName;
113973:         iRightCol = columnIndex(pRightTab, zName);
113974:         if( iRightCol<0
113975:          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
113976:         ){
113977:           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
113978:             "not present in both tables", zName);
113979:           return 1;
113980:         }
113981:         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
113982:                      isOuter, &p->pWhere);
113983:       }
113984:     }
113985:   }
113986:   return 0;
113987: }
113988: 
113989: /* Forward reference */
113990: static KeyInfo *keyInfoFromExprList(
113991:   Parse *pParse,       /* Parsing context */
113992:   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
113993:   int iStart,          /* Begin with this column of pList */
113994:   int nExtra           /* Add this many extra columns to the end */
113995: );
113996: 
113997: /*
113998: ** Generate code that will push the record in registers regData
113999: ** through regData+nData-1 onto the sorter.
114000: */
114001: static void pushOntoSorter(
114002:   Parse *pParse,         /* Parser context */
114003:   SortCtx *pSort,        /* Information about the ORDER BY clause */
114004:   Select *pSelect,       /* The whole SELECT statement */
114005:   int regData,           /* First register holding data to be sorted */
114006:   int regOrigData,       /* First register holding data before packing */
114007:   int nData,             /* Number of elements in the data array */
114008:   int nPrefixReg         /* No. of reg prior to regData available for use */
114009: ){
114010:   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
114011:   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
114012:   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
114013:   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
114014:   int regBase;                                     /* Regs for sorter record */
114015:   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
114016:   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
114017:   int op;                            /* Opcode to add sorter record to sorter */
114018:   int iLimit;                        /* LIMIT counter */
114019: 
114020:   assert( bSeq==0 || bSeq==1 );
114021:   assert( nData==1 || regData==regOrigData );
114022:   if( nPrefixReg ){
114023:     assert( nPrefixReg==nExpr+bSeq );
114024:     regBase = regData - nExpr - bSeq;
114025:   }else{
114026:     regBase = pParse->nMem + 1;
114027:     pParse->nMem += nBase;
114028:   }
114029:   assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
114030:   iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
114031:   pSort->labelDone = sqlite3VdbeMakeLabel(v);
114032:   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
114033:                           SQLITE_ECEL_DUP|SQLITE_ECEL_REF);
114034:   if( bSeq ){
114035:     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
114036:   }
114037:   if( nPrefixReg==0 ){
114038:     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
114039:   }
114040:   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
114041:   if( nOBSat>0 ){
114042:     int regPrevKey;   /* The first nOBSat columns of the previous row */
114043:     int addrFirst;    /* Address of the OP_IfNot opcode */
114044:     int addrJmp;      /* Address of the OP_Jump opcode */
114045:     VdbeOp *pOp;      /* Opcode that opens the sorter */
114046:     int nKey;         /* Number of sorting key columns, including OP_Sequence */
114047:     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
114048: 
114049:     regPrevKey = pParse->nMem+1;
114050:     pParse->nMem += pSort->nOBSat;
114051:     nKey = nExpr - pSort->nOBSat + bSeq;
114052:     if( bSeq ){
114053:       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 
114054:     }else{
114055:       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
114056:     }
114057:     VdbeCoverage(v);
114058:     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
114059:     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
114060:     if( pParse->db->mallocFailed ) return;
114061:     pOp->p2 = nKey + nData;
114062:     pKI = pOp->p4.pKeyInfo;
114063:     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
114064:     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
114065:     testcase( pKI->nXField>2 );
114066:     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
114067:                                            pKI->nXField-1);
114068:     addrJmp = sqlite3VdbeCurrentAddr(v);
114069:     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
114070:     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
114071:     pSort->regReturn = ++pParse->nMem;
114072:     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114073:     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
114074:     if( iLimit ){
114075:       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
114076:       VdbeCoverage(v);
114077:     }
114078:     sqlite3VdbeJumpHere(v, addrFirst);
114079:     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
114080:     sqlite3VdbeJumpHere(v, addrJmp);
114081:   }
114082:   if( pSort->sortFlags & SORTFLAG_UseSorter ){
114083:     op = OP_SorterInsert;
114084:   }else{
114085:     op = OP_IdxInsert;
114086:   }
114087:   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
114088:   if( iLimit ){
114089:     int addr;
114090:     int r1 = 0;
114091:     /* Fill the sorter until it contains LIMIT+OFFSET entries.  (The iLimit
114092:     ** register is initialized with value of LIMIT+OFFSET.)  After the sorter
114093:     ** fills up, delete the least entry in the sorter after each insert.
114094:     ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
114095:     addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
114096:     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
114097:     if( pSort->bOrderedInnerLoop ){
114098:       r1 = ++pParse->nMem;
114099:       sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
114100:       VdbeComment((v, "seq"));
114101:     }
114102:     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
114103:     if( pSort->bOrderedInnerLoop ){
114104:       /* If the inner loop is driven by an index such that values from
114105:       ** the same iteration of the inner loop are in sorted order, then
114106:       ** immediately jump to the next iteration of an inner loop if the
114107:       ** entry from the current iteration does not fit into the top
114108:       ** LIMIT+OFFSET entries of the sorter. */
114109:       int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
114110:       sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
114111:       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
114112:       VdbeCoverage(v);
114113:     }
114114:     sqlite3VdbeJumpHere(v, addr);
114115:   }
114116: }
114117: 
114118: /*
114119: ** Add code to implement the OFFSET
114120: */
114121: static void codeOffset(
114122:   Vdbe *v,          /* Generate code into this VM */
114123:   int iOffset,      /* Register holding the offset counter */
114124:   int iContinue     /* Jump here to skip the current record */
114125: ){
114126:   if( iOffset>0 ){
114127:     sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
114128:     VdbeComment((v, "OFFSET"));
114129:   }
114130: }
114131: 
114132: /*
114133: ** Add code that will check to make sure the N registers starting at iMem
114134: ** form a distinct entry.  iTab is a sorting index that holds previously
114135: ** seen combinations of the N values.  A new entry is made in iTab
114136: ** if the current N values are new.
114137: **
114138: ** A jump to addrRepeat is made and the N+1 values are popped from the
114139: ** stack if the top N elements are not distinct.
114140: */
114141: static void codeDistinct(
114142:   Parse *pParse,     /* Parsing and code generating context */
114143:   int iTab,          /* A sorting index used to test for distinctness */
114144:   int addrRepeat,    /* Jump to here if not distinct */
114145:   int N,             /* Number of elements */
114146:   int iMem           /* First element */
114147: ){
114148:   Vdbe *v;
114149:   int r1;
114150: 
114151:   v = pParse->pVdbe;
114152:   r1 = sqlite3GetTempReg(pParse);
114153:   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
114154:   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
114155:   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
114156:   sqlite3ReleaseTempReg(pParse, r1);
114157: }
114158: 
114159: #ifndef SQLITE_OMIT_SUBQUERY
114160: /*
114161: ** Generate an error message when a SELECT is used within a subexpression
114162: ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
114163: ** column.  We do this in a subroutine because the error used to occur
114164: ** in multiple places.  (The error only occurs in one place now, but we
114165: ** retain the subroutine to minimize code disruption.)
114166: */
114167: static int checkForMultiColumnSelectError(
114168:   Parse *pParse,       /* Parse context. */
114169:   SelectDest *pDest,   /* Destination of SELECT results */
114170:   int nExpr            /* Number of result columns returned by SELECT */
114171: ){
114172:   int eDest = pDest->eDest;
114173:   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
114174:     sqlite3ErrorMsg(pParse, "only a single result allowed for "
114175:        "a SELECT that is part of an expression");
114176:     return 1;
114177:   }else{
114178:     return 0;
114179:   }
114180: }
114181: #endif
114182: 
114183: /*
114184: ** This routine generates the code for the inside of the inner loop
114185: ** of a SELECT.
114186: **
114187: ** If srcTab is negative, then the pEList expressions
114188: ** are evaluated in order to get the data for this row.  If srcTab is
114189: ** zero or more, then data is pulled from srcTab and pEList is used only 
114190: ** to get number columns and the datatype for each column.
114191: */
114192: static void selectInnerLoop(
114193:   Parse *pParse,          /* The parser context */
114194:   Select *p,              /* The complete select statement being coded */
114195:   ExprList *pEList,       /* List of values being extracted */
114196:   int srcTab,             /* Pull data from this table */
114197:   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
114198:   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
114199:   SelectDest *pDest,      /* How to dispose of the results */
114200:   int iContinue,          /* Jump here to continue with next row */
114201:   int iBreak              /* Jump here to break out of the inner loop */
114202: ){
114203:   Vdbe *v = pParse->pVdbe;
114204:   int i;
114205:   int hasDistinct;        /* True if the DISTINCT keyword is present */
114206:   int regResult;              /* Start of memory holding result set */
114207:   int eDest = pDest->eDest;   /* How to dispose of results */
114208:   int iParm = pDest->iSDParm; /* First argument to disposal method */
114209:   int nResultCol;             /* Number of result columns */
114210:   int nPrefixReg = 0;         /* Number of extra registers before regResult */
114211: 
114212:   assert( v );
114213:   assert( pEList!=0 );
114214:   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
114215:   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
114216:   if( pSort==0 && !hasDistinct ){
114217:     assert( iContinue!=0 );
114218:     codeOffset(v, p->iOffset, iContinue);
114219:   }
114220: 
114221:   /* Pull the requested columns.
114222:   */
114223:   nResultCol = pEList->nExpr;
114224: 
114225:   if( pDest->iSdst==0 ){
114226:     if( pSort ){
114227:       nPrefixReg = pSort->pOrderBy->nExpr;
114228:       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
114229:       pParse->nMem += nPrefixReg;
114230:     }
114231:     pDest->iSdst = pParse->nMem+1;
114232:     pParse->nMem += nResultCol;
114233:   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
114234:     /* This is an error condition that can result, for example, when a SELECT
114235:     ** on the right-hand side of an INSERT contains more result columns than
114236:     ** there are columns in the table on the left.  The error will be caught
114237:     ** and reported later.  But we need to make sure enough memory is allocated
114238:     ** to avoid other spurious errors in the meantime. */
114239:     pParse->nMem += nResultCol;
114240:   }
114241:   pDest->nSdst = nResultCol;
114242:   regResult = pDest->iSdst;
114243:   if( srcTab>=0 ){
114244:     for(i=0; i<nResultCol; i++){
114245:       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
114246:       VdbeComment((v, "%s", pEList->a[i].zName));
114247:     }
114248:   }else if( eDest!=SRT_Exists ){
114249:     /* If the destination is an EXISTS(...) expression, the actual
114250:     ** values returned by the SELECT are not required.
114251:     */
114252:     u8 ecelFlags;
114253:     if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
114254:       ecelFlags = SQLITE_ECEL_DUP;
114255:     }else{
114256:       ecelFlags = 0;
114257:     }
114258:     sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
114259:   }
114260: 
114261:   /* If the DISTINCT keyword was present on the SELECT statement
114262:   ** and this row has been seen before, then do not make this row
114263:   ** part of the result.
114264:   */
114265:   if( hasDistinct ){
114266:     switch( pDistinct->eTnctType ){
114267:       case WHERE_DISTINCT_ORDERED: {
114268:         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
114269:         int iJump;              /* Jump destination */
114270:         int regPrev;            /* Previous row content */
114271: 
114272:         /* Allocate space for the previous row */
114273:         regPrev = pParse->nMem+1;
114274:         pParse->nMem += nResultCol;
114275: 
114276:         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
114277:         ** sets the MEM_Cleared bit on the first register of the
114278:         ** previous value.  This will cause the OP_Ne below to always
114279:         ** fail on the first iteration of the loop even if the first
114280:         ** row is all NULLs.
114281:         */
114282:         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
114283:         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
114284:         pOp->opcode = OP_Null;
114285:         pOp->p1 = 1;
114286:         pOp->p2 = regPrev;
114287: 
114288:         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
114289:         for(i=0; i<nResultCol; i++){
114290:           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
114291:           if( i<nResultCol-1 ){
114292:             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
114293:             VdbeCoverage(v);
114294:           }else{
114295:             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
114296:             VdbeCoverage(v);
114297:            }
114298:           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
114299:           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
114300:         }
114301:         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
114302:         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
114303:         break;
114304:       }
114305: 
114306:       case WHERE_DISTINCT_UNIQUE: {
114307:         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
114308:         break;
114309:       }
114310: 
114311:       default: {
114312:         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
114313:         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
114314:                      regResult);
114315:         break;
114316:       }
114317:     }
114318:     if( pSort==0 ){
114319:       codeOffset(v, p->iOffset, iContinue);
114320:     }
114321:   }
114322: 
114323:   switch( eDest ){
114324:     /* In this mode, write each query result to the key of the temporary
114325:     ** table iParm.
114326:     */
114327: #ifndef SQLITE_OMIT_COMPOUND_SELECT
114328:     case SRT_Union: {
114329:       int r1;
114330:       r1 = sqlite3GetTempReg(pParse);
114331:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
114332:       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114333:       sqlite3ReleaseTempReg(pParse, r1);
114334:       break;
114335:     }
114336: 
114337:     /* Construct a record from the query result, but instead of
114338:     ** saving that record, use it as a key to delete elements from
114339:     ** the temporary table iParm.
114340:     */
114341:     case SRT_Except: {
114342:       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
114343:       break;
114344:     }
114345: #endif /* SQLITE_OMIT_COMPOUND_SELECT */
114346: 
114347:     /* Store the result as data using a unique key.
114348:     */
114349:     case SRT_Fifo:
114350:     case SRT_DistFifo:
114351:     case SRT_Table:
114352:     case SRT_EphemTab: {
114353:       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
114354:       testcase( eDest==SRT_Table );
114355:       testcase( eDest==SRT_EphemTab );
114356:       testcase( eDest==SRT_Fifo );
114357:       testcase( eDest==SRT_DistFifo );
114358:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
114359: #ifndef SQLITE_OMIT_CTE
114360:       if( eDest==SRT_DistFifo ){
114361:         /* If the destination is DistFifo, then cursor (iParm+1) is open
114362:         ** on an ephemeral index. If the current row is already present
114363:         ** in the index, do not write it to the output. If not, add the
114364:         ** current row to the index and proceed with writing it to the
114365:         ** output table as well.  */
114366:         int addr = sqlite3VdbeCurrentAddr(v) + 4;
114367:         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
114368:         VdbeCoverage(v);
114369:         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
114370:         assert( pSort==0 );
114371:       }
114372: #endif
114373:       if( pSort ){
114374:         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
114375:       }else{
114376:         int r2 = sqlite3GetTempReg(pParse);
114377:         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
114378:         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
114379:         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
114380:         sqlite3ReleaseTempReg(pParse, r2);
114381:       }
114382:       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
114383:       break;
114384:     }
114385: 
114386: #ifndef SQLITE_OMIT_SUBQUERY
114387:     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
114388:     ** then there should be a single item on the stack.  Write this
114389:     ** item into the set table with bogus data.
114390:     */
114391:     case SRT_Set: {
114392:       assert( nResultCol==1 );
114393:       pDest->affSdst =
114394:                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
114395:       if( pSort ){
114396:         /* At first glance you would think we could optimize out the
114397:         ** ORDER BY in this case since the order of entries in the set
114398:         ** does not matter.  But there might be a LIMIT clause, in which
114399:         ** case the order does matter */
114400:         pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
114401:       }else{
114402:         int r1 = sqlite3GetTempReg(pParse);
114403:         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
114404:         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
114405:         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114406:         sqlite3ReleaseTempReg(pParse, r1);
114407:       }
114408:       break;
114409:     }
114410: 
114411:     /* If any row exist in the result set, record that fact and abort.
114412:     */
114413:     case SRT_Exists: {
114414:       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
114415:       /* The LIMIT clause will terminate the loop for us */
114416:       break;
114417:     }
114418: 
114419:     /* If this is a scalar select that is part of an expression, then
114420:     ** store the results in the appropriate memory cell and break out
114421:     ** of the scan loop.
114422:     */
114423:     case SRT_Mem: {
114424:       assert( nResultCol==1 );
114425:       if( pSort ){
114426:         pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
114427:       }else{
114428:         assert( regResult==iParm );
114429:         /* The LIMIT clause will jump out of the loop for us */
114430:       }
114431:       break;
114432:     }
114433: #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
114434: 
114435:     case SRT_Coroutine:       /* Send data to a co-routine */
114436:     case SRT_Output: {        /* Return the results */
114437:       testcase( eDest==SRT_Coroutine );
114438:       testcase( eDest==SRT_Output );
114439:       if( pSort ){
114440:         pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
114441:                        nPrefixReg);
114442:       }else if( eDest==SRT_Coroutine ){
114443:         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
114444:       }else{
114445:         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
114446:         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
114447:       }
114448:       break;
114449:     }
114450: 
114451: #ifndef SQLITE_OMIT_CTE
114452:     /* Write the results into a priority queue that is order according to
114453:     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
114454:     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
114455:     ** pSO->nExpr columns, then make sure all keys are unique by adding a
114456:     ** final OP_Sequence column.  The last column is the record as a blob.
114457:     */
114458:     case SRT_DistQueue:
114459:     case SRT_Queue: {
114460:       int nKey;
114461:       int r1, r2, r3;
114462:       int addrTest = 0;
114463:       ExprList *pSO;
114464:       pSO = pDest->pOrderBy;
114465:       assert( pSO );
114466:       nKey = pSO->nExpr;
114467:       r1 = sqlite3GetTempReg(pParse);
114468:       r2 = sqlite3GetTempRange(pParse, nKey+2);
114469:       r3 = r2+nKey+1;
114470:       if( eDest==SRT_DistQueue ){
114471:         /* If the destination is DistQueue, then cursor (iParm+1) is open
114472:         ** on a second ephemeral index that holds all values every previously
114473:         ** added to the queue. */
114474:         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 
114475:                                         regResult, nResultCol);
114476:         VdbeCoverage(v);
114477:       }
114478:       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
114479:       if( eDest==SRT_DistQueue ){
114480:         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
114481:         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
114482:       }
114483:       for(i=0; i<nKey; i++){
114484:         sqlite3VdbeAddOp2(v, OP_SCopy,
114485:                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
114486:                           r2+i);
114487:       }
114488:       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
114489:       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
114490:       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
114491:       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
114492:       sqlite3ReleaseTempReg(pParse, r1);
114493:       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
114494:       break;
114495:     }
114496: #endif /* SQLITE_OMIT_CTE */
114497: 
114498: 
114499: 
114500: #if !defined(SQLITE_OMIT_TRIGGER)
114501:     /* Discard the results.  This is used for SELECT statements inside
114502:     ** the body of a TRIGGER.  The purpose of such selects is to call
114503:     ** user-defined functions that have side effects.  We do not care
114504:     ** about the actual results of the select.
114505:     */
114506:     default: {
114507:       assert( eDest==SRT_Discard );
114508:       break;
114509:     }
114510: #endif
114511:   }
114512: 
114513:   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
114514:   ** there is a sorter, in which case the sorter has already limited
114515:   ** the output for us.
114516:   */
114517:   if( pSort==0 && p->iLimit ){
114518:     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
114519:   }
114520: }
114521: 
114522: /*
114523: ** Allocate a KeyInfo object sufficient for an index of N key columns and
114524: ** X extra columns.
114525: */
114526: SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
114527:   int nExtra = (N+X)*(sizeof(CollSeq*)+1);
114528:   KeyInfo *p = sqlite3DbMallocRaw(db, sizeof(KeyInfo) + nExtra);
114529:   if( p ){
114530:     p->aSortOrder = (u8*)&p->aColl[N+X];
114531:     p->nField = (u16)N;
114532:     p->nXField = (u16)X;
114533:     p->enc = ENC(db);
114534:     p->db = db;
114535:     p->nRef = 1;
114536:     memset(&p[1], 0, nExtra);
114537:   }else{
114538:     sqlite3OomFault(db);
114539:   }
114540:   return p;
114541: }
114542: 
114543: /*
114544: ** Deallocate a KeyInfo object
114545: */
114546: SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
114547:   if( p ){
114548:     assert( p->nRef>0 );
114549:     p->nRef--;
114550:     if( p->nRef==0 ) sqlite3DbFree(p->db, p);
114551:   }
114552: }
114553: 
114554: /*
114555: ** Make a new pointer to a KeyInfo object
114556: */
114557: SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
114558:   if( p ){
114559:     assert( p->nRef>0 );
114560:     p->nRef++;
114561:   }
114562:   return p;
114563: }
114564: 
114565: #ifdef SQLITE_DEBUG
114566: /*
114567: ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
114568: ** can only be changed if this is just a single reference to the object.
114569: **
114570: ** This routine is used only inside of assert() statements.
114571: */
114572: SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
114573: #endif /* SQLITE_DEBUG */
114574: 
114575: /*
114576: ** Given an expression list, generate a KeyInfo structure that records
114577: ** the collating sequence for each expression in that expression list.
114578: **
114579: ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
114580: ** KeyInfo structure is appropriate for initializing a virtual index to
114581: ** implement that clause.  If the ExprList is the result set of a SELECT
114582: ** then the KeyInfo structure is appropriate for initializing a virtual
114583: ** index to implement a DISTINCT test.
114584: **
114585: ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
114586: ** function is responsible for seeing that this structure is eventually
114587: ** freed.
114588: */
114589: static KeyInfo *keyInfoFromExprList(
114590:   Parse *pParse,       /* Parsing context */
114591:   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
114592:   int iStart,          /* Begin with this column of pList */
114593:   int nExtra           /* Add this many extra columns to the end */
114594: ){
114595:   int nExpr;
114596:   KeyInfo *pInfo;
114597:   struct ExprList_item *pItem;
114598:   sqlite3 *db = pParse->db;
114599:   int i;
114600: 
114601:   nExpr = pList->nExpr;
114602:   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
114603:   if( pInfo ){
114604:     assert( sqlite3KeyInfoIsWriteable(pInfo) );
114605:     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
114606:       CollSeq *pColl;
114607:       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
114608:       if( !pColl ) pColl = db->pDfltColl;
114609:       pInfo->aColl[i-iStart] = pColl;
114610:       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
114611:     }
114612:   }
114613:   return pInfo;
114614: }
114615: 
114616: /*
114617: ** Name of the connection operator, used for error messages.
114618: */
114619: static const char *selectOpName(int id){
114620:   char *z;
114621:   switch( id ){
114622:     case TK_ALL:       z = "UNION ALL";   break;
114623:     case TK_INTERSECT: z = "INTERSECT";   break;
114624:     case TK_EXCEPT:    z = "EXCEPT";      break;
114625:     default:           z = "UNION";       break;
114626:   }
114627:   return z;
114628: }
114629: 
114630: #ifndef SQLITE_OMIT_EXPLAIN
114631: /*
114632: ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
114633: ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
114634: ** where the caption is of the form:
114635: **
114636: **   "USE TEMP B-TREE FOR xxx"
114637: **
114638: ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
114639: ** is determined by the zUsage argument.
114640: */
114641: static void explainTempTable(Parse *pParse, const char *zUsage){
114642:   if( pParse->explain==2 ){
114643:     Vdbe *v = pParse->pVdbe;
114644:     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
114645:     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
114646:   }
114647: }
114648: 
114649: /*
114650: ** Assign expression b to lvalue a. A second, no-op, version of this macro
114651: ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
114652: ** in sqlite3Select() to assign values to structure member variables that
114653: ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
114654: ** code with #ifndef directives.
114655: */
114656: # define explainSetInteger(a, b) a = b
114657: 
114658: #else
114659: /* No-op versions of the explainXXX() functions and macros. */
114660: # define explainTempTable(y,z)
114661: # define explainSetInteger(y,z)
114662: #endif
114663: 
114664: #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
114665: /*
114666: ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
114667: ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
114668: ** where the caption is of one of the two forms:
114669: **
114670: **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
114671: **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
114672: **
114673: ** where iSub1 and iSub2 are the integers passed as the corresponding
114674: ** function parameters, and op is the text representation of the parameter
114675: ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
114676: ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
114677: ** false, or the second form if it is true.
114678: */
114679: static void explainComposite(
114680:   Parse *pParse,                  /* Parse context */
114681:   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
114682:   int iSub1,                      /* Subquery id 1 */
114683:   int iSub2,                      /* Subquery id 2 */
114684:   int bUseTmp                     /* True if a temp table was used */
114685: ){
114686:   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
114687:   if( pParse->explain==2 ){
114688:     Vdbe *v = pParse->pVdbe;
114689:     char *zMsg = sqlite3MPrintf(
114690:         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
114691:         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
114692:     );
114693:     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
114694:   }
114695: }
114696: #else
114697: /* No-op versions of the explainXXX() functions and macros. */
114698: # define explainComposite(v,w,x,y,z)
114699: #endif
114700: 
114701: /*
114702: ** If the inner loop was generated using a non-null pOrderBy argument,
114703: ** then the results were placed in a sorter.  After the loop is terminated
114704: ** we need to run the sorter and output the results.  The following
114705: ** routine generates the code needed to do that.
114706: */
114707: static void generateSortTail(
114708:   Parse *pParse,    /* Parsing context */
114709:   Select *p,        /* The SELECT statement */
114710:   SortCtx *pSort,   /* Information on the ORDER BY clause */
114711:   int nColumn,      /* Number of columns of data */
114712:   SelectDest *pDest /* Write the sorted results here */
114713: ){
114714:   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
114715:   int addrBreak = pSort->labelDone;            /* Jump here to exit loop */
114716:   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
114717:   int addr;
114718:   int addrOnce = 0;
114719:   int iTab;
114720:   ExprList *pOrderBy = pSort->pOrderBy;
114721:   int eDest = pDest->eDest;
114722:   int iParm = pDest->iSDParm;
114723:   int regRow;
114724:   int regRowid;
114725:   int nKey;
114726:   int iSortTab;                   /* Sorter cursor to read from */
114727:   int nSortData;                  /* Trailing values to read from sorter */
114728:   int i;
114729:   int bSeq;                       /* True if sorter record includes seq. no. */
114730: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
114731:   struct ExprList_item *aOutEx = p->pEList->a;
114732: #endif
114733: 
114734:   assert( addrBreak<0 );
114735:   if( pSort->labelBkOut ){
114736:     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114737:     sqlite3VdbeGoto(v, addrBreak);
114738:     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
114739:   }
114740:   iTab = pSort->iECursor;
114741:   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
114742:     regRowid = 0;
114743:     regRow = pDest->iSdst;
114744:     nSortData = nColumn;
114745:   }else{
114746:     regRowid = sqlite3GetTempReg(pParse);
114747:     regRow = sqlite3GetTempReg(pParse);
114748:     nSortData = 1;
114749:   }
114750:   nKey = pOrderBy->nExpr - pSort->nOBSat;
114751:   if( pSort->sortFlags & SORTFLAG_UseSorter ){
114752:     int regSortOut = ++pParse->nMem;
114753:     iSortTab = pParse->nTab++;
114754:     if( pSort->labelBkOut ){
114755:       addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
114756:     }
114757:     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
114758:     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
114759:     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
114760:     VdbeCoverage(v);
114761:     codeOffset(v, p->iOffset, addrContinue);
114762:     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
114763:     bSeq = 0;
114764:   }else{
114765:     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
114766:     codeOffset(v, p->iOffset, addrContinue);
114767:     iSortTab = iTab;
114768:     bSeq = 1;
114769:   }
114770:   for(i=0; i<nSortData; i++){
114771:     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
114772:     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
114773:   }
114774:   switch( eDest ){
114775:     case SRT_EphemTab: {
114776:       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
114777:       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
114778:       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
114779:       break;
114780:     }
114781: #ifndef SQLITE_OMIT_SUBQUERY
114782:     case SRT_Set: {
114783:       assert( nColumn==1 );
114784:       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
114785:                         &pDest->affSdst, 1);
114786:       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
114787:       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
114788:       break;
114789:     }
114790:     case SRT_Mem: {
114791:       assert( nColumn==1 );
114792:       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
114793:       /* The LIMIT clause will terminate the loop for us */
114794:       break;
114795:     }
114796: #endif
114797:     default: {
114798:       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
114799:       testcase( eDest==SRT_Output );
114800:       testcase( eDest==SRT_Coroutine );
114801:       if( eDest==SRT_Output ){
114802:         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
114803:         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
114804:       }else{
114805:         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
114806:       }
114807:       break;
114808:     }
114809:   }
114810:   if( regRowid ){
114811:     sqlite3ReleaseTempReg(pParse, regRow);
114812:     sqlite3ReleaseTempReg(pParse, regRowid);
114813:   }
114814:   /* The bottom of the loop
114815:   */
114816:   sqlite3VdbeResolveLabel(v, addrContinue);
114817:   if( pSort->sortFlags & SORTFLAG_UseSorter ){
114818:     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
114819:   }else{
114820:     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
114821:   }
114822:   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
114823:   sqlite3VdbeResolveLabel(v, addrBreak);
114824: }
114825: 
114826: /*
114827: ** Return a pointer to a string containing the 'declaration type' of the
114828: ** expression pExpr. The string may be treated as static by the caller.
114829: **
114830: ** Also try to estimate the size of the returned value and return that
114831: ** result in *pEstWidth.
114832: **
114833: ** The declaration type is the exact datatype definition extracted from the
114834: ** original CREATE TABLE statement if the expression is a column. The
114835: ** declaration type for a ROWID field is INTEGER. Exactly when an expression
114836: ** is considered a column can be complex in the presence of subqueries. The
114837: ** result-set expression in all of the following SELECT statements is 
114838: ** considered a column by this function.
114839: **
114840: **   SELECT col FROM tbl;
114841: **   SELECT (SELECT col FROM tbl;
114842: **   SELECT (SELECT col FROM tbl);
114843: **   SELECT abc FROM (SELECT col AS abc FROM tbl);
114844: ** 
114845: ** The declaration type for any expression other than a column is NULL.
114846: **
114847: ** This routine has either 3 or 6 parameters depending on whether or not
114848: ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
114849: */
114850: #ifdef SQLITE_ENABLE_COLUMN_METADATA
114851: # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
114852: #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
114853: # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
114854: #endif
114855: static const char *columnTypeImpl(
114856:   NameContext *pNC, 
114857:   Expr *pExpr,
114858: #ifdef SQLITE_ENABLE_COLUMN_METADATA
114859:   const char **pzOrigDb,
114860:   const char **pzOrigTab,
114861:   const char **pzOrigCol,
114862: #endif
114863:   u8 *pEstWidth
114864: ){
114865:   char const *zType = 0;
114866:   int j;
114867:   u8 estWidth = 1;
114868: #ifdef SQLITE_ENABLE_COLUMN_METADATA
114869:   char const *zOrigDb = 0;
114870:   char const *zOrigTab = 0;
114871:   char const *zOrigCol = 0;
114872: #endif
114873: 
114874:   assert( pExpr!=0 );
114875:   assert( pNC->pSrcList!=0 );
114876:   switch( pExpr->op ){
114877:     case TK_AGG_COLUMN:
114878:     case TK_COLUMN: {
114879:       /* The expression is a column. Locate the table the column is being
114880:       ** extracted from in NameContext.pSrcList. This table may be real
114881:       ** database table or a subquery.
114882:       */
114883:       Table *pTab = 0;            /* Table structure column is extracted from */
114884:       Select *pS = 0;             /* Select the column is extracted from */
114885:       int iCol = pExpr->iColumn;  /* Index of column in pTab */
114886:       testcase( pExpr->op==TK_AGG_COLUMN );
114887:       testcase( pExpr->op==TK_COLUMN );
114888:       while( pNC && !pTab ){
114889:         SrcList *pTabList = pNC->pSrcList;
114890:         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
114891:         if( j<pTabList->nSrc ){
114892:           pTab = pTabList->a[j].pTab;
114893:           pS = pTabList->a[j].pSelect;
114894:         }else{
114895:           pNC = pNC->pNext;
114896:         }
114897:       }
114898: 
114899:       if( pTab==0 ){
114900:         /* At one time, code such as "SELECT new.x" within a trigger would
114901:         ** cause this condition to run.  Since then, we have restructured how
114902:         ** trigger code is generated and so this condition is no longer 
114903:         ** possible. However, it can still be true for statements like
114904:         ** the following:
114905:         **
114906:         **   CREATE TABLE t1(col INTEGER);
114907:         **   SELECT (SELECT t1.col) FROM FROM t1;
114908:         **
114909:         ** when columnType() is called on the expression "t1.col" in the 
114910:         ** sub-select. In this case, set the column type to NULL, even
114911:         ** though it should really be "INTEGER".
114912:         **
114913:         ** This is not a problem, as the column type of "t1.col" is never
114914:         ** used. When columnType() is called on the expression 
114915:         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
114916:         ** branch below.  */
114917:         break;
114918:       }
114919: 
114920:       assert( pTab && pExpr->pTab==pTab );
114921:       if( pS ){
114922:         /* The "table" is actually a sub-select or a view in the FROM clause
114923:         ** of the SELECT statement. Return the declaration type and origin
114924:         ** data for the result-set column of the sub-select.
114925:         */
114926:         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
114927:           /* If iCol is less than zero, then the expression requests the
114928:           ** rowid of the sub-select or view. This expression is legal (see 
114929:           ** test case misc2.2.2) - it always evaluates to NULL.
114930:           **
114931:           ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
114932:           ** caught already by name resolution.
114933:           */
114934:           NameContext sNC;
114935:           Expr *p = pS->pEList->a[iCol].pExpr;
114936:           sNC.pSrcList = pS->pSrc;
114937:           sNC.pNext = pNC;
114938:           sNC.pParse = pNC->pParse;
114939:           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 
114940:         }
114941:       }else if( pTab->pSchema ){
114942:         /* A real table */
114943:         assert( !pS );
114944:         if( iCol<0 ) iCol = pTab->iPKey;
114945:         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
114946: #ifdef SQLITE_ENABLE_COLUMN_METADATA
114947:         if( iCol<0 ){
114948:           zType = "INTEGER";
114949:           zOrigCol = "rowid";
114950:         }else{
114951:           zOrigCol = pTab->aCol[iCol].zName;
114952:           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114953:           estWidth = pTab->aCol[iCol].szEst;
114954:         }
114955:         zOrigTab = pTab->zName;
114956:         if( pNC->pParse ){
114957:           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
114958:           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
114959:         }
114960: #else
114961:         if( iCol<0 ){
114962:           zType = "INTEGER";
114963:         }else{
114964:           zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114965:           estWidth = pTab->aCol[iCol].szEst;
114966:         }
114967: #endif
114968:       }
114969:       break;
114970:     }
114971: #ifndef SQLITE_OMIT_SUBQUERY
114972:     case TK_SELECT: {
114973:       /* The expression is a sub-select. Return the declaration type and
114974:       ** origin info for the single column in the result set of the SELECT
114975:       ** statement.
114976:       */
114977:       NameContext sNC;
114978:       Select *pS = pExpr->x.pSelect;
114979:       Expr *p = pS->pEList->a[0].pExpr;
114980:       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
114981:       sNC.pSrcList = pS->pSrc;
114982:       sNC.pNext = pNC;
114983:       sNC.pParse = pNC->pParse;
114984:       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); 
114985:       break;
114986:     }
114987: #endif
114988:   }
114989: 
114990: #ifdef SQLITE_ENABLE_COLUMN_METADATA  
114991:   if( pzOrigDb ){
114992:     assert( pzOrigTab && pzOrigCol );
114993:     *pzOrigDb = zOrigDb;
114994:     *pzOrigTab = zOrigTab;
114995:     *pzOrigCol = zOrigCol;
114996:   }
114997: #endif
114998:   if( pEstWidth ) *pEstWidth = estWidth;
114999:   return zType;
115000: }
115001: 
115002: /*
115003: ** Generate code that will tell the VDBE the declaration types of columns
115004: ** in the result set.
115005: */
115006: static void generateColumnTypes(
115007:   Parse *pParse,      /* Parser context */
115008:   SrcList *pTabList,  /* List of tables */
115009:   ExprList *pEList    /* Expressions defining the result set */
115010: ){
115011: #ifndef SQLITE_OMIT_DECLTYPE
115012:   Vdbe *v = pParse->pVdbe;
115013:   int i;
115014:   NameContext sNC;
115015:   sNC.pSrcList = pTabList;
115016:   sNC.pParse = pParse;
115017:   for(i=0; i<pEList->nExpr; i++){
115018:     Expr *p = pEList->a[i].pExpr;
115019:     const char *zType;
115020: #ifdef SQLITE_ENABLE_COLUMN_METADATA
115021:     const char *zOrigDb = 0;
115022:     const char *zOrigTab = 0;
115023:     const char *zOrigCol = 0;
115024:     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
115025: 
115026:     /* The vdbe must make its own copy of the column-type and other 
115027:     ** column specific strings, in case the schema is reset before this
115028:     ** virtual machine is deleted.
115029:     */
115030:     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
115031:     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
115032:     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
115033: #else
115034:     zType = columnType(&sNC, p, 0, 0, 0, 0);
115035: #endif
115036:     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
115037:   }
115038: #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
115039: }
115040: 
115041: /*
115042: ** Generate code that will tell the VDBE the names of columns
115043: ** in the result set.  This information is used to provide the
115044: ** azCol[] values in the callback.
115045: */
115046: static void generateColumnNames(
115047:   Parse *pParse,      /* Parser context */
115048:   SrcList *pTabList,  /* List of tables */
115049:   ExprList *pEList    /* Expressions defining the result set */
115050: ){
115051:   Vdbe *v = pParse->pVdbe;
115052:   int i, j;
115053:   sqlite3 *db = pParse->db;
115054:   int fullNames, shortNames;
115055: 
115056: #ifndef SQLITE_OMIT_EXPLAIN
115057:   /* If this is an EXPLAIN, skip this step */
115058:   if( pParse->explain ){
115059:     return;
115060:   }
115061: #endif
115062: 
115063:   if( pParse->colNamesSet || db->mallocFailed ) return;
115064:   assert( v!=0 );
115065:   assert( pTabList!=0 );
115066:   pParse->colNamesSet = 1;
115067:   fullNames = (db->flags & SQLITE_FullColNames)!=0;
115068:   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
115069:   sqlite3VdbeSetNumCols(v, pEList->nExpr);
115070:   for(i=0; i<pEList->nExpr; i++){
115071:     Expr *p;
115072:     p = pEList->a[i].pExpr;
115073:     if( NEVER(p==0) ) continue;
115074:     if( pEList->a[i].zName ){
115075:       char *zName = pEList->a[i].zName;
115076:       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
115077:     }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
115078:       Table *pTab;
115079:       char *zCol;
115080:       int iCol = p->iColumn;
115081:       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
115082:         if( pTabList->a[j].iCursor==p->iTable ) break;
115083:       }
115084:       assert( j<pTabList->nSrc );
115085:       pTab = pTabList->a[j].pTab;
115086:       if( iCol<0 ) iCol = pTab->iPKey;
115087:       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
115088:       if( iCol<0 ){
115089:         zCol = "rowid";
115090:       }else{
115091:         zCol = pTab->aCol[iCol].zName;
115092:       }
115093:       if( !shortNames && !fullNames ){
115094:         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
115095:             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
115096:       }else if( fullNames ){
115097:         char *zName = 0;
115098:         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
115099:         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
115100:       }else{
115101:         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
115102:       }
115103:     }else{
115104:       const char *z = pEList->a[i].zSpan;
115105:       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
115106:       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
115107:     }
115108:   }
115109:   generateColumnTypes(pParse, pTabList, pEList);
115110: }
115111: 
115112: /*
115113: ** Given an expression list (which is really the list of expressions
115114: ** that form the result set of a SELECT statement) compute appropriate
115115: ** column names for a table that would hold the expression list.
115116: **
115117: ** All column names will be unique.
115118: **
115119: ** Only the column names are computed.  Column.zType, Column.zColl,
115120: ** and other fields of Column are zeroed.
115121: **
115122: ** Return SQLITE_OK on success.  If a memory allocation error occurs,
115123: ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
115124: */
115125: SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
115126:   Parse *pParse,          /* Parsing context */
115127:   ExprList *pEList,       /* Expr list from which to derive column names */
115128:   i16 *pnCol,             /* Write the number of columns here */
115129:   Column **paCol          /* Write the new column list here */
115130: ){
115131:   sqlite3 *db = pParse->db;   /* Database connection */
115132:   int i, j;                   /* Loop counters */
115133:   u32 cnt;                    /* Index added to make the name unique */
115134:   Column *aCol, *pCol;        /* For looping over result columns */
115135:   int nCol;                   /* Number of columns in the result set */
115136:   Expr *p;                    /* Expression for a single result column */
115137:   char *zName;                /* Column name */
115138:   int nName;                  /* Size of name in zName[] */
115139:   Hash ht;                    /* Hash table of column names */
115140: 
115141:   sqlite3HashInit(&ht);
115142:   if( pEList ){
115143:     nCol = pEList->nExpr;
115144:     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
115145:     testcase( aCol==0 );
115146:   }else{
115147:     nCol = 0;
115148:     aCol = 0;
115149:   }
115150:   assert( nCol==(i16)nCol );
115151:   *pnCol = nCol;
115152:   *paCol = aCol;
115153: 
115154:   for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
115155:     /* Get an appropriate name for the column
115156:     */
115157:     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
115158:     if( (zName = pEList->a[i].zName)!=0 ){
115159:       /* If the column contains an "AS <name>" phrase, use <name> as the name */
115160:     }else{
115161:       Expr *pColExpr = p;  /* The expression that is the result column name */
115162:       Table *pTab;         /* Table associated with this expression */
115163:       while( pColExpr->op==TK_DOT ){
115164:         pColExpr = pColExpr->pRight;
115165:         assert( pColExpr!=0 );
115166:       }
115167:       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
115168:         /* For columns use the column name name */
115169:         int iCol = pColExpr->iColumn;
115170:         pTab = pColExpr->pTab;
115171:         if( iCol<0 ) iCol = pTab->iPKey;
115172:         zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
115173:       }else if( pColExpr->op==TK_ID ){
115174:         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
115175:         zName = pColExpr->u.zToken;
115176:       }else{
115177:         /* Use the original text of the column expression as its name */
115178:         zName = pEList->a[i].zSpan;
115179:       }
115180:     }
115181:     zName = sqlite3MPrintf(db, "%s", zName);
115182: 
115183:     /* Make sure the column name is unique.  If the name is not unique,
115184:     ** append an integer to the name so that it becomes unique.
115185:     */
115186:     cnt = 0;
115187:     while( zName && sqlite3HashFind(&ht, zName)!=0 ){
115188:       nName = sqlite3Strlen30(zName);
115189:       if( nName>0 ){
115190:         for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
115191:         if( zName[j]==':' ) nName = j;
115192:       }
115193:       zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
115194:       if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
115195:     }
115196:     pCol->zName = zName;
115197:     sqlite3ColumnPropertiesFromName(0, pCol);
115198:     if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
115199:       sqlite3OomFault(db);
115200:     }
115201:   }
115202:   sqlite3HashClear(&ht);
115203:   if( db->mallocFailed ){
115204:     for(j=0; j<i; j++){
115205:       sqlite3DbFree(db, aCol[j].zName);
115206:     }
115207:     sqlite3DbFree(db, aCol);
115208:     *paCol = 0;
115209:     *pnCol = 0;
115210:     return SQLITE_NOMEM_BKPT;
115211:   }
115212:   return SQLITE_OK;
115213: }
115214: 
115215: /*
115216: ** Add type and collation information to a column list based on
115217: ** a SELECT statement.
115218: ** 
115219: ** The column list presumably came from selectColumnNamesFromExprList().
115220: ** The column list has only names, not types or collations.  This
115221: ** routine goes through and adds the types and collations.
115222: **
115223: ** This routine requires that all identifiers in the SELECT
115224: ** statement be resolved.
115225: */
115226: SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
115227:   Parse *pParse,        /* Parsing contexts */
115228:   Table *pTab,          /* Add column type information to this table */
115229:   Select *pSelect       /* SELECT used to determine types and collations */
115230: ){
115231:   sqlite3 *db = pParse->db;
115232:   NameContext sNC;
115233:   Column *pCol;
115234:   CollSeq *pColl;
115235:   int i;
115236:   Expr *p;
115237:   struct ExprList_item *a;
115238:   u64 szAll = 0;
115239: 
115240:   assert( pSelect!=0 );
115241:   assert( (pSelect->selFlags & SF_Resolved)!=0 );
115242:   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
115243:   if( db->mallocFailed ) return;
115244:   memset(&sNC, 0, sizeof(sNC));
115245:   sNC.pSrcList = pSelect->pSrc;
115246:   a = pSelect->pEList->a;
115247:   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
115248:     const char *zType;
115249:     int n, m;
115250:     p = a[i].pExpr;
115251:     zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
115252:     szAll += pCol->szEst;
115253:     pCol->affinity = sqlite3ExprAffinity(p);
115254:     if( zType && (m = sqlite3Strlen30(zType))>0 ){
115255:       n = sqlite3Strlen30(pCol->zName);
115256:       pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
115257:       if( pCol->zName ){
115258:         memcpy(&pCol->zName[n+1], zType, m+1);
115259:         pCol->colFlags |= COLFLAG_HASTYPE;
115260:       }
115261:     }
115262:     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
115263:     pColl = sqlite3ExprCollSeq(pParse, p);
115264:     if( pColl && pCol->zColl==0 ){
115265:       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
115266:     }
115267:   }
115268:   pTab->szTabRow = sqlite3LogEst(szAll*4);
115269: }
115270: 
115271: /*
115272: ** Given a SELECT statement, generate a Table structure that describes
115273: ** the result set of that SELECT.
115274: */
115275: SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
115276:   Table *pTab;
115277:   sqlite3 *db = pParse->db;
115278:   int savedFlags;
115279: 
115280:   savedFlags = db->flags;
115281:   db->flags &= ~SQLITE_FullColNames;
115282:   db->flags |= SQLITE_ShortColNames;
115283:   sqlite3SelectPrep(pParse, pSelect, 0);
115284:   if( pParse->nErr ) return 0;
115285:   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
115286:   db->flags = savedFlags;
115287:   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
115288:   if( pTab==0 ){
115289:     return 0;
115290:   }
115291:   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
115292:   ** is disabled */
115293:   assert( db->lookaside.bDisable );
115294:   pTab->nRef = 1;
115295:   pTab->zName = 0;
115296:   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
115297:   sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
115298:   sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
115299:   pTab->iPKey = -1;
115300:   if( db->mallocFailed ){
115301:     sqlite3DeleteTable(db, pTab);
115302:     return 0;
115303:   }
115304:   return pTab;
115305: }
115306: 
115307: /*
115308: ** Get a VDBE for the given parser context.  Create a new one if necessary.
115309: ** If an error occurs, return NULL and leave a message in pParse.
115310: */
115311: static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
115312:   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
115313:   if( v ) sqlite3VdbeAddOp0(v, OP_Init);
115314:   if( pParse->pToplevel==0
115315:    && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
115316:   ){
115317:     pParse->okConstFactor = 1;
115318:   }
115319:   return v;
115320: }
115321: SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
115322:   Vdbe *v = pParse->pVdbe;
115323:   return v ? v : allocVdbe(pParse);
115324: }
115325: 
115326: 
115327: /*
115328: ** Compute the iLimit and iOffset fields of the SELECT based on the
115329: ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
115330: ** that appear in the original SQL statement after the LIMIT and OFFSET
115331: ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
115332: ** are the integer memory register numbers for counters used to compute 
115333: ** the limit and offset.  If there is no limit and/or offset, then 
115334: ** iLimit and iOffset are negative.
115335: **
115336: ** This routine changes the values of iLimit and iOffset only if
115337: ** a limit or offset is defined by pLimit and pOffset.  iLimit and
115338: ** iOffset should have been preset to appropriate default values (zero)
115339: ** prior to calling this routine.
115340: **
115341: ** The iOffset register (if it exists) is initialized to the value
115342: ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
115343: ** iOffset+1 is initialized to LIMIT+OFFSET.
115344: **
115345: ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
115346: ** redefined.  The UNION ALL operator uses this property to force
115347: ** the reuse of the same limit and offset registers across multiple
115348: ** SELECT statements.
115349: */
115350: static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
115351:   Vdbe *v = 0;
115352:   int iLimit = 0;
115353:   int iOffset;
115354:   int n;
115355:   if( p->iLimit ) return;
115356: 
115357:   /* 
115358:   ** "LIMIT -1" always shows all rows.  There is some
115359:   ** controversy about what the correct behavior should be.
115360:   ** The current implementation interprets "LIMIT 0" to mean
115361:   ** no rows.
115362:   */
115363:   sqlite3ExprCacheClear(pParse);
115364:   assert( p->pOffset==0 || p->pLimit!=0 );
115365:   if( p->pLimit ){
115366:     p->iLimit = iLimit = ++pParse->nMem;
115367:     v = sqlite3GetVdbe(pParse);
115368:     assert( v!=0 );
115369:     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
115370:       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
115371:       VdbeComment((v, "LIMIT counter"));
115372:       if( n==0 ){
115373:         sqlite3VdbeGoto(v, iBreak);
115374:       }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
115375:         p->nSelectRow = sqlite3LogEst((u64)n);
115376:         p->selFlags |= SF_FixedLimit;
115377:       }
115378:     }else{
115379:       sqlite3ExprCode(pParse, p->pLimit, iLimit);
115380:       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
115381:       VdbeComment((v, "LIMIT counter"));
115382:       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
115383:     }
115384:     if( p->pOffset ){
115385:       p->iOffset = iOffset = ++pParse->nMem;
115386:       pParse->nMem++;   /* Allocate an extra register for limit+offset */
115387:       sqlite3ExprCode(pParse, p->pOffset, iOffset);
115388:       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
115389:       VdbeComment((v, "OFFSET counter"));
115390:       sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
115391:       VdbeComment((v, "LIMIT+OFFSET"));
115392:     }
115393:   }
115394: }
115395: 
115396: #ifndef SQLITE_OMIT_COMPOUND_SELECT
115397: /*
115398: ** Return the appropriate collating sequence for the iCol-th column of
115399: ** the result set for the compound-select statement "p".  Return NULL if
115400: ** the column has no default collating sequence.
115401: **
115402: ** The collating sequence for the compound select is taken from the
115403: ** left-most term of the select that has a collating sequence.
115404: */
115405: static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
115406:   CollSeq *pRet;
115407:   if( p->pPrior ){
115408:     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
115409:   }else{
115410:     pRet = 0;
115411:   }
115412:   assert( iCol>=0 );
115413:   /* iCol must be less than p->pEList->nExpr.  Otherwise an error would
115414:   ** have been thrown during name resolution and we would not have gotten
115415:   ** this far */
115416:   if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
115417:     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
115418:   }
115419:   return pRet;
115420: }
115421: 
115422: /*
115423: ** The select statement passed as the second parameter is a compound SELECT
115424: ** with an ORDER BY clause. This function allocates and returns a KeyInfo
115425: ** structure suitable for implementing the ORDER BY.
115426: **
115427: ** Space to hold the KeyInfo structure is obtained from malloc. The calling
115428: ** function is responsible for ensuring that this structure is eventually
115429: ** freed.
115430: */
115431: static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
115432:   ExprList *pOrderBy = p->pOrderBy;
115433:   int nOrderBy = p->pOrderBy->nExpr;
115434:   sqlite3 *db = pParse->db;
115435:   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
115436:   if( pRet ){
115437:     int i;
115438:     for(i=0; i<nOrderBy; i++){
115439:       struct ExprList_item *pItem = &pOrderBy->a[i];
115440:       Expr *pTerm = pItem->pExpr;
115441:       CollSeq *pColl;
115442: 
115443:       if( pTerm->flags & EP_Collate ){
115444:         pColl = sqlite3ExprCollSeq(pParse, pTerm);
115445:       }else{
115446:         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
115447:         if( pColl==0 ) pColl = db->pDfltColl;
115448:         pOrderBy->a[i].pExpr =
115449:           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
115450:       }
115451:       assert( sqlite3KeyInfoIsWriteable(pRet) );
115452:       pRet->aColl[i] = pColl;
115453:       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
115454:     }
115455:   }
115456: 
115457:   return pRet;
115458: }
115459: 
115460: #ifndef SQLITE_OMIT_CTE
115461: /*
115462: ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
115463: ** query of the form:
115464: **
115465: **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
115466: **                         \___________/             \_______________/
115467: **                           p->pPrior                      p
115468: **
115469: **
115470: ** There is exactly one reference to the recursive-table in the FROM clause
115471: ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
115472: **
115473: ** The setup-query runs once to generate an initial set of rows that go
115474: ** into a Queue table.  Rows are extracted from the Queue table one by
115475: ** one.  Each row extracted from Queue is output to pDest.  Then the single
115476: ** extracted row (now in the iCurrent table) becomes the content of the
115477: ** recursive-table for a recursive-query run.  The output of the recursive-query
115478: ** is added back into the Queue table.  Then another row is extracted from Queue
115479: ** and the iteration continues until the Queue table is empty.
115480: **
115481: ** If the compound query operator is UNION then no duplicate rows are ever
115482: ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
115483: ** that have ever been inserted into Queue and causes duplicates to be
115484: ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
115485: ** 
115486: ** If the query has an ORDER BY, then entries in the Queue table are kept in
115487: ** ORDER BY order and the first entry is extracted for each cycle.  Without
115488: ** an ORDER BY, the Queue table is just a FIFO.
115489: **
115490: ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
115491: ** have been output to pDest.  A LIMIT of zero means to output no rows and a
115492: ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
115493: ** with a positive value, then the first OFFSET outputs are discarded rather
115494: ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
115495: ** rows have been skipped.
115496: */
115497: static void generateWithRecursiveQuery(
115498:   Parse *pParse,        /* Parsing context */
115499:   Select *p,            /* The recursive SELECT to be coded */
115500:   SelectDest *pDest     /* What to do with query results */
115501: ){
115502:   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
115503:   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
115504:   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
115505:   Select *pSetup = p->pPrior;   /* The setup query */
115506:   int addrTop;                  /* Top of the loop */
115507:   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
115508:   int iCurrent = 0;             /* The Current table */
115509:   int regCurrent;               /* Register holding Current table */
115510:   int iQueue;                   /* The Queue table */
115511:   int iDistinct = 0;            /* To ensure unique results if UNION */
115512:   int eDest = SRT_Fifo;         /* How to write to Queue */
115513:   SelectDest destQueue;         /* SelectDest targetting the Queue table */
115514:   int i;                        /* Loop counter */
115515:   int rc;                       /* Result code */
115516:   ExprList *pOrderBy;           /* The ORDER BY clause */
115517:   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
115518:   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
115519: 
115520:   /* Obtain authorization to do a recursive query */
115521:   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
115522: 
115523:   /* Process the LIMIT and OFFSET clauses, if they exist */
115524:   addrBreak = sqlite3VdbeMakeLabel(v);
115525:   computeLimitRegisters(pParse, p, addrBreak);
115526:   pLimit = p->pLimit;
115527:   pOffset = p->pOffset;
115528:   regLimit = p->iLimit;
115529:   regOffset = p->iOffset;
115530:   p->pLimit = p->pOffset = 0;
115531:   p->iLimit = p->iOffset = 0;
115532:   pOrderBy = p->pOrderBy;
115533: 
115534:   /* Locate the cursor number of the Current table */
115535:   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
115536:     if( pSrc->a[i].fg.isRecursive ){
115537:       iCurrent = pSrc->a[i].iCursor;
115538:       break;
115539:     }
115540:   }
115541: 
115542:   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
115543:   ** the Distinct table must be exactly one greater than Queue in order
115544:   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
115545:   iQueue = pParse->nTab++;
115546:   if( p->op==TK_UNION ){
115547:     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
115548:     iDistinct = pParse->nTab++;
115549:   }else{
115550:     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
115551:   }
115552:   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
115553: 
115554:   /* Allocate cursors for Current, Queue, and Distinct. */
115555:   regCurrent = ++pParse->nMem;
115556:   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
115557:   if( pOrderBy ){
115558:     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
115559:     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
115560:                       (char*)pKeyInfo, P4_KEYINFO);
115561:     destQueue.pOrderBy = pOrderBy;
115562:   }else{
115563:     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
115564:   }
115565:   VdbeComment((v, "Queue table"));
115566:   if( iDistinct ){
115567:     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
115568:     p->selFlags |= SF_UsesEphemeral;
115569:   }
115570: 
115571:   /* Detach the ORDER BY clause from the compound SELECT */
115572:   p->pOrderBy = 0;
115573: 
115574:   /* Store the results of the setup-query in Queue. */
115575:   pSetup->pNext = 0;
115576:   rc = sqlite3Select(pParse, pSetup, &destQueue);
115577:   pSetup->pNext = p;
115578:   if( rc ) goto end_of_recursive_query;
115579: 
115580:   /* Find the next row in the Queue and output that row */
115581:   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
115582: 
115583:   /* Transfer the next row in Queue over to Current */
115584:   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
115585:   if( pOrderBy ){
115586:     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
115587:   }else{
115588:     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
115589:   }
115590:   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
115591: 
115592:   /* Output the single row in Current */
115593:   addrCont = sqlite3VdbeMakeLabel(v);
115594:   codeOffset(v, regOffset, addrCont);
115595:   selectInnerLoop(pParse, p, p->pEList, iCurrent,
115596:       0, 0, pDest, addrCont, addrBreak);
115597:   if( regLimit ){
115598:     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
115599:     VdbeCoverage(v);
115600:   }
115601:   sqlite3VdbeResolveLabel(v, addrCont);
115602: 
115603:   /* Execute the recursive SELECT taking the single row in Current as
115604:   ** the value for the recursive-table. Store the results in the Queue.
115605:   */
115606:   if( p->selFlags & SF_Aggregate ){
115607:     sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
115608:   }else{
115609:     p->pPrior = 0;
115610:     sqlite3Select(pParse, p, &destQueue);
115611:     assert( p->pPrior==0 );
115612:     p->pPrior = pSetup;
115613:   }
115614: 
115615:   /* Keep running the loop until the Queue is empty */
115616:   sqlite3VdbeGoto(v, addrTop);
115617:   sqlite3VdbeResolveLabel(v, addrBreak);
115618: 
115619: end_of_recursive_query:
115620:   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
115621:   p->pOrderBy = pOrderBy;
115622:   p->pLimit = pLimit;
115623:   p->pOffset = pOffset;
115624:   return;
115625: }
115626: #endif /* SQLITE_OMIT_CTE */
115627: 
115628: /* Forward references */
115629: static int multiSelectOrderBy(
115630:   Parse *pParse,        /* Parsing context */
115631:   Select *p,            /* The right-most of SELECTs to be coded */
115632:   SelectDest *pDest     /* What to do with query results */
115633: );
115634: 
115635: /*
115636: ** Handle the special case of a compound-select that originates from a
115637: ** VALUES clause.  By handling this as a special case, we avoid deep
115638: ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
115639: ** on a VALUES clause.
115640: **
115641: ** Because the Select object originates from a VALUES clause:
115642: **   (1) It has no LIMIT or OFFSET
115643: **   (2) All terms are UNION ALL
115644: **   (3) There is no ORDER BY clause
115645: */
115646: static int multiSelectValues(
115647:   Parse *pParse,        /* Parsing context */
115648:   Select *p,            /* The right-most of SELECTs to be coded */
115649:   SelectDest *pDest     /* What to do with query results */
115650: ){
115651:   Select *pPrior;
115652:   int nRow = 1;
115653:   int rc = 0;
115654:   assert( p->selFlags & SF_MultiValue );
115655:   do{
115656:     assert( p->selFlags & SF_Values );
115657:     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
115658:     assert( p->pLimit==0 );
115659:     assert( p->pOffset==0 );
115660:     assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
115661:     if( p->pPrior==0 ) break;
115662:     assert( p->pPrior->pNext==p );
115663:     p = p->pPrior;
115664:     nRow++;
115665:   }while(1);
115666:   while( p ){
115667:     pPrior = p->pPrior;
115668:     p->pPrior = 0;
115669:     rc = sqlite3Select(pParse, p, pDest);
115670:     p->pPrior = pPrior;
115671:     if( rc ) break;
115672:     p->nSelectRow = nRow;
115673:     p = p->pNext;
115674:   }
115675:   return rc;
115676: }
115677: 
115678: /*
115679: ** This routine is called to process a compound query form from
115680: ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
115681: ** INTERSECT
115682: **
115683: ** "p" points to the right-most of the two queries.  the query on the
115684: ** left is p->pPrior.  The left query could also be a compound query
115685: ** in which case this routine will be called recursively. 
115686: **
115687: ** The results of the total query are to be written into a destination
115688: ** of type eDest with parameter iParm.
115689: **
115690: ** Example 1:  Consider a three-way compound SQL statement.
115691: **
115692: **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
115693: **
115694: ** This statement is parsed up as follows:
115695: **
115696: **     SELECT c FROM t3
115697: **      |
115698: **      `----->  SELECT b FROM t2
115699: **                |
115700: **                `------>  SELECT a FROM t1
115701: **
115702: ** The arrows in the diagram above represent the Select.pPrior pointer.
115703: ** So if this routine is called with p equal to the t3 query, then
115704: ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
115705: **
115706: ** Notice that because of the way SQLite parses compound SELECTs, the
115707: ** individual selects always group from left to right.
115708: */
115709: static int multiSelect(
115710:   Parse *pParse,        /* Parsing context */
115711:   Select *p,            /* The right-most of SELECTs to be coded */
115712:   SelectDest *pDest     /* What to do with query results */
115713: ){
115714:   int rc = SQLITE_OK;   /* Success code from a subroutine */
115715:   Select *pPrior;       /* Another SELECT immediately to our left */
115716:   Vdbe *v;              /* Generate code to this VDBE */
115717:   SelectDest dest;      /* Alternative data destination */
115718:   Select *pDelete = 0;  /* Chain of simple selects to delete */
115719:   sqlite3 *db;          /* Database connection */
115720: #ifndef SQLITE_OMIT_EXPLAIN
115721:   int iSub1 = 0;        /* EQP id of left-hand query */
115722:   int iSub2 = 0;        /* EQP id of right-hand query */
115723: #endif
115724: 
115725:   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
115726:   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
115727:   */
115728:   assert( p && p->pPrior );  /* Calling function guarantees this much */
115729:   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
115730:   db = pParse->db;
115731:   pPrior = p->pPrior;
115732:   dest = *pDest;
115733:   if( pPrior->pOrderBy ){
115734:     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
115735:       selectOpName(p->op));
115736:     rc = 1;
115737:     goto multi_select_end;
115738:   }
115739:   if( pPrior->pLimit ){
115740:     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
115741:       selectOpName(p->op));
115742:     rc = 1;
115743:     goto multi_select_end;
115744:   }
115745: 
115746:   v = sqlite3GetVdbe(pParse);
115747:   assert( v!=0 );  /* The VDBE already created by calling function */
115748: 
115749:   /* Create the destination temporary table if necessary
115750:   */
115751:   if( dest.eDest==SRT_EphemTab ){
115752:     assert( p->pEList );
115753:     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
115754:     dest.eDest = SRT_Table;
115755:   }
115756: 
115757:   /* Special handling for a compound-select that originates as a VALUES clause.
115758:   */
115759:   if( p->selFlags & SF_MultiValue ){
115760:     rc = multiSelectValues(pParse, p, &dest);
115761:     goto multi_select_end;
115762:   }
115763: 
115764:   /* Make sure all SELECTs in the statement have the same number of elements
115765:   ** in their result sets.
115766:   */
115767:   assert( p->pEList && pPrior->pEList );
115768:   assert( p->pEList->nExpr==pPrior->pEList->nExpr );
115769: 
115770: #ifndef SQLITE_OMIT_CTE
115771:   if( p->selFlags & SF_Recursive ){
115772:     generateWithRecursiveQuery(pParse, p, &dest);
115773:   }else
115774: #endif
115775: 
115776:   /* Compound SELECTs that have an ORDER BY clause are handled separately.
115777:   */
115778:   if( p->pOrderBy ){
115779:     return multiSelectOrderBy(pParse, p, pDest);
115780:   }else
115781: 
115782:   /* Generate code for the left and right SELECT statements.
115783:   */
115784:   switch( p->op ){
115785:     case TK_ALL: {
115786:       int addr = 0;
115787:       int nLimit;
115788:       assert( !pPrior->pLimit );
115789:       pPrior->iLimit = p->iLimit;
115790:       pPrior->iOffset = p->iOffset;
115791:       pPrior->pLimit = p->pLimit;
115792:       pPrior->pOffset = p->pOffset;
115793:       explainSetInteger(iSub1, pParse->iNextSelectId);
115794:       rc = sqlite3Select(pParse, pPrior, &dest);
115795:       p->pLimit = 0;
115796:       p->pOffset = 0;
115797:       if( rc ){
115798:         goto multi_select_end;
115799:       }
115800:       p->pPrior = 0;
115801:       p->iLimit = pPrior->iLimit;
115802:       p->iOffset = pPrior->iOffset;
115803:       if( p->iLimit ){
115804:         addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
115805:         VdbeComment((v, "Jump ahead if LIMIT reached"));
115806:         if( p->iOffset ){
115807:           sqlite3VdbeAddOp3(v, OP_OffsetLimit,
115808:                             p->iLimit, p->iOffset+1, p->iOffset);
115809:         }
115810:       }
115811:       explainSetInteger(iSub2, pParse->iNextSelectId);
115812:       rc = sqlite3Select(pParse, p, &dest);
115813:       testcase( rc!=SQLITE_OK );
115814:       pDelete = p->pPrior;
115815:       p->pPrior = pPrior;
115816:       p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115817:       if( pPrior->pLimit
115818:        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
115819:        && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit) 
115820:       ){
115821:         p->nSelectRow = sqlite3LogEst((u64)nLimit);
115822:       }
115823:       if( addr ){
115824:         sqlite3VdbeJumpHere(v, addr);
115825:       }
115826:       break;
115827:     }
115828:     case TK_EXCEPT:
115829:     case TK_UNION: {
115830:       int unionTab;    /* Cursor number of the temporary table holding result */
115831:       u8 op = 0;       /* One of the SRT_ operations to apply to self */
115832:       int priorOp;     /* The SRT_ operation to apply to prior selects */
115833:       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
115834:       int addr;
115835:       SelectDest uniondest;
115836: 
115837:       testcase( p->op==TK_EXCEPT );
115838:       testcase( p->op==TK_UNION );
115839:       priorOp = SRT_Union;
115840:       if( dest.eDest==priorOp ){
115841:         /* We can reuse a temporary table generated by a SELECT to our
115842:         ** right.
115843:         */
115844:         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
115845:         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
115846:         unionTab = dest.iSDParm;
115847:       }else{
115848:         /* We will need to create our own temporary table to hold the
115849:         ** intermediate results.
115850:         */
115851:         unionTab = pParse->nTab++;
115852:         assert( p->pOrderBy==0 );
115853:         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
115854:         assert( p->addrOpenEphm[0] == -1 );
115855:         p->addrOpenEphm[0] = addr;
115856:         findRightmost(p)->selFlags |= SF_UsesEphemeral;
115857:         assert( p->pEList );
115858:       }
115859: 
115860:       /* Code the SELECT statements to our left
115861:       */
115862:       assert( !pPrior->pOrderBy );
115863:       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
115864:       explainSetInteger(iSub1, pParse->iNextSelectId);
115865:       rc = sqlite3Select(pParse, pPrior, &uniondest);
115866:       if( rc ){
115867:         goto multi_select_end;
115868:       }
115869: 
115870:       /* Code the current SELECT statement
115871:       */
115872:       if( p->op==TK_EXCEPT ){
115873:         op = SRT_Except;
115874:       }else{
115875:         assert( p->op==TK_UNION );
115876:         op = SRT_Union;
115877:       }
115878:       p->pPrior = 0;
115879:       pLimit = p->pLimit;
115880:       p->pLimit = 0;
115881:       pOffset = p->pOffset;
115882:       p->pOffset = 0;
115883:       uniondest.eDest = op;
115884:       explainSetInteger(iSub2, pParse->iNextSelectId);
115885:       rc = sqlite3Select(pParse, p, &uniondest);
115886:       testcase( rc!=SQLITE_OK );
115887:       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
115888:       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
115889:       sqlite3ExprListDelete(db, p->pOrderBy);
115890:       pDelete = p->pPrior;
115891:       p->pPrior = pPrior;
115892:       p->pOrderBy = 0;
115893:       if( p->op==TK_UNION ){
115894:         p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115895:       }
115896:       sqlite3ExprDelete(db, p->pLimit);
115897:       p->pLimit = pLimit;
115898:       p->pOffset = pOffset;
115899:       p->iLimit = 0;
115900:       p->iOffset = 0;
115901: 
115902:       /* Convert the data in the temporary table into whatever form
115903:       ** it is that we currently need.
115904:       */
115905:       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
115906:       if( dest.eDest!=priorOp ){
115907:         int iCont, iBreak, iStart;
115908:         assert( p->pEList );
115909:         if( dest.eDest==SRT_Output ){
115910:           Select *pFirst = p;
115911:           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115912:           generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115913:         }
115914:         iBreak = sqlite3VdbeMakeLabel(v);
115915:         iCont = sqlite3VdbeMakeLabel(v);
115916:         computeLimitRegisters(pParse, p, iBreak);
115917:         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
115918:         iStart = sqlite3VdbeCurrentAddr(v);
115919:         selectInnerLoop(pParse, p, p->pEList, unionTab,
115920:                         0, 0, &dest, iCont, iBreak);
115921:         sqlite3VdbeResolveLabel(v, iCont);
115922:         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
115923:         sqlite3VdbeResolveLabel(v, iBreak);
115924:         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
115925:       }
115926:       break;
115927:     }
115928:     default: assert( p->op==TK_INTERSECT ); {
115929:       int tab1, tab2;
115930:       int iCont, iBreak, iStart;
115931:       Expr *pLimit, *pOffset;
115932:       int addr;
115933:       SelectDest intersectdest;
115934:       int r1;
115935: 
115936:       /* INTERSECT is different from the others since it requires
115937:       ** two temporary tables.  Hence it has its own case.  Begin
115938:       ** by allocating the tables we will need.
115939:       */
115940:       tab1 = pParse->nTab++;
115941:       tab2 = pParse->nTab++;
115942:       assert( p->pOrderBy==0 );
115943: 
115944:       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
115945:       assert( p->addrOpenEphm[0] == -1 );
115946:       p->addrOpenEphm[0] = addr;
115947:       findRightmost(p)->selFlags |= SF_UsesEphemeral;
115948:       assert( p->pEList );
115949: 
115950:       /* Code the SELECTs to our left into temporary table "tab1".
115951:       */
115952:       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
115953:       explainSetInteger(iSub1, pParse->iNextSelectId);
115954:       rc = sqlite3Select(pParse, pPrior, &intersectdest);
115955:       if( rc ){
115956:         goto multi_select_end;
115957:       }
115958: 
115959:       /* Code the current SELECT into temporary table "tab2"
115960:       */
115961:       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
115962:       assert( p->addrOpenEphm[1] == -1 );
115963:       p->addrOpenEphm[1] = addr;
115964:       p->pPrior = 0;
115965:       pLimit = p->pLimit;
115966:       p->pLimit = 0;
115967:       pOffset = p->pOffset;
115968:       p->pOffset = 0;
115969:       intersectdest.iSDParm = tab2;
115970:       explainSetInteger(iSub2, pParse->iNextSelectId);
115971:       rc = sqlite3Select(pParse, p, &intersectdest);
115972:       testcase( rc!=SQLITE_OK );
115973:       pDelete = p->pPrior;
115974:       p->pPrior = pPrior;
115975:       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
115976:       sqlite3ExprDelete(db, p->pLimit);
115977:       p->pLimit = pLimit;
115978:       p->pOffset = pOffset;
115979: 
115980:       /* Generate code to take the intersection of the two temporary
115981:       ** tables.
115982:       */
115983:       assert( p->pEList );
115984:       if( dest.eDest==SRT_Output ){
115985:         Select *pFirst = p;
115986:         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115987:         generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115988:       }
115989:       iBreak = sqlite3VdbeMakeLabel(v);
115990:       iCont = sqlite3VdbeMakeLabel(v);
115991:       computeLimitRegisters(pParse, p, iBreak);
115992:       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
115993:       r1 = sqlite3GetTempReg(pParse);
115994:       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
115995:       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
115996:       sqlite3ReleaseTempReg(pParse, r1);
115997:       selectInnerLoop(pParse, p, p->pEList, tab1,
115998:                       0, 0, &dest, iCont, iBreak);
115999:       sqlite3VdbeResolveLabel(v, iCont);
116000:       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
116001:       sqlite3VdbeResolveLabel(v, iBreak);
116002:       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
116003:       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
116004:       break;
116005:     }
116006:   }
116007: 
116008:   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
116009: 
116010:   /* Compute collating sequences used by 
116011:   ** temporary tables needed to implement the compound select.
116012:   ** Attach the KeyInfo structure to all temporary tables.
116013:   **
116014:   ** This section is run by the right-most SELECT statement only.
116015:   ** SELECT statements to the left always skip this part.  The right-most
116016:   ** SELECT might also skip this part if it has no ORDER BY clause and
116017:   ** no temp tables are required.
116018:   */
116019:   if( p->selFlags & SF_UsesEphemeral ){
116020:     int i;                        /* Loop counter */
116021:     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
116022:     Select *pLoop;                /* For looping through SELECT statements */
116023:     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
116024:     int nCol;                     /* Number of columns in result set */
116025: 
116026:     assert( p->pNext==0 );
116027:     nCol = p->pEList->nExpr;
116028:     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
116029:     if( !pKeyInfo ){
116030:       rc = SQLITE_NOMEM_BKPT;
116031:       goto multi_select_end;
116032:     }
116033:     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
116034:       *apColl = multiSelectCollSeq(pParse, p, i);
116035:       if( 0==*apColl ){
116036:         *apColl = db->pDfltColl;
116037:       }
116038:     }
116039: 
116040:     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
116041:       for(i=0; i<2; i++){
116042:         int addr = pLoop->addrOpenEphm[i];
116043:         if( addr<0 ){
116044:           /* If [0] is unused then [1] is also unused.  So we can
116045:           ** always safely abort as soon as the first unused slot is found */
116046:           assert( pLoop->addrOpenEphm[1]<0 );
116047:           break;
116048:         }
116049:         sqlite3VdbeChangeP2(v, addr, nCol);
116050:         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
116051:                             P4_KEYINFO);
116052:         pLoop->addrOpenEphm[i] = -1;
116053:       }
116054:     }
116055:     sqlite3KeyInfoUnref(pKeyInfo);
116056:   }
116057: 
116058: multi_select_end:
116059:   pDest->iSdst = dest.iSdst;
116060:   pDest->nSdst = dest.nSdst;
116061:   sqlite3SelectDelete(db, pDelete);
116062:   return rc;
116063: }
116064: #endif /* SQLITE_OMIT_COMPOUND_SELECT */
116065: 
116066: /*
116067: ** Error message for when two or more terms of a compound select have different
116068: ** size result sets.
116069: */
116070: SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
116071:   if( p->selFlags & SF_Values ){
116072:     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
116073:   }else{
116074:     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
116075:       " do not have the same number of result columns", selectOpName(p->op));
116076:   }
116077: }
116078: 
116079: /*
116080: ** Code an output subroutine for a coroutine implementation of a
116081: ** SELECT statment.
116082: **
116083: ** The data to be output is contained in pIn->iSdst.  There are
116084: ** pIn->nSdst columns to be output.  pDest is where the output should
116085: ** be sent.
116086: **
116087: ** regReturn is the number of the register holding the subroutine
116088: ** return address.
116089: **
116090: ** If regPrev>0 then it is the first register in a vector that
116091: ** records the previous output.  mem[regPrev] is a flag that is false
116092: ** if there has been no previous output.  If regPrev>0 then code is
116093: ** generated to suppress duplicates.  pKeyInfo is used for comparing
116094: ** keys.
116095: **
116096: ** If the LIMIT found in p->iLimit is reached, jump immediately to
116097: ** iBreak.
116098: */
116099: static int generateOutputSubroutine(
116100:   Parse *pParse,          /* Parsing context */
116101:   Select *p,              /* The SELECT statement */
116102:   SelectDest *pIn,        /* Coroutine supplying data */
116103:   SelectDest *pDest,      /* Where to send the data */
116104:   int regReturn,          /* The return address register */
116105:   int regPrev,            /* Previous result register.  No uniqueness if 0 */
116106:   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
116107:   int iBreak              /* Jump here if we hit the LIMIT */
116108: ){
116109:   Vdbe *v = pParse->pVdbe;
116110:   int iContinue;
116111:   int addr;
116112: 
116113:   addr = sqlite3VdbeCurrentAddr(v);
116114:   iContinue = sqlite3VdbeMakeLabel(v);
116115: 
116116:   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
116117:   */
116118:   if( regPrev ){
116119:     int addr1, addr2;
116120:     addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
116121:     addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
116122:                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
116123:     sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
116124:     sqlite3VdbeJumpHere(v, addr1);
116125:     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
116126:     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
116127:   }
116128:   if( pParse->db->mallocFailed ) return 0;
116129: 
116130:   /* Suppress the first OFFSET entries if there is an OFFSET clause
116131:   */
116132:   codeOffset(v, p->iOffset, iContinue);
116133: 
116134:   assert( pDest->eDest!=SRT_Exists );
116135:   assert( pDest->eDest!=SRT_Table );
116136:   switch( pDest->eDest ){
116137:     /* Store the result as data using a unique key.
116138:     */
116139:     case SRT_EphemTab: {
116140:       int r1 = sqlite3GetTempReg(pParse);
116141:       int r2 = sqlite3GetTempReg(pParse);
116142:       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
116143:       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
116144:       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
116145:       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
116146:       sqlite3ReleaseTempReg(pParse, r2);
116147:       sqlite3ReleaseTempReg(pParse, r1);
116148:       break;
116149:     }
116150: 
116151: #ifndef SQLITE_OMIT_SUBQUERY
116152:     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
116153:     ** then there should be a single item on the stack.  Write this
116154:     ** item into the set table with bogus data.
116155:     */
116156:     case SRT_Set: {
116157:       int r1;
116158:       assert( pIn->nSdst==1 || pParse->nErr>0 );
116159:       pDest->affSdst = 
116160:          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
116161:       r1 = sqlite3GetTempReg(pParse);
116162:       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
116163:       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
116164:       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
116165:       sqlite3ReleaseTempReg(pParse, r1);
116166:       break;
116167:     }
116168: 
116169:     /* If this is a scalar select that is part of an expression, then
116170:     ** store the results in the appropriate memory cell and break out
116171:     ** of the scan loop.
116172:     */
116173:     case SRT_Mem: {
116174:       assert( pIn->nSdst==1 || pParse->nErr>0 );  testcase( pIn->nSdst!=1 );
116175:       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
116176:       /* The LIMIT clause will jump out of the loop for us */
116177:       break;
116178:     }
116179: #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
116180: 
116181:     /* The results are stored in a sequence of registers
116182:     ** starting at pDest->iSdst.  Then the co-routine yields.
116183:     */
116184:     case SRT_Coroutine: {
116185:       if( pDest->iSdst==0 ){
116186:         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
116187:         pDest->nSdst = pIn->nSdst;
116188:       }
116189:       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
116190:       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
116191:       break;
116192:     }
116193: 
116194:     /* If none of the above, then the result destination must be
116195:     ** SRT_Output.  This routine is never called with any other
116196:     ** destination other than the ones handled above or SRT_Output.
116197:     **
116198:     ** For SRT_Output, results are stored in a sequence of registers.  
116199:     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
116200:     ** return the next row of result.
116201:     */
116202:     default: {
116203:       assert( pDest->eDest==SRT_Output );
116204:       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
116205:       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
116206:       break;
116207:     }
116208:   }
116209: 
116210:   /* Jump to the end of the loop if the LIMIT is reached.
116211:   */
116212:   if( p->iLimit ){
116213:     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
116214:   }
116215: 
116216:   /* Generate the subroutine return
116217:   */
116218:   sqlite3VdbeResolveLabel(v, iContinue);
116219:   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
116220: 
116221:   return addr;
116222: }
116223: 
116224: /*
116225: ** Alternative compound select code generator for cases when there
116226: ** is an ORDER BY clause.
116227: **
116228: ** We assume a query of the following form:
116229: **
116230: **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
116231: **
116232: ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
116233: ** is to code both <selectA> and <selectB> with the ORDER BY clause as
116234: ** co-routines.  Then run the co-routines in parallel and merge the results
116235: ** into the output.  In addition to the two coroutines (called selectA and
116236: ** selectB) there are 7 subroutines:
116237: **
116238: **    outA:    Move the output of the selectA coroutine into the output
116239: **             of the compound query.
116240: **
116241: **    outB:    Move the output of the selectB coroutine into the output
116242: **             of the compound query.  (Only generated for UNION and
116243: **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
116244: **             appears only in B.)
116245: **
116246: **    AltB:    Called when there is data from both coroutines and A<B.
116247: **
116248: **    AeqB:    Called when there is data from both coroutines and A==B.
116249: **
116250: **    AgtB:    Called when there is data from both coroutines and A>B.
116251: **
116252: **    EofA:    Called when data is exhausted from selectA.
116253: **
116254: **    EofB:    Called when data is exhausted from selectB.
116255: **
116256: ** The implementation of the latter five subroutines depend on which 
116257: ** <operator> is used:
116258: **
116259: **
116260: **             UNION ALL         UNION            EXCEPT          INTERSECT
116261: **          -------------  -----------------  --------------  -----------------
116262: **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
116263: **
116264: **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
116265: **
116266: **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
116267: **
116268: **   EofA:   outB, nextB      outB, nextB          halt             halt
116269: **
116270: **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
116271: **
116272: ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
116273: ** causes an immediate jump to EofA and an EOF on B following nextB causes
116274: ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
116275: ** following nextX causes a jump to the end of the select processing.
116276: **
116277: ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
116278: ** within the output subroutine.  The regPrev register set holds the previously
116279: ** output value.  A comparison is made against this value and the output
116280: ** is skipped if the next results would be the same as the previous.
116281: **
116282: ** The implementation plan is to implement the two coroutines and seven
116283: ** subroutines first, then put the control logic at the bottom.  Like this:
116284: **
116285: **          goto Init
116286: **     coA: coroutine for left query (A)
116287: **     coB: coroutine for right query (B)
116288: **    outA: output one row of A
116289: **    outB: output one row of B (UNION and UNION ALL only)
116290: **    EofA: ...
116291: **    EofB: ...
116292: **    AltB: ...
116293: **    AeqB: ...
116294: **    AgtB: ...
116295: **    Init: initialize coroutine registers
116296: **          yield coA
116297: **          if eof(A) goto EofA
116298: **          yield coB
116299: **          if eof(B) goto EofB
116300: **    Cmpr: Compare A, B
116301: **          Jump AltB, AeqB, AgtB
116302: **     End: ...
116303: **
116304: ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
116305: ** actually called using Gosub and they do not Return.  EofA and EofB loop
116306: ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
116307: ** and AgtB jump to either L2 or to one of EofA or EofB.
116308: */
116309: #ifndef SQLITE_OMIT_COMPOUND_SELECT
116310: static int multiSelectOrderBy(
116311:   Parse *pParse,        /* Parsing context */
116312:   Select *p,            /* The right-most of SELECTs to be coded */
116313:   SelectDest *pDest     /* What to do with query results */
116314: ){
116315:   int i, j;             /* Loop counters */
116316:   Select *pPrior;       /* Another SELECT immediately to our left */
116317:   Vdbe *v;              /* Generate code to this VDBE */
116318:   SelectDest destA;     /* Destination for coroutine A */
116319:   SelectDest destB;     /* Destination for coroutine B */
116320:   int regAddrA;         /* Address register for select-A coroutine */
116321:   int regAddrB;         /* Address register for select-B coroutine */
116322:   int addrSelectA;      /* Address of the select-A coroutine */
116323:   int addrSelectB;      /* Address of the select-B coroutine */
116324:   int regOutA;          /* Address register for the output-A subroutine */
116325:   int regOutB;          /* Address register for the output-B subroutine */
116326:   int addrOutA;         /* Address of the output-A subroutine */
116327:   int addrOutB = 0;     /* Address of the output-B subroutine */
116328:   int addrEofA;         /* Address of the select-A-exhausted subroutine */
116329:   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
116330:   int addrEofB;         /* Address of the select-B-exhausted subroutine */
116331:   int addrAltB;         /* Address of the A<B subroutine */
116332:   int addrAeqB;         /* Address of the A==B subroutine */
116333:   int addrAgtB;         /* Address of the A>B subroutine */
116334:   int regLimitA;        /* Limit register for select-A */
116335:   int regLimitB;        /* Limit register for select-A */
116336:   int regPrev;          /* A range of registers to hold previous output */
116337:   int savedLimit;       /* Saved value of p->iLimit */
116338:   int savedOffset;      /* Saved value of p->iOffset */
116339:   int labelCmpr;        /* Label for the start of the merge algorithm */
116340:   int labelEnd;         /* Label for the end of the overall SELECT stmt */
116341:   int addr1;            /* Jump instructions that get retargetted */
116342:   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
116343:   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
116344:   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
116345:   sqlite3 *db;          /* Database connection */
116346:   ExprList *pOrderBy;   /* The ORDER BY clause */
116347:   int nOrderBy;         /* Number of terms in the ORDER BY clause */
116348:   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
116349: #ifndef SQLITE_OMIT_EXPLAIN
116350:   int iSub1;            /* EQP id of left-hand query */
116351:   int iSub2;            /* EQP id of right-hand query */
116352: #endif
116353: 
116354:   assert( p->pOrderBy!=0 );
116355:   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
116356:   db = pParse->db;
116357:   v = pParse->pVdbe;
116358:   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
116359:   labelEnd = sqlite3VdbeMakeLabel(v);
116360:   labelCmpr = sqlite3VdbeMakeLabel(v);
116361: 
116362: 
116363:   /* Patch up the ORDER BY clause
116364:   */
116365:   op = p->op;  
116366:   pPrior = p->pPrior;
116367:   assert( pPrior->pOrderBy==0 );
116368:   pOrderBy = p->pOrderBy;
116369:   assert( pOrderBy );
116370:   nOrderBy = pOrderBy->nExpr;
116371: 
116372:   /* For operators other than UNION ALL we have to make sure that
116373:   ** the ORDER BY clause covers every term of the result set.  Add
116374:   ** terms to the ORDER BY clause as necessary.
116375:   */
116376:   if( op!=TK_ALL ){
116377:     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
116378:       struct ExprList_item *pItem;
116379:       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
116380:         assert( pItem->u.x.iOrderByCol>0 );
116381:         if( pItem->u.x.iOrderByCol==i ) break;
116382:       }
116383:       if( j==nOrderBy ){
116384:         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
116385:         if( pNew==0 ) return SQLITE_NOMEM_BKPT;
116386:         pNew->flags |= EP_IntValue;
116387:         pNew->u.iValue = i;
116388:         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
116389:         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
116390:       }
116391:     }
116392:   }
116393: 
116394:   /* Compute the comparison permutation and keyinfo that is used with
116395:   ** the permutation used to determine if the next
116396:   ** row of results comes from selectA or selectB.  Also add explicit
116397:   ** collations to the ORDER BY clause terms so that when the subqueries
116398:   ** to the right and the left are evaluated, they use the correct
116399:   ** collation.
116400:   */
116401:   aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
116402:   if( aPermute ){
116403:     struct ExprList_item *pItem;
116404:     aPermute[0] = nOrderBy;
116405:     for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
116406:       assert( pItem->u.x.iOrderByCol>0 );
116407:       assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
116408:       aPermute[i] = pItem->u.x.iOrderByCol - 1;
116409:     }
116410:     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
116411:   }else{
116412:     pKeyMerge = 0;
116413:   }
116414: 
116415:   /* Reattach the ORDER BY clause to the query.
116416:   */
116417:   p->pOrderBy = pOrderBy;
116418:   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
116419: 
116420:   /* Allocate a range of temporary registers and the KeyInfo needed
116421:   ** for the logic that removes duplicate result rows when the
116422:   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
116423:   */
116424:   if( op==TK_ALL ){
116425:     regPrev = 0;
116426:   }else{
116427:     int nExpr = p->pEList->nExpr;
116428:     assert( nOrderBy>=nExpr || db->mallocFailed );
116429:     regPrev = pParse->nMem+1;
116430:     pParse->nMem += nExpr+1;
116431:     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
116432:     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
116433:     if( pKeyDup ){
116434:       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
116435:       for(i=0; i<nExpr; i++){
116436:         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
116437:         pKeyDup->aSortOrder[i] = 0;
116438:       }
116439:     }
116440:   }
116441:  
116442:   /* Separate the left and the right query from one another
116443:   */
116444:   p->pPrior = 0;
116445:   pPrior->pNext = 0;
116446:   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
116447:   if( pPrior->pPrior==0 ){
116448:     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
116449:   }
116450: 
116451:   /* Compute the limit registers */
116452:   computeLimitRegisters(pParse, p, labelEnd);
116453:   if( p->iLimit && op==TK_ALL ){
116454:     regLimitA = ++pParse->nMem;
116455:     regLimitB = ++pParse->nMem;
116456:     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
116457:                                   regLimitA);
116458:     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
116459:   }else{
116460:     regLimitA = regLimitB = 0;
116461:   }
116462:   sqlite3ExprDelete(db, p->pLimit);
116463:   p->pLimit = 0;
116464:   sqlite3ExprDelete(db, p->pOffset);
116465:   p->pOffset = 0;
116466: 
116467:   regAddrA = ++pParse->nMem;
116468:   regAddrB = ++pParse->nMem;
116469:   regOutA = ++pParse->nMem;
116470:   regOutB = ++pParse->nMem;
116471:   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
116472:   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
116473: 
116474:   /* Generate a coroutine to evaluate the SELECT statement to the
116475:   ** left of the compound operator - the "A" select.
116476:   */
116477:   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
116478:   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
116479:   VdbeComment((v, "left SELECT"));
116480:   pPrior->iLimit = regLimitA;
116481:   explainSetInteger(iSub1, pParse->iNextSelectId);
116482:   sqlite3Select(pParse, pPrior, &destA);
116483:   sqlite3VdbeEndCoroutine(v, regAddrA);
116484:   sqlite3VdbeJumpHere(v, addr1);
116485: 
116486:   /* Generate a coroutine to evaluate the SELECT statement on 
116487:   ** the right - the "B" select
116488:   */
116489:   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
116490:   addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
116491:   VdbeComment((v, "right SELECT"));
116492:   savedLimit = p->iLimit;
116493:   savedOffset = p->iOffset;
116494:   p->iLimit = regLimitB;
116495:   p->iOffset = 0;  
116496:   explainSetInteger(iSub2, pParse->iNextSelectId);
116497:   sqlite3Select(pParse, p, &destB);
116498:   p->iLimit = savedLimit;
116499:   p->iOffset = savedOffset;
116500:   sqlite3VdbeEndCoroutine(v, regAddrB);
116501: 
116502:   /* Generate a subroutine that outputs the current row of the A
116503:   ** select as the next output row of the compound select.
116504:   */
116505:   VdbeNoopComment((v, "Output routine for A"));
116506:   addrOutA = generateOutputSubroutine(pParse,
116507:                  p, &destA, pDest, regOutA,
116508:                  regPrev, pKeyDup, labelEnd);
116509:   
116510:   /* Generate a subroutine that outputs the current row of the B
116511:   ** select as the next output row of the compound select.
116512:   */
116513:   if( op==TK_ALL || op==TK_UNION ){
116514:     VdbeNoopComment((v, "Output routine for B"));
116515:     addrOutB = generateOutputSubroutine(pParse,
116516:                  p, &destB, pDest, regOutB,
116517:                  regPrev, pKeyDup, labelEnd);
116518:   }
116519:   sqlite3KeyInfoUnref(pKeyDup);
116520: 
116521:   /* Generate a subroutine to run when the results from select A
116522:   ** are exhausted and only data in select B remains.
116523:   */
116524:   if( op==TK_EXCEPT || op==TK_INTERSECT ){
116525:     addrEofA_noB = addrEofA = labelEnd;
116526:   }else{  
116527:     VdbeNoopComment((v, "eof-A subroutine"));
116528:     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
116529:     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
116530:                                      VdbeCoverage(v);
116531:     sqlite3VdbeGoto(v, addrEofA);
116532:     p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
116533:   }
116534: 
116535:   /* Generate a subroutine to run when the results from select B
116536:   ** are exhausted and only data in select A remains.
116537:   */
116538:   if( op==TK_INTERSECT ){
116539:     addrEofB = addrEofA;
116540:     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
116541:   }else{  
116542:     VdbeNoopComment((v, "eof-B subroutine"));
116543:     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
116544:     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
116545:     sqlite3VdbeGoto(v, addrEofB);
116546:   }
116547: 
116548:   /* Generate code to handle the case of A<B
116549:   */
116550:   VdbeNoopComment((v, "A-lt-B subroutine"));
116551:   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
116552:   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
116553:   sqlite3VdbeGoto(v, labelCmpr);
116554: 
116555:   /* Generate code to handle the case of A==B
116556:   */
116557:   if( op==TK_ALL ){
116558:     addrAeqB = addrAltB;
116559:   }else if( op==TK_INTERSECT ){
116560:     addrAeqB = addrAltB;
116561:     addrAltB++;
116562:   }else{
116563:     VdbeNoopComment((v, "A-eq-B subroutine"));
116564:     addrAeqB =
116565:     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
116566:     sqlite3VdbeGoto(v, labelCmpr);
116567:   }
116568: 
116569:   /* Generate code to handle the case of A>B
116570:   */
116571:   VdbeNoopComment((v, "A-gt-B subroutine"));
116572:   addrAgtB = sqlite3VdbeCurrentAddr(v);
116573:   if( op==TK_ALL || op==TK_UNION ){
116574:     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
116575:   }
116576:   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
116577:   sqlite3VdbeGoto(v, labelCmpr);
116578: 
116579:   /* This code runs once to initialize everything.
116580:   */
116581:   sqlite3VdbeJumpHere(v, addr1);
116582:   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
116583:   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
116584: 
116585:   /* Implement the main merge loop
116586:   */
116587:   sqlite3VdbeResolveLabel(v, labelCmpr);
116588:   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
116589:   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
116590:                          (char*)pKeyMerge, P4_KEYINFO);
116591:   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
116592:   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
116593: 
116594:   /* Jump to the this point in order to terminate the query.
116595:   */
116596:   sqlite3VdbeResolveLabel(v, labelEnd);
116597: 
116598:   /* Set the number of output columns
116599:   */
116600:   if( pDest->eDest==SRT_Output ){
116601:     Select *pFirst = pPrior;
116602:     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
116603:     generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
116604:   }
116605: 
116606:   /* Reassembly the compound query so that it will be freed correctly
116607:   ** by the calling function */
116608:   if( p->pPrior ){
116609:     sqlite3SelectDelete(db, p->pPrior);
116610:   }
116611:   p->pPrior = pPrior;
116612:   pPrior->pNext = p;
116613: 
116614:   /*** TBD:  Insert subroutine calls to close cursors on incomplete
116615:   **** subqueries ****/
116616:   explainComposite(pParse, p->op, iSub1, iSub2, 0);
116617:   return pParse->nErr!=0;
116618: }
116619: #endif
116620: 
116621: #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
116622: /* Forward Declarations */
116623: static void substExprList(sqlite3*, ExprList*, int, ExprList*);
116624: static void substSelect(sqlite3*, Select *, int, ExprList*, int);
116625: 
116626: /*
116627: ** Scan through the expression pExpr.  Replace every reference to
116628: ** a column in table number iTable with a copy of the iColumn-th
116629: ** entry in pEList.  (But leave references to the ROWID column 
116630: ** unchanged.)
116631: **
116632: ** This routine is part of the flattening procedure.  A subquery
116633: ** whose result set is defined by pEList appears as entry in the
116634: ** FROM clause of a SELECT such that the VDBE cursor assigned to that
116635: ** FORM clause entry is iTable.  This routine make the necessary 
116636: ** changes to pExpr so that it refers directly to the source table
116637: ** of the subquery rather the result set of the subquery.
116638: */
116639: static Expr *substExpr(
116640:   sqlite3 *db,        /* Report malloc errors to this connection */
116641:   Expr *pExpr,        /* Expr in which substitution occurs */
116642:   int iTable,         /* Table to be substituted */
116643:   ExprList *pEList    /* Substitute expressions */
116644: ){
116645:   if( pExpr==0 ) return 0;
116646:   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
116647:     if( pExpr->iColumn<0 ){
116648:       pExpr->op = TK_NULL;
116649:     }else{
116650:       Expr *pNew;
116651:       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
116652:       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
116653:       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
116654:       sqlite3ExprDelete(db, pExpr);
116655:       pExpr = pNew;
116656:     }
116657:   }else{
116658:     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
116659:     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
116660:     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
116661:       substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
116662:     }else{
116663:       substExprList(db, pExpr->x.pList, iTable, pEList);
116664:     }
116665:   }
116666:   return pExpr;
116667: }
116668: static void substExprList(
116669:   sqlite3 *db,         /* Report malloc errors here */
116670:   ExprList *pList,     /* List to scan and in which to make substitutes */
116671:   int iTable,          /* Table to be substituted */
116672:   ExprList *pEList     /* Substitute values */
116673: ){
116674:   int i;
116675:   if( pList==0 ) return;
116676:   for(i=0; i<pList->nExpr; i++){
116677:     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
116678:   }
116679: }
116680: static void substSelect(
116681:   sqlite3 *db,         /* Report malloc errors here */
116682:   Select *p,           /* SELECT statement in which to make substitutions */
116683:   int iTable,          /* Table to be replaced */
116684:   ExprList *pEList,    /* Substitute values */
116685:   int doPrior          /* Do substitutes on p->pPrior too */
116686: ){
116687:   SrcList *pSrc;
116688:   struct SrcList_item *pItem;
116689:   int i;
116690:   if( !p ) return;
116691:   do{
116692:     substExprList(db, p->pEList, iTable, pEList);
116693:     substExprList(db, p->pGroupBy, iTable, pEList);
116694:     substExprList(db, p->pOrderBy, iTable, pEList);
116695:     p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
116696:     p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
116697:     pSrc = p->pSrc;
116698:     assert( pSrc!=0 );
116699:     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
116700:       substSelect(db, pItem->pSelect, iTable, pEList, 1);
116701:       if( pItem->fg.isTabFunc ){
116702:         substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
116703:       }
116704:     }
116705:   }while( doPrior && (p = p->pPrior)!=0 );
116706: }
116707: #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
116708: 
116709: #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
116710: /*
116711: ** This routine attempts to flatten subqueries as a performance optimization.
116712: ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
116713: **
116714: ** To understand the concept of flattening, consider the following
116715: ** query:
116716: **
116717: **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
116718: **
116719: ** The default way of implementing this query is to execute the
116720: ** subquery first and store the results in a temporary table, then
116721: ** run the outer query on that temporary table.  This requires two
116722: ** passes over the data.  Furthermore, because the temporary table
116723: ** has no indices, the WHERE clause on the outer query cannot be
116724: ** optimized.
116725: **
116726: ** This routine attempts to rewrite queries such as the above into
116727: ** a single flat select, like this:
116728: **
116729: **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
116730: **
116731: ** The code generated for this simplification gives the same result
116732: ** but only has to scan the data once.  And because indices might 
116733: ** exist on the table t1, a complete scan of the data might be
116734: ** avoided.
116735: **
116736: ** Flattening is only attempted if all of the following are true:
116737: **
116738: **   (1)  The subquery and the outer query do not both use aggregates.
116739: **
116740: **   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
116741: **        and (2b) the outer query does not use subqueries other than the one
116742: **        FROM-clause subquery that is a candidate for flattening.  (2b is
116743: **        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
116744: **
116745: **   (3)  The subquery is not the right operand of a left outer join
116746: **        (Originally ticket #306.  Strengthened by ticket #3300)
116747: **
116748: **   (4)  The subquery is not DISTINCT.
116749: **
116750: **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
116751: **        sub-queries that were excluded from this optimization. Restriction 
116752: **        (4) has since been expanded to exclude all DISTINCT subqueries.
116753: **
116754: **   (6)  The subquery does not use aggregates or the outer query is not
116755: **        DISTINCT.
116756: **
116757: **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
116758: **        A FROM clause, consider adding a FROM close with the special
116759: **        table sqlite_once that consists of a single row containing a
116760: **        single NULL.
116761: **
116762: **   (8)  The subquery does not use LIMIT or the outer query is not a join.
116763: **
116764: **   (9)  The subquery does not use LIMIT or the outer query does not use
116765: **        aggregates.
116766: **
116767: **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
116768: **        accidently carried the comment forward until 2014-09-15.  Original
116769: **        text: "The subquery does not use aggregates or the outer query 
116770: **        does not use LIMIT."
116771: **
116772: **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
116773: **
116774: **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
116775: **        a separate restriction deriving from ticket #350.
116776: **
116777: **  (13)  The subquery and outer query do not both use LIMIT.
116778: **
116779: **  (14)  The subquery does not use OFFSET.
116780: **
116781: **  (15)  The outer query is not part of a compound select or the
116782: **        subquery does not have a LIMIT clause.
116783: **        (See ticket #2339 and ticket [02a8e81d44]).
116784: **
116785: **  (16)  The outer query is not an aggregate or the subquery does
116786: **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
116787: **        until we introduced the group_concat() function.  
116788: **
116789: **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
116790: **        compound clause made up entirely of non-aggregate queries, and 
116791: **        the parent query:
116792: **
116793: **          * is not itself part of a compound select,
116794: **          * is not an aggregate or DISTINCT query, and
116795: **          * is not a join
116796: **
116797: **        The parent and sub-query may contain WHERE clauses. Subject to
116798: **        rules (11), (13) and (14), they may also contain ORDER BY,
116799: **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
116800: **        operator other than UNION ALL because all the other compound
116801: **        operators have an implied DISTINCT which is disallowed by
116802: **        restriction (4).
116803: **
116804: **        Also, each component of the sub-query must return the same number
116805: **        of result columns. This is actually a requirement for any compound
116806: **        SELECT statement, but all the code here does is make sure that no
116807: **        such (illegal) sub-query is flattened. The caller will detect the
116808: **        syntax error and return a detailed message.
116809: **
116810: **  (18)  If the sub-query is a compound select, then all terms of the
116811: **        ORDER by clause of the parent must be simple references to 
116812: **        columns of the sub-query.
116813: **
116814: **  (19)  The subquery does not use LIMIT or the outer query does not
116815: **        have a WHERE clause.
116816: **
116817: **  (20)  If the sub-query is a compound select, then it must not use
116818: **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
116819: **        somewhat by saying that the terms of the ORDER BY clause must
116820: **        appear as unmodified result columns in the outer query.  But we
116821: **        have other optimizations in mind to deal with that case.
116822: **
116823: **  (21)  The subquery does not use LIMIT or the outer query is not
116824: **        DISTINCT.  (See ticket [752e1646fc]).
116825: **
116826: **  (22)  The subquery is not a recursive CTE.
116827: **
116828: **  (23)  The parent is not a recursive CTE, or the sub-query is not a
116829: **        compound query. This restriction is because transforming the
116830: **        parent to a compound query confuses the code that handles
116831: **        recursive queries in multiSelect().
116832: **
116833: **  (24)  The subquery is not an aggregate that uses the built-in min() or 
116834: **        or max() functions.  (Without this restriction, a query like:
116835: **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
116836: **        return the value X for which Y was maximal.)
116837: **
116838: **
116839: ** In this routine, the "p" parameter is a pointer to the outer query.
116840: ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
116841: ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
116842: **
116843: ** If flattening is not attempted, this routine is a no-op and returns 0.
116844: ** If flattening is attempted this routine returns 1.
116845: **
116846: ** All of the expression analysis must occur on both the outer query and
116847: ** the subquery before this routine runs.
116848: */
116849: static int flattenSubquery(
116850:   Parse *pParse,       /* Parsing context */
116851:   Select *p,           /* The parent or outer SELECT statement */
116852:   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
116853:   int isAgg,           /* True if outer SELECT uses aggregate functions */
116854:   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
116855: ){
116856:   const char *zSavedAuthContext = pParse->zAuthContext;
116857:   Select *pParent;    /* Current UNION ALL term of the other query */
116858:   Select *pSub;       /* The inner query or "subquery" */
116859:   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
116860:   SrcList *pSrc;      /* The FROM clause of the outer query */
116861:   SrcList *pSubSrc;   /* The FROM clause of the subquery */
116862:   ExprList *pList;    /* The result set of the outer query */
116863:   int iParent;        /* VDBE cursor number of the pSub result set temp table */
116864:   int i;              /* Loop counter */
116865:   Expr *pWhere;                    /* The WHERE clause */
116866:   struct SrcList_item *pSubitem;   /* The subquery */
116867:   sqlite3 *db = pParse->db;
116868: 
116869:   /* Check to see if flattening is permitted.  Return 0 if not.
116870:   */
116871:   assert( p!=0 );
116872:   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
116873:   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
116874:   pSrc = p->pSrc;
116875:   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
116876:   pSubitem = &pSrc->a[iFrom];
116877:   iParent = pSubitem->iCursor;
116878:   pSub = pSubitem->pSelect;
116879:   assert( pSub!=0 );
116880:   if( subqueryIsAgg ){
116881:     if( isAgg ) return 0;                                /* Restriction (1)   */
116882:     if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
116883:     if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
116884:      || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
116885:      || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
116886:     ){
116887:       return 0;                                          /* Restriction (2b)  */
116888:     }
116889:   }
116890:     
116891:   pSubSrc = pSub->pSrc;
116892:   assert( pSubSrc );
116893:   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
116894:   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
116895:   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
116896:   ** became arbitrary expressions, we were forced to add restrictions (13)
116897:   ** and (14). */
116898:   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
116899:   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
116900:   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
116901:     return 0;                                            /* Restriction (15) */
116902:   }
116903:   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
116904:   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
116905:   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
116906:      return 0;         /* Restrictions (8)(9) */
116907:   }
116908:   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
116909:      return 0;         /* Restriction (6)  */
116910:   }
116911:   if( p->pOrderBy && pSub->pOrderBy ){
116912:      return 0;                                           /* Restriction (11) */
116913:   }
116914:   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
116915:   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
116916:   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
116917:      return 0;         /* Restriction (21) */
116918:   }
116919:   testcase( pSub->selFlags & SF_Recursive );
116920:   testcase( pSub->selFlags & SF_MinMaxAgg );
116921:   if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
116922:     return 0; /* Restrictions (22) and (24) */
116923:   }
116924:   if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
116925:     return 0; /* Restriction (23) */
116926:   }
116927: 
116928:   /* OBSOLETE COMMENT 1:
116929:   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
116930:   ** not used as the right operand of an outer join.  Examples of why this
116931:   ** is not allowed:
116932:   **
116933:   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
116934:   **
116935:   ** If we flatten the above, we would get
116936:   **
116937:   **         (t1 LEFT OUTER JOIN t2) JOIN t3
116938:   **
116939:   ** which is not at all the same thing.
116940:   **
116941:   ** OBSOLETE COMMENT 2:
116942:   ** Restriction 12:  If the subquery is the right operand of a left outer
116943:   ** join, make sure the subquery has no WHERE clause.
116944:   ** An examples of why this is not allowed:
116945:   **
116946:   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
116947:   **
116948:   ** If we flatten the above, we would get
116949:   **
116950:   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
116951:   **
116952:   ** But the t2.x>0 test will always fail on a NULL row of t2, which
116953:   ** effectively converts the OUTER JOIN into an INNER JOIN.
116954:   **
116955:   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
116956:   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
116957:   ** is fraught with danger.  Best to avoid the whole thing.  If the
116958:   ** subquery is the right term of a LEFT JOIN, then do not flatten.
116959:   */
116960:   if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
116961:     return 0;
116962:   }
116963: 
116964:   /* Restriction 17: If the sub-query is a compound SELECT, then it must
116965:   ** use only the UNION ALL operator. And none of the simple select queries
116966:   ** that make up the compound SELECT are allowed to be aggregate or distinct
116967:   ** queries.
116968:   */
116969:   if( pSub->pPrior ){
116970:     if( pSub->pOrderBy ){
116971:       return 0;  /* Restriction 20 */
116972:     }
116973:     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
116974:       return 0;
116975:     }
116976:     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
116977:       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
116978:       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
116979:       assert( pSub->pSrc!=0 );
116980:       assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
116981:       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
116982:        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
116983:        || pSub1->pSrc->nSrc<1
116984:       ){
116985:         return 0;
116986:       }
116987:       testcase( pSub1->pSrc->nSrc>1 );
116988:     }
116989: 
116990:     /* Restriction 18. */
116991:     if( p->pOrderBy ){
116992:       int ii;
116993:       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
116994:         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
116995:       }
116996:     }
116997:   }
116998: 
116999:   /***** If we reach this point, flattening is permitted. *****/
117000:   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
117001:                    pSub->zSelName, pSub, iFrom));
117002: 
117003:   /* Authorize the subquery */
117004:   pParse->zAuthContext = pSubitem->zName;
117005:   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
117006:   testcase( i==SQLITE_DENY );
117007:   pParse->zAuthContext = zSavedAuthContext;
117008: 
117009:   /* If the sub-query is a compound SELECT statement, then (by restrictions
117010:   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
117011:   ** be of the form:
117012:   **
117013:   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
117014:   **
117015:   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
117016:   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
117017:   ** OFFSET clauses and joins them to the left-hand-side of the original
117018:   ** using UNION ALL operators. In this case N is the number of simple
117019:   ** select statements in the compound sub-query.
117020:   **
117021:   ** Example:
117022:   **
117023:   **     SELECT a+1 FROM (
117024:   **        SELECT x FROM tab
117025:   **        UNION ALL
117026:   **        SELECT y FROM tab
117027:   **        UNION ALL
117028:   **        SELECT abs(z*2) FROM tab2
117029:   **     ) WHERE a!=5 ORDER BY 1
117030:   **
117031:   ** Transformed into:
117032:   **
117033:   **     SELECT x+1 FROM tab WHERE x+1!=5
117034:   **     UNION ALL
117035:   **     SELECT y+1 FROM tab WHERE y+1!=5
117036:   **     UNION ALL
117037:   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
117038:   **     ORDER BY 1
117039:   **
117040:   ** We call this the "compound-subquery flattening".
117041:   */
117042:   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
117043:     Select *pNew;
117044:     ExprList *pOrderBy = p->pOrderBy;
117045:     Expr *pLimit = p->pLimit;
117046:     Expr *pOffset = p->pOffset;
117047:     Select *pPrior = p->pPrior;
117048:     p->pOrderBy = 0;
117049:     p->pSrc = 0;
117050:     p->pPrior = 0;
117051:     p->pLimit = 0;
117052:     p->pOffset = 0;
117053:     pNew = sqlite3SelectDup(db, p, 0);
117054:     sqlite3SelectSetName(pNew, pSub->zSelName);
117055:     p->pOffset = pOffset;
117056:     p->pLimit = pLimit;
117057:     p->pOrderBy = pOrderBy;
117058:     p->pSrc = pSrc;
117059:     p->op = TK_ALL;
117060:     if( pNew==0 ){
117061:       p->pPrior = pPrior;
117062:     }else{
117063:       pNew->pPrior = pPrior;
117064:       if( pPrior ) pPrior->pNext = pNew;
117065:       pNew->pNext = p;
117066:       p->pPrior = pNew;
117067:       SELECTTRACE(2,pParse,p,
117068:          ("compound-subquery flattener creates %s.%p as peer\n",
117069:          pNew->zSelName, pNew));
117070:     }
117071:     if( db->mallocFailed ) return 1;
117072:   }
117073: 
117074:   /* Begin flattening the iFrom-th entry of the FROM clause 
117075:   ** in the outer query.
117076:   */
117077:   pSub = pSub1 = pSubitem->pSelect;
117078: 
117079:   /* Delete the transient table structure associated with the
117080:   ** subquery
117081:   */
117082:   sqlite3DbFree(db, pSubitem->zDatabase);
117083:   sqlite3DbFree(db, pSubitem->zName);
117084:   sqlite3DbFree(db, pSubitem->zAlias);
117085:   pSubitem->zDatabase = 0;
117086:   pSubitem->zName = 0;
117087:   pSubitem->zAlias = 0;
117088:   pSubitem->pSelect = 0;
117089: 
117090:   /* Defer deleting the Table object associated with the
117091:   ** subquery until code generation is
117092:   ** complete, since there may still exist Expr.pTab entries that
117093:   ** refer to the subquery even after flattening.  Ticket #3346.
117094:   **
117095:   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
117096:   */
117097:   if( ALWAYS(pSubitem->pTab!=0) ){
117098:     Table *pTabToDel = pSubitem->pTab;
117099:     if( pTabToDel->nRef==1 ){
117100:       Parse *pToplevel = sqlite3ParseToplevel(pParse);
117101:       pTabToDel->pNextZombie = pToplevel->pZombieTab;
117102:       pToplevel->pZombieTab = pTabToDel;
117103:     }else{
117104:       pTabToDel->nRef--;
117105:     }
117106:     pSubitem->pTab = 0;
117107:   }
117108: 
117109:   /* The following loop runs once for each term in a compound-subquery
117110:   ** flattening (as described above).  If we are doing a different kind
117111:   ** of flattening - a flattening other than a compound-subquery flattening -
117112:   ** then this loop only runs once.
117113:   **
117114:   ** This loop moves all of the FROM elements of the subquery into the
117115:   ** the FROM clause of the outer query.  Before doing this, remember
117116:   ** the cursor number for the original outer query FROM element in
117117:   ** iParent.  The iParent cursor will never be used.  Subsequent code
117118:   ** will scan expressions looking for iParent references and replace
117119:   ** those references with expressions that resolve to the subquery FROM
117120:   ** elements we are now copying in.
117121:   */
117122:   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
117123:     int nSubSrc;
117124:     u8 jointype = 0;
117125:     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
117126:     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
117127:     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
117128: 
117129:     if( pSrc ){
117130:       assert( pParent==p );  /* First time through the loop */
117131:       jointype = pSubitem->fg.jointype;
117132:     }else{
117133:       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
117134:       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
117135:       if( pSrc==0 ){
117136:         assert( db->mallocFailed );
117137:         break;
117138:       }
117139:     }
117140: 
117141:     /* The subquery uses a single slot of the FROM clause of the outer
117142:     ** query.  If the subquery has more than one element in its FROM clause,
117143:     ** then expand the outer query to make space for it to hold all elements
117144:     ** of the subquery.
117145:     **
117146:     ** Example:
117147:     **
117148:     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
117149:     **
117150:     ** The outer query has 3 slots in its FROM clause.  One slot of the
117151:     ** outer query (the middle slot) is used by the subquery.  The next
117152:     ** block of code will expand the outer query FROM clause to 4 slots.
117153:     ** The middle slot is expanded to two slots in order to make space
117154:     ** for the two elements in the FROM clause of the subquery.
117155:     */
117156:     if( nSubSrc>1 ){
117157:       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
117158:       if( db->mallocFailed ){
117159:         break;
117160:       }
117161:     }
117162: 
117163:     /* Transfer the FROM clause terms from the subquery into the
117164:     ** outer query.
117165:     */
117166:     for(i=0; i<nSubSrc; i++){
117167:       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
117168:       assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
117169:       pSrc->a[i+iFrom] = pSubSrc->a[i];
117170:       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
117171:     }
117172:     pSrc->a[iFrom].fg.jointype = jointype;
117173:   
117174:     /* Now begin substituting subquery result set expressions for 
117175:     ** references to the iParent in the outer query.
117176:     ** 
117177:     ** Example:
117178:     **
117179:     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
117180:     **   \                     \_____________ subquery __________/          /
117181:     **    \_____________________ outer query ______________________________/
117182:     **
117183:     ** We look at every expression in the outer query and every place we see
117184:     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
117185:     */
117186:     pList = pParent->pEList;
117187:     for(i=0; i<pList->nExpr; i++){
117188:       if( pList->a[i].zName==0 ){
117189:         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
117190:         sqlite3Dequote(zName);
117191:         pList->a[i].zName = zName;
117192:       }
117193:     }
117194:     if( pSub->pOrderBy ){
117195:       /* At this point, any non-zero iOrderByCol values indicate that the
117196:       ** ORDER BY column expression is identical to the iOrderByCol'th
117197:       ** expression returned by SELECT statement pSub. Since these values
117198:       ** do not necessarily correspond to columns in SELECT statement pParent,
117199:       ** zero them before transfering the ORDER BY clause.
117200:       **
117201:       ** Not doing this may cause an error if a subsequent call to this
117202:       ** function attempts to flatten a compound sub-query into pParent
117203:       ** (the only way this can happen is if the compound sub-query is
117204:       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
117205:       ExprList *pOrderBy = pSub->pOrderBy;
117206:       for(i=0; i<pOrderBy->nExpr; i++){
117207:         pOrderBy->a[i].u.x.iOrderByCol = 0;
117208:       }
117209:       assert( pParent->pOrderBy==0 );
117210:       assert( pSub->pPrior==0 );
117211:       pParent->pOrderBy = pOrderBy;
117212:       pSub->pOrderBy = 0;
117213:     }
117214:     pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
117215:     if( subqueryIsAgg ){
117216:       assert( pParent->pHaving==0 );
117217:       pParent->pHaving = pParent->pWhere;
117218:       pParent->pWhere = pWhere;
117219:       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
117220:                                   sqlite3ExprDup(db, pSub->pHaving, 0));
117221:       assert( pParent->pGroupBy==0 );
117222:       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
117223:     }else{
117224:       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
117225:     }
117226:     substSelect(db, pParent, iParent, pSub->pEList, 0);
117227:   
117228:     /* The flattened query is distinct if either the inner or the
117229:     ** outer query is distinct. 
117230:     */
117231:     pParent->selFlags |= pSub->selFlags & SF_Distinct;
117232:   
117233:     /*
117234:     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
117235:     **
117236:     ** One is tempted to try to add a and b to combine the limits.  But this
117237:     ** does not work if either limit is negative.
117238:     */
117239:     if( pSub->pLimit ){
117240:       pParent->pLimit = pSub->pLimit;
117241:       pSub->pLimit = 0;
117242:     }
117243:   }
117244: 
117245:   /* Finially, delete what is left of the subquery and return
117246:   ** success.
117247:   */
117248:   sqlite3SelectDelete(db, pSub1);
117249: 
117250: #if SELECTTRACE_ENABLED
117251:   if( sqlite3SelectTrace & 0x100 ){
117252:     SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
117253:     sqlite3TreeViewSelect(0, p, 0);
117254:   }
117255: #endif
117256: 
117257:   return 1;
117258: }
117259: #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117260: 
117261: 
117262: 
117263: #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117264: /*
117265: ** Make copies of relevant WHERE clause terms of the outer query into
117266: ** the WHERE clause of subquery.  Example:
117267: **
117268: **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
117269: **
117270: ** Transformed into:
117271: **
117272: **    SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
117273: **     WHERE x=5 AND y=10;
117274: **
117275: ** The hope is that the terms added to the inner query will make it more
117276: ** efficient.
117277: **
117278: ** Do not attempt this optimization if:
117279: **
117280: **   (1) The inner query is an aggregate.  (In that case, we'd really want
117281: **       to copy the outer WHERE-clause terms onto the HAVING clause of the
117282: **       inner query.  But they probably won't help there so do not bother.)
117283: **
117284: **   (2) The inner query is the recursive part of a common table expression.
117285: **
117286: **   (3) The inner query has a LIMIT clause (since the changes to the WHERE
117287: **       close would change the meaning of the LIMIT).
117288: **
117289: **   (4) The inner query is the right operand of a LEFT JOIN.  (The caller
117290: **       enforces this restriction since this routine does not have enough
117291: **       information to know.)
117292: **
117293: **   (5) The WHERE clause expression originates in the ON or USING clause
117294: **       of a LEFT JOIN.
117295: **
117296: ** Return 0 if no changes are made and non-zero if one or more WHERE clause
117297: ** terms are duplicated into the subquery.
117298: */
117299: static int pushDownWhereTerms(
117300:   sqlite3 *db,          /* The database connection (for malloc()) */
117301:   Select *pSubq,        /* The subquery whose WHERE clause is to be augmented */
117302:   Expr *pWhere,         /* The WHERE clause of the outer query */
117303:   int iCursor           /* Cursor number of the subquery */
117304: ){
117305:   Expr *pNew;
117306:   int nChng = 0;
117307:   Select *pX;           /* For looping over compound SELECTs in pSubq */
117308:   if( pWhere==0 ) return 0;
117309:   for(pX=pSubq; pX; pX=pX->pPrior){
117310:     if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
117311:       testcase( pX->selFlags & SF_Aggregate );
117312:       testcase( pX->selFlags & SF_Recursive );
117313:       testcase( pX!=pSubq );
117314:       return 0; /* restrictions (1) and (2) */
117315:     }
117316:   }
117317:   if( pSubq->pLimit!=0 ){
117318:     return 0; /* restriction (3) */
117319:   }
117320:   while( pWhere->op==TK_AND ){
117321:     nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
117322:     pWhere = pWhere->pLeft;
117323:   }
117324:   if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
117325:   if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
117326:     nChng++;
117327:     while( pSubq ){
117328:       pNew = sqlite3ExprDup(db, pWhere, 0);
117329:       pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
117330:       pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
117331:       pSubq = pSubq->pPrior;
117332:     }
117333:   }
117334:   return nChng;
117335: }
117336: #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
117337: 
117338: /*
117339: ** Based on the contents of the AggInfo structure indicated by the first
117340: ** argument, this function checks if the following are true:
117341: **
117342: **    * the query contains just a single aggregate function,
117343: **    * the aggregate function is either min() or max(), and
117344: **    * the argument to the aggregate function is a column value.
117345: **
117346: ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
117347: ** is returned as appropriate. Also, *ppMinMax is set to point to the 
117348: ** list of arguments passed to the aggregate before returning.
117349: **
117350: ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
117351: ** WHERE_ORDERBY_NORMAL is returned.
117352: */
117353: static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
117354:   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
117355: 
117356:   *ppMinMax = 0;
117357:   if( pAggInfo->nFunc==1 ){
117358:     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
117359:     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
117360: 
117361:     assert( pExpr->op==TK_AGG_FUNCTION );
117362:     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
117363:       const char *zFunc = pExpr->u.zToken;
117364:       if( sqlite3StrICmp(zFunc, "min")==0 ){
117365:         eRet = WHERE_ORDERBY_MIN;
117366:         *ppMinMax = pEList;
117367:       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
117368:         eRet = WHERE_ORDERBY_MAX;
117369:         *ppMinMax = pEList;
117370:       }
117371:     }
117372:   }
117373: 
117374:   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
117375:   return eRet;
117376: }
117377: 
117378: /*
117379: ** The select statement passed as the first argument is an aggregate query.
117380: ** The second argument is the associated aggregate-info object. This 
117381: ** function tests if the SELECT is of the form:
117382: **
117383: **   SELECT count(*) FROM <tbl>
117384: **
117385: ** where table is a database table, not a sub-select or view. If the query
117386: ** does match this pattern, then a pointer to the Table object representing
117387: ** <tbl> is returned. Otherwise, 0 is returned.
117388: */
117389: static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
117390:   Table *pTab;
117391:   Expr *pExpr;
117392: 
117393:   assert( !p->pGroupBy );
117394: 
117395:   if( p->pWhere || p->pEList->nExpr!=1 
117396:    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
117397:   ){
117398:     return 0;
117399:   }
117400:   pTab = p->pSrc->a[0].pTab;
117401:   pExpr = p->pEList->a[0].pExpr;
117402:   assert( pTab && !pTab->pSelect && pExpr );
117403: 
117404:   if( IsVirtual(pTab) ) return 0;
117405:   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
117406:   if( NEVER(pAggInfo->nFunc==0) ) return 0;
117407:   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
117408:   if( pExpr->flags&EP_Distinct ) return 0;
117409: 
117410:   return pTab;
117411: }
117412: 
117413: /*
117414: ** If the source-list item passed as an argument was augmented with an
117415: ** INDEXED BY clause, then try to locate the specified index. If there
117416: ** was such a clause and the named index cannot be found, return 
117417: ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
117418: ** pFrom->pIndex and return SQLITE_OK.
117419: */
117420: SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
117421:   if( pFrom->pTab && pFrom->fg.isIndexedBy ){
117422:     Table *pTab = pFrom->pTab;
117423:     char *zIndexedBy = pFrom->u1.zIndexedBy;
117424:     Index *pIdx;
117425:     for(pIdx=pTab->pIndex; 
117426:         pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy); 
117427:         pIdx=pIdx->pNext
117428:     );
117429:     if( !pIdx ){
117430:       sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
117431:       pParse->checkSchema = 1;
117432:       return SQLITE_ERROR;
117433:     }
117434:     pFrom->pIBIndex = pIdx;
117435:   }
117436:   return SQLITE_OK;
117437: }
117438: /*
117439: ** Detect compound SELECT statements that use an ORDER BY clause with 
117440: ** an alternative collating sequence.
117441: **
117442: **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
117443: **
117444: ** These are rewritten as a subquery:
117445: **
117446: **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
117447: **     ORDER BY ... COLLATE ...
117448: **
117449: ** This transformation is necessary because the multiSelectOrderBy() routine
117450: ** above that generates the code for a compound SELECT with an ORDER BY clause
117451: ** uses a merge algorithm that requires the same collating sequence on the
117452: ** result columns as on the ORDER BY clause.  See ticket
117453: ** http://www.sqlite.org/src/info/6709574d2a
117454: **
117455: ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
117456: ** The UNION ALL operator works fine with multiSelectOrderBy() even when
117457: ** there are COLLATE terms in the ORDER BY.
117458: */
117459: static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
117460:   int i;
117461:   Select *pNew;
117462:   Select *pX;
117463:   sqlite3 *db;
117464:   struct ExprList_item *a;
117465:   SrcList *pNewSrc;
117466:   Parse *pParse;
117467:   Token dummy;
117468: 
117469:   if( p->pPrior==0 ) return WRC_Continue;
117470:   if( p->pOrderBy==0 ) return WRC_Continue;
117471:   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
117472:   if( pX==0 ) return WRC_Continue;
117473:   a = p->pOrderBy->a;
117474:   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
117475:     if( a[i].pExpr->flags & EP_Collate ) break;
117476:   }
117477:   if( i<0 ) return WRC_Continue;
117478: 
117479:   /* If we reach this point, that means the transformation is required. */
117480: 
117481:   pParse = pWalker->pParse;
117482:   db = pParse->db;
117483:   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
117484:   if( pNew==0 ) return WRC_Abort;
117485:   memset(&dummy, 0, sizeof(dummy));
117486:   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
117487:   if( pNewSrc==0 ) return WRC_Abort;
117488:   *pNew = *p;
117489:   p->pSrc = pNewSrc;
117490:   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
117491:   p->op = TK_SELECT;
117492:   p->pWhere = 0;
117493:   pNew->pGroupBy = 0;
117494:   pNew->pHaving = 0;
117495:   pNew->pOrderBy = 0;
117496:   p->pPrior = 0;
117497:   p->pNext = 0;
117498:   p->pWith = 0;
117499:   p->selFlags &= ~SF_Compound;
117500:   assert( (p->selFlags & SF_Converted)==0 );
117501:   p->selFlags |= SF_Converted;
117502:   assert( pNew->pPrior!=0 );
117503:   pNew->pPrior->pNext = pNew;
117504:   pNew->pLimit = 0;
117505:   pNew->pOffset = 0;
117506:   return WRC_Continue;
117507: }
117508: 
117509: /*
117510: ** Check to see if the FROM clause term pFrom has table-valued function
117511: ** arguments.  If it does, leave an error message in pParse and return
117512: ** non-zero, since pFrom is not allowed to be a table-valued function.
117513: */
117514: static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
117515:   if( pFrom->fg.isTabFunc ){
117516:     sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
117517:     return 1;
117518:   }
117519:   return 0;
117520: }
117521: 
117522: #ifndef SQLITE_OMIT_CTE
117523: /*
117524: ** Argument pWith (which may be NULL) points to a linked list of nested 
117525: ** WITH contexts, from inner to outermost. If the table identified by 
117526: ** FROM clause element pItem is really a common-table-expression (CTE) 
117527: ** then return a pointer to the CTE definition for that table. Otherwise
117528: ** return NULL.
117529: **
117530: ** If a non-NULL value is returned, set *ppContext to point to the With
117531: ** object that the returned CTE belongs to.
117532: */
117533: static struct Cte *searchWith(
117534:   With *pWith,                    /* Current innermost WITH clause */
117535:   struct SrcList_item *pItem,     /* FROM clause element to resolve */
117536:   With **ppContext                /* OUT: WITH clause return value belongs to */
117537: ){
117538:   const char *zName;
117539:   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
117540:     With *p;
117541:     for(p=pWith; p; p=p->pOuter){
117542:       int i;
117543:       for(i=0; i<p->nCte; i++){
117544:         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
117545:           *ppContext = p;
117546:           return &p->a[i];
117547:         }
117548:       }
117549:     }
117550:   }
117551:   return 0;
117552: }
117553: 
117554: /* The code generator maintains a stack of active WITH clauses
117555: ** with the inner-most WITH clause being at the top of the stack.
117556: **
117557: ** This routine pushes the WITH clause passed as the second argument
117558: ** onto the top of the stack. If argument bFree is true, then this
117559: ** WITH clause will never be popped from the stack. In this case it
117560: ** should be freed along with the Parse object. In other cases, when
117561: ** bFree==0, the With object will be freed along with the SELECT 
117562: ** statement with which it is associated.
117563: */
117564: SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
117565:   assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
117566:   if( pWith ){
117567:     assert( pParse->pWith!=pWith );
117568:     pWith->pOuter = pParse->pWith;
117569:     pParse->pWith = pWith;
117570:     if( bFree ) pParse->pWithToFree = pWith;
117571:   }
117572: }
117573: 
117574: /*
117575: ** This function checks if argument pFrom refers to a CTE declared by 
117576: ** a WITH clause on the stack currently maintained by the parser. And,
117577: ** if currently processing a CTE expression, if it is a recursive
117578: ** reference to the current CTE.
117579: **
117580: ** If pFrom falls into either of the two categories above, pFrom->pTab
117581: ** and other fields are populated accordingly. The caller should check
117582: ** (pFrom->pTab!=0) to determine whether or not a successful match
117583: ** was found.
117584: **
117585: ** Whether or not a match is found, SQLITE_OK is returned if no error
117586: ** occurs. If an error does occur, an error message is stored in the
117587: ** parser and some error code other than SQLITE_OK returned.
117588: */
117589: static int withExpand(
117590:   Walker *pWalker, 
117591:   struct SrcList_item *pFrom
117592: ){
117593:   Parse *pParse = pWalker->pParse;
117594:   sqlite3 *db = pParse->db;
117595:   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
117596:   With *pWith;                    /* WITH clause that pCte belongs to */
117597: 
117598:   assert( pFrom->pTab==0 );
117599: 
117600:   pCte = searchWith(pParse->pWith, pFrom, &pWith);
117601:   if( pCte ){
117602:     Table *pTab;
117603:     ExprList *pEList;
117604:     Select *pSel;
117605:     Select *pLeft;                /* Left-most SELECT statement */
117606:     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
117607:     With *pSavedWith;             /* Initial value of pParse->pWith */
117608: 
117609:     /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
117610:     ** recursive reference to CTE pCte. Leave an error in pParse and return
117611:     ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
117612:     ** In this case, proceed.  */
117613:     if( pCte->zCteErr ){
117614:       sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
117615:       return SQLITE_ERROR;
117616:     }
117617:     if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
117618: 
117619:     assert( pFrom->pTab==0 );
117620:     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
117621:     if( pTab==0 ) return WRC_Abort;
117622:     pTab->nRef = 1;
117623:     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
117624:     pTab->iPKey = -1;
117625:     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
117626:     pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
117627:     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
117628:     if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
117629:     assert( pFrom->pSelect );
117630: 
117631:     /* Check if this is a recursive CTE. */
117632:     pSel = pFrom->pSelect;
117633:     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
117634:     if( bMayRecursive ){
117635:       int i;
117636:       SrcList *pSrc = pFrom->pSelect->pSrc;
117637:       for(i=0; i<pSrc->nSrc; i++){
117638:         struct SrcList_item *pItem = &pSrc->a[i];
117639:         if( pItem->zDatabase==0 
117640:          && pItem->zName!=0 
117641:          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
117642:           ){
117643:           pItem->pTab = pTab;
117644:           pItem->fg.isRecursive = 1;
117645:           pTab->nRef++;
117646:           pSel->selFlags |= SF_Recursive;
117647:         }
117648:       }
117649:     }
117650: 
117651:     /* Only one recursive reference is permitted. */ 
117652:     if( pTab->nRef>2 ){
117653:       sqlite3ErrorMsg(
117654:           pParse, "multiple references to recursive table: %s", pCte->zName
117655:       );
117656:       return SQLITE_ERROR;
117657:     }
117658:     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
117659: 
117660:     pCte->zCteErr = "circular reference: %s";
117661:     pSavedWith = pParse->pWith;
117662:     pParse->pWith = pWith;
117663:     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
117664:     pParse->pWith = pWith;
117665: 
117666:     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
117667:     pEList = pLeft->pEList;
117668:     if( pCte->pCols ){
117669:       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
117670:         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
117671:             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
117672:         );
117673:         pParse->pWith = pSavedWith;
117674:         return SQLITE_ERROR;
117675:       }
117676:       pEList = pCte->pCols;
117677:     }
117678: 
117679:     sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
117680:     if( bMayRecursive ){
117681:       if( pSel->selFlags & SF_Recursive ){
117682:         pCte->zCteErr = "multiple recursive references: %s";
117683:       }else{
117684:         pCte->zCteErr = "recursive reference in a subquery: %s";
117685:       }
117686:       sqlite3WalkSelect(pWalker, pSel);
117687:     }
117688:     pCte->zCteErr = 0;
117689:     pParse->pWith = pSavedWith;
117690:   }
117691: 
117692:   return SQLITE_OK;
117693: }
117694: #endif
117695: 
117696: #ifndef SQLITE_OMIT_CTE
117697: /*
117698: ** If the SELECT passed as the second argument has an associated WITH 
117699: ** clause, pop it from the stack stored as part of the Parse object.
117700: **
117701: ** This function is used as the xSelectCallback2() callback by
117702: ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
117703: ** names and other FROM clause elements. 
117704: */
117705: static void selectPopWith(Walker *pWalker, Select *p){
117706:   Parse *pParse = pWalker->pParse;
117707:   With *pWith = findRightmost(p)->pWith;
117708:   if( pWith!=0 ){
117709:     assert( pParse->pWith==pWith );
117710:     pParse->pWith = pWith->pOuter;
117711:   }
117712: }
117713: #else
117714: #define selectPopWith 0
117715: #endif
117716: 
117717: /*
117718: ** This routine is a Walker callback for "expanding" a SELECT statement.
117719: ** "Expanding" means to do the following:
117720: **
117721: **    (1)  Make sure VDBE cursor numbers have been assigned to every
117722: **         element of the FROM clause.
117723: **
117724: **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
117725: **         defines FROM clause.  When views appear in the FROM clause,
117726: **         fill pTabList->a[].pSelect with a copy of the SELECT statement
117727: **         that implements the view.  A copy is made of the view's SELECT
117728: **         statement so that we can freely modify or delete that statement
117729: **         without worrying about messing up the persistent representation
117730: **         of the view.
117731: **
117732: **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
117733: **         on joins and the ON and USING clause of joins.
117734: **
117735: **    (4)  Scan the list of columns in the result set (pEList) looking
117736: **         for instances of the "*" operator or the TABLE.* operator.
117737: **         If found, expand each "*" to be every column in every table
117738: **         and TABLE.* to be every column in TABLE.
117739: **
117740: */
117741: static int selectExpander(Walker *pWalker, Select *p){
117742:   Parse *pParse = pWalker->pParse;
117743:   int i, j, k;
117744:   SrcList *pTabList;
117745:   ExprList *pEList;
117746:   struct SrcList_item *pFrom;
117747:   sqlite3 *db = pParse->db;
117748:   Expr *pE, *pRight, *pExpr;
117749:   u16 selFlags = p->selFlags;
117750: 
117751:   p->selFlags |= SF_Expanded;
117752:   if( db->mallocFailed  ){
117753:     return WRC_Abort;
117754:   }
117755:   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
117756:     return WRC_Prune;
117757:   }
117758:   pTabList = p->pSrc;
117759:   pEList = p->pEList;
117760:   if( pWalker->xSelectCallback2==selectPopWith ){
117761:     sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
117762:   }
117763: 
117764:   /* Make sure cursor numbers have been assigned to all entries in
117765:   ** the FROM clause of the SELECT statement.
117766:   */
117767:   sqlite3SrcListAssignCursors(pParse, pTabList);
117768: 
117769:   /* Look up every table named in the FROM clause of the select.  If
117770:   ** an entry of the FROM clause is a subquery instead of a table or view,
117771:   ** then create a transient table structure to describe the subquery.
117772:   */
117773:   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117774:     Table *pTab;
117775:     assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
117776:     if( pFrom->fg.isRecursive ) continue;
117777:     assert( pFrom->pTab==0 );
117778: #ifndef SQLITE_OMIT_CTE
117779:     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
117780:     if( pFrom->pTab ) {} else
117781: #endif
117782:     if( pFrom->zName==0 ){
117783: #ifndef SQLITE_OMIT_SUBQUERY
117784:       Select *pSel = pFrom->pSelect;
117785:       /* A sub-query in the FROM clause of a SELECT */
117786:       assert( pSel!=0 );
117787:       assert( pFrom->pTab==0 );
117788:       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
117789:       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
117790:       if( pTab==0 ) return WRC_Abort;
117791:       pTab->nRef = 1;
117792:       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
117793:       while( pSel->pPrior ){ pSel = pSel->pPrior; }
117794:       sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
117795:       pTab->iPKey = -1;
117796:       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
117797:       pTab->tabFlags |= TF_Ephemeral;
117798: #endif
117799:     }else{
117800:       /* An ordinary table or view name in the FROM clause */
117801:       assert( pFrom->pTab==0 );
117802:       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
117803:       if( pTab==0 ) return WRC_Abort;
117804:       if( pTab->nRef==0xffff ){
117805:         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
117806:            pTab->zName);
117807:         pFrom->pTab = 0;
117808:         return WRC_Abort;
117809:       }
117810:       pTab->nRef++;
117811:       if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
117812:         return WRC_Abort;
117813:       }
117814: #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
117815:       if( IsVirtual(pTab) || pTab->pSelect ){
117816:         i16 nCol;
117817:         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
117818:         assert( pFrom->pSelect==0 );
117819:         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
117820:         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
117821:         nCol = pTab->nCol;
117822:         pTab->nCol = -1;
117823:         sqlite3WalkSelect(pWalker, pFrom->pSelect);
117824:         pTab->nCol = nCol;
117825:       }
117826: #endif
117827:     }
117828: 
117829:     /* Locate the index named by the INDEXED BY clause, if any. */
117830:     if( sqlite3IndexedByLookup(pParse, pFrom) ){
117831:       return WRC_Abort;
117832:     }
117833:   }
117834: 
117835:   /* Process NATURAL keywords, and ON and USING clauses of joins.
117836:   */
117837:   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
117838:     return WRC_Abort;
117839:   }
117840: 
117841:   /* For every "*" that occurs in the column list, insert the names of
117842:   ** all columns in all tables.  And for every TABLE.* insert the names
117843:   ** of all columns in TABLE.  The parser inserted a special expression
117844:   ** with the TK_ASTERISK operator for each "*" that it found in the column
117845:   ** list.  The following code just has to locate the TK_ASTERISK
117846:   ** expressions and expand each one to the list of all columns in
117847:   ** all tables.
117848:   **
117849:   ** The first loop just checks to see if there are any "*" operators
117850:   ** that need expanding.
117851:   */
117852:   for(k=0; k<pEList->nExpr; k++){
117853:     pE = pEList->a[k].pExpr;
117854:     if( pE->op==TK_ASTERISK ) break;
117855:     assert( pE->op!=TK_DOT || pE->pRight!=0 );
117856:     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
117857:     if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
117858:   }
117859:   if( k<pEList->nExpr ){
117860:     /*
117861:     ** If we get here it means the result set contains one or more "*"
117862:     ** operators that need to be expanded.  Loop through each expression
117863:     ** in the result set and expand them one by one.
117864:     */
117865:     struct ExprList_item *a = pEList->a;
117866:     ExprList *pNew = 0;
117867:     int flags = pParse->db->flags;
117868:     int longNames = (flags & SQLITE_FullColNames)!=0
117869:                       && (flags & SQLITE_ShortColNames)==0;
117870: 
117871:     for(k=0; k<pEList->nExpr; k++){
117872:       pE = a[k].pExpr;
117873:       pRight = pE->pRight;
117874:       assert( pE->op!=TK_DOT || pRight!=0 );
117875:       if( pE->op!=TK_ASTERISK
117876:        && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
117877:       ){
117878:         /* This particular expression does not need to be expanded.
117879:         */
117880:         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
117881:         if( pNew ){
117882:           pNew->a[pNew->nExpr-1].zName = a[k].zName;
117883:           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
117884:           a[k].zName = 0;
117885:           a[k].zSpan = 0;
117886:         }
117887:         a[k].pExpr = 0;
117888:       }else{
117889:         /* This expression is a "*" or a "TABLE.*" and needs to be
117890:         ** expanded. */
117891:         int tableSeen = 0;      /* Set to 1 when TABLE matches */
117892:         char *zTName = 0;       /* text of name of TABLE */
117893:         if( pE->op==TK_DOT ){
117894:           assert( pE->pLeft!=0 );
117895:           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
117896:           zTName = pE->pLeft->u.zToken;
117897:         }
117898:         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117899:           Table *pTab = pFrom->pTab;
117900:           Select *pSub = pFrom->pSelect;
117901:           char *zTabName = pFrom->zAlias;
117902:           const char *zSchemaName = 0;
117903:           int iDb;
117904:           if( zTabName==0 ){
117905:             zTabName = pTab->zName;
117906:           }
117907:           if( db->mallocFailed ) break;
117908:           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
117909:             pSub = 0;
117910:             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
117911:               continue;
117912:             }
117913:             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117914:             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
117915:           }
117916:           for(j=0; j<pTab->nCol; j++){
117917:             char *zName = pTab->aCol[j].zName;
117918:             char *zColname;  /* The computed column name */
117919:             char *zToFree;   /* Malloced string that needs to be freed */
117920:             Token sColname;  /* Computed column name as a token */
117921: 
117922:             assert( zName );
117923:             if( zTName && pSub
117924:              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
117925:             ){
117926:               continue;
117927:             }
117928: 
117929:             /* If a column is marked as 'hidden', omit it from the expanded
117930:             ** result-set list unless the SELECT has the SF_IncludeHidden
117931:             ** bit set.
117932:             */
117933:             if( (p->selFlags & SF_IncludeHidden)==0
117934:              && IsHiddenColumn(&pTab->aCol[j]) 
117935:             ){
117936:               continue;
117937:             }
117938:             tableSeen = 1;
117939: 
117940:             if( i>0 && zTName==0 ){
117941:               if( (pFrom->fg.jointype & JT_NATURAL)!=0
117942:                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
117943:               ){
117944:                 /* In a NATURAL join, omit the join columns from the 
117945:                 ** table to the right of the join */
117946:                 continue;
117947:               }
117948:               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
117949:                 /* In a join with a USING clause, omit columns in the
117950:                 ** using clause from the table on the right. */
117951:                 continue;
117952:               }
117953:             }
117954:             pRight = sqlite3Expr(db, TK_ID, zName);
117955:             zColname = zName;
117956:             zToFree = 0;
117957:             if( longNames || pTabList->nSrc>1 ){
117958:               Expr *pLeft;
117959:               pLeft = sqlite3Expr(db, TK_ID, zTabName);
117960:               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
117961:               if( zSchemaName ){
117962:                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
117963:                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
117964:               }
117965:               if( longNames ){
117966:                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
117967:                 zToFree = zColname;
117968:               }
117969:             }else{
117970:               pExpr = pRight;
117971:             }
117972:             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
117973:             sqlite3TokenInit(&sColname, zColname);
117974:             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
117975:             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
117976:               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
117977:               if( pSub ){
117978:                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
117979:                 testcase( pX->zSpan==0 );
117980:               }else{
117981:                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
117982:                                            zSchemaName, zTabName, zColname);
117983:                 testcase( pX->zSpan==0 );
117984:               }
117985:               pX->bSpanIsTab = 1;
117986:             }
117987:             sqlite3DbFree(db, zToFree);
117988:           }
117989:         }
117990:         if( !tableSeen ){
117991:           if( zTName ){
117992:             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
117993:           }else{
117994:             sqlite3ErrorMsg(pParse, "no tables specified");
117995:           }
117996:         }
117997:       }
117998:     }
117999:     sqlite3ExprListDelete(db, pEList);
118000:     p->pEList = pNew;
118001:   }
118002: #if SQLITE_MAX_COLUMN
118003:   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
118004:     sqlite3ErrorMsg(pParse, "too many columns in result set");
118005:     return WRC_Abort;
118006:   }
118007: #endif
118008:   return WRC_Continue;
118009: }
118010: 
118011: /*
118012: ** No-op routine for the parse-tree walker.
118013: **
118014: ** When this routine is the Walker.xExprCallback then expression trees
118015: ** are walked without any actions being taken at each node.  Presumably,
118016: ** when this routine is used for Walker.xExprCallback then 
118017: ** Walker.xSelectCallback is set to do something useful for every 
118018: ** subquery in the parser tree.
118019: */
118020: SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
118021:   UNUSED_PARAMETER2(NotUsed, NotUsed2);
118022:   return WRC_Continue;
118023: }
118024: 
118025: /*
118026: ** This routine "expands" a SELECT statement and all of its subqueries.
118027: ** For additional information on what it means to "expand" a SELECT
118028: ** statement, see the comment on the selectExpand worker callback above.
118029: **
118030: ** Expanding a SELECT statement is the first step in processing a
118031: ** SELECT statement.  The SELECT statement must be expanded before
118032: ** name resolution is performed.
118033: **
118034: ** If anything goes wrong, an error message is written into pParse.
118035: ** The calling function can detect the problem by looking at pParse->nErr
118036: ** and/or pParse->db->mallocFailed.
118037: */
118038: static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
118039:   Walker w;
118040:   memset(&w, 0, sizeof(w));
118041:   w.xExprCallback = sqlite3ExprWalkNoop;
118042:   w.pParse = pParse;
118043:   if( pParse->hasCompound ){
118044:     w.xSelectCallback = convertCompoundSelectToSubquery;
118045:     sqlite3WalkSelect(&w, pSelect);
118046:   }
118047:   w.xSelectCallback = selectExpander;
118048:   if( (pSelect->selFlags & SF_MultiValue)==0 ){
118049:     w.xSelectCallback2 = selectPopWith;
118050:   }
118051:   sqlite3WalkSelect(&w, pSelect);
118052: }
118053: 
118054: 
118055: #ifndef SQLITE_OMIT_SUBQUERY
118056: /*
118057: ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
118058: ** interface.
118059: **
118060: ** For each FROM-clause subquery, add Column.zType and Column.zColl
118061: ** information to the Table structure that represents the result set
118062: ** of that subquery.
118063: **
118064: ** The Table structure that represents the result set was constructed
118065: ** by selectExpander() but the type and collation information was omitted
118066: ** at that point because identifiers had not yet been resolved.  This
118067: ** routine is called after identifier resolution.
118068: */
118069: static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
118070:   Parse *pParse;
118071:   int i;
118072:   SrcList *pTabList;
118073:   struct SrcList_item *pFrom;
118074: 
118075:   assert( p->selFlags & SF_Resolved );
118076:   assert( (p->selFlags & SF_HasTypeInfo)==0 );
118077:   p->selFlags |= SF_HasTypeInfo;
118078:   pParse = pWalker->pParse;
118079:   pTabList = p->pSrc;
118080:   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
118081:     Table *pTab = pFrom->pTab;
118082:     assert( pTab!=0 );
118083:     if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
118084:       /* A sub-query in the FROM clause of a SELECT */
118085:       Select *pSel = pFrom->pSelect;
118086:       if( pSel ){
118087:         while( pSel->pPrior ) pSel = pSel->pPrior;
118088:         sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
118089:       }
118090:     }
118091:   }
118092: }
118093: #endif
118094: 
118095: 
118096: /*
118097: ** This routine adds datatype and collating sequence information to
118098: ** the Table structures of all FROM-clause subqueries in a
118099: ** SELECT statement.
118100: **
118101: ** Use this routine after name resolution.
118102: */
118103: static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
118104: #ifndef SQLITE_OMIT_SUBQUERY
118105:   Walker w;
118106:   memset(&w, 0, sizeof(w));
118107:   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
118108:   w.xExprCallback = sqlite3ExprWalkNoop;
118109:   w.pParse = pParse;
118110:   sqlite3WalkSelect(&w, pSelect);
118111: #endif
118112: }
118113: 
118114: 
118115: /*
118116: ** This routine sets up a SELECT statement for processing.  The
118117: ** following is accomplished:
118118: **
118119: **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
118120: **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
118121: **     *  ON and USING clauses are shifted into WHERE statements
118122: **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
118123: **     *  Identifiers in expression are matched to tables.
118124: **
118125: ** This routine acts recursively on all subqueries within the SELECT.
118126: */
118127: SQLITE_PRIVATE void sqlite3SelectPrep(
118128:   Parse *pParse,         /* The parser context */
118129:   Select *p,             /* The SELECT statement being coded. */
118130:   NameContext *pOuterNC  /* Name context for container */
118131: ){
118132:   sqlite3 *db;
118133:   if( NEVER(p==0) ) return;
118134:   db = pParse->db;
118135:   if( db->mallocFailed ) return;
118136:   if( p->selFlags & SF_HasTypeInfo ) return;
118137:   sqlite3SelectExpand(pParse, p);
118138:   if( pParse->nErr || db->mallocFailed ) return;
118139:   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
118140:   if( pParse->nErr || db->mallocFailed ) return;
118141:   sqlite3SelectAddTypeInfo(pParse, p);
118142: }
118143: 
118144: /*
118145: ** Reset the aggregate accumulator.
118146: **
118147: ** The aggregate accumulator is a set of memory cells that hold
118148: ** intermediate results while calculating an aggregate.  This
118149: ** routine generates code that stores NULLs in all of those memory
118150: ** cells.
118151: */
118152: static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
118153:   Vdbe *v = pParse->pVdbe;
118154:   int i;
118155:   struct AggInfo_func *pFunc;
118156:   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
118157:   if( nReg==0 ) return;
118158: #ifdef SQLITE_DEBUG
118159:   /* Verify that all AggInfo registers are within the range specified by
118160:   ** AggInfo.mnReg..AggInfo.mxReg */
118161:   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
118162:   for(i=0; i<pAggInfo->nColumn; i++){
118163:     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
118164:          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
118165:   }
118166:   for(i=0; i<pAggInfo->nFunc; i++){
118167:     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
118168:          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
118169:   }
118170: #endif
118171:   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
118172:   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
118173:     if( pFunc->iDistinct>=0 ){
118174:       Expr *pE = pFunc->pExpr;
118175:       assert( !ExprHasProperty(pE, EP_xIsSelect) );
118176:       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
118177:         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
118178:            "argument");
118179:         pFunc->iDistinct = -1;
118180:       }else{
118181:         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
118182:         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
118183:                           (char*)pKeyInfo, P4_KEYINFO);
118184:       }
118185:     }
118186:   }
118187: }
118188: 
118189: /*
118190: ** Invoke the OP_AggFinalize opcode for every aggregate function
118191: ** in the AggInfo structure.
118192: */
118193: static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
118194:   Vdbe *v = pParse->pVdbe;
118195:   int i;
118196:   struct AggInfo_func *pF;
118197:   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
118198:     ExprList *pList = pF->pExpr->x.pList;
118199:     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
118200:     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
118201:                       (void*)pF->pFunc, P4_FUNCDEF);
118202:   }
118203: }
118204: 
118205: /*
118206: ** Update the accumulator memory cells for an aggregate based on
118207: ** the current cursor position.
118208: */
118209: static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
118210:   Vdbe *v = pParse->pVdbe;
118211:   int i;
118212:   int regHit = 0;
118213:   int addrHitTest = 0;
118214:   struct AggInfo_func *pF;
118215:   struct AggInfo_col *pC;
118216: 
118217:   pAggInfo->directMode = 1;
118218:   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
118219:     int nArg;
118220:     int addrNext = 0;
118221:     int regAgg;
118222:     ExprList *pList = pF->pExpr->x.pList;
118223:     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
118224:     if( pList ){
118225:       nArg = pList->nExpr;
118226:       regAgg = sqlite3GetTempRange(pParse, nArg);
118227:       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
118228:     }else{
118229:       nArg = 0;
118230:       regAgg = 0;
118231:     }
118232:     if( pF->iDistinct>=0 ){
118233:       addrNext = sqlite3VdbeMakeLabel(v);
118234:       testcase( nArg==0 );  /* Error condition */
118235:       testcase( nArg>1 );   /* Also an error */
118236:       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
118237:     }
118238:     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
118239:       CollSeq *pColl = 0;
118240:       struct ExprList_item *pItem;
118241:       int j;
118242:       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
118243:       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
118244:         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
118245:       }
118246:       if( !pColl ){
118247:         pColl = pParse->db->pDfltColl;
118248:       }
118249:       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
118250:       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
118251:     }
118252:     sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
118253:                       (void*)pF->pFunc, P4_FUNCDEF);
118254:     sqlite3VdbeChangeP5(v, (u8)nArg);
118255:     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
118256:     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
118257:     if( addrNext ){
118258:       sqlite3VdbeResolveLabel(v, addrNext);
118259:       sqlite3ExprCacheClear(pParse);
118260:     }
118261:   }
118262: 
118263:   /* Before populating the accumulator registers, clear the column cache.
118264:   ** Otherwise, if any of the required column values are already present 
118265:   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
118266:   ** to pC->iMem. But by the time the value is used, the original register
118267:   ** may have been used, invalidating the underlying buffer holding the
118268:   ** text or blob value. See ticket [883034dcb5].
118269:   **
118270:   ** Another solution would be to change the OP_SCopy used to copy cached
118271:   ** values to an OP_Copy.
118272:   */
118273:   if( regHit ){
118274:     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
118275:   }
118276:   sqlite3ExprCacheClear(pParse);
118277:   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
118278:     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
118279:   }
118280:   pAggInfo->directMode = 0;
118281:   sqlite3ExprCacheClear(pParse);
118282:   if( addrHitTest ){
118283:     sqlite3VdbeJumpHere(v, addrHitTest);
118284:   }
118285: }
118286: 
118287: /*
118288: ** Add a single OP_Explain instruction to the VDBE to explain a simple
118289: ** count(*) query ("SELECT count(*) FROM pTab").
118290: */
118291: #ifndef SQLITE_OMIT_EXPLAIN
118292: static void explainSimpleCount(
118293:   Parse *pParse,                  /* Parse context */
118294:   Table *pTab,                    /* Table being queried */
118295:   Index *pIdx                     /* Index used to optimize scan, or NULL */
118296: ){
118297:   if( pParse->explain==2 ){
118298:     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
118299:     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
118300:         pTab->zName,
118301:         bCover ? " USING COVERING INDEX " : "",
118302:         bCover ? pIdx->zName : ""
118303:     );
118304:     sqlite3VdbeAddOp4(
118305:         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
118306:     );
118307:   }
118308: }
118309: #else
118310: # define explainSimpleCount(a,b,c)
118311: #endif
118312: 
118313: /*
118314: ** Generate code for the SELECT statement given in the p argument.  
118315: **
118316: ** The results are returned according to the SelectDest structure.
118317: ** See comments in sqliteInt.h for further information.
118318: **
118319: ** This routine returns the number of errors.  If any errors are
118320: ** encountered, then an appropriate error message is left in
118321: ** pParse->zErrMsg.
118322: **
118323: ** This routine does NOT free the Select structure passed in.  The
118324: ** calling function needs to do that.
118325: */
118326: SQLITE_PRIVATE int sqlite3Select(
118327:   Parse *pParse,         /* The parser context */
118328:   Select *p,             /* The SELECT statement being coded. */
118329:   SelectDest *pDest      /* What to do with the query results */
118330: ){
118331:   int i, j;              /* Loop counters */
118332:   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
118333:   Vdbe *v;               /* The virtual machine under construction */
118334:   int isAgg;             /* True for select lists like "count(*)" */
118335:   ExprList *pEList = 0;  /* List of columns to extract. */
118336:   SrcList *pTabList;     /* List of tables to select from */
118337:   Expr *pWhere;          /* The WHERE clause.  May be NULL */
118338:   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
118339:   Expr *pHaving;         /* The HAVING clause.  May be NULL */
118340:   int rc = 1;            /* Value to return from this function */
118341:   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
118342:   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
118343:   AggInfo sAggInfo;      /* Information used by aggregate queries */
118344:   int iEnd;              /* Address of the end of the query */
118345:   sqlite3 *db;           /* The database connection */
118346: 
118347: #ifndef SQLITE_OMIT_EXPLAIN
118348:   int iRestoreSelectId = pParse->iSelectId;
118349:   pParse->iSelectId = pParse->iNextSelectId++;
118350: #endif
118351: 
118352:   db = pParse->db;
118353:   if( p==0 || db->mallocFailed || pParse->nErr ){
118354:     return 1;
118355:   }
118356:   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
118357:   memset(&sAggInfo, 0, sizeof(sAggInfo));
118358: #if SELECTTRACE_ENABLED
118359:   pParse->nSelectIndent++;
118360:   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
118361:   if( sqlite3SelectTrace & 0x100 ){
118362:     sqlite3TreeViewSelect(0, p, 0);
118363:   }
118364: #endif
118365: 
118366:   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
118367:   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
118368:   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
118369:   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
118370:   if( IgnorableOrderby(pDest) ){
118371:     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
118372:            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
118373:            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
118374:            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
118375:     /* If ORDER BY makes no difference in the output then neither does
118376:     ** DISTINCT so it can be removed too. */
118377:     sqlite3ExprListDelete(db, p->pOrderBy);
118378:     p->pOrderBy = 0;
118379:     p->selFlags &= ~SF_Distinct;
118380:   }
118381:   sqlite3SelectPrep(pParse, p, 0);
118382:   memset(&sSort, 0, sizeof(sSort));
118383:   sSort.pOrderBy = p->pOrderBy;
118384:   pTabList = p->pSrc;
118385:   if( pParse->nErr || db->mallocFailed ){
118386:     goto select_end;
118387:   }
118388:   assert( p->pEList!=0 );
118389:   isAgg = (p->selFlags & SF_Aggregate)!=0;
118390: #if SELECTTRACE_ENABLED
118391:   if( sqlite3SelectTrace & 0x100 ){
118392:     SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
118393:     sqlite3TreeViewSelect(0, p, 0);
118394:   }
118395: #endif
118396: 
118397: 
118398:   /* If writing to memory or generating a set
118399:   ** only a single column may be output.
118400:   */
118401: #ifndef SQLITE_OMIT_SUBQUERY
118402:   if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
118403:     goto select_end;
118404:   }
118405: #endif
118406: 
118407:   /* Try to flatten subqueries in the FROM clause up into the main query
118408:   */
118409: #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118410:   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
118411:     struct SrcList_item *pItem = &pTabList->a[i];
118412:     Select *pSub = pItem->pSelect;
118413:     int isAggSub;
118414:     Table *pTab = pItem->pTab;
118415:     if( pSub==0 ) continue;
118416: 
118417:     /* Catch mismatch in the declared columns of a view and the number of
118418:     ** columns in the SELECT on the RHS */
118419:     if( pTab->nCol!=pSub->pEList->nExpr ){
118420:       sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
118421:                       pTab->nCol, pTab->zName, pSub->pEList->nExpr);
118422:       goto select_end;
118423:     }
118424: 
118425:     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
118426:     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
118427:       /* This subquery can be absorbed into its parent. */
118428:       if( isAggSub ){
118429:         isAgg = 1;
118430:         p->selFlags |= SF_Aggregate;
118431:       }
118432:       i = -1;
118433:     }
118434:     pTabList = p->pSrc;
118435:     if( db->mallocFailed ) goto select_end;
118436:     if( !IgnorableOrderby(pDest) ){
118437:       sSort.pOrderBy = p->pOrderBy;
118438:     }
118439:   }
118440: #endif
118441: 
118442:   /* Get a pointer the VDBE under construction, allocating a new VDBE if one
118443:   ** does not already exist */
118444:   v = sqlite3GetVdbe(pParse);
118445:   if( v==0 ) goto select_end;
118446: 
118447: #ifndef SQLITE_OMIT_COMPOUND_SELECT
118448:   /* Handle compound SELECT statements using the separate multiSelect()
118449:   ** procedure.
118450:   */
118451:   if( p->pPrior ){
118452:     rc = multiSelect(pParse, p, pDest);
118453:     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
118454: #if SELECTTRACE_ENABLED
118455:     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
118456:     pParse->nSelectIndent--;
118457: #endif
118458:     return rc;
118459:   }
118460: #endif
118461: 
118462:   /* Generate code for all sub-queries in the FROM clause
118463:   */
118464: #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
118465:   for(i=0; i<pTabList->nSrc; i++){
118466:     struct SrcList_item *pItem = &pTabList->a[i];
118467:     SelectDest dest;
118468:     Select *pSub = pItem->pSelect;
118469:     if( pSub==0 ) continue;
118470: 
118471:     /* Sometimes the code for a subquery will be generated more than
118472:     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
118473:     ** for example.  In that case, do not regenerate the code to manifest
118474:     ** a view or the co-routine to implement a view.  The first instance
118475:     ** is sufficient, though the subroutine to manifest the view does need
118476:     ** to be invoked again. */
118477:     if( pItem->addrFillSub ){
118478:       if( pItem->fg.viaCoroutine==0 ){
118479:         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
118480:       }
118481:       continue;
118482:     }
118483: 
118484:     /* Increment Parse.nHeight by the height of the largest expression
118485:     ** tree referred to by this, the parent select. The child select
118486:     ** may contain expression trees of at most
118487:     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
118488:     ** more conservative than necessary, but much easier than enforcing
118489:     ** an exact limit.
118490:     */
118491:     pParse->nHeight += sqlite3SelectExprHeight(p);
118492: 
118493:     /* Make copies of constant WHERE-clause terms in the outer query down
118494:     ** inside the subquery.  This can help the subquery to run more efficiently.
118495:     */
118496:     if( (pItem->fg.jointype & JT_OUTER)==0
118497:      && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
118498:     ){
118499: #if SELECTTRACE_ENABLED
118500:       if( sqlite3SelectTrace & 0x100 ){
118501:         SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
118502:         sqlite3TreeViewSelect(0, p, 0);
118503:       }
118504: #endif
118505:     }
118506: 
118507:     /* Generate code to implement the subquery
118508:     **
118509:     ** The subquery is implemented as a co-routine if all of these are true:
118510:     **   (1)  The subquery is guaranteed to be the outer loop (so that it
118511:     **        does not need to be computed more than once)
118512:     **   (2)  The ALL keyword after SELECT is omitted.  (Applications are
118513:     **        allowed to say "SELECT ALL" instead of just "SELECT" to disable
118514:     **        the use of co-routines.)
118515:     **   (3)  Co-routines are not disabled using sqlite3_test_control()
118516:     **        with SQLITE_TESTCTRL_OPTIMIZATIONS.
118517:     **
118518:     ** TODO: Are there other reasons beside (1) to use a co-routine
118519:     ** implementation?
118520:     */
118521:     if( i==0
118522:      && (pTabList->nSrc==1
118523:             || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)  /* (1) */
118524:      && (p->selFlags & SF_All)==0                                   /* (2) */
118525:      && OptimizationEnabled(db, SQLITE_SubqCoroutine)               /* (3) */
118526:     ){
118527:       /* Implement a co-routine that will return a single row of the result
118528:       ** set on each invocation.
118529:       */
118530:       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
118531:       pItem->regReturn = ++pParse->nMem;
118532:       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
118533:       VdbeComment((v, "%s", pItem->pTab->zName));
118534:       pItem->addrFillSub = addrTop;
118535:       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
118536:       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
118537:       sqlite3Select(pParse, pSub, &dest);
118538:       pItem->pTab->nRowLogEst = pSub->nSelectRow;
118539:       pItem->fg.viaCoroutine = 1;
118540:       pItem->regResult = dest.iSdst;
118541:       sqlite3VdbeEndCoroutine(v, pItem->regReturn);
118542:       sqlite3VdbeJumpHere(v, addrTop-1);
118543:       sqlite3ClearTempRegCache(pParse);
118544:     }else{
118545:       /* Generate a subroutine that will fill an ephemeral table with
118546:       ** the content of this subquery.  pItem->addrFillSub will point
118547:       ** to the address of the generated subroutine.  pItem->regReturn
118548:       ** is a register allocated to hold the subroutine return address
118549:       */
118550:       int topAddr;
118551:       int onceAddr = 0;
118552:       int retAddr;
118553:       assert( pItem->addrFillSub==0 );
118554:       pItem->regReturn = ++pParse->nMem;
118555:       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
118556:       pItem->addrFillSub = topAddr+1;
118557:       if( pItem->fg.isCorrelated==0 ){
118558:         /* If the subquery is not correlated and if we are not inside of
118559:         ** a trigger, then we only need to compute the value of the subquery
118560:         ** once. */
118561:         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
118562:         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
118563:       }else{
118564:         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
118565:       }
118566:       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
118567:       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
118568:       sqlite3Select(pParse, pSub, &dest);
118569:       pItem->pTab->nRowLogEst = pSub->nSelectRow;
118570:       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
118571:       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
118572:       VdbeComment((v, "end %s", pItem->pTab->zName));
118573:       sqlite3VdbeChangeP1(v, topAddr, retAddr);
118574:       sqlite3ClearTempRegCache(pParse);
118575:     }
118576:     if( db->mallocFailed ) goto select_end;
118577:     pParse->nHeight -= sqlite3SelectExprHeight(p);
118578:   }
118579: #endif
118580: 
118581:   /* Various elements of the SELECT copied into local variables for
118582:   ** convenience */
118583:   pEList = p->pEList;
118584:   pWhere = p->pWhere;
118585:   pGroupBy = p->pGroupBy;
118586:   pHaving = p->pHaving;
118587:   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
118588: 
118589: #if SELECTTRACE_ENABLED
118590:   if( sqlite3SelectTrace & 0x400 ){
118591:     SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
118592:     sqlite3TreeViewSelect(0, p, 0);
118593:   }
118594: #endif
118595: 
118596:   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
118597:   ** if the select-list is the same as the ORDER BY list, then this query
118598:   ** can be rewritten as a GROUP BY. In other words, this:
118599:   **
118600:   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
118601:   **
118602:   ** is transformed to:
118603:   **
118604:   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
118605:   **
118606:   ** The second form is preferred as a single index (or temp-table) may be 
118607:   ** used for both the ORDER BY and DISTINCT processing. As originally 
118608:   ** written the query must use a temp-table for at least one of the ORDER 
118609:   ** BY and DISTINCT, and an index or separate temp-table for the other.
118610:   */
118611:   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
118612:    && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
118613:   ){
118614:     p->selFlags &= ~SF_Distinct;
118615:     pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
118616:     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
118617:     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
118618:     ** original setting of the SF_Distinct flag, not the current setting */
118619:     assert( sDistinct.isTnct );
118620: 
118621: #if SELECTTRACE_ENABLED
118622:     if( sqlite3SelectTrace & 0x400 ){
118623:       SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
118624:       sqlite3TreeViewSelect(0, p, 0);
118625:     }
118626: #endif
118627:   }
118628: 
118629:   /* If there is an ORDER BY clause, then create an ephemeral index to
118630:   ** do the sorting.  But this sorting ephemeral index might end up
118631:   ** being unused if the data can be extracted in pre-sorted order.
118632:   ** If that is the case, then the OP_OpenEphemeral instruction will be
118633:   ** changed to an OP_Noop once we figure out that the sorting index is
118634:   ** not needed.  The sSort.addrSortIndex variable is used to facilitate
118635:   ** that change.
118636:   */
118637:   if( sSort.pOrderBy ){
118638:     KeyInfo *pKeyInfo;
118639:     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
118640:     sSort.iECursor = pParse->nTab++;
118641:     sSort.addrSortIndex =
118642:       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
118643:           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
118644:           (char*)pKeyInfo, P4_KEYINFO
118645:       );
118646:   }else{
118647:     sSort.addrSortIndex = -1;
118648:   }
118649: 
118650:   /* If the output is destined for a temporary table, open that table.
118651:   */
118652:   if( pDest->eDest==SRT_EphemTab ){
118653:     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
118654:   }
118655: 
118656:   /* Set the limiter.
118657:   */
118658:   iEnd = sqlite3VdbeMakeLabel(v);
118659:   p->nSelectRow = 320;  /* 4 billion rows */
118660:   computeLimitRegisters(pParse, p, iEnd);
118661:   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
118662:     sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
118663:     sSort.sortFlags |= SORTFLAG_UseSorter;
118664:   }
118665: 
118666:   /* Open an ephemeral index to use for the distinct set.
118667:   */
118668:   if( p->selFlags & SF_Distinct ){
118669:     sDistinct.tabTnct = pParse->nTab++;
118670:     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
118671:                              sDistinct.tabTnct, 0, 0,
118672:                              (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
118673:                              P4_KEYINFO);
118674:     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
118675:     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
118676:   }else{
118677:     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
118678:   }
118679: 
118680:   if( !isAgg && pGroupBy==0 ){
118681:     /* No aggregate functions and no GROUP BY clause */
118682:     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
118683:     assert( WHERE_USE_LIMIT==SF_FixedLimit );
118684:     wctrlFlags |= p->selFlags & SF_FixedLimit;
118685: 
118686:     /* Begin the database scan. */
118687:     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
118688:                                p->pEList, wctrlFlags, p->nSelectRow);
118689:     if( pWInfo==0 ) goto select_end;
118690:     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
118691:       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
118692:     }
118693:     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
118694:       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
118695:     }
118696:     if( sSort.pOrderBy ){
118697:       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
118698:       sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
118699:       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
118700:         sSort.pOrderBy = 0;
118701:       }
118702:     }
118703: 
118704:     /* If sorting index that was created by a prior OP_OpenEphemeral 
118705:     ** instruction ended up not being needed, then change the OP_OpenEphemeral
118706:     ** into an OP_Noop.
118707:     */
118708:     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
118709:       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
118710:     }
118711: 
118712:     /* Use the standard inner loop. */
118713:     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
118714:                     sqlite3WhereContinueLabel(pWInfo),
118715:                     sqlite3WhereBreakLabel(pWInfo));
118716: 
118717:     /* End the database scan loop.
118718:     */
118719:     sqlite3WhereEnd(pWInfo);
118720:   }else{
118721:     /* This case when there exist aggregate functions or a GROUP BY clause
118722:     ** or both */
118723:     NameContext sNC;    /* Name context for processing aggregate information */
118724:     int iAMem;          /* First Mem address for storing current GROUP BY */
118725:     int iBMem;          /* First Mem address for previous GROUP BY */
118726:     int iUseFlag;       /* Mem address holding flag indicating that at least
118727:                         ** one row of the input to the aggregator has been
118728:                         ** processed */
118729:     int iAbortFlag;     /* Mem address which causes query abort if positive */
118730:     int groupBySort;    /* Rows come from source in GROUP BY order */
118731:     int addrEnd;        /* End of processing for this SELECT */
118732:     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
118733:     int sortOut = 0;    /* Output register from the sorter */
118734:     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
118735: 
118736:     /* Remove any and all aliases between the result set and the
118737:     ** GROUP BY clause.
118738:     */
118739:     if( pGroupBy ){
118740:       int k;                        /* Loop counter */
118741:       struct ExprList_item *pItem;  /* For looping over expression in a list */
118742: 
118743:       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
118744:         pItem->u.x.iAlias = 0;
118745:       }
118746:       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
118747:         pItem->u.x.iAlias = 0;
118748:       }
118749:       assert( 66==sqlite3LogEst(100) );
118750:       if( p->nSelectRow>66 ) p->nSelectRow = 66;
118751:     }else{
118752:       assert( 0==sqlite3LogEst(1) );
118753:       p->nSelectRow = 0;
118754:     }
118755: 
118756:     /* If there is both a GROUP BY and an ORDER BY clause and they are
118757:     ** identical, then it may be possible to disable the ORDER BY clause 
118758:     ** on the grounds that the GROUP BY will cause elements to come out 
118759:     ** in the correct order. It also may not - the GROUP BY might use a
118760:     ** database index that causes rows to be grouped together as required
118761:     ** but not actually sorted. Either way, record the fact that the
118762:     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
118763:     ** variable.  */
118764:     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
118765:       orderByGrp = 1;
118766:     }
118767:  
118768:     /* Create a label to jump to when we want to abort the query */
118769:     addrEnd = sqlite3VdbeMakeLabel(v);
118770: 
118771:     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
118772:     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
118773:     ** SELECT statement.
118774:     */
118775:     memset(&sNC, 0, sizeof(sNC));
118776:     sNC.pParse = pParse;
118777:     sNC.pSrcList = pTabList;
118778:     sNC.pAggInfo = &sAggInfo;
118779:     sAggInfo.mnReg = pParse->nMem+1;
118780:     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
118781:     sAggInfo.pGroupBy = pGroupBy;
118782:     sqlite3ExprAnalyzeAggList(&sNC, pEList);
118783:     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
118784:     if( pHaving ){
118785:       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
118786:     }
118787:     sAggInfo.nAccumulator = sAggInfo.nColumn;
118788:     for(i=0; i<sAggInfo.nFunc; i++){
118789:       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
118790:       sNC.ncFlags |= NC_InAggFunc;
118791:       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
118792:       sNC.ncFlags &= ~NC_InAggFunc;
118793:     }
118794:     sAggInfo.mxReg = pParse->nMem;
118795:     if( db->mallocFailed ) goto select_end;
118796: 
118797:     /* Processing for aggregates with GROUP BY is very different and
118798:     ** much more complex than aggregates without a GROUP BY.
118799:     */
118800:     if( pGroupBy ){
118801:       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
118802:       int addr1;          /* A-vs-B comparision jump */
118803:       int addrOutputRow;  /* Start of subroutine that outputs a result row */
118804:       int regOutputRow;   /* Return address register for output subroutine */
118805:       int addrSetAbort;   /* Set the abort flag and return */
118806:       int addrTopOfLoop;  /* Top of the input loop */
118807:       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
118808:       int addrReset;      /* Subroutine for resetting the accumulator */
118809:       int regReset;       /* Return address register for reset subroutine */
118810: 
118811:       /* If there is a GROUP BY clause we might need a sorting index to
118812:       ** implement it.  Allocate that sorting index now.  If it turns out
118813:       ** that we do not need it after all, the OP_SorterOpen instruction
118814:       ** will be converted into a Noop.  
118815:       */
118816:       sAggInfo.sortingIdx = pParse->nTab++;
118817:       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
118818:       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
118819:           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
118820:           0, (char*)pKeyInfo, P4_KEYINFO);
118821: 
118822:       /* Initialize memory locations used by GROUP BY aggregate processing
118823:       */
118824:       iUseFlag = ++pParse->nMem;
118825:       iAbortFlag = ++pParse->nMem;
118826:       regOutputRow = ++pParse->nMem;
118827:       addrOutputRow = sqlite3VdbeMakeLabel(v);
118828:       regReset = ++pParse->nMem;
118829:       addrReset = sqlite3VdbeMakeLabel(v);
118830:       iAMem = pParse->nMem + 1;
118831:       pParse->nMem += pGroupBy->nExpr;
118832:       iBMem = pParse->nMem + 1;
118833:       pParse->nMem += pGroupBy->nExpr;
118834:       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
118835:       VdbeComment((v, "clear abort flag"));
118836:       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
118837:       VdbeComment((v, "indicate accumulator empty"));
118838:       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
118839: 
118840:       /* Begin a loop that will extract all source rows in GROUP BY order.
118841:       ** This might involve two separate loops with an OP_Sort in between, or
118842:       ** it might be a single loop that uses an index to extract information
118843:       ** in the right order to begin with.
118844:       */
118845:       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118846:       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
118847:           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
118848:       );
118849:       if( pWInfo==0 ) goto select_end;
118850:       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
118851:         /* The optimizer is able to deliver rows in group by order so
118852:         ** we do not have to sort.  The OP_OpenEphemeral table will be
118853:         ** cancelled later because we still need to use the pKeyInfo
118854:         */
118855:         groupBySort = 0;
118856:       }else{
118857:         /* Rows are coming out in undetermined order.  We have to push
118858:         ** each row into a sorting index, terminate the first loop,
118859:         ** then loop over the sorting index in order to get the output
118860:         ** in sorted order
118861:         */
118862:         int regBase;
118863:         int regRecord;
118864:         int nCol;
118865:         int nGroupBy;
118866: 
118867:         explainTempTable(pParse, 
118868:             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
118869:                     "DISTINCT" : "GROUP BY");
118870: 
118871:         groupBySort = 1;
118872:         nGroupBy = pGroupBy->nExpr;
118873:         nCol = nGroupBy;
118874:         j = nGroupBy;
118875:         for(i=0; i<sAggInfo.nColumn; i++){
118876:           if( sAggInfo.aCol[i].iSorterColumn>=j ){
118877:             nCol++;
118878:             j++;
118879:           }
118880:         }
118881:         regBase = sqlite3GetTempRange(pParse, nCol);
118882:         sqlite3ExprCacheClear(pParse);
118883:         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
118884:         j = nGroupBy;
118885:         for(i=0; i<sAggInfo.nColumn; i++){
118886:           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
118887:           if( pCol->iSorterColumn>=j ){
118888:             int r1 = j + regBase;
118889:             sqlite3ExprCodeGetColumnToReg(pParse, 
118890:                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
118891:             j++;
118892:           }
118893:         }
118894:         regRecord = sqlite3GetTempReg(pParse);
118895:         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
118896:         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
118897:         sqlite3ReleaseTempReg(pParse, regRecord);
118898:         sqlite3ReleaseTempRange(pParse, regBase, nCol);
118899:         sqlite3WhereEnd(pWInfo);
118900:         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
118901:         sortOut = sqlite3GetTempReg(pParse);
118902:         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
118903:         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
118904:         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
118905:         sAggInfo.useSortingIdx = 1;
118906:         sqlite3ExprCacheClear(pParse);
118907: 
118908:       }
118909: 
118910:       /* If the index or temporary table used by the GROUP BY sort
118911:       ** will naturally deliver rows in the order required by the ORDER BY
118912:       ** clause, cancel the ephemeral table open coded earlier.
118913:       **
118914:       ** This is an optimization - the correct answer should result regardless.
118915:       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 
118916:       ** disable this optimization for testing purposes.  */
118917:       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 
118918:        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
118919:       ){
118920:         sSort.pOrderBy = 0;
118921:         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
118922:       }
118923: 
118924:       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
118925:       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
118926:       ** Then compare the current GROUP BY terms against the GROUP BY terms
118927:       ** from the previous row currently stored in a0, a1, a2...
118928:       */
118929:       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
118930:       sqlite3ExprCacheClear(pParse);
118931:       if( groupBySort ){
118932:         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
118933:                           sortOut, sortPTab);
118934:       }
118935:       for(j=0; j<pGroupBy->nExpr; j++){
118936:         if( groupBySort ){
118937:           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
118938:         }else{
118939:           sAggInfo.directMode = 1;
118940:           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
118941:         }
118942:       }
118943:       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
118944:                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
118945:       addr1 = sqlite3VdbeCurrentAddr(v);
118946:       sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
118947: 
118948:       /* Generate code that runs whenever the GROUP BY changes.
118949:       ** Changes in the GROUP BY are detected by the previous code
118950:       ** block.  If there were no changes, this block is skipped.
118951:       **
118952:       ** This code copies current group by terms in b0,b1,b2,...
118953:       ** over to a0,a1,a2.  It then calls the output subroutine
118954:       ** and resets the aggregate accumulator registers in preparation
118955:       ** for the next GROUP BY batch.
118956:       */
118957:       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
118958:       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118959:       VdbeComment((v, "output one row"));
118960:       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
118961:       VdbeComment((v, "check abort flag"));
118962:       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118963:       VdbeComment((v, "reset accumulator"));
118964: 
118965:       /* Update the aggregate accumulators based on the content of
118966:       ** the current row
118967:       */
118968:       sqlite3VdbeJumpHere(v, addr1);
118969:       updateAccumulator(pParse, &sAggInfo);
118970:       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
118971:       VdbeComment((v, "indicate data in accumulator"));
118972: 
118973:       /* End of the loop
118974:       */
118975:       if( groupBySort ){
118976:         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
118977:         VdbeCoverage(v);
118978:       }else{
118979:         sqlite3WhereEnd(pWInfo);
118980:         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
118981:       }
118982: 
118983:       /* Output the final row of result
118984:       */
118985:       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118986:       VdbeComment((v, "output final row"));
118987: 
118988:       /* Jump over the subroutines
118989:       */
118990:       sqlite3VdbeGoto(v, addrEnd);
118991: 
118992:       /* Generate a subroutine that outputs a single row of the result
118993:       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
118994:       ** is less than or equal to zero, the subroutine is a no-op.  If
118995:       ** the processing calls for the query to abort, this subroutine
118996:       ** increments the iAbortFlag memory location before returning in
118997:       ** order to signal the caller to abort.
118998:       */
118999:       addrSetAbort = sqlite3VdbeCurrentAddr(v);
119000:       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
119001:       VdbeComment((v, "set abort flag"));
119002:       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119003:       sqlite3VdbeResolveLabel(v, addrOutputRow);
119004:       addrOutputRow = sqlite3VdbeCurrentAddr(v);
119005:       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
119006:       VdbeCoverage(v);
119007:       VdbeComment((v, "Groupby result generator entry point"));
119008:       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119009:       finalizeAggFunctions(pParse, &sAggInfo);
119010:       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
119011:       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
119012:                       &sDistinct, pDest,
119013:                       addrOutputRow+1, addrSetAbort);
119014:       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
119015:       VdbeComment((v, "end groupby result generator"));
119016: 
119017:       /* Generate a subroutine that will reset the group-by accumulator
119018:       */
119019:       sqlite3VdbeResolveLabel(v, addrReset);
119020:       resetAccumulator(pParse, &sAggInfo);
119021:       sqlite3VdbeAddOp1(v, OP_Return, regReset);
119022:      
119023:     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
119024:     else {
119025:       ExprList *pDel = 0;
119026: #ifndef SQLITE_OMIT_BTREECOUNT
119027:       Table *pTab;
119028:       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
119029:         /* If isSimpleCount() returns a pointer to a Table structure, then
119030:         ** the SQL statement is of the form:
119031:         **
119032:         **   SELECT count(*) FROM <tbl>
119033:         **
119034:         ** where the Table structure returned represents table <tbl>.
119035:         **
119036:         ** This statement is so common that it is optimized specially. The
119037:         ** OP_Count instruction is executed either on the intkey table that
119038:         ** contains the data for table <tbl> or on one of its indexes. It
119039:         ** is better to execute the op on an index, as indexes are almost
119040:         ** always spread across less pages than their corresponding tables.
119041:         */
119042:         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119043:         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
119044:         Index *pIdx;                         /* Iterator variable */
119045:         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
119046:         Index *pBest = 0;                    /* Best index found so far */
119047:         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
119048: 
119049:         sqlite3CodeVerifySchema(pParse, iDb);
119050:         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
119051: 
119052:         /* Search for the index that has the lowest scan cost.
119053:         **
119054:         ** (2011-04-15) Do not do a full scan of an unordered index.
119055:         **
119056:         ** (2013-10-03) Do not count the entries in a partial index.
119057:         **
119058:         ** In practice the KeyInfo structure will not be used. It is only 
119059:         ** passed to keep OP_OpenRead happy.
119060:         */
119061:         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
119062:         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119063:           if( pIdx->bUnordered==0
119064:            && pIdx->szIdxRow<pTab->szTabRow
119065:            && pIdx->pPartIdxWhere==0
119066:            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
119067:           ){
119068:             pBest = pIdx;
119069:           }
119070:         }
119071:         if( pBest ){
119072:           iRoot = pBest->tnum;
119073:           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
119074:         }
119075: 
119076:         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
119077:         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
119078:         if( pKeyInfo ){
119079:           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
119080:         }
119081:         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
119082:         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
119083:         explainSimpleCount(pParse, pTab, pBest);
119084:       }else
119085: #endif /* SQLITE_OMIT_BTREECOUNT */
119086:       {
119087:         /* Check if the query is of one of the following forms:
119088:         **
119089:         **   SELECT min(x) FROM ...
119090:         **   SELECT max(x) FROM ...
119091:         **
119092:         ** If it is, then ask the code in where.c to attempt to sort results
119093:         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
119094:         ** If where.c is able to produce results sorted in this order, then
119095:         ** add vdbe code to break out of the processing loop after the 
119096:         ** first iteration (since the first iteration of the loop is 
119097:         ** guaranteed to operate on the row with the minimum or maximum 
119098:         ** value of x, the only row required).
119099:         **
119100:         ** A special flag must be passed to sqlite3WhereBegin() to slightly
119101:         ** modify behavior as follows:
119102:         **
119103:         **   + If the query is a "SELECT min(x)", then the loop coded by
119104:         **     where.c should not iterate over any values with a NULL value
119105:         **     for x.
119106:         **
119107:         **   + The optimizer code in where.c (the thing that decides which
119108:         **     index or indices to use) should place a different priority on 
119109:         **     satisfying the 'ORDER BY' clause than it does in other cases.
119110:         **     Refer to code and comments in where.c for details.
119111:         */
119112:         ExprList *pMinMax = 0;
119113:         u8 flag = WHERE_ORDERBY_NORMAL;
119114:         
119115:         assert( p->pGroupBy==0 );
119116:         assert( flag==0 );
119117:         if( p->pHaving==0 ){
119118:           flag = minMaxQuery(&sAggInfo, &pMinMax);
119119:         }
119120:         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
119121: 
119122:         if( flag ){
119123:           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
119124:           pDel = pMinMax;
119125:           assert( db->mallocFailed || pMinMax!=0 );
119126:           if( !db->mallocFailed ){
119127:             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
119128:             pMinMax->a[0].pExpr->op = TK_COLUMN;
119129:           }
119130:         }
119131:   
119132:         /* This case runs if the aggregate has no GROUP BY clause.  The
119133:         ** processing is much simpler since there is only a single row
119134:         ** of output.
119135:         */
119136:         resetAccumulator(pParse, &sAggInfo);
119137:         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
119138:         if( pWInfo==0 ){
119139:           sqlite3ExprListDelete(db, pDel);
119140:           goto select_end;
119141:         }
119142:         updateAccumulator(pParse, &sAggInfo);
119143:         assert( pMinMax==0 || pMinMax->nExpr==1 );
119144:         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
119145:           sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
119146:           VdbeComment((v, "%s() by index",
119147:                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
119148:         }
119149:         sqlite3WhereEnd(pWInfo);
119150:         finalizeAggFunctions(pParse, &sAggInfo);
119151:       }
119152: 
119153:       sSort.pOrderBy = 0;
119154:       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
119155:       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, 
119156:                       pDest, addrEnd, addrEnd);
119157:       sqlite3ExprListDelete(db, pDel);
119158:     }
119159:     sqlite3VdbeResolveLabel(v, addrEnd);
119160:     
119161:   } /* endif aggregate query */
119162: 
119163:   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
119164:     explainTempTable(pParse, "DISTINCT");
119165:   }
119166: 
119167:   /* If there is an ORDER BY clause, then we need to sort the results
119168:   ** and send them to the callback one by one.
119169:   */
119170:   if( sSort.pOrderBy ){
119171:     explainTempTable(pParse,
119172:                      sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
119173:     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
119174:   }
119175: 
119176:   /* Jump here to skip this query
119177:   */
119178:   sqlite3VdbeResolveLabel(v, iEnd);
119179: 
119180:   /* The SELECT has been coded. If there is an error in the Parse structure,
119181:   ** set the return code to 1. Otherwise 0. */
119182:   rc = (pParse->nErr>0);
119183: 
119184:   /* Control jumps to here if an error is encountered above, or upon
119185:   ** successful coding of the SELECT.
119186:   */
119187: select_end:
119188:   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
119189: 
119190:   /* Identify column names if results of the SELECT are to be output.
119191:   */
119192:   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
119193:     generateColumnNames(pParse, pTabList, pEList);
119194:   }
119195: 
119196:   sqlite3DbFree(db, sAggInfo.aCol);
119197:   sqlite3DbFree(db, sAggInfo.aFunc);
119198: #if SELECTTRACE_ENABLED
119199:   SELECTTRACE(1,pParse,p,("end processing\n"));
119200:   pParse->nSelectIndent--;
119201: #endif
119202:   return rc;
119203: }
119204: 
119205: /************** End of select.c **********************************************/
119206: /************** Begin file table.c *******************************************/
119207: /*
119208: ** 2001 September 15
119209: **
119210: ** The author disclaims copyright to this source code.  In place of
119211: ** a legal notice, here is a blessing:
119212: **
119213: **    May you do good and not evil.
119214: **    May you find forgiveness for yourself and forgive others.
119215: **    May you share freely, never taking more than you give.
119216: **
119217: *************************************************************************
119218: ** This file contains the sqlite3_get_table() and sqlite3_free_table()
119219: ** interface routines.  These are just wrappers around the main
119220: ** interface routine of sqlite3_exec().
119221: **
119222: ** These routines are in a separate files so that they will not be linked
119223: ** if they are not used.
119224: */
119225: /* #include "sqliteInt.h" */
119226: /* #include <stdlib.h> */
119227: /* #include <string.h> */
119228: 
119229: #ifndef SQLITE_OMIT_GET_TABLE
119230: 
119231: /*
119232: ** This structure is used to pass data from sqlite3_get_table() through
119233: ** to the callback function is uses to build the result.
119234: */
119235: typedef struct TabResult {
119236:   char **azResult;   /* Accumulated output */
119237:   char *zErrMsg;     /* Error message text, if an error occurs */
119238:   u32 nAlloc;        /* Slots allocated for azResult[] */
119239:   u32 nRow;          /* Number of rows in the result */
119240:   u32 nColumn;       /* Number of columns in the result */
119241:   u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
119242:   int rc;            /* Return code from sqlite3_exec() */
119243: } TabResult;
119244: 
119245: /*
119246: ** This routine is called once for each row in the result table.  Its job
119247: ** is to fill in the TabResult structure appropriately, allocating new
119248: ** memory as necessary.
119249: */
119250: static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
119251:   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
119252:   int need;                         /* Slots needed in p->azResult[] */
119253:   int i;                            /* Loop counter */
119254:   char *z;                          /* A single column of result */
119255: 
119256:   /* Make sure there is enough space in p->azResult to hold everything
119257:   ** we need to remember from this invocation of the callback.
119258:   */
119259:   if( p->nRow==0 && argv!=0 ){
119260:     need = nCol*2;
119261:   }else{
119262:     need = nCol;
119263:   }
119264:   if( p->nData + need > p->nAlloc ){
119265:     char **azNew;
119266:     p->nAlloc = p->nAlloc*2 + need;
119267:     azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
119268:     if( azNew==0 ) goto malloc_failed;
119269:     p->azResult = azNew;
119270:   }
119271: 
119272:   /* If this is the first row, then generate an extra row containing
119273:   ** the names of all columns.
119274:   */
119275:   if( p->nRow==0 ){
119276:     p->nColumn = nCol;
119277:     for(i=0; i<nCol; i++){
119278:       z = sqlite3_mprintf("%s", colv[i]);
119279:       if( z==0 ) goto malloc_failed;
119280:       p->azResult[p->nData++] = z;
119281:     }
119282:   }else if( (int)p->nColumn!=nCol ){
119283:     sqlite3_free(p->zErrMsg);
119284:     p->zErrMsg = sqlite3_mprintf(
119285:        "sqlite3_get_table() called with two or more incompatible queries"
119286:     );
119287:     p->rc = SQLITE_ERROR;
119288:     return 1;
119289:   }
119290: 
119291:   /* Copy over the row data
119292:   */
119293:   if( argv!=0 ){
119294:     for(i=0; i<nCol; i++){
119295:       if( argv[i]==0 ){
119296:         z = 0;
119297:       }else{
119298:         int n = sqlite3Strlen30(argv[i])+1;
119299:         z = sqlite3_malloc64( n );
119300:         if( z==0 ) goto malloc_failed;
119301:         memcpy(z, argv[i], n);
119302:       }
119303:       p->azResult[p->nData++] = z;
119304:     }
119305:     p->nRow++;
119306:   }
119307:   return 0;
119308: 
119309: malloc_failed:
119310:   p->rc = SQLITE_NOMEM_BKPT;
119311:   return 1;
119312: }
119313: 
119314: /*
119315: ** Query the database.  But instead of invoking a callback for each row,
119316: ** malloc() for space to hold the result and return the entire results
119317: ** at the conclusion of the call.
119318: **
119319: ** The result that is written to ***pazResult is held in memory obtained
119320: ** from malloc().  But the caller cannot free this memory directly.  
119321: ** Instead, the entire table should be passed to sqlite3_free_table() when
119322: ** the calling procedure is finished using it.
119323: */
119324: SQLITE_API int sqlite3_get_table(
119325:   sqlite3 *db,                /* The database on which the SQL executes */
119326:   const char *zSql,           /* The SQL to be executed */
119327:   char ***pazResult,          /* Write the result table here */
119328:   int *pnRow,                 /* Write the number of rows in the result here */
119329:   int *pnColumn,              /* Write the number of columns of result here */
119330:   char **pzErrMsg             /* Write error messages here */
119331: ){
119332:   int rc;
119333:   TabResult res;
119334: 
119335: #ifdef SQLITE_ENABLE_API_ARMOR
119336:   if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
119337: #endif
119338:   *pazResult = 0;
119339:   if( pnColumn ) *pnColumn = 0;
119340:   if( pnRow ) *pnRow = 0;
119341:   if( pzErrMsg ) *pzErrMsg = 0;
119342:   res.zErrMsg = 0;
119343:   res.nRow = 0;
119344:   res.nColumn = 0;
119345:   res.nData = 1;
119346:   res.nAlloc = 20;
119347:   res.rc = SQLITE_OK;
119348:   res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
119349:   if( res.azResult==0 ){
119350:      db->errCode = SQLITE_NOMEM;
119351:      return SQLITE_NOMEM_BKPT;
119352:   }
119353:   res.azResult[0] = 0;
119354:   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
119355:   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
119356:   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
119357:   if( (rc&0xff)==SQLITE_ABORT ){
119358:     sqlite3_free_table(&res.azResult[1]);
119359:     if( res.zErrMsg ){
119360:       if( pzErrMsg ){
119361:         sqlite3_free(*pzErrMsg);
119362:         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
119363:       }
119364:       sqlite3_free(res.zErrMsg);
119365:     }
119366:     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
119367:     return res.rc;
119368:   }
119369:   sqlite3_free(res.zErrMsg);
119370:   if( rc!=SQLITE_OK ){
119371:     sqlite3_free_table(&res.azResult[1]);
119372:     return rc;
119373:   }
119374:   if( res.nAlloc>res.nData ){
119375:     char **azNew;
119376:     azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
119377:     if( azNew==0 ){
119378:       sqlite3_free_table(&res.azResult[1]);
119379:       db->errCode = SQLITE_NOMEM;
119380:       return SQLITE_NOMEM_BKPT;
119381:     }
119382:     res.azResult = azNew;
119383:   }
119384:   *pazResult = &res.azResult[1];
119385:   if( pnColumn ) *pnColumn = res.nColumn;
119386:   if( pnRow ) *pnRow = res.nRow;
119387:   return rc;
119388: }
119389: 
119390: /*
119391: ** This routine frees the space the sqlite3_get_table() malloced.
119392: */
119393: SQLITE_API void sqlite3_free_table(
119394:   char **azResult            /* Result returned from sqlite3_get_table() */
119395: ){
119396:   if( azResult ){
119397:     int i, n;
119398:     azResult--;
119399:     assert( azResult!=0 );
119400:     n = SQLITE_PTR_TO_INT(azResult[0]);
119401:     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
119402:     sqlite3_free(azResult);
119403:   }
119404: }
119405: 
119406: #endif /* SQLITE_OMIT_GET_TABLE */
119407: 
119408: /************** End of table.c ***********************************************/
119409: /************** Begin file trigger.c *****************************************/
119410: /*
119411: **
119412: ** The author disclaims copyright to this source code.  In place of
119413: ** a legal notice, here is a blessing:
119414: **
119415: **    May you do good and not evil.
119416: **    May you find forgiveness for yourself and forgive others.
119417: **    May you share freely, never taking more than you give.
119418: **
119419: *************************************************************************
119420: ** This file contains the implementation for TRIGGERs
119421: */
119422: /* #include "sqliteInt.h" */
119423: 
119424: #ifndef SQLITE_OMIT_TRIGGER
119425: /*
119426: ** Delete a linked list of TriggerStep structures.
119427: */
119428: SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
119429:   while( pTriggerStep ){
119430:     TriggerStep * pTmp = pTriggerStep;
119431:     pTriggerStep = pTriggerStep->pNext;
119432: 
119433:     sqlite3ExprDelete(db, pTmp->pWhere);
119434:     sqlite3ExprListDelete(db, pTmp->pExprList);
119435:     sqlite3SelectDelete(db, pTmp->pSelect);
119436:     sqlite3IdListDelete(db, pTmp->pIdList);
119437: 
119438:     sqlite3DbFree(db, pTmp);
119439:   }
119440: }
119441: 
119442: /*
119443: ** Given table pTab, return a list of all the triggers attached to 
119444: ** the table. The list is connected by Trigger.pNext pointers.
119445: **
119446: ** All of the triggers on pTab that are in the same database as pTab
119447: ** are already attached to pTab->pTrigger.  But there might be additional
119448: ** triggers on pTab in the TEMP schema.  This routine prepends all
119449: ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
119450: ** and returns the combined list.
119451: **
119452: ** To state it another way:  This routine returns a list of all triggers
119453: ** that fire off of pTab.  The list will include any TEMP triggers on
119454: ** pTab as well as the triggers lised in pTab->pTrigger.
119455: */
119456: SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
119457:   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
119458:   Trigger *pList = 0;                  /* List of triggers to return */
119459: 
119460:   if( pParse->disableTriggers ){
119461:     return 0;
119462:   }
119463: 
119464:   if( pTmpSchema!=pTab->pSchema ){
119465:     HashElem *p;
119466:     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
119467:     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
119468:       Trigger *pTrig = (Trigger *)sqliteHashData(p);
119469:       if( pTrig->pTabSchema==pTab->pSchema
119470:        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
119471:       ){
119472:         pTrig->pNext = (pList ? pList : pTab->pTrigger);
119473:         pList = pTrig;
119474:       }
119475:     }
119476:   }
119477: 
119478:   return (pList ? pList : pTab->pTrigger);
119479: }
119480: 
119481: /*
119482: ** This is called by the parser when it sees a CREATE TRIGGER statement
119483: ** up to the point of the BEGIN before the trigger actions.  A Trigger
119484: ** structure is generated based on the information available and stored
119485: ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
119486: ** sqlite3FinishTrigger() function is called to complete the trigger
119487: ** construction process.
119488: */
119489: SQLITE_PRIVATE void sqlite3BeginTrigger(
119490:   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
119491:   Token *pName1,      /* The name of the trigger */
119492:   Token *pName2,      /* The name of the trigger */
119493:   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
119494:   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
119495:   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
119496:   SrcList *pTableName,/* The name of the table/view the trigger applies to */
119497:   Expr *pWhen,        /* WHEN clause */
119498:   int isTemp,         /* True if the TEMPORARY keyword is present */
119499:   int noErr           /* Suppress errors if the trigger already exists */
119500: ){
119501:   Trigger *pTrigger = 0;  /* The new trigger */
119502:   Table *pTab;            /* Table that the trigger fires off of */
119503:   char *zName = 0;        /* Name of the trigger */
119504:   sqlite3 *db = pParse->db;  /* The database connection */
119505:   int iDb;                /* The database to store the trigger in */
119506:   Token *pName;           /* The unqualified db name */
119507:   DbFixer sFix;           /* State vector for the DB fixer */
119508:   int iTabDb;             /* Index of the database holding pTab */
119509: 
119510:   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
119511:   assert( pName2!=0 );
119512:   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
119513:   assert( op>0 && op<0xff );
119514:   if( isTemp ){
119515:     /* If TEMP was specified, then the trigger name may not be qualified. */
119516:     if( pName2->n>0 ){
119517:       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
119518:       goto trigger_cleanup;
119519:     }
119520:     iDb = 1;
119521:     pName = pName1;
119522:   }else{
119523:     /* Figure out the db that the trigger will be created in */
119524:     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
119525:     if( iDb<0 ){
119526:       goto trigger_cleanup;
119527:     }
119528:   }
119529:   if( !pTableName || db->mallocFailed ){
119530:     goto trigger_cleanup;
119531:   }
119532: 
119533:   /* A long-standing parser bug is that this syntax was allowed:
119534:   **
119535:   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
119536:   **                                                 ^^^^^^^^
119537:   **
119538:   ** To maintain backwards compatibility, ignore the database
119539:   ** name on pTableName if we are reparsing out of SQLITE_MASTER.
119540:   */
119541:   if( db->init.busy && iDb!=1 ){
119542:     sqlite3DbFree(db, pTableName->a[0].zDatabase);
119543:     pTableName->a[0].zDatabase = 0;
119544:   }
119545: 
119546:   /* If the trigger name was unqualified, and the table is a temp table,
119547:   ** then set iDb to 1 to create the trigger in the temporary database.
119548:   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
119549:   ** exist, the error is caught by the block below.
119550:   */
119551:   pTab = sqlite3SrcListLookup(pParse, pTableName);
119552:   if( db->init.busy==0 && pName2->n==0 && pTab
119553:         && pTab->pSchema==db->aDb[1].pSchema ){
119554:     iDb = 1;
119555:   }
119556: 
119557:   /* Ensure the table name matches database name and that the table exists */
119558:   if( db->mallocFailed ) goto trigger_cleanup;
119559:   assert( pTableName->nSrc==1 );
119560:   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
119561:   if( sqlite3FixSrcList(&sFix, pTableName) ){
119562:     goto trigger_cleanup;
119563:   }
119564:   pTab = sqlite3SrcListLookup(pParse, pTableName);
119565:   if( !pTab ){
119566:     /* The table does not exist. */
119567:     if( db->init.iDb==1 ){
119568:       /* Ticket #3810.
119569:       ** Normally, whenever a table is dropped, all associated triggers are
119570:       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
119571:       ** and the table is dropped by a different database connection, the
119572:       ** trigger is not visible to the database connection that does the
119573:       ** drop so the trigger cannot be dropped.  This results in an
119574:       ** "orphaned trigger" - a trigger whose associated table is missing.
119575:       */
119576:       db->init.orphanTrigger = 1;
119577:     }
119578:     goto trigger_cleanup;
119579:   }
119580:   if( IsVirtual(pTab) ){
119581:     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
119582:     goto trigger_cleanup;
119583:   }
119584: 
119585:   /* Check that the trigger name is not reserved and that no trigger of the
119586:   ** specified name exists */
119587:   zName = sqlite3NameFromToken(db, pName);
119588:   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
119589:     goto trigger_cleanup;
119590:   }
119591:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119592:   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
119593:     if( !noErr ){
119594:       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
119595:     }else{
119596:       assert( !db->init.busy );
119597:       sqlite3CodeVerifySchema(pParse, iDb);
119598:     }
119599:     goto trigger_cleanup;
119600:   }
119601: 
119602:   /* Do not create a trigger on a system table */
119603:   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
119604:     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
119605:     goto trigger_cleanup;
119606:   }
119607: 
119608:   /* INSTEAD of triggers are only for views and views only support INSTEAD
119609:   ** of triggers.
119610:   */
119611:   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
119612:     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
119613:         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
119614:     goto trigger_cleanup;
119615:   }
119616:   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
119617:     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
119618:         " trigger on table: %S", pTableName, 0);
119619:     goto trigger_cleanup;
119620:   }
119621:   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
119622: 
119623: #ifndef SQLITE_OMIT_AUTHORIZATION
119624:   {
119625:     int code = SQLITE_CREATE_TRIGGER;
119626:     const char *zDb = db->aDb[iTabDb].zName;
119627:     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
119628:     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
119629:     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
119630:       goto trigger_cleanup;
119631:     }
119632:     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
119633:       goto trigger_cleanup;
119634:     }
119635:   }
119636: #endif
119637: 
119638:   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
119639:   ** cannot appear on views.  So we might as well translate every
119640:   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
119641:   ** elsewhere.
119642:   */
119643:   if (tr_tm == TK_INSTEAD){
119644:     tr_tm = TK_BEFORE;
119645:   }
119646: 
119647:   /* Build the Trigger object */
119648:   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
119649:   if( pTrigger==0 ) goto trigger_cleanup;
119650:   pTrigger->zName = zName;
119651:   zName = 0;
119652:   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
119653:   pTrigger->pSchema = db->aDb[iDb].pSchema;
119654:   pTrigger->pTabSchema = pTab->pSchema;
119655:   pTrigger->op = (u8)op;
119656:   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
119657:   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
119658:   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
119659:   assert( pParse->pNewTrigger==0 );
119660:   pParse->pNewTrigger = pTrigger;
119661: 
119662: trigger_cleanup:
119663:   sqlite3DbFree(db, zName);
119664:   sqlite3SrcListDelete(db, pTableName);
119665:   sqlite3IdListDelete(db, pColumns);
119666:   sqlite3ExprDelete(db, pWhen);
119667:   if( !pParse->pNewTrigger ){
119668:     sqlite3DeleteTrigger(db, pTrigger);
119669:   }else{
119670:     assert( pParse->pNewTrigger==pTrigger );
119671:   }
119672: }
119673: 
119674: /*
119675: ** This routine is called after all of the trigger actions have been parsed
119676: ** in order to complete the process of building the trigger.
119677: */
119678: SQLITE_PRIVATE void sqlite3FinishTrigger(
119679:   Parse *pParse,          /* Parser context */
119680:   TriggerStep *pStepList, /* The triggered program */
119681:   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
119682: ){
119683:   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
119684:   char *zName;                            /* Name of trigger */
119685:   sqlite3 *db = pParse->db;               /* The database */
119686:   DbFixer sFix;                           /* Fixer object */
119687:   int iDb;                                /* Database containing the trigger */
119688:   Token nameToken;                        /* Trigger name for error reporting */
119689: 
119690:   pParse->pNewTrigger = 0;
119691:   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
119692:   zName = pTrig->zName;
119693:   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
119694:   pTrig->step_list = pStepList;
119695:   while( pStepList ){
119696:     pStepList->pTrig = pTrig;
119697:     pStepList = pStepList->pNext;
119698:   }
119699:   sqlite3TokenInit(&nameToken, pTrig->zName);
119700:   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
119701:   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) 
119702:    || sqlite3FixExpr(&sFix, pTrig->pWhen) 
119703:   ){
119704:     goto triggerfinish_cleanup;
119705:   }
119706: 
119707:   /* if we are not initializing,
119708:   ** build the sqlite_master entry
119709:   */
119710:   if( !db->init.busy ){
119711:     Vdbe *v;
119712:     char *z;
119713: 
119714:     /* Make an entry in the sqlite_master table */
119715:     v = sqlite3GetVdbe(pParse);
119716:     if( v==0 ) goto triggerfinish_cleanup;
119717:     sqlite3BeginWriteOperation(pParse, 0, iDb);
119718:     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
119719:     sqlite3NestedParse(pParse,
119720:        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
119721:        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
119722:        pTrig->table, z);
119723:     sqlite3DbFree(db, z);
119724:     sqlite3ChangeCookie(pParse, iDb);
119725:     sqlite3VdbeAddParseSchemaOp(v, iDb,
119726:         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
119727:   }
119728: 
119729:   if( db->init.busy ){
119730:     Trigger *pLink = pTrig;
119731:     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
119732:     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119733:     pTrig = sqlite3HashInsert(pHash, zName, pTrig);
119734:     if( pTrig ){
119735:       sqlite3OomFault(db);
119736:     }else if( pLink->pSchema==pLink->pTabSchema ){
119737:       Table *pTab;
119738:       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
119739:       assert( pTab!=0 );
119740:       pLink->pNext = pTab->pTrigger;
119741:       pTab->pTrigger = pLink;
119742:     }
119743:   }
119744: 
119745: triggerfinish_cleanup:
119746:   sqlite3DeleteTrigger(db, pTrig);
119747:   assert( !pParse->pNewTrigger );
119748:   sqlite3DeleteTriggerStep(db, pStepList);
119749: }
119750: 
119751: /*
119752: ** Turn a SELECT statement (that the pSelect parameter points to) into
119753: ** a trigger step.  Return a pointer to a TriggerStep structure.
119754: **
119755: ** The parser calls this routine when it finds a SELECT statement in
119756: ** body of a TRIGGER.  
119757: */
119758: SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
119759:   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
119760:   if( pTriggerStep==0 ) {
119761:     sqlite3SelectDelete(db, pSelect);
119762:     return 0;
119763:   }
119764:   pTriggerStep->op = TK_SELECT;
119765:   pTriggerStep->pSelect = pSelect;
119766:   pTriggerStep->orconf = OE_Default;
119767:   return pTriggerStep;
119768: }
119769: 
119770: /*
119771: ** Allocate space to hold a new trigger step.  The allocated space
119772: ** holds both the TriggerStep object and the TriggerStep.target.z string.
119773: **
119774: ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
119775: */
119776: static TriggerStep *triggerStepAllocate(
119777:   sqlite3 *db,                /* Database connection */
119778:   u8 op,                      /* Trigger opcode */
119779:   Token *pName                /* The target name */
119780: ){
119781:   TriggerStep *pTriggerStep;
119782: 
119783:   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
119784:   if( pTriggerStep ){
119785:     char *z = (char*)&pTriggerStep[1];
119786:     memcpy(z, pName->z, pName->n);
119787:     sqlite3Dequote(z);
119788:     pTriggerStep->zTarget = z;
119789:     pTriggerStep->op = op;
119790:   }
119791:   return pTriggerStep;
119792: }
119793: 
119794: /*
119795: ** Build a trigger step out of an INSERT statement.  Return a pointer
119796: ** to the new trigger step.
119797: **
119798: ** The parser calls this routine when it sees an INSERT inside the
119799: ** body of a trigger.
119800: */
119801: SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
119802:   sqlite3 *db,        /* The database connection */
119803:   Token *pTableName,  /* Name of the table into which we insert */
119804:   IdList *pColumn,    /* List of columns in pTableName to insert into */
119805:   Select *pSelect,    /* A SELECT statement that supplies values */
119806:   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
119807: ){
119808:   TriggerStep *pTriggerStep;
119809: 
119810:   assert(pSelect != 0 || db->mallocFailed);
119811: 
119812:   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
119813:   if( pTriggerStep ){
119814:     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
119815:     pTriggerStep->pIdList = pColumn;
119816:     pTriggerStep->orconf = orconf;
119817:   }else{
119818:     sqlite3IdListDelete(db, pColumn);
119819:   }
119820:   sqlite3SelectDelete(db, pSelect);
119821: 
119822:   return pTriggerStep;
119823: }
119824: 
119825: /*
119826: ** Construct a trigger step that implements an UPDATE statement and return
119827: ** a pointer to that trigger step.  The parser calls this routine when it
119828: ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
119829: */
119830: SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
119831:   sqlite3 *db,         /* The database connection */
119832:   Token *pTableName,   /* Name of the table to be updated */
119833:   ExprList *pEList,    /* The SET clause: list of column and new values */
119834:   Expr *pWhere,        /* The WHERE clause */
119835:   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
119836: ){
119837:   TriggerStep *pTriggerStep;
119838: 
119839:   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
119840:   if( pTriggerStep ){
119841:     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
119842:     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119843:     pTriggerStep->orconf = orconf;
119844:   }
119845:   sqlite3ExprListDelete(db, pEList);
119846:   sqlite3ExprDelete(db, pWhere);
119847:   return pTriggerStep;
119848: }
119849: 
119850: /*
119851: ** Construct a trigger step that implements a DELETE statement and return
119852: ** a pointer to that trigger step.  The parser calls this routine when it
119853: ** sees a DELETE statement inside the body of a CREATE TRIGGER.
119854: */
119855: SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
119856:   sqlite3 *db,            /* Database connection */
119857:   Token *pTableName,      /* The table from which rows are deleted */
119858:   Expr *pWhere            /* The WHERE clause */
119859: ){
119860:   TriggerStep *pTriggerStep;
119861: 
119862:   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
119863:   if( pTriggerStep ){
119864:     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119865:     pTriggerStep->orconf = OE_Default;
119866:   }
119867:   sqlite3ExprDelete(db, pWhere);
119868:   return pTriggerStep;
119869: }
119870: 
119871: /* 
119872: ** Recursively delete a Trigger structure
119873: */
119874: SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
119875:   if( pTrigger==0 ) return;
119876:   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
119877:   sqlite3DbFree(db, pTrigger->zName);
119878:   sqlite3DbFree(db, pTrigger->table);
119879:   sqlite3ExprDelete(db, pTrigger->pWhen);
119880:   sqlite3IdListDelete(db, pTrigger->pColumns);
119881:   sqlite3DbFree(db, pTrigger);
119882: }
119883: 
119884: /*
119885: ** This function is called to drop a trigger from the database schema. 
119886: **
119887: ** This may be called directly from the parser and therefore identifies
119888: ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
119889: ** same job as this routine except it takes a pointer to the trigger
119890: ** instead of the trigger name.
119891: **/
119892: SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
119893:   Trigger *pTrigger = 0;
119894:   int i;
119895:   const char *zDb;
119896:   const char *zName;
119897:   sqlite3 *db = pParse->db;
119898: 
119899:   if( db->mallocFailed ) goto drop_trigger_cleanup;
119900:   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
119901:     goto drop_trigger_cleanup;
119902:   }
119903: 
119904:   assert( pName->nSrc==1 );
119905:   zDb = pName->a[0].zDatabase;
119906:   zName = pName->a[0].zName;
119907:   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
119908:   for(i=OMIT_TEMPDB; i<db->nDb; i++){
119909:     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
119910:     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
119911:     assert( sqlite3SchemaMutexHeld(db, j, 0) );
119912:     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
119913:     if( pTrigger ) break;
119914:   }
119915:   if( !pTrigger ){
119916:     if( !noErr ){
119917:       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
119918:     }else{
119919:       sqlite3CodeVerifyNamedSchema(pParse, zDb);
119920:     }
119921:     pParse->checkSchema = 1;
119922:     goto drop_trigger_cleanup;
119923:   }
119924:   sqlite3DropTriggerPtr(pParse, pTrigger);
119925: 
119926: drop_trigger_cleanup:
119927:   sqlite3SrcListDelete(db, pName);
119928: }
119929: 
119930: /*
119931: ** Return a pointer to the Table structure for the table that a trigger
119932: ** is set on.
119933: */
119934: static Table *tableOfTrigger(Trigger *pTrigger){
119935:   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
119936: }
119937: 
119938: 
119939: /*
119940: ** Drop a trigger given a pointer to that trigger. 
119941: */
119942: SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
119943:   Table   *pTable;
119944:   Vdbe *v;
119945:   sqlite3 *db = pParse->db;
119946:   int iDb;
119947: 
119948:   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
119949:   assert( iDb>=0 && iDb<db->nDb );
119950:   pTable = tableOfTrigger(pTrigger);
119951:   assert( pTable );
119952:   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
119953: #ifndef SQLITE_OMIT_AUTHORIZATION
119954:   {
119955:     int code = SQLITE_DROP_TRIGGER;
119956:     const char *zDb = db->aDb[iDb].zName;
119957:     const char *zTab = SCHEMA_TABLE(iDb);
119958:     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
119959:     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
119960:       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
119961:       return;
119962:     }
119963:   }
119964: #endif
119965: 
119966:   /* Generate code to destroy the database record of the trigger.
119967:   */
119968:   assert( pTable!=0 );
119969:   if( (v = sqlite3GetVdbe(pParse))!=0 ){
119970:     sqlite3NestedParse(pParse,
119971:        "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
119972:        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
119973:     );
119974:     sqlite3ChangeCookie(pParse, iDb);
119975:     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
119976:   }
119977: }
119978: 
119979: /*
119980: ** Remove a trigger from the hash tables of the sqlite* pointer.
119981: */
119982: SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
119983:   Trigger *pTrigger;
119984:   Hash *pHash;
119985: 
119986:   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119987:   pHash = &(db->aDb[iDb].pSchema->trigHash);
119988:   pTrigger = sqlite3HashInsert(pHash, zName, 0);
119989:   if( ALWAYS(pTrigger) ){
119990:     if( pTrigger->pSchema==pTrigger->pTabSchema ){
119991:       Table *pTab = tableOfTrigger(pTrigger);
119992:       Trigger **pp;
119993:       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
119994:       *pp = (*pp)->pNext;
119995:     }
119996:     sqlite3DeleteTrigger(db, pTrigger);
119997:     db->flags |= SQLITE_InternChanges;
119998:   }
119999: }
120000: 
120001: /*
120002: ** pEList is the SET clause of an UPDATE statement.  Each entry
120003: ** in pEList is of the format <id>=<expr>.  If any of the entries
120004: ** in pEList have an <id> which matches an identifier in pIdList,
120005: ** then return TRUE.  If pIdList==NULL, then it is considered a
120006: ** wildcard that matches anything.  Likewise if pEList==NULL then
120007: ** it matches anything so always return true.  Return false only
120008: ** if there is no match.
120009: */
120010: static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
120011:   int e;
120012:   if( pIdList==0 || NEVER(pEList==0) ) return 1;
120013:   for(e=0; e<pEList->nExpr; e++){
120014:     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
120015:   }
120016:   return 0; 
120017: }
120018: 
120019: /*
120020: ** Return a list of all triggers on table pTab if there exists at least
120021: ** one trigger that must be fired when an operation of type 'op' is 
120022: ** performed on the table, and, if that operation is an UPDATE, if at
120023: ** least one of the columns in pChanges is being modified.
120024: */
120025: SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
120026:   Parse *pParse,          /* Parse context */
120027:   Table *pTab,            /* The table the contains the triggers */
120028:   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
120029:   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
120030:   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120031: ){
120032:   int mask = 0;
120033:   Trigger *pList = 0;
120034:   Trigger *p;
120035: 
120036:   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
120037:     pList = sqlite3TriggerList(pParse, pTab);
120038:   }
120039:   assert( pList==0 || IsVirtual(pTab)==0 );
120040:   for(p=pList; p; p=p->pNext){
120041:     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
120042:       mask |= p->tr_tm;
120043:     }
120044:   }
120045:   if( pMask ){
120046:     *pMask = mask;
120047:   }
120048:   return (mask ? pList : 0);
120049: }
120050: 
120051: /*
120052: ** Convert the pStep->zTarget string into a SrcList and return a pointer
120053: ** to that SrcList.
120054: **
120055: ** This routine adds a specific database name, if needed, to the target when
120056: ** forming the SrcList.  This prevents a trigger in one database from
120057: ** referring to a target in another database.  An exception is when the
120058: ** trigger is in TEMP in which case it can refer to any other database it
120059: ** wants.
120060: */
120061: static SrcList *targetSrcList(
120062:   Parse *pParse,       /* The parsing context */
120063:   TriggerStep *pStep   /* The trigger containing the target token */
120064: ){
120065:   sqlite3 *db = pParse->db;
120066:   int iDb;             /* Index of the database to use */
120067:   SrcList *pSrc;       /* SrcList to be returned */
120068: 
120069:   pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
120070:   if( pSrc ){
120071:     assert( pSrc->nSrc>0 );
120072:     pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
120073:     iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
120074:     if( iDb==0 || iDb>=2 ){
120075:       assert( iDb<db->nDb );
120076:       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
120077:     }
120078:   }
120079:   return pSrc;
120080: }
120081: 
120082: /*
120083: ** Generate VDBE code for the statements inside the body of a single 
120084: ** trigger.
120085: */
120086: static int codeTriggerProgram(
120087:   Parse *pParse,            /* The parser context */
120088:   TriggerStep *pStepList,   /* List of statements inside the trigger body */
120089:   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
120090: ){
120091:   TriggerStep *pStep;
120092:   Vdbe *v = pParse->pVdbe;
120093:   sqlite3 *db = pParse->db;
120094: 
120095:   assert( pParse->pTriggerTab && pParse->pToplevel );
120096:   assert( pStepList );
120097:   assert( v!=0 );
120098:   for(pStep=pStepList; pStep; pStep=pStep->pNext){
120099:     /* Figure out the ON CONFLICT policy that will be used for this step
120100:     ** of the trigger program. If the statement that caused this trigger
120101:     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
120102:     ** the ON CONFLICT policy that was specified as part of the trigger
120103:     ** step statement. Example:
120104:     **
120105:     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
120106:     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
120107:     **   END;
120108:     **
120109:     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
120110:     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
120111:     */
120112:     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
120113:     assert( pParse->okConstFactor==0 );
120114: 
120115:     switch( pStep->op ){
120116:       case TK_UPDATE: {
120117:         sqlite3Update(pParse, 
120118:           targetSrcList(pParse, pStep),
120119:           sqlite3ExprListDup(db, pStep->pExprList, 0), 
120120:           sqlite3ExprDup(db, pStep->pWhere, 0), 
120121:           pParse->eOrconf
120122:         );
120123:         break;
120124:       }
120125:       case TK_INSERT: {
120126:         sqlite3Insert(pParse, 
120127:           targetSrcList(pParse, pStep),
120128:           sqlite3SelectDup(db, pStep->pSelect, 0), 
120129:           sqlite3IdListDup(db, pStep->pIdList), 
120130:           pParse->eOrconf
120131:         );
120132:         break;
120133:       }
120134:       case TK_DELETE: {
120135:         sqlite3DeleteFrom(pParse, 
120136:           targetSrcList(pParse, pStep),
120137:           sqlite3ExprDup(db, pStep->pWhere, 0)
120138:         );
120139:         break;
120140:       }
120141:       default: assert( pStep->op==TK_SELECT ); {
120142:         SelectDest sDest;
120143:         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
120144:         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
120145:         sqlite3Select(pParse, pSelect, &sDest);
120146:         sqlite3SelectDelete(db, pSelect);
120147:         break;
120148:       }
120149:     } 
120150:     if( pStep->op!=TK_SELECT ){
120151:       sqlite3VdbeAddOp0(v, OP_ResetCount);
120152:     }
120153:   }
120154: 
120155:   return 0;
120156: }
120157: 
120158: #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
120159: /*
120160: ** This function is used to add VdbeComment() annotations to a VDBE
120161: ** program. It is not used in production code, only for debugging.
120162: */
120163: static const char *onErrorText(int onError){
120164:   switch( onError ){
120165:     case OE_Abort:    return "abort";
120166:     case OE_Rollback: return "rollback";
120167:     case OE_Fail:     return "fail";
120168:     case OE_Replace:  return "replace";
120169:     case OE_Ignore:   return "ignore";
120170:     case OE_Default:  return "default";
120171:   }
120172:   return "n/a";
120173: }
120174: #endif
120175: 
120176: /*
120177: ** Parse context structure pFrom has just been used to create a sub-vdbe
120178: ** (trigger program). If an error has occurred, transfer error information
120179: ** from pFrom to pTo.
120180: */
120181: static void transferParseError(Parse *pTo, Parse *pFrom){
120182:   assert( pFrom->zErrMsg==0 || pFrom->nErr );
120183:   assert( pTo->zErrMsg==0 || pTo->nErr );
120184:   if( pTo->nErr==0 ){
120185:     pTo->zErrMsg = pFrom->zErrMsg;
120186:     pTo->nErr = pFrom->nErr;
120187:     pTo->rc = pFrom->rc;
120188:   }else{
120189:     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
120190:   }
120191: }
120192: 
120193: /*
120194: ** Create and populate a new TriggerPrg object with a sub-program 
120195: ** implementing trigger pTrigger with ON CONFLICT policy orconf.
120196: */
120197: static TriggerPrg *codeRowTrigger(
120198:   Parse *pParse,       /* Current parse context */
120199:   Trigger *pTrigger,   /* Trigger to code */
120200:   Table *pTab,         /* The table pTrigger is attached to */
120201:   int orconf           /* ON CONFLICT policy to code trigger program with */
120202: ){
120203:   Parse *pTop = sqlite3ParseToplevel(pParse);
120204:   sqlite3 *db = pParse->db;   /* Database handle */
120205:   TriggerPrg *pPrg;           /* Value to return */
120206:   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
120207:   Vdbe *v;                    /* Temporary VM */
120208:   NameContext sNC;            /* Name context for sub-vdbe */
120209:   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
120210:   Parse *pSubParse;           /* Parse context for sub-vdbe */
120211:   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
120212: 
120213:   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
120214:   assert( pTop->pVdbe );
120215: 
120216:   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
120217:   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
120218:   ** list of the top-level Parse object sooner rather than later.  */
120219:   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
120220:   if( !pPrg ) return 0;
120221:   pPrg->pNext = pTop->pTriggerPrg;
120222:   pTop->pTriggerPrg = pPrg;
120223:   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
120224:   if( !pProgram ) return 0;
120225:   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
120226:   pPrg->pTrigger = pTrigger;
120227:   pPrg->orconf = orconf;
120228:   pPrg->aColmask[0] = 0xffffffff;
120229:   pPrg->aColmask[1] = 0xffffffff;
120230: 
120231:   /* Allocate and populate a new Parse context to use for coding the 
120232:   ** trigger sub-program.  */
120233:   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
120234:   if( !pSubParse ) return 0;
120235:   memset(&sNC, 0, sizeof(sNC));
120236:   sNC.pParse = pSubParse;
120237:   pSubParse->db = db;
120238:   pSubParse->pTriggerTab = pTab;
120239:   pSubParse->pToplevel = pTop;
120240:   pSubParse->zAuthContext = pTrigger->zName;
120241:   pSubParse->eTriggerOp = pTrigger->op;
120242:   pSubParse->nQueryLoop = pParse->nQueryLoop;
120243: 
120244:   v = sqlite3GetVdbe(pSubParse);
120245:   if( v ){
120246:     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
120247:       pTrigger->zName, onErrorText(orconf),
120248:       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
120249:         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
120250:         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
120251:         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
120252:       pTab->zName
120253:     ));
120254: #ifndef SQLITE_OMIT_TRACE
120255:     sqlite3VdbeChangeP4(v, -1, 
120256:       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
120257:     );
120258: #endif
120259: 
120260:     /* If one was specified, code the WHEN clause. If it evaluates to false
120261:     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
120262:     ** OP_Halt inserted at the end of the program.  */
120263:     if( pTrigger->pWhen ){
120264:       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
120265:       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
120266:        && db->mallocFailed==0 
120267:       ){
120268:         iEndTrigger = sqlite3VdbeMakeLabel(v);
120269:         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
120270:       }
120271:       sqlite3ExprDelete(db, pWhen);
120272:     }
120273: 
120274:     /* Code the trigger program into the sub-vdbe. */
120275:     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
120276: 
120277:     /* Insert an OP_Halt at the end of the sub-program. */
120278:     if( iEndTrigger ){
120279:       sqlite3VdbeResolveLabel(v, iEndTrigger);
120280:     }
120281:     sqlite3VdbeAddOp0(v, OP_Halt);
120282:     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
120283: 
120284:     transferParseError(pParse, pSubParse);
120285:     if( db->mallocFailed==0 ){
120286:       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
120287:     }
120288:     pProgram->nMem = pSubParse->nMem;
120289:     pProgram->nCsr = pSubParse->nTab;
120290:     pProgram->nOnce = pSubParse->nOnce;
120291:     pProgram->token = (void *)pTrigger;
120292:     pPrg->aColmask[0] = pSubParse->oldmask;
120293:     pPrg->aColmask[1] = pSubParse->newmask;
120294:     sqlite3VdbeDelete(v);
120295:   }
120296: 
120297:   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
120298:   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
120299:   sqlite3ParserReset(pSubParse);
120300:   sqlite3StackFree(db, pSubParse);
120301: 
120302:   return pPrg;
120303: }
120304:     
120305: /*
120306: ** Return a pointer to a TriggerPrg object containing the sub-program for
120307: ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
120308: ** TriggerPrg object exists, a new object is allocated and populated before
120309: ** being returned.
120310: */
120311: static TriggerPrg *getRowTrigger(
120312:   Parse *pParse,       /* Current parse context */
120313:   Trigger *pTrigger,   /* Trigger to code */
120314:   Table *pTab,         /* The table trigger pTrigger is attached to */
120315:   int orconf           /* ON CONFLICT algorithm. */
120316: ){
120317:   Parse *pRoot = sqlite3ParseToplevel(pParse);
120318:   TriggerPrg *pPrg;
120319: 
120320:   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
120321: 
120322:   /* It may be that this trigger has already been coded (or is in the
120323:   ** process of being coded). If this is the case, then an entry with
120324:   ** a matching TriggerPrg.pTrigger field will be present somewhere
120325:   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
120326:   for(pPrg=pRoot->pTriggerPrg; 
120327:       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
120328:       pPrg=pPrg->pNext
120329:   );
120330: 
120331:   /* If an existing TriggerPrg could not be located, create a new one. */
120332:   if( !pPrg ){
120333:     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
120334:   }
120335: 
120336:   return pPrg;
120337: }
120338: 
120339: /*
120340: ** Generate code for the trigger program associated with trigger p on 
120341: ** table pTab. The reg, orconf and ignoreJump parameters passed to this
120342: ** function are the same as those described in the header function for
120343: ** sqlite3CodeRowTrigger()
120344: */
120345: SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
120346:   Parse *pParse,       /* Parse context */
120347:   Trigger *p,          /* Trigger to code */
120348:   Table *pTab,         /* The table to code triggers from */
120349:   int reg,             /* Reg array containing OLD.* and NEW.* values */
120350:   int orconf,          /* ON CONFLICT policy */
120351:   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
120352: ){
120353:   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
120354:   TriggerPrg *pPrg;
120355:   pPrg = getRowTrigger(pParse, p, pTab, orconf);
120356:   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
120357: 
120358:   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
120359:   ** is a pointer to the sub-vdbe containing the trigger program.  */
120360:   if( pPrg ){
120361:     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
120362: 
120363:     sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
120364:                       (const char *)pPrg->pProgram, P4_SUBPROGRAM);
120365:     VdbeComment(
120366:         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
120367: 
120368:     /* Set the P5 operand of the OP_Program instruction to non-zero if
120369:     ** recursive invocation of this trigger program is disallowed. Recursive
120370:     ** invocation is disallowed if (a) the sub-program is really a trigger,
120371:     ** not a foreign key action, and (b) the flag to enable recursive triggers
120372:     ** is clear.  */
120373:     sqlite3VdbeChangeP5(v, (u8)bRecursive);
120374:   }
120375: }
120376: 
120377: /*
120378: ** This is called to code the required FOR EACH ROW triggers for an operation
120379: ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
120380: ** is given by the op parameter. The tr_tm parameter determines whether the
120381: ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
120382: ** parameter pChanges is passed the list of columns being modified.
120383: **
120384: ** If there are no triggers that fire at the specified time for the specified
120385: ** operation on pTab, this function is a no-op.
120386: **
120387: ** The reg argument is the address of the first in an array of registers 
120388: ** that contain the values substituted for the new.* and old.* references
120389: ** in the trigger program. If N is the number of columns in table pTab
120390: ** (a copy of pTab->nCol), then registers are populated as follows:
120391: **
120392: **   Register       Contains
120393: **   ------------------------------------------------------
120394: **   reg+0          OLD.rowid
120395: **   reg+1          OLD.* value of left-most column of pTab
120396: **   ...            ...
120397: **   reg+N          OLD.* value of right-most column of pTab
120398: **   reg+N+1        NEW.rowid
120399: **   reg+N+2        OLD.* value of left-most column of pTab
120400: **   ...            ...
120401: **   reg+N+N+1      NEW.* value of right-most column of pTab
120402: **
120403: ** For ON DELETE triggers, the registers containing the NEW.* values will
120404: ** never be accessed by the trigger program, so they are not allocated or 
120405: ** populated by the caller (there is no data to populate them with anyway). 
120406: ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
120407: ** are never accessed, and so are not allocated by the caller. So, for an
120408: ** ON INSERT trigger, the value passed to this function as parameter reg
120409: ** is not a readable register, although registers (reg+N) through 
120410: ** (reg+N+N+1) are.
120411: **
120412: ** Parameter orconf is the default conflict resolution algorithm for the
120413: ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
120414: ** is the instruction that control should jump to if a trigger program
120415: ** raises an IGNORE exception.
120416: */
120417: SQLITE_PRIVATE void sqlite3CodeRowTrigger(
120418:   Parse *pParse,       /* Parse context */
120419:   Trigger *pTrigger,   /* List of triggers on table pTab */
120420:   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
120421:   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
120422:   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
120423:   Table *pTab,         /* The table to code triggers from */
120424:   int reg,             /* The first in an array of registers (see above) */
120425:   int orconf,          /* ON CONFLICT policy */
120426:   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
120427: ){
120428:   Trigger *p;          /* Used to iterate through pTrigger list */
120429: 
120430:   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
120431:   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
120432:   assert( (op==TK_UPDATE)==(pChanges!=0) );
120433: 
120434:   for(p=pTrigger; p; p=p->pNext){
120435: 
120436:     /* Sanity checking:  The schema for the trigger and for the table are
120437:     ** always defined.  The trigger must be in the same schema as the table
120438:     ** or else it must be a TEMP trigger. */
120439:     assert( p->pSchema!=0 );
120440:     assert( p->pTabSchema!=0 );
120441:     assert( p->pSchema==p->pTabSchema 
120442:          || p->pSchema==pParse->db->aDb[1].pSchema );
120443: 
120444:     /* Determine whether we should code this trigger */
120445:     if( p->op==op 
120446:      && p->tr_tm==tr_tm 
120447:      && checkColumnOverlap(p->pColumns, pChanges)
120448:     ){
120449:       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
120450:     }
120451:   }
120452: }
120453: 
120454: /*
120455: ** Triggers may access values stored in the old.* or new.* pseudo-table. 
120456: ** This function returns a 32-bit bitmask indicating which columns of the 
120457: ** old.* or new.* tables actually are used by triggers. This information 
120458: ** may be used by the caller, for example, to avoid having to load the entire
120459: ** old.* record into memory when executing an UPDATE or DELETE command.
120460: **
120461: ** Bit 0 of the returned mask is set if the left-most column of the
120462: ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
120463: ** the second leftmost column value is required, and so on. If there
120464: ** are more than 32 columns in the table, and at least one of the columns
120465: ** with an index greater than 32 may be accessed, 0xffffffff is returned.
120466: **
120467: ** It is not possible to determine if the old.rowid or new.rowid column is 
120468: ** accessed by triggers. The caller must always assume that it is.
120469: **
120470: ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
120471: ** applies to the old.* table. If 1, the new.* table.
120472: **
120473: ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
120474: ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
120475: ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
120476: ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
120477: ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
120478: */
120479: SQLITE_PRIVATE u32 sqlite3TriggerColmask(
120480:   Parse *pParse,       /* Parse context */
120481:   Trigger *pTrigger,   /* List of triggers on table pTab */
120482:   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
120483:   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
120484:   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120485:   Table *pTab,         /* The table to code triggers from */
120486:   int orconf           /* Default ON CONFLICT policy for trigger steps */
120487: ){
120488:   const int op = pChanges ? TK_UPDATE : TK_DELETE;
120489:   u32 mask = 0;
120490:   Trigger *p;
120491: 
120492:   assert( isNew==1 || isNew==0 );
120493:   for(p=pTrigger; p; p=p->pNext){
120494:     if( p->op==op && (tr_tm&p->tr_tm)
120495:      && checkColumnOverlap(p->pColumns,pChanges)
120496:     ){
120497:       TriggerPrg *pPrg;
120498:       pPrg = getRowTrigger(pParse, p, pTab, orconf);
120499:       if( pPrg ){
120500:         mask |= pPrg->aColmask[isNew];
120501:       }
120502:     }
120503:   }
120504: 
120505:   return mask;
120506: }
120507: 
120508: #endif /* !defined(SQLITE_OMIT_TRIGGER) */
120509: 
120510: /************** End of trigger.c *********************************************/
120511: /************** Begin file update.c ******************************************/
120512: /*
120513: ** 2001 September 15
120514: **
120515: ** The author disclaims copyright to this source code.  In place of
120516: ** a legal notice, here is a blessing:
120517: **
120518: **    May you do good and not evil.
120519: **    May you find forgiveness for yourself and forgive others.
120520: **    May you share freely, never taking more than you give.
120521: **
120522: *************************************************************************
120523: ** This file contains C code routines that are called by the parser
120524: ** to handle UPDATE statements.
120525: */
120526: /* #include "sqliteInt.h" */
120527: 
120528: #ifndef SQLITE_OMIT_VIRTUALTABLE
120529: /* Forward declaration */
120530: static void updateVirtualTable(
120531:   Parse *pParse,       /* The parsing context */
120532:   SrcList *pSrc,       /* The virtual table to be modified */
120533:   Table *pTab,         /* The virtual table */
120534:   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
120535:   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
120536:   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
120537:   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
120538:   int onError          /* ON CONFLICT strategy */
120539: );
120540: #endif /* SQLITE_OMIT_VIRTUALTABLE */
120541: 
120542: /*
120543: ** The most recently coded instruction was an OP_Column to retrieve the
120544: ** i-th column of table pTab. This routine sets the P4 parameter of the 
120545: ** OP_Column to the default value, if any.
120546: **
120547: ** The default value of a column is specified by a DEFAULT clause in the 
120548: ** column definition. This was either supplied by the user when the table
120549: ** was created, or added later to the table definition by an ALTER TABLE
120550: ** command. If the latter, then the row-records in the table btree on disk
120551: ** may not contain a value for the column and the default value, taken
120552: ** from the P4 parameter of the OP_Column instruction, is returned instead.
120553: ** If the former, then all row-records are guaranteed to include a value
120554: ** for the column and the P4 value is not required.
120555: **
120556: ** Column definitions created by an ALTER TABLE command may only have 
120557: ** literal default values specified: a number, null or a string. (If a more
120558: ** complicated default expression value was provided, it is evaluated 
120559: ** when the ALTER TABLE is executed and one of the literal values written
120560: ** into the sqlite_master table.)
120561: **
120562: ** Therefore, the P4 parameter is only required if the default value for
120563: ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
120564: ** function is capable of transforming these types of expressions into
120565: ** sqlite3_value objects.
120566: **
120567: ** If parameter iReg is not negative, code an OP_RealAffinity instruction
120568: ** on register iReg. This is used when an equivalent integer value is 
120569: ** stored in place of an 8-byte floating point value in order to save 
120570: ** space.
120571: */
120572: SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
120573:   assert( pTab!=0 );
120574:   if( !pTab->pSelect ){
120575:     sqlite3_value *pValue = 0;
120576:     u8 enc = ENC(sqlite3VdbeDb(v));
120577:     Column *pCol = &pTab->aCol[i];
120578:     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
120579:     assert( i<pTab->nCol );
120580:     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
120581:                          pCol->affinity, &pValue);
120582:     if( pValue ){
120583:       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
120584:     }
120585: #ifndef SQLITE_OMIT_FLOATING_POINT
120586:     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
120587:       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
120588:     }
120589: #endif
120590:   }
120591: }
120592: 
120593: /*
120594: ** Process an UPDATE statement.
120595: **
120596: **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
120597: **          \_______/ \________/     \______/       \________________/
120598: *            onError   pTabList      pChanges             pWhere
120599: */
120600: SQLITE_PRIVATE void sqlite3Update(
120601:   Parse *pParse,         /* The parser context */
120602:   SrcList *pTabList,     /* The table in which we should change things */
120603:   ExprList *pChanges,    /* Things to be changed */
120604:   Expr *pWhere,          /* The WHERE clause.  May be null */
120605:   int onError            /* How to handle constraint errors */
120606: ){
120607:   int i, j;              /* Loop counters */
120608:   Table *pTab;           /* The table to be updated */
120609:   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
120610:   WhereInfo *pWInfo;     /* Information about the WHERE clause */
120611:   Vdbe *v;               /* The virtual database engine */
120612:   Index *pIdx;           /* For looping over indices */
120613:   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
120614:   int nIdx;              /* Number of indices that need updating */
120615:   int iBaseCur;          /* Base cursor number */
120616:   int iDataCur;          /* Cursor for the canonical data btree */
120617:   int iIdxCur;           /* Cursor for the first index */
120618:   sqlite3 *db;           /* The database structure */
120619:   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
120620:   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
120621:                          ** an expression for the i-th column of the table.
120622:                          ** aXRef[i]==-1 if the i-th column is not changed. */
120623:   u8 *aToOpen;           /* 1 for tables and indices to be opened */
120624:   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
120625:   u8 chngRowid;          /* Rowid changed in a normal table */
120626:   u8 chngKey;            /* Either chngPk or chngRowid */
120627:   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
120628:   AuthContext sContext;  /* The authorization context */
120629:   NameContext sNC;       /* The name-context to resolve expressions in */
120630:   int iDb;               /* Database containing the table being updated */
120631:   int okOnePass;         /* True for one-pass algorithm without the FIFO */
120632:   int hasFK;             /* True if foreign key processing is required */
120633:   int labelBreak;        /* Jump here to break out of UPDATE loop */
120634:   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
120635: 
120636: #ifndef SQLITE_OMIT_TRIGGER
120637:   int isView;            /* True when updating a view (INSTEAD OF trigger) */
120638:   Trigger *pTrigger;     /* List of triggers on pTab, if required */
120639:   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
120640: #endif
120641:   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
120642:   int iEph = 0;          /* Ephemeral table holding all primary key values */
120643:   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
120644:   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
120645: 
120646:   /* Register Allocations */
120647:   int regRowCount = 0;   /* A count of rows changed */
120648:   int regOldRowid = 0;   /* The old rowid */
120649:   int regNewRowid = 0;   /* The new rowid */
120650:   int regNew = 0;        /* Content of the NEW.* table in triggers */
120651:   int regOld = 0;        /* Content of OLD.* table in triggers */
120652:   int regRowSet = 0;     /* Rowset of rows to be updated */
120653:   int regKey = 0;        /* composite PRIMARY KEY value */
120654: 
120655:   memset(&sContext, 0, sizeof(sContext));
120656:   db = pParse->db;
120657:   if( pParse->nErr || db->mallocFailed ){
120658:     goto update_cleanup;
120659:   }
120660:   assert( pTabList->nSrc==1 );
120661: 
120662:   /* Locate the table which we want to update. 
120663:   */
120664:   pTab = sqlite3SrcListLookup(pParse, pTabList);
120665:   if( pTab==0 ) goto update_cleanup;
120666:   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
120667: 
120668:   /* Figure out if we have any triggers and if the table being
120669:   ** updated is a view.
120670:   */
120671: #ifndef SQLITE_OMIT_TRIGGER
120672:   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
120673:   isView = pTab->pSelect!=0;
120674:   assert( pTrigger || tmask==0 );
120675: #else
120676: # define pTrigger 0
120677: # define isView 0
120678: # define tmask 0
120679: #endif
120680: #ifdef SQLITE_OMIT_VIEW
120681: # undef isView
120682: # define isView 0
120683: #endif
120684: 
120685:   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
120686:     goto update_cleanup;
120687:   }
120688:   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
120689:     goto update_cleanup;
120690:   }
120691: 
120692:   /* Allocate a cursors for the main database table and for all indices.
120693:   ** The index cursors might not be used, but if they are used they
120694:   ** need to occur right after the database cursor.  So go ahead and
120695:   ** allocate enough space, just in case.
120696:   */
120697:   pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
120698:   iIdxCur = iDataCur+1;
120699:   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
120700:   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
120701:     if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
120702:       iDataCur = pParse->nTab;
120703:       pTabList->a[0].iCursor = iDataCur;
120704:     }
120705:     pParse->nTab++;
120706:   }
120707: 
120708:   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  
120709:   ** Initialize aXRef[] and aToOpen[] to their default values.
120710:   */
120711:   aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
120712:   if( aXRef==0 ) goto update_cleanup;
120713:   aRegIdx = aXRef+pTab->nCol;
120714:   aToOpen = (u8*)(aRegIdx+nIdx);
120715:   memset(aToOpen, 1, nIdx+1);
120716:   aToOpen[nIdx+1] = 0;
120717:   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
120718: 
120719:   /* Initialize the name-context */
120720:   memset(&sNC, 0, sizeof(sNC));
120721:   sNC.pParse = pParse;
120722:   sNC.pSrcList = pTabList;
120723: 
120724:   /* Resolve the column names in all the expressions of the
120725:   ** of the UPDATE statement.  Also find the column index
120726:   ** for each column to be updated in the pChanges array.  For each
120727:   ** column to be updated, make sure we have authorization to change
120728:   ** that column.
120729:   */
120730:   chngRowid = chngPk = 0;
120731:   for(i=0; i<pChanges->nExpr; i++){
120732:     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
120733:       goto update_cleanup;
120734:     }
120735:     for(j=0; j<pTab->nCol; j++){
120736:       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
120737:         if( j==pTab->iPKey ){
120738:           chngRowid = 1;
120739:           pRowidExpr = pChanges->a[i].pExpr;
120740:         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
120741:           chngPk = 1;
120742:         }
120743:         aXRef[j] = i;
120744:         break;
120745:       }
120746:     }
120747:     if( j>=pTab->nCol ){
120748:       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
120749:         j = -1;
120750:         chngRowid = 1;
120751:         pRowidExpr = pChanges->a[i].pExpr;
120752:       }else{
120753:         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
120754:         pParse->checkSchema = 1;
120755:         goto update_cleanup;
120756:       }
120757:     }
120758: #ifndef SQLITE_OMIT_AUTHORIZATION
120759:     {
120760:       int rc;
120761:       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
120762:                             j<0 ? "ROWID" : pTab->aCol[j].zName,
120763:                             db->aDb[iDb].zName);
120764:       if( rc==SQLITE_DENY ){
120765:         goto update_cleanup;
120766:       }else if( rc==SQLITE_IGNORE ){
120767:         aXRef[j] = -1;
120768:       }
120769:     }
120770: #endif
120771:   }
120772:   assert( (chngRowid & chngPk)==0 );
120773:   assert( chngRowid==0 || chngRowid==1 );
120774:   assert( chngPk==0 || chngPk==1 );
120775:   chngKey = chngRowid + chngPk;
120776: 
120777:   /* The SET expressions are not actually used inside the WHERE loop.  
120778:   ** So reset the colUsed mask. Unless this is a virtual table. In that
120779:   ** case, set all bits of the colUsed mask (to ensure that the virtual
120780:   ** table implementation makes all columns available).
120781:   */
120782:   pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
120783: 
120784:   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
120785: 
120786:   /* There is one entry in the aRegIdx[] array for each index on the table
120787:   ** being updated.  Fill in aRegIdx[] with a register number that will hold
120788:   ** the key for accessing each index.
120789:   **
120790:   ** FIXME:  Be smarter about omitting indexes that use expressions.
120791:   */
120792:   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
120793:     int reg;
120794:     if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
120795:       reg = ++pParse->nMem;
120796:     }else{
120797:       reg = 0;
120798:       for(i=0; i<pIdx->nKeyCol; i++){
120799:         i16 iIdxCol = pIdx->aiColumn[i];
120800:         if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
120801:           reg = ++pParse->nMem;
120802:           break;
120803:         }
120804:       }
120805:     }
120806:     if( reg==0 ) aToOpen[j+1] = 0;
120807:     aRegIdx[j] = reg;
120808:   }
120809: 
120810:   /* Begin generating code. */
120811:   v = sqlite3GetVdbe(pParse);
120812:   if( v==0 ) goto update_cleanup;
120813:   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
120814:   sqlite3BeginWriteOperation(pParse, 1, iDb);
120815: 
120816:   /* Allocate required registers. */
120817:   if( !IsVirtual(pTab) ){
120818:     regRowSet = ++pParse->nMem;
120819:     regOldRowid = regNewRowid = ++pParse->nMem;
120820:     if( chngPk || pTrigger || hasFK ){
120821:       regOld = pParse->nMem + 1;
120822:       pParse->nMem += pTab->nCol;
120823:     }
120824:     if( chngKey || pTrigger || hasFK ){
120825:       regNewRowid = ++pParse->nMem;
120826:     }
120827:     regNew = pParse->nMem + 1;
120828:     pParse->nMem += pTab->nCol;
120829:   }
120830: 
120831:   /* Start the view context. */
120832:   if( isView ){
120833:     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
120834:   }
120835: 
120836:   /* If we are trying to update a view, realize that view into
120837:   ** an ephemeral table.
120838:   */
120839: #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
120840:   if( isView ){
120841:     sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
120842:   }
120843: #endif
120844: 
120845:   /* Resolve the column names in all the expressions in the
120846:   ** WHERE clause.
120847:   */
120848:   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
120849:     goto update_cleanup;
120850:   }
120851: 
120852: #ifndef SQLITE_OMIT_VIRTUALTABLE
120853:   /* Virtual tables must be handled separately */
120854:   if( IsVirtual(pTab) ){
120855:     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
120856:                        pWhere, onError);
120857:     goto update_cleanup;
120858:   }
120859: #endif
120860: 
120861:   /* Begin the database scan
120862:   */
120863:   if( HasRowid(pTab) ){
120864:     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
120865:     pWInfo = sqlite3WhereBegin(
120866:         pParse, pTabList, pWhere, 0, 0,
120867:             WHERE_ONEPASS_DESIRED | WHERE_SEEK_TABLE, iIdxCur
120868:     );
120869:     if( pWInfo==0 ) goto update_cleanup;
120870:     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120871:   
120872:     /* Remember the rowid of every item to be updated.
120873:     */
120874:     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
120875:     if( !okOnePass ){
120876:       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
120877:     }
120878:   
120879:     /* End the database scan loop.
120880:     */
120881:     sqlite3WhereEnd(pWInfo);
120882:   }else{
120883:     int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
120884:     i16 nPk;         /* Number of components of the PRIMARY KEY */
120885:     int addrOpen;    /* Address of the OpenEphemeral instruction */
120886: 
120887:     assert( pPk!=0 );
120888:     nPk = pPk->nKeyCol;
120889:     iPk = pParse->nMem+1;
120890:     pParse->nMem += nPk;
120891:     regKey = ++pParse->nMem;
120892:     iEph = pParse->nTab++;
120893:     sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
120894:     addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
120895:     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
120896:     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, 
120897:                                WHERE_ONEPASS_DESIRED, iIdxCur);
120898:     if( pWInfo==0 ) goto update_cleanup;
120899:     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120900:     for(i=0; i<nPk; i++){
120901:       assert( pPk->aiColumn[i]>=0 );
120902:       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
120903:                                       iPk+i);
120904:     }
120905:     if( okOnePass ){
120906:       sqlite3VdbeChangeToNoop(v, addrOpen);
120907:       nKey = nPk;
120908:       regKey = iPk;
120909:     }else{
120910:       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
120911:                         sqlite3IndexAffinityStr(db, pPk), nPk);
120912:       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
120913:     }
120914:     sqlite3WhereEnd(pWInfo);
120915:   }
120916: 
120917:   /* Initialize the count of updated rows
120918:   */
120919:   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
120920:     regRowCount = ++pParse->nMem;
120921:     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
120922:   }
120923: 
120924:   labelBreak = sqlite3VdbeMakeLabel(v);
120925:   if( !isView ){
120926:     /* 
120927:     ** Open every index that needs updating.  Note that if any
120928:     ** index could potentially invoke a REPLACE conflict resolution 
120929:     ** action, then we need to open all indices because we might need
120930:     ** to be deleting some records.
120931:     */
120932:     if( onError==OE_Replace ){
120933:       memset(aToOpen, 1, nIdx+1);
120934:     }else{
120935:       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120936:         if( pIdx->onError==OE_Replace ){
120937:           memset(aToOpen, 1, nIdx+1);
120938:           break;
120939:         }
120940:       }
120941:     }
120942:     if( okOnePass ){
120943:       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
120944:       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
120945:     }
120946:     sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
120947:                                0, 0);
120948:   }
120949: 
120950:   /* Top of the update loop */
120951:   if( okOnePass ){
120952:     if( aToOpen[iDataCur-iBaseCur] && !isView ){
120953:       assert( pPk );
120954:       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
120955:       VdbeCoverageNeverTaken(v);
120956:     }
120957:     labelContinue = labelBreak;
120958:     sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
120959:     VdbeCoverageIf(v, pPk==0);
120960:     VdbeCoverageIf(v, pPk!=0);
120961:   }else if( pPk ){
120962:     labelContinue = sqlite3VdbeMakeLabel(v);
120963:     sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
120964:     addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
120965:     sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
120966:     VdbeCoverage(v);
120967:   }else{
120968:     labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
120969:                              regOldRowid);
120970:     VdbeCoverage(v);
120971:     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
120972:     VdbeCoverage(v);
120973:   }
120974: 
120975:   /* If the record number will change, set register regNewRowid to
120976:   ** contain the new value. If the record number is not being modified,
120977:   ** then regNewRowid is the same register as regOldRowid, which is
120978:   ** already populated.  */
120979:   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
120980:   if( chngRowid ){
120981:     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
120982:     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
120983:   }
120984: 
120985:   /* Compute the old pre-UPDATE content of the row being changed, if that
120986:   ** information is needed */
120987:   if( chngPk || hasFK || pTrigger ){
120988:     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
120989:     oldmask |= sqlite3TriggerColmask(pParse, 
120990:         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
120991:     );
120992:     for(i=0; i<pTab->nCol; i++){
120993:       if( oldmask==0xffffffff
120994:        || (i<32 && (oldmask & MASKBIT32(i))!=0)
120995:        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
120996:       ){
120997:         testcase(  oldmask!=0xffffffff && i==31 );
120998:         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
120999:       }else{
121000:         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
121001:       }
121002:     }
121003:     if( chngRowid==0 && pPk==0 ){
121004:       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
121005:     }
121006:   }
121007: 
121008:   /* Populate the array of registers beginning at regNew with the new
121009:   ** row data. This array is used to check constants, create the new
121010:   ** table and index records, and as the values for any new.* references
121011:   ** made by triggers.
121012:   **
121013:   ** If there are one or more BEFORE triggers, then do not populate the
121014:   ** registers associated with columns that are (a) not modified by
121015:   ** this UPDATE statement and (b) not accessed by new.* references. The
121016:   ** values for registers not modified by the UPDATE must be reloaded from 
121017:   ** the database after the BEFORE triggers are fired anyway (as the trigger 
121018:   ** may have modified them). So not loading those that are not going to
121019:   ** be used eliminates some redundant opcodes.
121020:   */
121021:   newmask = sqlite3TriggerColmask(
121022:       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
121023:   );
121024:   for(i=0; i<pTab->nCol; i++){
121025:     if( i==pTab->iPKey ){
121026:       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121027:     }else{
121028:       j = aXRef[i];
121029:       if( j>=0 ){
121030:         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
121031:       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
121032:         /* This branch loads the value of a column that will not be changed 
121033:         ** into a register. This is done if there are no BEFORE triggers, or
121034:         ** if there are one or more BEFORE triggers that use this value via
121035:         ** a new.* reference in a trigger program.
121036:         */
121037:         testcase( i==31 );
121038:         testcase( i==32 );
121039:         sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
121040:       }else{
121041:         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
121042:       }
121043:     }
121044:   }
121045: 
121046:   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
121047:   ** verified. One could argue that this is wrong.
121048:   */
121049:   if( tmask&TRIGGER_BEFORE ){
121050:     sqlite3TableAffinity(v, pTab, regNew);
121051:     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
121052:         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
121053: 
121054:     /* The row-trigger may have deleted the row being updated. In this
121055:     ** case, jump to the next row. No updates or AFTER triggers are 
121056:     ** required. This behavior - what happens when the row being updated
121057:     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
121058:     ** documentation.
121059:     */
121060:     if( pPk ){
121061:       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
121062:       VdbeCoverage(v);
121063:     }else{
121064:       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
121065:       VdbeCoverage(v);
121066:     }
121067: 
121068:     /* If it did not delete it, the row-trigger may still have modified 
121069:     ** some of the columns of the row being updated. Load the values for 
121070:     ** all columns not modified by the update statement into their 
121071:     ** registers in case this has happened.
121072:     */
121073:     for(i=0; i<pTab->nCol; i++){
121074:       if( aXRef[i]<0 && i!=pTab->iPKey ){
121075:         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
121076:       }
121077:     }
121078:   }
121079: 
121080:   if( !isView ){
121081:     int addr1 = 0;        /* Address of jump instruction */
121082:     int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
121083: 
121084:     /* Do constraint checks. */
121085:     assert( regOldRowid>0 );
121086:     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
121087:         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
121088:         aXRef);
121089: 
121090:     /* Do FK constraint checks. */
121091:     if( hasFK ){
121092:       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
121093:     }
121094: 
121095:     /* Delete the index entries associated with the current record.  */
121096:     if( bReplace || chngKey ){
121097:       if( pPk ){
121098:         addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
121099:       }else{
121100:         addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
121101:       }
121102:       VdbeCoverageNeverTaken(v);
121103:     }
121104:     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
121105: 
121106:     /* If changing the rowid value, or if there are foreign key constraints
121107:     ** to process, delete the old record. Otherwise, add a noop OP_Delete
121108:     ** to invoke the pre-update hook.
121109:     **
121110:     ** That (regNew==regnewRowid+1) is true is also important for the 
121111:     ** pre-update hook. If the caller invokes preupdate_new(), the returned
121112:     ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
121113:     ** is the column index supplied by the user.
121114:     */
121115:     assert( regNew==regNewRowid+1 );
121116: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
121117:     sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
121118:         OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
121119:         regNewRowid
121120:     );
121121:     if( !pParse->nested ){
121122:       sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
121123:     }
121124: #else
121125:     if( hasFK || chngKey || pPk!=0 ){
121126:       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
121127:     }
121128: #endif
121129:     if( bReplace || chngKey ){
121130:       sqlite3VdbeJumpHere(v, addr1);
121131:     }
121132: 
121133:     if( hasFK ){
121134:       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
121135:     }
121136:   
121137:     /* Insert the new index entries and the new record. */
121138:     sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
121139:                              regNewRowid, aRegIdx, 1, 0, 0);
121140: 
121141:     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
121142:     ** handle rows (possibly in other tables) that refer via a foreign key
121143:     ** to the row just updated. */ 
121144:     if( hasFK ){
121145:       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
121146:     }
121147:   }
121148: 
121149:   /* Increment the row counter 
121150:   */
121151:   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
121152:     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
121153:   }
121154: 
121155:   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
121156:       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
121157: 
121158:   /* Repeat the above with the next record to be updated, until
121159:   ** all record selected by the WHERE clause have been updated.
121160:   */
121161:   if( okOnePass ){
121162:     /* Nothing to do at end-of-loop for a single-pass */
121163:   }else if( pPk ){
121164:     sqlite3VdbeResolveLabel(v, labelContinue);
121165:     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
121166:   }else{
121167:     sqlite3VdbeGoto(v, labelContinue);
121168:   }
121169:   sqlite3VdbeResolveLabel(v, labelBreak);
121170: 
121171:   /* Close all tables */
121172:   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
121173:     assert( aRegIdx );
121174:     if( aToOpen[i+1] ){
121175:       sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
121176:     }
121177:   }
121178:   if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
121179: 
121180:   /* Update the sqlite_sequence table by storing the content of the
121181:   ** maximum rowid counter values recorded while inserting into
121182:   ** autoincrement tables.
121183:   */
121184:   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
121185:     sqlite3AutoincrementEnd(pParse);
121186:   }
121187: 
121188:   /*
121189:   ** Return the number of rows that were changed. If this routine is 
121190:   ** generating code because of a call to sqlite3NestedParse(), do not
121191:   ** invoke the callback function.
121192:   */
121193:   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
121194:     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
121195:     sqlite3VdbeSetNumCols(v, 1);
121196:     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
121197:   }
121198: 
121199: update_cleanup:
121200:   sqlite3AuthContextPop(&sContext);
121201:   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
121202:   sqlite3SrcListDelete(db, pTabList);
121203:   sqlite3ExprListDelete(db, pChanges);
121204:   sqlite3ExprDelete(db, pWhere);
121205:   return;
121206: }
121207: /* Make sure "isView" and other macros defined above are undefined. Otherwise
121208: ** they may interfere with compilation of other functions in this file
121209: ** (or in another file, if this file becomes part of the amalgamation).  */
121210: #ifdef isView
121211:  #undef isView
121212: #endif
121213: #ifdef pTrigger
121214:  #undef pTrigger
121215: #endif
121216: 
121217: #ifndef SQLITE_OMIT_VIRTUALTABLE
121218: /*
121219: ** Generate code for an UPDATE of a virtual table.
121220: **
121221: ** There are two possible strategies - the default and the special 
121222: ** "onepass" strategy. Onepass is only used if the virtual table 
121223: ** implementation indicates that pWhere may match at most one row.
121224: **
121225: ** The default strategy is to create an ephemeral table that contains
121226: ** for each row to be changed:
121227: **
121228: **   (A)  The original rowid of that row.
121229: **   (B)  The revised rowid for the row.
121230: **   (C)  The content of every column in the row.
121231: **
121232: ** Then loop through the contents of this ephemeral table executing a
121233: ** VUpdate for each row. When finished, drop the ephemeral table.
121234: **
121235: ** The "onepass" strategy does not use an ephemeral table. Instead, it
121236: ** stores the same values (A, B and C above) in a register array and
121237: ** makes a single invocation of VUpdate.
121238: */
121239: static void updateVirtualTable(
121240:   Parse *pParse,       /* The parsing context */
121241:   SrcList *pSrc,       /* The virtual table to be modified */
121242:   Table *pTab,         /* The virtual table */
121243:   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
121244:   Expr *pRowid,        /* Expression used to recompute the rowid */
121245:   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
121246:   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
121247:   int onError          /* ON CONFLICT strategy */
121248: ){
121249:   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
121250:   int ephemTab;             /* Table holding the result of the SELECT */
121251:   int i;                    /* Loop counter */
121252:   sqlite3 *db = pParse->db; /* Database connection */
121253:   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
121254:   WhereInfo *pWInfo;
121255:   int nArg = 2 + pTab->nCol;      /* Number of arguments to VUpdate */
121256:   int regArg;                     /* First register in VUpdate arg array */
121257:   int regRec;                     /* Register in which to assemble record */
121258:   int regRowid;                   /* Register for ephem table rowid */
121259:   int iCsr = pSrc->a[0].iCursor;  /* Cursor used for virtual table scan */
121260:   int aDummy[2];                  /* Unused arg for sqlite3WhereOkOnePass() */
121261:   int bOnePass;                   /* True to use onepass strategy */
121262:   int addr;                       /* Address of OP_OpenEphemeral */
121263: 
121264:   /* Allocate nArg registers to martial the arguments to VUpdate. Then
121265:   ** create and open the ephemeral table in which the records created from
121266:   ** these arguments will be temporarily stored. */
121267:   assert( v );
121268:   ephemTab = pParse->nTab++;
121269:   addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
121270:   regArg = pParse->nMem + 1;
121271:   pParse->nMem += nArg;
121272:   regRec = ++pParse->nMem;
121273:   regRowid = ++pParse->nMem;
121274: 
121275:   /* Start scanning the virtual table */
121276:   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
121277:   if( pWInfo==0 ) return;
121278: 
121279:   /* Populate the argument registers. */
121280:   sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
121281:   if( pRowid ){
121282:     sqlite3ExprCode(pParse, pRowid, regArg+1);
121283:   }else{
121284:     sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
121285:   }
121286:   for(i=0; i<pTab->nCol; i++){
121287:     if( aXRef[i]>=0 ){
121288:       sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
121289:     }else{
121290:       sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
121291:     }
121292:   }
121293: 
121294:   bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
121295: 
121296:   if( bOnePass ){
121297:     /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
121298:     ** above. Also, if this is a top-level parse (not a trigger), clear the
121299:     ** multi-write flag so that the VM does not open a statement journal */
121300:     sqlite3VdbeChangeToNoop(v, addr);
121301:     if( sqlite3IsToplevel(pParse) ){
121302:       pParse->isMultiWrite = 0;
121303:     }
121304:   }else{
121305:     /* Create a record from the argument register contents and insert it into
121306:     ** the ephemeral table. */
121307:     sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
121308:     sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
121309:     sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
121310:   }
121311: 
121312: 
121313:   if( bOnePass==0 ){
121314:     /* End the virtual table scan */
121315:     sqlite3WhereEnd(pWInfo);
121316: 
121317:     /* Begin scannning through the ephemeral table. */
121318:     addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
121319: 
121320:     /* Extract arguments from the current row of the ephemeral table and 
121321:     ** invoke the VUpdate method.  */
121322:     for(i=0; i<nArg; i++){
121323:       sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
121324:     }
121325:   }
121326:   sqlite3VtabMakeWritable(pParse, pTab);
121327:   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
121328:   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
121329:   sqlite3MayAbort(pParse);
121330: 
121331:   /* End of the ephemeral table scan. Or, if using the onepass strategy,
121332:   ** jump to here if the scan visited zero rows. */
121333:   if( bOnePass==0 ){
121334:     sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
121335:     sqlite3VdbeJumpHere(v, addr);
121336:     sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
121337:   }else{
121338:     sqlite3WhereEnd(pWInfo);
121339:   }
121340: }
121341: #endif /* SQLITE_OMIT_VIRTUALTABLE */
121342: 
121343: /************** End of update.c **********************************************/
121344: /************** Begin file vacuum.c ******************************************/
121345: /*
121346: ** 2003 April 6
121347: **
121348: ** The author disclaims copyright to this source code.  In place of
121349: ** a legal notice, here is a blessing:
121350: **
121351: **    May you do good and not evil.
121352: **    May you find forgiveness for yourself and forgive others.
121353: **    May you share freely, never taking more than you give.
121354: **
121355: *************************************************************************
121356: ** This file contains code used to implement the VACUUM command.
121357: **
121358: ** Most of the code in this file may be omitted by defining the
121359: ** SQLITE_OMIT_VACUUM macro.
121360: */
121361: /* #include "sqliteInt.h" */
121362: /* #include "vdbeInt.h" */
121363: 
121364: #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
121365: /*
121366: ** Finalize a prepared statement.  If there was an error, store the
121367: ** text of the error message in *pzErrMsg.  Return the result code.
121368: */
121369: static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
121370:   int rc;
121371:   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
121372:   if( rc ){
121373:     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
121374:   }
121375:   return rc;
121376: }
121377: 
121378: /*
121379: ** Execute zSql on database db. Return an error code.
121380: */
121381: static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
121382:   sqlite3_stmt *pStmt;
121383:   VVA_ONLY( int rc; )
121384:   if( !zSql ){
121385:     return SQLITE_NOMEM_BKPT;
121386:   }
121387:   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
121388:     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
121389:     return sqlite3_errcode(db);
121390:   }
121391:   VVA_ONLY( rc = ) sqlite3_step(pStmt);
121392:   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
121393:   return vacuumFinalize(db, pStmt, pzErrMsg);
121394: }
121395: 
121396: /*
121397: ** Execute zSql on database db. The statement returns exactly
121398: ** one column. Execute this as SQL on the same database.
121399: */
121400: static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
121401:   sqlite3_stmt *pStmt;
121402:   int rc;
121403: 
121404:   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
121405:   if( rc!=SQLITE_OK ) return rc;
121406: 
121407:   while( SQLITE_ROW==sqlite3_step(pStmt) ){
121408:     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
121409:     if( rc!=SQLITE_OK ){
121410:       vacuumFinalize(db, pStmt, pzErrMsg);
121411:       return rc;
121412:     }
121413:   }
121414: 
121415:   return vacuumFinalize(db, pStmt, pzErrMsg);
121416: }
121417: 
121418: /*
121419: ** The VACUUM command is used to clean up the database,
121420: ** collapse free space, etc.  It is modelled after the VACUUM command
121421: ** in PostgreSQL.  The VACUUM command works as follows:
121422: **
121423: **   (1)  Create a new transient database file
121424: **   (2)  Copy all content from the database being vacuumed into
121425: **        the new transient database file
121426: **   (3)  Copy content from the transient database back into the
121427: **        original database.
121428: **
121429: ** The transient database requires temporary disk space approximately
121430: ** equal to the size of the original database.  The copy operation of
121431: ** step (3) requires additional temporary disk space approximately equal
121432: ** to the size of the original database for the rollback journal.
121433: ** Hence, temporary disk space that is approximately 2x the size of the
121434: ** original database is required.  Every page of the database is written
121435: ** approximately 3 times:  Once for step (2) and twice for step (3).
121436: ** Two writes per page are required in step (3) because the original
121437: ** database content must be written into the rollback journal prior to
121438: ** overwriting the database with the vacuumed content.
121439: **
121440: ** Only 1x temporary space and only 1x writes would be required if
121441: ** the copy of step (3) were replaced by deleting the original database
121442: ** and renaming the transient database as the original.  But that will
121443: ** not work if other processes are attached to the original database.
121444: ** And a power loss in between deleting the original and renaming the
121445: ** transient would cause the database file to appear to be deleted
121446: ** following reboot.
121447: */
121448: SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
121449:   Vdbe *v = sqlite3GetVdbe(pParse);
121450:   if( v ){
121451:     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
121452:     sqlite3VdbeUsesBtree(v, 0);
121453:   }
121454:   return;
121455: }
121456: 
121457: /*
121458: ** This routine implements the OP_Vacuum opcode of the VDBE.
121459: */
121460: SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
121461:   int rc = SQLITE_OK;     /* Return code from service routines */
121462:   Btree *pMain;           /* The database being vacuumed */
121463:   Btree *pTemp;           /* The temporary database we vacuum into */
121464:   char *zSql = 0;         /* SQL statements */
121465:   int saved_flags;        /* Saved value of the db->flags */
121466:   int saved_nChange;      /* Saved value of db->nChange */
121467:   int saved_nTotalChange; /* Saved value of db->nTotalChange */
121468:   u8 saved_mTrace;        /* Saved trace settings */
121469:   Db *pDb = 0;            /* Database to detach at end of vacuum */
121470:   int isMemDb;            /* True if vacuuming a :memory: database */
121471:   int nRes;               /* Bytes of reserved space at the end of each page */
121472:   int nDb;                /* Number of attached databases */
121473: 
121474:   if( !db->autoCommit ){
121475:     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
121476:     return SQLITE_ERROR;
121477:   }
121478:   if( db->nVdbeActive>1 ){
121479:     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
121480:     return SQLITE_ERROR;
121481:   }
121482: 
121483:   /* Save the current value of the database flags so that it can be 
121484:   ** restored before returning. Then set the writable-schema flag, and
121485:   ** disable CHECK and foreign key constraints.  */
121486:   saved_flags = db->flags;
121487:   saved_nChange = db->nChange;
121488:   saved_nTotalChange = db->nTotalChange;
121489:   saved_mTrace = db->mTrace;
121490:   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
121491:   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
121492:   db->mTrace = 0;
121493: 
121494:   pMain = db->aDb[0].pBt;
121495:   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
121496: 
121497:   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
121498:   ** can be set to 'off' for this file, as it is not recovered if a crash
121499:   ** occurs anyway. The integrity of the database is maintained by a
121500:   ** (possibly synchronous) transaction opened on the main database before
121501:   ** sqlite3BtreeCopyFile() is called.
121502:   **
121503:   ** An optimisation would be to use a non-journaled pager.
121504:   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
121505:   ** that actually made the VACUUM run slower.  Very little journalling
121506:   ** actually occurs when doing a vacuum since the vacuum_db is initially
121507:   ** empty.  Only the journal header is written.  Apparently it takes more
121508:   ** time to parse and run the PRAGMA to turn journalling off than it does
121509:   ** to write the journal header file.
121510:   */
121511:   nDb = db->nDb;
121512:   if( sqlite3TempInMemory(db) ){
121513:     zSql = "ATTACH ':memory:' AS vacuum_db;";
121514:   }else{
121515:     zSql = "ATTACH '' AS vacuum_db;";
121516:   }
121517:   rc = execSql(db, pzErrMsg, zSql);
121518:   if( db->nDb>nDb ){
121519:     pDb = &db->aDb[db->nDb-1];
121520:     assert( strcmp(pDb->zName,"vacuum_db")==0 );
121521:   }
121522:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121523:   pTemp = db->aDb[db->nDb-1].pBt;
121524: 
121525:   /* The call to execSql() to attach the temp database has left the file
121526:   ** locked (as there was more than one active statement when the transaction
121527:   ** to read the schema was concluded. Unlock it here so that this doesn't
121528:   ** cause problems for the call to BtreeSetPageSize() below.  */
121529:   sqlite3BtreeCommit(pTemp);
121530: 
121531:   nRes = sqlite3BtreeGetOptimalReserve(pMain);
121532: 
121533:   /* A VACUUM cannot change the pagesize of an encrypted database. */
121534: #ifdef SQLITE_HAS_CODEC
121535:   if( db->nextPagesize ){
121536:     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
121537:     int nKey;
121538:     char *zKey;
121539:     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
121540:     if( nKey ) db->nextPagesize = 0;
121541:   }
121542: #endif
121543: 
121544:   sqlite3BtreeSetCacheSize(pTemp, db->aDb[0].pSchema->cache_size);
121545:   sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
121546:   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
121547:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121548: 
121549:   /* Begin a transaction and take an exclusive lock on the main database
121550:   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
121551:   ** to ensure that we do not try to change the page-size on a WAL database.
121552:   */
121553:   rc = execSql(db, pzErrMsg, "BEGIN;");
121554:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121555:   rc = sqlite3BtreeBeginTrans(pMain, 2);
121556:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121557: 
121558:   /* Do not attempt to change the page size for a WAL database */
121559:   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
121560:                                                ==PAGER_JOURNALMODE_WAL ){
121561:     db->nextPagesize = 0;
121562:   }
121563: 
121564:   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
121565:    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
121566:    || NEVER(db->mallocFailed)
121567:   ){
121568:     rc = SQLITE_NOMEM_BKPT;
121569:     goto end_of_vacuum;
121570:   }
121571: 
121572: #ifndef SQLITE_OMIT_AUTOVACUUM
121573:   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
121574:                                            sqlite3BtreeGetAutoVacuum(pMain));
121575: #endif
121576: 
121577:   /* Query the schema of the main database. Create a mirror schema
121578:   ** in the temporary database.
121579:   */
121580:   rc = execExecSql(db, pzErrMsg,
121581:       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
121582:       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
121583:       "   AND coalesce(rootpage,1)>0"
121584:   );
121585:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121586:   rc = execExecSql(db, pzErrMsg,
121587:       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
121588:       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
121589:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121590:   rc = execExecSql(db, pzErrMsg,
121591:       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
121592:       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
121593:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121594: 
121595:   /* Loop through the tables in the main database. For each, do
121596:   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
121597:   ** the contents to the temporary database.
121598:   */
121599:   assert( (db->flags & SQLITE_Vacuum)==0 );
121600:   db->flags |= SQLITE_Vacuum;
121601:   rc = execExecSql(db, pzErrMsg,
121602:       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
121603:       "|| ' SELECT * FROM main.' || quote(name) || ';'"
121604:       "FROM main.sqlite_master "
121605:       "WHERE type = 'table' AND name!='sqlite_sequence' "
121606:       "  AND coalesce(rootpage,1)>0"
121607:   );
121608:   assert( (db->flags & SQLITE_Vacuum)!=0 );
121609:   db->flags &= ~SQLITE_Vacuum;
121610:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121611: 
121612:   /* Copy over the sequence table
121613:   */
121614:   rc = execExecSql(db, pzErrMsg,
121615:       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
121616:       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
121617:   );
121618:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121619:   rc = execExecSql(db, pzErrMsg,
121620:       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
121621:       "|| ' SELECT * FROM main.' || quote(name) || ';' "
121622:       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
121623:   );
121624:   if( rc!=SQLITE_OK ) goto end_of_vacuum;
121625: 
121626: 
121627:   /* Copy the triggers, views, and virtual tables from the main database
121628:   ** over to the temporary database.  None of these objects has any
121629:   ** associated storage, so all we have to do is copy their entries
121630:   ** from the SQLITE_MASTER table.
121631:   */
121632:   rc = execSql(db, pzErrMsg,
121633:       "INSERT INTO vacuum_db.sqlite_master "
121634:       "  SELECT type, name, tbl_name, rootpage, sql"
121635:       "    FROM main.sqlite_master"
121636:       "   WHERE type='view' OR type='trigger'"
121637:       "      OR (type='table' AND rootpage=0)"
121638:   );
121639:   if( rc ) goto end_of_vacuum;
121640: 
121641:   /* At this point, there is a write transaction open on both the 
121642:   ** vacuum database and the main database. Assuming no error occurs,
121643:   ** both transactions are closed by this block - the main database
121644:   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
121645:   ** call to sqlite3BtreeCommit().
121646:   */
121647:   {
121648:     u32 meta;
121649:     int i;
121650: 
121651:     /* This array determines which meta meta values are preserved in the
121652:     ** vacuum.  Even entries are the meta value number and odd entries
121653:     ** are an increment to apply to the meta value after the vacuum.
121654:     ** The increment is used to increase the schema cookie so that other
121655:     ** connections to the same database will know to reread the schema.
121656:     */
121657:     static const unsigned char aCopy[] = {
121658:        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
121659:        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
121660:        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
121661:        BTREE_USER_VERSION,       0,  /* Preserve the user version */
121662:        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
121663:     };
121664: 
121665:     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
121666:     assert( 1==sqlite3BtreeIsInTrans(pMain) );
121667: 
121668:     /* Copy Btree meta values */
121669:     for(i=0; i<ArraySize(aCopy); i+=2){
121670:       /* GetMeta() and UpdateMeta() cannot fail in this context because
121671:       ** we already have page 1 loaded into cache and marked dirty. */
121672:       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
121673:       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
121674:       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
121675:     }
121676: 
121677:     rc = sqlite3BtreeCopyFile(pMain, pTemp);
121678:     if( rc!=SQLITE_OK ) goto end_of_vacuum;
121679:     rc = sqlite3BtreeCommit(pTemp);
121680:     if( rc!=SQLITE_OK ) goto end_of_vacuum;
121681: #ifndef SQLITE_OMIT_AUTOVACUUM
121682:     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
121683: #endif
121684:   }
121685: 
121686:   assert( rc==SQLITE_OK );
121687:   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
121688: 
121689: end_of_vacuum:
121690:   /* Restore the original value of db->flags */
121691:   db->flags = saved_flags;
121692:   db->nChange = saved_nChange;
121693:   db->nTotalChange = saved_nTotalChange;
121694:   db->mTrace = saved_mTrace;
121695:   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
121696: 
121697:   /* Currently there is an SQL level transaction open on the vacuum
121698:   ** database. No locks are held on any other files (since the main file
121699:   ** was committed at the btree level). So it safe to end the transaction
121700:   ** by manually setting the autoCommit flag to true and detaching the
121701:   ** vacuum database. The vacuum_db journal file is deleted when the pager
121702:   ** is closed by the DETACH.
121703:   */
121704:   db->autoCommit = 1;
121705: 
121706:   if( pDb ){
121707:     sqlite3BtreeClose(pDb->pBt);
121708:     pDb->pBt = 0;
121709:     pDb->pSchema = 0;
121710:   }
121711: 
121712:   /* This both clears the schemas and reduces the size of the db->aDb[]
121713:   ** array. */ 
121714:   sqlite3ResetAllSchemasOfConnection(db);
121715: 
121716:   return rc;
121717: }
121718: 
121719: #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
121720: 
121721: /************** End of vacuum.c **********************************************/
121722: /************** Begin file vtab.c ********************************************/
121723: /*
121724: ** 2006 June 10
121725: **
121726: ** The author disclaims copyright to this source code.  In place of
121727: ** a legal notice, here is a blessing:
121728: **
121729: **    May you do good and not evil.
121730: **    May you find forgiveness for yourself and forgive others.
121731: **    May you share freely, never taking more than you give.
121732: **
121733: *************************************************************************
121734: ** This file contains code used to help implement virtual tables.
121735: */
121736: #ifndef SQLITE_OMIT_VIRTUALTABLE
121737: /* #include "sqliteInt.h" */
121738: 
121739: /*
121740: ** Before a virtual table xCreate() or xConnect() method is invoked, the
121741: ** sqlite3.pVtabCtx member variable is set to point to an instance of
121742: ** this struct allocated on the stack. It is used by the implementation of 
121743: ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
121744: ** are invoked only from within xCreate and xConnect methods.
121745: */
121746: struct VtabCtx {
121747:   VTable *pVTable;    /* The virtual table being constructed */
121748:   Table *pTab;        /* The Table object to which the virtual table belongs */
121749:   VtabCtx *pPrior;    /* Parent context (if any) */
121750:   int bDeclared;      /* True after sqlite3_declare_vtab() is called */
121751: };
121752: 
121753: /*
121754: ** The actual function that does the work of creating a new module.
121755: ** This function implements the sqlite3_create_module() and
121756: ** sqlite3_create_module_v2() interfaces.
121757: */
121758: static int createModule(
121759:   sqlite3 *db,                    /* Database in which module is registered */
121760:   const char *zName,              /* Name assigned to this module */
121761:   const sqlite3_module *pModule,  /* The definition of the module */
121762:   void *pAux,                     /* Context pointer for xCreate/xConnect */
121763:   void (*xDestroy)(void *)        /* Module destructor function */
121764: ){
121765:   int rc = SQLITE_OK;
121766:   int nName;
121767: 
121768:   sqlite3_mutex_enter(db->mutex);
121769:   nName = sqlite3Strlen30(zName);
121770:   if( sqlite3HashFind(&db->aModule, zName) ){
121771:     rc = SQLITE_MISUSE_BKPT;
121772:   }else{
121773:     Module *pMod;
121774:     pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
121775:     if( pMod ){
121776:       Module *pDel;
121777:       char *zCopy = (char *)(&pMod[1]);
121778:       memcpy(zCopy, zName, nName+1);
121779:       pMod->zName = zCopy;
121780:       pMod->pModule = pModule;
121781:       pMod->pAux = pAux;
121782:       pMod->xDestroy = xDestroy;
121783:       pMod->pEpoTab = 0;
121784:       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
121785:       assert( pDel==0 || pDel==pMod );
121786:       if( pDel ){
121787:         sqlite3OomFault(db);
121788:         sqlite3DbFree(db, pDel);
121789:       }
121790:     }
121791:   }
121792:   rc = sqlite3ApiExit(db, rc);
121793:   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
121794: 
121795:   sqlite3_mutex_leave(db->mutex);
121796:   return rc;
121797: }
121798: 
121799: 
121800: /*
121801: ** External API function used to create a new virtual-table module.
121802: */
121803: SQLITE_API int sqlite3_create_module(
121804:   sqlite3 *db,                    /* Database in which module is registered */
121805:   const char *zName,              /* Name assigned to this module */
121806:   const sqlite3_module *pModule,  /* The definition of the module */
121807:   void *pAux                      /* Context pointer for xCreate/xConnect */
121808: ){
121809: #ifdef SQLITE_ENABLE_API_ARMOR
121810:   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121811: #endif
121812:   return createModule(db, zName, pModule, pAux, 0);
121813: }
121814: 
121815: /*
121816: ** External API function used to create a new virtual-table module.
121817: */
121818: SQLITE_API int sqlite3_create_module_v2(
121819:   sqlite3 *db,                    /* Database in which module is registered */
121820:   const char *zName,              /* Name assigned to this module */
121821:   const sqlite3_module *pModule,  /* The definition of the module */
121822:   void *pAux,                     /* Context pointer for xCreate/xConnect */
121823:   void (*xDestroy)(void *)        /* Module destructor function */
121824: ){
121825: #ifdef SQLITE_ENABLE_API_ARMOR
121826:   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121827: #endif
121828:   return createModule(db, zName, pModule, pAux, xDestroy);
121829: }
121830: 
121831: /*
121832: ** Lock the virtual table so that it cannot be disconnected.
121833: ** Locks nest.  Every lock should have a corresponding unlock.
121834: ** If an unlock is omitted, resources leaks will occur.  
121835: **
121836: ** If a disconnect is attempted while a virtual table is locked,
121837: ** the disconnect is deferred until all locks have been removed.
121838: */
121839: SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
121840:   pVTab->nRef++;
121841: }
121842: 
121843: 
121844: /*
121845: ** pTab is a pointer to a Table structure representing a virtual-table.
121846: ** Return a pointer to the VTable object used by connection db to access 
121847: ** this virtual-table, if one has been created, or NULL otherwise.
121848: */
121849: SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
121850:   VTable *pVtab;
121851:   assert( IsVirtual(pTab) );
121852:   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
121853:   return pVtab;
121854: }
121855: 
121856: /*
121857: ** Decrement the ref-count on a virtual table object. When the ref-count
121858: ** reaches zero, call the xDisconnect() method to delete the object.
121859: */
121860: SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
121861:   sqlite3 *db = pVTab->db;
121862: 
121863:   assert( db );
121864:   assert( pVTab->nRef>0 );
121865:   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
121866: 
121867:   pVTab->nRef--;
121868:   if( pVTab->nRef==0 ){
121869:     sqlite3_vtab *p = pVTab->pVtab;
121870:     if( p ){
121871:       p->pModule->xDisconnect(p);
121872:     }
121873:     sqlite3DbFree(db, pVTab);
121874:   }
121875: }
121876: 
121877: /*
121878: ** Table p is a virtual table. This function moves all elements in the
121879: ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
121880: ** database connections to be disconnected at the next opportunity. 
121881: ** Except, if argument db is not NULL, then the entry associated with
121882: ** connection db is left in the p->pVTable list.
121883: */
121884: static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
121885:   VTable *pRet = 0;
121886:   VTable *pVTable = p->pVTable;
121887:   p->pVTable = 0;
121888: 
121889:   /* Assert that the mutex (if any) associated with the BtShared database 
121890:   ** that contains table p is held by the caller. See header comments 
121891:   ** above function sqlite3VtabUnlockList() for an explanation of why
121892:   ** this makes it safe to access the sqlite3.pDisconnect list of any
121893:   ** database connection that may have an entry in the p->pVTable list.
121894:   */
121895:   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
121896: 
121897:   while( pVTable ){
121898:     sqlite3 *db2 = pVTable->db;
121899:     VTable *pNext = pVTable->pNext;
121900:     assert( db2 );
121901:     if( db2==db ){
121902:       pRet = pVTable;
121903:       p->pVTable = pRet;
121904:       pRet->pNext = 0;
121905:     }else{
121906:       pVTable->pNext = db2->pDisconnect;
121907:       db2->pDisconnect = pVTable;
121908:     }
121909:     pVTable = pNext;
121910:   }
121911: 
121912:   assert( !db || pRet );
121913:   return pRet;
121914: }
121915: 
121916: /*
121917: ** Table *p is a virtual table. This function removes the VTable object
121918: ** for table *p associated with database connection db from the linked
121919: ** list in p->pVTab. It also decrements the VTable ref count. This is
121920: ** used when closing database connection db to free all of its VTable
121921: ** objects without disturbing the rest of the Schema object (which may
121922: ** be being used by other shared-cache connections).
121923: */
121924: SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
121925:   VTable **ppVTab;
121926: 
121927:   assert( IsVirtual(p) );
121928:   assert( sqlite3BtreeHoldsAllMutexes(db) );
121929:   assert( sqlite3_mutex_held(db->mutex) );
121930: 
121931:   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
121932:     if( (*ppVTab)->db==db  ){
121933:       VTable *pVTab = *ppVTab;
121934:       *ppVTab = pVTab->pNext;
121935:       sqlite3VtabUnlock(pVTab);
121936:       break;
121937:     }
121938:   }
121939: }
121940: 
121941: 
121942: /*
121943: ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
121944: **
121945: ** This function may only be called when the mutexes associated with all
121946: ** shared b-tree databases opened using connection db are held by the 
121947: ** caller. This is done to protect the sqlite3.pDisconnect list. The
121948: ** sqlite3.pDisconnect list is accessed only as follows:
121949: **
121950: **   1) By this function. In this case, all BtShared mutexes and the mutex
121951: **      associated with the database handle itself must be held.
121952: **
121953: **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
121954: **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
121955: **      associated with the database the virtual table is stored in is held
121956: **      or, if the virtual table is stored in a non-sharable database, then
121957: **      the database handle mutex is held.
121958: **
121959: ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
121960: ** by multiple threads. It is thread-safe.
121961: */
121962: SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
121963:   VTable *p = db->pDisconnect;
121964:   db->pDisconnect = 0;
121965: 
121966:   assert( sqlite3BtreeHoldsAllMutexes(db) );
121967:   assert( sqlite3_mutex_held(db->mutex) );
121968: 
121969:   if( p ){
121970:     sqlite3ExpirePreparedStatements(db);
121971:     do {
121972:       VTable *pNext = p->pNext;
121973:       sqlite3VtabUnlock(p);
121974:       p = pNext;
121975:     }while( p );
121976:   }
121977: }
121978: 
121979: /*
121980: ** Clear any and all virtual-table information from the Table record.
121981: ** This routine is called, for example, just before deleting the Table
121982: ** record.
121983: **
121984: ** Since it is a virtual-table, the Table structure contains a pointer
121985: ** to the head of a linked list of VTable structures. Each VTable 
121986: ** structure is associated with a single sqlite3* user of the schema.
121987: ** The reference count of the VTable structure associated with database 
121988: ** connection db is decremented immediately (which may lead to the 
121989: ** structure being xDisconnected and free). Any other VTable structures
121990: ** in the list are moved to the sqlite3.pDisconnect list of the associated 
121991: ** database connection.
121992: */
121993: SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
121994:   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
121995:   if( p->azModuleArg ){
121996:     int i;
121997:     for(i=0; i<p->nModuleArg; i++){
121998:       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
121999:     }
122000:     sqlite3DbFree(db, p->azModuleArg);
122001:   }
122002: }
122003: 
122004: /*
122005: ** Add a new module argument to pTable->azModuleArg[].
122006: ** The string is not copied - the pointer is stored.  The
122007: ** string will be freed automatically when the table is
122008: ** deleted.
122009: */
122010: static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
122011:   int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
122012:   char **azModuleArg;
122013:   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
122014:   if( azModuleArg==0 ){
122015:     sqlite3DbFree(db, zArg);
122016:   }else{
122017:     int i = pTable->nModuleArg++;
122018:     azModuleArg[i] = zArg;
122019:     azModuleArg[i+1] = 0;
122020:     pTable->azModuleArg = azModuleArg;
122021:   }
122022: }
122023: 
122024: /*
122025: ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
122026: ** statement.  The module name has been parsed, but the optional list
122027: ** of parameters that follow the module name are still pending.
122028: */
122029: SQLITE_PRIVATE void sqlite3VtabBeginParse(
122030:   Parse *pParse,        /* Parsing context */
122031:   Token *pName1,        /* Name of new table, or database name */
122032:   Token *pName2,        /* Name of new table or NULL */
122033:   Token *pModuleName,   /* Name of the module for the virtual table */
122034:   int ifNotExists       /* No error if the table already exists */
122035: ){
122036:   int iDb;              /* The database the table is being created in */
122037:   Table *pTable;        /* The new virtual table */
122038:   sqlite3 *db;          /* Database connection */
122039: 
122040:   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
122041:   pTable = pParse->pNewTable;
122042:   if( pTable==0 ) return;
122043:   assert( 0==pTable->pIndex );
122044: 
122045:   db = pParse->db;
122046:   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
122047:   assert( iDb>=0 );
122048: 
122049:   pTable->tabFlags |= TF_Virtual;
122050:   pTable->nModuleArg = 0;
122051:   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
122052:   addModuleArgument(db, pTable, 0);
122053:   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
122054:   assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
122055:        || (pParse->sNameToken.z==pName1->z && pName2->z==0)
122056:   );
122057:   pParse->sNameToken.n = (int)(
122058:       &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
122059:   );
122060: 
122061: #ifndef SQLITE_OMIT_AUTHORIZATION
122062:   /* Creating a virtual table invokes the authorization callback twice.
122063:   ** The first invocation, to obtain permission to INSERT a row into the
122064:   ** sqlite_master table, has already been made by sqlite3StartTable().
122065:   ** The second call, to obtain permission to create the table, is made now.
122066:   */
122067:   if( pTable->azModuleArg ){
122068:     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
122069:             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
122070:   }
122071: #endif
122072: }
122073: 
122074: /*
122075: ** This routine takes the module argument that has been accumulating
122076: ** in pParse->zArg[] and appends it to the list of arguments on the
122077: ** virtual table currently under construction in pParse->pTable.
122078: */
122079: static void addArgumentToVtab(Parse *pParse){
122080:   if( pParse->sArg.z && pParse->pNewTable ){
122081:     const char *z = (const char*)pParse->sArg.z;
122082:     int n = pParse->sArg.n;
122083:     sqlite3 *db = pParse->db;
122084:     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
122085:   }
122086: }
122087: 
122088: /*
122089: ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
122090: ** has been completely parsed.
122091: */
122092: SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
122093:   Table *pTab = pParse->pNewTable;  /* The table being constructed */
122094:   sqlite3 *db = pParse->db;         /* The database connection */
122095: 
122096:   if( pTab==0 ) return;
122097:   addArgumentToVtab(pParse);
122098:   pParse->sArg.z = 0;
122099:   if( pTab->nModuleArg<1 ) return;
122100:   
122101:   /* If the CREATE VIRTUAL TABLE statement is being entered for the
122102:   ** first time (in other words if the virtual table is actually being
122103:   ** created now instead of just being read out of sqlite_master) then
122104:   ** do additional initialization work and store the statement text
122105:   ** in the sqlite_master table.
122106:   */
122107:   if( !db->init.busy ){
122108:     char *zStmt;
122109:     char *zWhere;
122110:     int iDb;
122111:     int iReg;
122112:     Vdbe *v;
122113: 
122114:     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
122115:     if( pEnd ){
122116:       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
122117:     }
122118:     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
122119: 
122120:     /* A slot for the record has already been allocated in the 
122121:     ** SQLITE_MASTER table.  We just need to update that slot with all
122122:     ** the information we've collected.  
122123:     **
122124:     ** The VM register number pParse->regRowid holds the rowid of an
122125:     ** entry in the sqlite_master table tht was created for this vtab
122126:     ** by sqlite3StartTable().
122127:     */
122128:     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122129:     sqlite3NestedParse(pParse,
122130:       "UPDATE %Q.%s "
122131:          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
122132:        "WHERE rowid=#%d",
122133:       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
122134:       pTab->zName,
122135:       pTab->zName,
122136:       zStmt,
122137:       pParse->regRowid
122138:     );
122139:     sqlite3DbFree(db, zStmt);
122140:     v = sqlite3GetVdbe(pParse);
122141:     sqlite3ChangeCookie(pParse, iDb);
122142: 
122143:     sqlite3VdbeAddOp0(v, OP_Expire);
122144:     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
122145:     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
122146: 
122147:     iReg = ++pParse->nMem;
122148:     sqlite3VdbeLoadString(v, iReg, pTab->zName);
122149:     sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
122150:   }
122151: 
122152:   /* If we are rereading the sqlite_master table create the in-memory
122153:   ** record of the table. The xConnect() method is not called until
122154:   ** the first time the virtual table is used in an SQL statement. This
122155:   ** allows a schema that contains virtual tables to be loaded before
122156:   ** the required virtual table implementations are registered.  */
122157:   else {
122158:     Table *pOld;
122159:     Schema *pSchema = pTab->pSchema;
122160:     const char *zName = pTab->zName;
122161:     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
122162:     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
122163:     if( pOld ){
122164:       sqlite3OomFault(db);
122165:       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
122166:       return;
122167:     }
122168:     pParse->pNewTable = 0;
122169:   }
122170: }
122171: 
122172: /*
122173: ** The parser calls this routine when it sees the first token
122174: ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
122175: */
122176: SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
122177:   addArgumentToVtab(pParse);
122178:   pParse->sArg.z = 0;
122179:   pParse->sArg.n = 0;
122180: }
122181: 
122182: /*
122183: ** The parser calls this routine for each token after the first token
122184: ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
122185: */
122186: SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
122187:   Token *pArg = &pParse->sArg;
122188:   if( pArg->z==0 ){
122189:     pArg->z = p->z;
122190:     pArg->n = p->n;
122191:   }else{
122192:     assert(pArg->z <= p->z);
122193:     pArg->n = (int)(&p->z[p->n] - pArg->z);
122194:   }
122195: }
122196: 
122197: /*
122198: ** Invoke a virtual table constructor (either xCreate or xConnect). The
122199: ** pointer to the function to invoke is passed as the fourth parameter
122200: ** to this procedure.
122201: */
122202: static int vtabCallConstructor(
122203:   sqlite3 *db, 
122204:   Table *pTab,
122205:   Module *pMod,
122206:   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
122207:   char **pzErr
122208: ){
122209:   VtabCtx sCtx;
122210:   VTable *pVTable;
122211:   int rc;
122212:   const char *const*azArg = (const char *const*)pTab->azModuleArg;
122213:   int nArg = pTab->nModuleArg;
122214:   char *zErr = 0;
122215:   char *zModuleName;
122216:   int iDb;
122217:   VtabCtx *pCtx;
122218: 
122219:   /* Check that the virtual-table is not already being initialized */
122220:   for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
122221:     if( pCtx->pTab==pTab ){
122222:       *pzErr = sqlite3MPrintf(db, 
122223:           "vtable constructor called recursively: %s", pTab->zName
122224:       );
122225:       return SQLITE_LOCKED;
122226:     }
122227:   }
122228: 
122229:   zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
122230:   if( !zModuleName ){
122231:     return SQLITE_NOMEM_BKPT;
122232:   }
122233: 
122234:   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
122235:   if( !pVTable ){
122236:     sqlite3DbFree(db, zModuleName);
122237:     return SQLITE_NOMEM_BKPT;
122238:   }
122239:   pVTable->db = db;
122240:   pVTable->pMod = pMod;
122241: 
122242:   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122243:   pTab->azModuleArg[1] = db->aDb[iDb].zName;
122244: 
122245:   /* Invoke the virtual table constructor */
122246:   assert( &db->pVtabCtx );
122247:   assert( xConstruct );
122248:   sCtx.pTab = pTab;
122249:   sCtx.pVTable = pVTable;
122250:   sCtx.pPrior = db->pVtabCtx;
122251:   sCtx.bDeclared = 0;
122252:   db->pVtabCtx = &sCtx;
122253:   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
122254:   db->pVtabCtx = sCtx.pPrior;
122255:   if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
122256:   assert( sCtx.pTab==pTab );
122257: 
122258:   if( SQLITE_OK!=rc ){
122259:     if( zErr==0 ){
122260:       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
122261:     }else {
122262:       *pzErr = sqlite3MPrintf(db, "%s", zErr);
122263:       sqlite3_free(zErr);
122264:     }
122265:     sqlite3DbFree(db, pVTable);
122266:   }else if( ALWAYS(pVTable->pVtab) ){
122267:     /* Justification of ALWAYS():  A correct vtab constructor must allocate
122268:     ** the sqlite3_vtab object if successful.  */
122269:     memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
122270:     pVTable->pVtab->pModule = pMod->pModule;
122271:     pVTable->nRef = 1;
122272:     if( sCtx.bDeclared==0 ){
122273:       const char *zFormat = "vtable constructor did not declare schema: %s";
122274:       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
122275:       sqlite3VtabUnlock(pVTable);
122276:       rc = SQLITE_ERROR;
122277:     }else{
122278:       int iCol;
122279:       u8 oooHidden = 0;
122280:       /* If everything went according to plan, link the new VTable structure
122281:       ** into the linked list headed by pTab->pVTable. Then loop through the 
122282:       ** columns of the table to see if any of them contain the token "hidden".
122283:       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
122284:       ** the type string.  */
122285:       pVTable->pNext = pTab->pVTable;
122286:       pTab->pVTable = pVTable;
122287: 
122288:       for(iCol=0; iCol<pTab->nCol; iCol++){
122289:         char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
122290:         int nType;
122291:         int i = 0;
122292:         nType = sqlite3Strlen30(zType);
122293:         for(i=0; i<nType; i++){
122294:           if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
122295:            && (i==0 || zType[i-1]==' ')
122296:            && (zType[i+6]=='\0' || zType[i+6]==' ')
122297:           ){
122298:             break;
122299:           }
122300:         }
122301:         if( i<nType ){
122302:           int j;
122303:           int nDel = 6 + (zType[i+6] ? 1 : 0);
122304:           for(j=i; (j+nDel)<=nType; j++){
122305:             zType[j] = zType[j+nDel];
122306:           }
122307:           if( zType[i]=='\0' && i>0 ){
122308:             assert(zType[i-1]==' ');
122309:             zType[i-1] = '\0';
122310:           }
122311:           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
122312:           oooHidden = TF_OOOHidden;
122313:         }else{
122314:           pTab->tabFlags |= oooHidden;
122315:         }
122316:       }
122317:     }
122318:   }
122319: 
122320:   sqlite3DbFree(db, zModuleName);
122321:   return rc;
122322: }
122323: 
122324: /*
122325: ** This function is invoked by the parser to call the xConnect() method
122326: ** of the virtual table pTab. If an error occurs, an error code is returned 
122327: ** and an error left in pParse.
122328: **
122329: ** This call is a no-op if table pTab is not a virtual table.
122330: */
122331: SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
122332:   sqlite3 *db = pParse->db;
122333:   const char *zMod;
122334:   Module *pMod;
122335:   int rc;
122336: 
122337:   assert( pTab );
122338:   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
122339:     return SQLITE_OK;
122340:   }
122341: 
122342:   /* Locate the required virtual table module */
122343:   zMod = pTab->azModuleArg[0];
122344:   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
122345: 
122346:   if( !pMod ){
122347:     const char *zModule = pTab->azModuleArg[0];
122348:     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
122349:     rc = SQLITE_ERROR;
122350:   }else{
122351:     char *zErr = 0;
122352:     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
122353:     if( rc!=SQLITE_OK ){
122354:       sqlite3ErrorMsg(pParse, "%s", zErr);
122355:     }
122356:     sqlite3DbFree(db, zErr);
122357:   }
122358: 
122359:   return rc;
122360: }
122361: /*
122362: ** Grow the db->aVTrans[] array so that there is room for at least one
122363: ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
122364: */
122365: static int growVTrans(sqlite3 *db){
122366:   const int ARRAY_INCR = 5;
122367: 
122368:   /* Grow the sqlite3.aVTrans array if required */
122369:   if( (db->nVTrans%ARRAY_INCR)==0 ){
122370:     VTable **aVTrans;
122371:     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
122372:     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
122373:     if( !aVTrans ){
122374:       return SQLITE_NOMEM_BKPT;
122375:     }
122376:     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
122377:     db->aVTrans = aVTrans;
122378:   }
122379: 
122380:   return SQLITE_OK;
122381: }
122382: 
122383: /*
122384: ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
122385: ** have already been reserved using growVTrans().
122386: */
122387: static void addToVTrans(sqlite3 *db, VTable *pVTab){
122388:   /* Add pVtab to the end of sqlite3.aVTrans */
122389:   db->aVTrans[db->nVTrans++] = pVTab;
122390:   sqlite3VtabLock(pVTab);
122391: }
122392: 
122393: /*
122394: ** This function is invoked by the vdbe to call the xCreate method
122395: ** of the virtual table named zTab in database iDb. 
122396: **
122397: ** If an error occurs, *pzErr is set to point an an English language
122398: ** description of the error and an SQLITE_XXX error code is returned.
122399: ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
122400: */
122401: SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
122402:   int rc = SQLITE_OK;
122403:   Table *pTab;
122404:   Module *pMod;
122405:   const char *zMod;
122406: 
122407:   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
122408:   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
122409: 
122410:   /* Locate the required virtual table module */
122411:   zMod = pTab->azModuleArg[0];
122412:   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
122413: 
122414:   /* If the module has been registered and includes a Create method, 
122415:   ** invoke it now. If the module has not been registered, return an 
122416:   ** error. Otherwise, do nothing.
122417:   */
122418:   if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
122419:     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
122420:     rc = SQLITE_ERROR;
122421:   }else{
122422:     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
122423:   }
122424: 
122425:   /* Justification of ALWAYS():  The xConstructor method is required to
122426:   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
122427:   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
122428:     rc = growVTrans(db);
122429:     if( rc==SQLITE_OK ){
122430:       addToVTrans(db, sqlite3GetVTable(db, pTab));
122431:     }
122432:   }
122433: 
122434:   return rc;
122435: }
122436: 
122437: /*
122438: ** This function is used to set the schema of a virtual table.  It is only
122439: ** valid to call this function from within the xCreate() or xConnect() of a
122440: ** virtual table module.
122441: */
122442: SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
122443:   VtabCtx *pCtx;
122444:   Parse *pParse;
122445:   int rc = SQLITE_OK;
122446:   Table *pTab;
122447:   char *zErr = 0;
122448: 
122449: #ifdef SQLITE_ENABLE_API_ARMOR
122450:   if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
122451:     return SQLITE_MISUSE_BKPT;
122452:   }
122453: #endif
122454:   sqlite3_mutex_enter(db->mutex);
122455:   pCtx = db->pVtabCtx;
122456:   if( !pCtx || pCtx->bDeclared ){
122457:     sqlite3Error(db, SQLITE_MISUSE);
122458:     sqlite3_mutex_leave(db->mutex);
122459:     return SQLITE_MISUSE_BKPT;
122460:   }
122461:   pTab = pCtx->pTab;
122462:   assert( (pTab->tabFlags & TF_Virtual)!=0 );
122463: 
122464:   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
122465:   if( pParse==0 ){
122466:     rc = SQLITE_NOMEM_BKPT;
122467:   }else{
122468:     pParse->declareVtab = 1;
122469:     pParse->db = db;
122470:     pParse->nQueryLoop = 1;
122471:   
122472:     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
122473:      && pParse->pNewTable
122474:      && !db->mallocFailed
122475:      && !pParse->pNewTable->pSelect
122476:      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
122477:     ){
122478:       if( !pTab->aCol ){
122479:         Table *pNew = pParse->pNewTable;
122480:         Index *pIdx;
122481:         pTab->aCol = pNew->aCol;
122482:         pTab->nCol = pNew->nCol;
122483:         pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
122484:         pNew->nCol = 0;
122485:         pNew->aCol = 0;
122486:         assert( pTab->pIndex==0 );
122487:         if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
122488:           rc = SQLITE_ERROR;
122489:         }
122490:         pIdx = pNew->pIndex;
122491:         if( pIdx ){
122492:           assert( pIdx->pNext==0 );
122493:           pTab->pIndex = pIdx;
122494:           pNew->pIndex = 0;
122495:           pIdx->pTable = pTab;
122496:         }
122497:       }
122498:       pCtx->bDeclared = 1;
122499:     }else{
122500:       sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
122501:       sqlite3DbFree(db, zErr);
122502:       rc = SQLITE_ERROR;
122503:     }
122504:     pParse->declareVtab = 0;
122505:   
122506:     if( pParse->pVdbe ){
122507:       sqlite3VdbeFinalize(pParse->pVdbe);
122508:     }
122509:     sqlite3DeleteTable(db, pParse->pNewTable);
122510:     sqlite3ParserReset(pParse);
122511:     sqlite3StackFree(db, pParse);
122512:   }
122513: 
122514:   assert( (rc&0xff)==rc );
122515:   rc = sqlite3ApiExit(db, rc);
122516:   sqlite3_mutex_leave(db->mutex);
122517:   return rc;
122518: }
122519: 
122520: /*
122521: ** This function is invoked by the vdbe to call the xDestroy method
122522: ** of the virtual table named zTab in database iDb. This occurs
122523: ** when a DROP TABLE is mentioned.
122524: **
122525: ** This call is a no-op if zTab is not a virtual table.
122526: */
122527: SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
122528:   int rc = SQLITE_OK;
122529:   Table *pTab;
122530: 
122531:   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
122532:   if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
122533:     VTable *p;
122534:     int (*xDestroy)(sqlite3_vtab *);
122535:     for(p=pTab->pVTable; p; p=p->pNext){
122536:       assert( p->pVtab );
122537:       if( p->pVtab->nRef>0 ){
122538:         return SQLITE_LOCKED;
122539:       }
122540:     }
122541:     p = vtabDisconnectAll(db, pTab);
122542:     xDestroy = p->pMod->pModule->xDestroy;
122543:     assert( xDestroy!=0 );  /* Checked before the virtual table is created */
122544:     rc = xDestroy(p->pVtab);
122545:     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
122546:     if( rc==SQLITE_OK ){
122547:       assert( pTab->pVTable==p && p->pNext==0 );
122548:       p->pVtab = 0;
122549:       pTab->pVTable = 0;
122550:       sqlite3VtabUnlock(p);
122551:     }
122552:   }
122553: 
122554:   return rc;
122555: }
122556: 
122557: /*
122558: ** This function invokes either the xRollback or xCommit method
122559: ** of each of the virtual tables in the sqlite3.aVTrans array. The method
122560: ** called is identified by the second argument, "offset", which is
122561: ** the offset of the method to call in the sqlite3_module structure.
122562: **
122563: ** The array is cleared after invoking the callbacks. 
122564: */
122565: static void callFinaliser(sqlite3 *db, int offset){
122566:   int i;
122567:   if( db->aVTrans ){
122568:     VTable **aVTrans = db->aVTrans;
122569:     db->aVTrans = 0;
122570:     for(i=0; i<db->nVTrans; i++){
122571:       VTable *pVTab = aVTrans[i];
122572:       sqlite3_vtab *p = pVTab->pVtab;
122573:       if( p ){
122574:         int (*x)(sqlite3_vtab *);
122575:         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
122576:         if( x ) x(p);
122577:       }
122578:       pVTab->iSavepoint = 0;
122579:       sqlite3VtabUnlock(pVTab);
122580:     }
122581:     sqlite3DbFree(db, aVTrans);
122582:     db->nVTrans = 0;
122583:   }
122584: }
122585: 
122586: /*
122587: ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
122588: ** array. Return the error code for the first error that occurs, or
122589: ** SQLITE_OK if all xSync operations are successful.
122590: **
122591: ** If an error message is available, leave it in p->zErrMsg.
122592: */
122593: SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
122594:   int i;
122595:   int rc = SQLITE_OK;
122596:   VTable **aVTrans = db->aVTrans;
122597: 
122598:   db->aVTrans = 0;
122599:   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
122600:     int (*x)(sqlite3_vtab *);
122601:     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
122602:     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
122603:       rc = x(pVtab);
122604:       sqlite3VtabImportErrmsg(p, pVtab);
122605:     }
122606:   }
122607:   db->aVTrans = aVTrans;
122608:   return rc;
122609: }
122610: 
122611: /*
122612: ** Invoke the xRollback method of all virtual tables in the 
122613: ** sqlite3.aVTrans array. Then clear the array itself.
122614: */
122615: SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
122616:   callFinaliser(db, offsetof(sqlite3_module,xRollback));
122617:   return SQLITE_OK;
122618: }
122619: 
122620: /*
122621: ** Invoke the xCommit method of all virtual tables in the 
122622: ** sqlite3.aVTrans array. Then clear the array itself.
122623: */
122624: SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
122625:   callFinaliser(db, offsetof(sqlite3_module,xCommit));
122626:   return SQLITE_OK;
122627: }
122628: 
122629: /*
122630: ** If the virtual table pVtab supports the transaction interface
122631: ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
122632: ** not currently open, invoke the xBegin method now.
122633: **
122634: ** If the xBegin call is successful, place the sqlite3_vtab pointer
122635: ** in the sqlite3.aVTrans array.
122636: */
122637: SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
122638:   int rc = SQLITE_OK;
122639:   const sqlite3_module *pModule;
122640: 
122641:   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
122642:   ** than zero, then this function is being called from within a
122643:   ** virtual module xSync() callback. It is illegal to write to 
122644:   ** virtual module tables in this case, so return SQLITE_LOCKED.
122645:   */
122646:   if( sqlite3VtabInSync(db) ){
122647:     return SQLITE_LOCKED;
122648:   }
122649:   if( !pVTab ){
122650:     return SQLITE_OK;
122651:   } 
122652:   pModule = pVTab->pVtab->pModule;
122653: 
122654:   if( pModule->xBegin ){
122655:     int i;
122656: 
122657:     /* If pVtab is already in the aVTrans array, return early */
122658:     for(i=0; i<db->nVTrans; i++){
122659:       if( db->aVTrans[i]==pVTab ){
122660:         return SQLITE_OK;
122661:       }
122662:     }
122663: 
122664:     /* Invoke the xBegin method. If successful, add the vtab to the 
122665:     ** sqlite3.aVTrans[] array. */
122666:     rc = growVTrans(db);
122667:     if( rc==SQLITE_OK ){
122668:       rc = pModule->xBegin(pVTab->pVtab);
122669:       if( rc==SQLITE_OK ){
122670:         int iSvpt = db->nStatement + db->nSavepoint;
122671:         addToVTrans(db, pVTab);
122672:         if( iSvpt && pModule->xSavepoint ){
122673:           pVTab->iSavepoint = iSvpt;
122674:           rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
122675:         }
122676:       }
122677:     }
122678:   }
122679:   return rc;
122680: }
122681: 
122682: /*
122683: ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
122684: ** virtual tables that currently have an open transaction. Pass iSavepoint
122685: ** as the second argument to the virtual table method invoked.
122686: **
122687: ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
122688: ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
122689: ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
122690: ** an open transaction is invoked.
122691: **
122692: ** If any virtual table method returns an error code other than SQLITE_OK, 
122693: ** processing is abandoned and the error returned to the caller of this
122694: ** function immediately. If all calls to virtual table methods are successful,
122695: ** SQLITE_OK is returned.
122696: */
122697: SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
122698:   int rc = SQLITE_OK;
122699: 
122700:   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
122701:   assert( iSavepoint>=-1 );
122702:   if( db->aVTrans ){
122703:     int i;
122704:     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
122705:       VTable *pVTab = db->aVTrans[i];
122706:       const sqlite3_module *pMod = pVTab->pMod->pModule;
122707:       if( pVTab->pVtab && pMod->iVersion>=2 ){
122708:         int (*xMethod)(sqlite3_vtab *, int);
122709:         switch( op ){
122710:           case SAVEPOINT_BEGIN:
122711:             xMethod = pMod->xSavepoint;
122712:             pVTab->iSavepoint = iSavepoint+1;
122713:             break;
122714:           case SAVEPOINT_ROLLBACK:
122715:             xMethod = pMod->xRollbackTo;
122716:             break;
122717:           default:
122718:             xMethod = pMod->xRelease;
122719:             break;
122720:         }
122721:         if( xMethod && pVTab->iSavepoint>iSavepoint ){
122722:           rc = xMethod(pVTab->pVtab, iSavepoint);
122723:         }
122724:       }
122725:     }
122726:   }
122727:   return rc;
122728: }
122729: 
122730: /*
122731: ** The first parameter (pDef) is a function implementation.  The
122732: ** second parameter (pExpr) is the first argument to this function.
122733: ** If pExpr is a column in a virtual table, then let the virtual
122734: ** table implementation have an opportunity to overload the function.
122735: **
122736: ** This routine is used to allow virtual table implementations to
122737: ** overload MATCH, LIKE, GLOB, and REGEXP operators.
122738: **
122739: ** Return either the pDef argument (indicating no change) or a 
122740: ** new FuncDef structure that is marked as ephemeral using the
122741: ** SQLITE_FUNC_EPHEM flag.
122742: */
122743: SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
122744:   sqlite3 *db,    /* Database connection for reporting malloc problems */
122745:   FuncDef *pDef,  /* Function to possibly overload */
122746:   int nArg,       /* Number of arguments to the function */
122747:   Expr *pExpr     /* First argument to the function */
122748: ){
122749:   Table *pTab;
122750:   sqlite3_vtab *pVtab;
122751:   sqlite3_module *pMod;
122752:   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
122753:   void *pArg = 0;
122754:   FuncDef *pNew;
122755:   int rc = 0;
122756:   char *zLowerName;
122757:   unsigned char *z;
122758: 
122759: 
122760:   /* Check to see the left operand is a column in a virtual table */
122761:   if( NEVER(pExpr==0) ) return pDef;
122762:   if( pExpr->op!=TK_COLUMN ) return pDef;
122763:   pTab = pExpr->pTab;
122764:   if( NEVER(pTab==0) ) return pDef;
122765:   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
122766:   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
122767:   assert( pVtab!=0 );
122768:   assert( pVtab->pModule!=0 );
122769:   pMod = (sqlite3_module *)pVtab->pModule;
122770:   if( pMod->xFindFunction==0 ) return pDef;
122771:  
122772:   /* Call the xFindFunction method on the virtual table implementation
122773:   ** to see if the implementation wants to overload this function 
122774:   */
122775:   zLowerName = sqlite3DbStrDup(db, pDef->zName);
122776:   if( zLowerName ){
122777:     for(z=(unsigned char*)zLowerName; *z; z++){
122778:       *z = sqlite3UpperToLower[*z];
122779:     }
122780:     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
122781:     sqlite3DbFree(db, zLowerName);
122782:   }
122783:   if( rc==0 ){
122784:     return pDef;
122785:   }
122786: 
122787:   /* Create a new ephemeral function definition for the overloaded
122788:   ** function */
122789:   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
122790:                              + sqlite3Strlen30(pDef->zName) + 1);
122791:   if( pNew==0 ){
122792:     return pDef;
122793:   }
122794:   *pNew = *pDef;
122795:   pNew->zName = (const char*)&pNew[1];
122796:   memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
122797:   pNew->xSFunc = xSFunc;
122798:   pNew->pUserData = pArg;
122799:   pNew->funcFlags |= SQLITE_FUNC_EPHEM;
122800:   return pNew;
122801: }
122802: 
122803: /*
122804: ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
122805: ** array so that an OP_VBegin will get generated for it.  Add pTab to the
122806: ** array if it is missing.  If pTab is already in the array, this routine
122807: ** is a no-op.
122808: */
122809: SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
122810:   Parse *pToplevel = sqlite3ParseToplevel(pParse);
122811:   int i, n;
122812:   Table **apVtabLock;
122813: 
122814:   assert( IsVirtual(pTab) );
122815:   for(i=0; i<pToplevel->nVtabLock; i++){
122816:     if( pTab==pToplevel->apVtabLock[i] ) return;
122817:   }
122818:   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
122819:   apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
122820:   if( apVtabLock ){
122821:     pToplevel->apVtabLock = apVtabLock;
122822:     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
122823:   }else{
122824:     sqlite3OomFault(pToplevel->db);
122825:   }
122826: }
122827: 
122828: /*
122829: ** Check to see if virtual table module pMod can be have an eponymous
122830: ** virtual table instance.  If it can, create one if one does not already
122831: ** exist. Return non-zero if the eponymous virtual table instance exists
122832: ** when this routine returns, and return zero if it does not exist.
122833: **
122834: ** An eponymous virtual table instance is one that is named after its
122835: ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
122836: ** statement in order to come into existance.  Eponymous virtual table
122837: ** instances always exist.  They cannot be DROP-ed.
122838: **
122839: ** Any virtual table module for which xConnect and xCreate are the same
122840: ** method can have an eponymous virtual table instance.
122841: */
122842: SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
122843:   const sqlite3_module *pModule = pMod->pModule;
122844:   Table *pTab;
122845:   char *zErr = 0;
122846:   int rc;
122847:   sqlite3 *db = pParse->db;
122848:   if( pMod->pEpoTab ) return 1;
122849:   if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
122850:   pTab = sqlite3DbMallocZero(db, sizeof(Table));
122851:   if( pTab==0 ) return 0;
122852:   pTab->zName = sqlite3DbStrDup(db, pMod->zName);
122853:   if( pTab->zName==0 ){
122854:     sqlite3DbFree(db, pTab);
122855:     return 0;
122856:   }
122857:   pMod->pEpoTab = pTab;
122858:   pTab->nRef = 1;
122859:   pTab->pSchema = db->aDb[0].pSchema;
122860:   pTab->tabFlags |= TF_Virtual;
122861:   pTab->nModuleArg = 0;
122862:   pTab->iPKey = -1;
122863:   addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122864:   addModuleArgument(db, pTab, 0);
122865:   addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122866:   rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
122867:   if( rc ){
122868:     sqlite3ErrorMsg(pParse, "%s", zErr);
122869:     sqlite3DbFree(db, zErr);
122870:     sqlite3VtabEponymousTableClear(db, pMod);
122871:     return 0;
122872:   }
122873:   return 1;
122874: }
122875: 
122876: /*
122877: ** Erase the eponymous virtual table instance associated with
122878: ** virtual table module pMod, if it exists.
122879: */
122880: SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
122881:   Table *pTab = pMod->pEpoTab;
122882:   if( pTab!=0 ){
122883:     /* Mark the table as Ephemeral prior to deleting it, so that the
122884:     ** sqlite3DeleteTable() routine will know that it is not stored in 
122885:     ** the schema. */
122886:     pTab->tabFlags |= TF_Ephemeral;
122887:     sqlite3DeleteTable(db, pTab);
122888:     pMod->pEpoTab = 0;
122889:   }
122890: }
122891: 
122892: /*
122893: ** Return the ON CONFLICT resolution mode in effect for the virtual
122894: ** table update operation currently in progress.
122895: **
122896: ** The results of this routine are undefined unless it is called from
122897: ** within an xUpdate method.
122898: */
122899: SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
122900:   static const unsigned char aMap[] = { 
122901:     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
122902:   };
122903: #ifdef SQLITE_ENABLE_API_ARMOR
122904:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122905: #endif
122906:   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
122907:   assert( OE_Ignore==4 && OE_Replace==5 );
122908:   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
122909:   return (int)aMap[db->vtabOnConflict-1];
122910: }
122911: 
122912: /*
122913: ** Call from within the xCreate() or xConnect() methods to provide 
122914: ** the SQLite core with additional information about the behavior
122915: ** of the virtual table being implemented.
122916: */
122917: SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
122918:   va_list ap;
122919:   int rc = SQLITE_OK;
122920: 
122921: #ifdef SQLITE_ENABLE_API_ARMOR
122922:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122923: #endif
122924:   sqlite3_mutex_enter(db->mutex);
122925:   va_start(ap, op);
122926:   switch( op ){
122927:     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
122928:       VtabCtx *p = db->pVtabCtx;
122929:       if( !p ){
122930:         rc = SQLITE_MISUSE_BKPT;
122931:       }else{
122932:         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
122933:         p->pVTable->bConstraint = (u8)va_arg(ap, int);
122934:       }
122935:       break;
122936:     }
122937:     default:
122938:       rc = SQLITE_MISUSE_BKPT;
122939:       break;
122940:   }
122941:   va_end(ap);
122942: 
122943:   if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
122944:   sqlite3_mutex_leave(db->mutex);
122945:   return rc;
122946: }
122947: 
122948: #endif /* SQLITE_OMIT_VIRTUALTABLE */
122949: 
122950: /************** End of vtab.c ************************************************/
122951: /************** Begin file wherecode.c ***************************************/
122952: /*
122953: ** 2015-06-06
122954: **
122955: ** The author disclaims copyright to this source code.  In place of
122956: ** a legal notice, here is a blessing:
122957: **
122958: **    May you do good and not evil.
122959: **    May you find forgiveness for yourself and forgive others.
122960: **    May you share freely, never taking more than you give.
122961: **
122962: *************************************************************************
122963: ** This module contains C code that generates VDBE code used to process
122964: ** the WHERE clause of SQL statements.
122965: **
122966: ** This file was split off from where.c on 2015-06-06 in order to reduce the
122967: ** size of where.c and make it easier to edit.  This file contains the routines
122968: ** that actually generate the bulk of the WHERE loop code.  The original where.c
122969: ** file retains the code that does query planning and analysis.
122970: */
122971: /* #include "sqliteInt.h" */
122972: /************** Include whereInt.h in the middle of wherecode.c **************/
122973: /************** Begin file whereInt.h ****************************************/
122974: /*
122975: ** 2013-11-12
122976: **
122977: ** The author disclaims copyright to this source code.  In place of
122978: ** a legal notice, here is a blessing:
122979: **
122980: **    May you do good and not evil.
122981: **    May you find forgiveness for yourself and forgive others.
122982: **    May you share freely, never taking more than you give.
122983: **
122984: *************************************************************************
122985: **
122986: ** This file contains structure and macro definitions for the query
122987: ** planner logic in "where.c".  These definitions are broken out into
122988: ** a separate source file for easier editing.
122989: */
122990: 
122991: /*
122992: ** Trace output macros
122993: */
122994: #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
122995: /***/ int sqlite3WhereTrace;
122996: #endif
122997: #if defined(SQLITE_DEBUG) \
122998:     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
122999: # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
123000: # define WHERETRACE_ENABLED 1
123001: #else
123002: # define WHERETRACE(K,X)
123003: #endif
123004: 
123005: /* Forward references
123006: */
123007: typedef struct WhereClause WhereClause;
123008: typedef struct WhereMaskSet WhereMaskSet;
123009: typedef struct WhereOrInfo WhereOrInfo;
123010: typedef struct WhereAndInfo WhereAndInfo;
123011: typedef struct WhereLevel WhereLevel;
123012: typedef struct WhereLoop WhereLoop;
123013: typedef struct WherePath WherePath;
123014: typedef struct WhereTerm WhereTerm;
123015: typedef struct WhereLoopBuilder WhereLoopBuilder;
123016: typedef struct WhereScan WhereScan;
123017: typedef struct WhereOrCost WhereOrCost;
123018: typedef struct WhereOrSet WhereOrSet;
123019: 
123020: /*
123021: ** This object contains information needed to implement a single nested
123022: ** loop in WHERE clause.
123023: **
123024: ** Contrast this object with WhereLoop.  This object describes the
123025: ** implementation of the loop.  WhereLoop describes the algorithm.
123026: ** This object contains a pointer to the WhereLoop algorithm as one of
123027: ** its elements.
123028: **
123029: ** The WhereInfo object contains a single instance of this object for
123030: ** each term in the FROM clause (which is to say, for each of the
123031: ** nested loops as implemented).  The order of WhereLevel objects determines
123032: ** the loop nested order, with WhereInfo.a[0] being the outer loop and
123033: ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
123034: */
123035: struct WhereLevel {
123036:   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
123037:   int iTabCur;          /* The VDBE cursor used to access the table */
123038:   int iIdxCur;          /* The VDBE cursor used to access pIdx */
123039:   int addrBrk;          /* Jump here to break out of the loop */
123040:   int addrNxt;          /* Jump here to start the next IN combination */
123041:   int addrSkip;         /* Jump here for next iteration of skip-scan */
123042:   int addrCont;         /* Jump here to continue with the next loop cycle */
123043:   int addrFirst;        /* First instruction of interior of the loop */
123044:   int addrBody;         /* Beginning of the body of this loop */
123045: #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123046:   u32 iLikeRepCntr;     /* LIKE range processing counter register (times 2) */
123047:   int addrLikeRep;      /* LIKE range processing address */
123048: #endif
123049:   u8 iFrom;             /* Which entry in the FROM clause */
123050:   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
123051:   int p1, p2;           /* Operands of the opcode used to ends the loop */
123052:   union {               /* Information that depends on pWLoop->wsFlags */
123053:     struct {
123054:       int nIn;              /* Number of entries in aInLoop[] */
123055:       struct InLoop {
123056:         int iCur;              /* The VDBE cursor used by this IN operator */
123057:         int addrInTop;         /* Top of the IN loop */
123058:         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
123059:       } *aInLoop;           /* Information about each nested IN operator */
123060:     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
123061:     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
123062:   } u;
123063:   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
123064:   Bitmask notReady;          /* FROM entries not usable at this level */
123065: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123066:   int addrVisit;        /* Address at which row is visited */
123067: #endif
123068: };
123069: 
123070: /*
123071: ** Each instance of this object represents an algorithm for evaluating one
123072: ** term of a join.  Every term of the FROM clause will have at least
123073: ** one corresponding WhereLoop object (unless INDEXED BY constraints
123074: ** prevent a query solution - which is an error) and many terms of the
123075: ** FROM clause will have multiple WhereLoop objects, each describing a
123076: ** potential way of implementing that FROM-clause term, together with
123077: ** dependencies and cost estimates for using the chosen algorithm.
123078: **
123079: ** Query planning consists of building up a collection of these WhereLoop
123080: ** objects, then computing a particular sequence of WhereLoop objects, with
123081: ** one WhereLoop object per FROM clause term, that satisfy all dependencies
123082: ** and that minimize the overall cost.
123083: */
123084: struct WhereLoop {
123085:   Bitmask prereq;       /* Bitmask of other loops that must run first */
123086:   Bitmask maskSelf;     /* Bitmask identifying table iTab */
123087: #ifdef SQLITE_DEBUG
123088:   char cId;             /* Symbolic ID of this loop for debugging use */
123089: #endif
123090:   u8 iTab;              /* Position in FROM clause of table for this loop */
123091:   u8 iSortIdx;          /* Sorting index number.  0==None */
123092:   LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
123093:   LogEst rRun;          /* Cost of running each loop */
123094:   LogEst nOut;          /* Estimated number of output rows */
123095:   union {
123096:     struct {               /* Information for internal btree tables */
123097:       u16 nEq;               /* Number of equality constraints */
123098:       Index *pIndex;         /* Index used, or NULL */
123099:     } btree;
123100:     struct {               /* Information for virtual tables */
123101:       int idxNum;            /* Index number */
123102:       u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
123103:       i8 isOrdered;          /* True if satisfies ORDER BY */
123104:       u16 omitMask;          /* Terms that may be omitted */
123105:       char *idxStr;          /* Index identifier string */
123106:     } vtab;
123107:   } u;
123108:   u32 wsFlags;          /* WHERE_* flags describing the plan */
123109:   u16 nLTerm;           /* Number of entries in aLTerm[] */
123110:   u16 nSkip;            /* Number of NULL aLTerm[] entries */
123111:   /**** whereLoopXfer() copies fields above ***********************/
123112: # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
123113:   u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
123114:   WhereTerm **aLTerm;   /* WhereTerms used */
123115:   WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
123116:   WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
123117: };
123118: 
123119: /* This object holds the prerequisites and the cost of running a
123120: ** subquery on one operand of an OR operator in the WHERE clause.
123121: ** See WhereOrSet for additional information 
123122: */
123123: struct WhereOrCost {
123124:   Bitmask prereq;     /* Prerequisites */
123125:   LogEst rRun;        /* Cost of running this subquery */
123126:   LogEst nOut;        /* Number of outputs for this subquery */
123127: };
123128: 
123129: /* The WhereOrSet object holds a set of possible WhereOrCosts that
123130: ** correspond to the subquery(s) of OR-clause processing.  Only the
123131: ** best N_OR_COST elements are retained.
123132: */
123133: #define N_OR_COST 3
123134: struct WhereOrSet {
123135:   u16 n;                      /* Number of valid a[] entries */
123136:   WhereOrCost a[N_OR_COST];   /* Set of best costs */
123137: };
123138: 
123139: /*
123140: ** Each instance of this object holds a sequence of WhereLoop objects
123141: ** that implement some or all of a query plan.
123142: **
123143: ** Think of each WhereLoop object as a node in a graph with arcs
123144: ** showing dependencies and costs for travelling between nodes.  (That is
123145: ** not a completely accurate description because WhereLoop costs are a
123146: ** vector, not a scalar, and because dependencies are many-to-one, not
123147: ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
123148: ** Then a WherePath object is a path through the graph that visits some
123149: ** or all of the WhereLoop objects once.
123150: **
123151: ** The "solver" works by creating the N best WherePath objects of length
123152: ** 1.  Then using those as a basis to compute the N best WherePath objects
123153: ** of length 2.  And so forth until the length of WherePaths equals the
123154: ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
123155: ** at the end is the chosen query plan.
123156: */
123157: struct WherePath {
123158:   Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
123159:   Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
123160:   LogEst nRow;          /* Estimated number of rows generated by this path */
123161:   LogEst rCost;         /* Total cost of this path */
123162:   LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
123163:   i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
123164:   WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
123165: };
123166: 
123167: /*
123168: ** The query generator uses an array of instances of this structure to
123169: ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
123170: ** clause subexpression is separated from the others by AND operators,
123171: ** usually, or sometimes subexpressions separated by OR.
123172: **
123173: ** All WhereTerms are collected into a single WhereClause structure.  
123174: ** The following identity holds:
123175: **
123176: **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
123177: **
123178: ** When a term is of the form:
123179: **
123180: **              X <op> <expr>
123181: **
123182: ** where X is a column name and <op> is one of certain operators,
123183: ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
123184: ** cursor number and column number for X.  WhereTerm.eOperator records
123185: ** the <op> using a bitmask encoding defined by WO_xxx below.  The
123186: ** use of a bitmask encoding for the operator allows us to search
123187: ** quickly for terms that match any of several different operators.
123188: **
123189: ** A WhereTerm might also be two or more subterms connected by OR:
123190: **
123191: **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
123192: **
123193: ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
123194: ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
123195: ** is collected about the OR clause.
123196: **
123197: ** If a term in the WHERE clause does not match either of the two previous
123198: ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
123199: ** to the original subexpression content and wtFlags is set up appropriately
123200: ** but no other fields in the WhereTerm object are meaningful.
123201: **
123202: ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
123203: ** but they do so indirectly.  A single WhereMaskSet structure translates
123204: ** cursor number into bits and the translated bit is stored in the prereq
123205: ** fields.  The translation is used in order to maximize the number of
123206: ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
123207: ** spread out over the non-negative integers.  For example, the cursor
123208: ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
123209: ** translates these sparse cursor numbers into consecutive integers
123210: ** beginning with 0 in order to make the best possible use of the available
123211: ** bits in the Bitmask.  So, in the example above, the cursor numbers
123212: ** would be mapped into integers 0 through 7.
123213: **
123214: ** The number of terms in a join is limited by the number of bits
123215: ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
123216: ** is only able to process joins with 64 or fewer tables.
123217: */
123218: struct WhereTerm {
123219:   Expr *pExpr;            /* Pointer to the subexpression that is this term */
123220:   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
123221:   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
123222:   union {
123223:     int leftColumn;         /* Column number of X in "X <op> <expr>" */
123224:     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
123225:     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
123226:   } u;
123227:   LogEst truthProb;       /* Probability of truth for this expression */
123228:   u16 eOperator;          /* A WO_xx value describing <op> */
123229:   u16 wtFlags;            /* TERM_xxx bit flags.  See below */
123230:   u8 nChild;              /* Number of children that must disable us */
123231:   u8 eMatchOp;            /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
123232:   WhereClause *pWC;       /* The clause this term is part of */
123233:   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
123234:   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
123235: };
123236: 
123237: /*
123238: ** Allowed values of WhereTerm.wtFlags
123239: */
123240: #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
123241: #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
123242: #define TERM_CODED      0x04   /* This term is already coded */
123243: #define TERM_COPIED     0x08   /* Has a child */
123244: #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
123245: #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
123246: #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
123247: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123248: #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
123249: #else
123250: #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
123251: #endif
123252: #define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
123253: #define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
123254: #define TERM_LIKE       0x400  /* The original LIKE operator */
123255: #define TERM_IS         0x800  /* Term.pExpr is an IS operator */
123256: 
123257: /*
123258: ** An instance of the WhereScan object is used as an iterator for locating
123259: ** terms in the WHERE clause that are useful to the query planner.
123260: */
123261: struct WhereScan {
123262:   WhereClause *pOrigWC;      /* Original, innermost WhereClause */
123263:   WhereClause *pWC;          /* WhereClause currently being scanned */
123264:   const char *zCollName;     /* Required collating sequence, if not NULL */
123265:   Expr *pIdxExpr;            /* Search for this index expression */
123266:   char idxaff;               /* Must match this affinity, if zCollName!=NULL */
123267:   unsigned char nEquiv;      /* Number of entries in aEquiv[] */
123268:   unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
123269:   u32 opMask;                /* Acceptable operators */
123270:   int k;                     /* Resume scanning at this->pWC->a[this->k] */
123271:   int aiCur[11];             /* Cursors in the equivalence class */
123272:   i16 aiColumn[11];          /* Corresponding column number in the eq-class */
123273: };
123274: 
123275: /*
123276: ** An instance of the following structure holds all information about a
123277: ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
123278: **
123279: ** Explanation of pOuter:  For a WHERE clause of the form
123280: **
123281: **           a AND ((b AND c) OR (d AND e)) AND f
123282: **
123283: ** There are separate WhereClause objects for the whole clause and for
123284: ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
123285: ** subclauses points to the WhereClause object for the whole clause.
123286: */
123287: struct WhereClause {
123288:   WhereInfo *pWInfo;       /* WHERE clause processing context */
123289:   WhereClause *pOuter;     /* Outer conjunction */
123290:   u8 op;                   /* Split operator.  TK_AND or TK_OR */
123291:   int nTerm;               /* Number of terms */
123292:   int nSlot;               /* Number of entries in a[] */
123293:   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
123294: #if defined(SQLITE_SMALL_STACK)
123295:   WhereTerm aStatic[1];    /* Initial static space for a[] */
123296: #else
123297:   WhereTerm aStatic[8];    /* Initial static space for a[] */
123298: #endif
123299: };
123300: 
123301: /*
123302: ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
123303: ** a dynamically allocated instance of the following structure.
123304: */
123305: struct WhereOrInfo {
123306:   WhereClause wc;          /* Decomposition into subterms */
123307:   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
123308: };
123309: 
123310: /*
123311: ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
123312: ** a dynamically allocated instance of the following structure.
123313: */
123314: struct WhereAndInfo {
123315:   WhereClause wc;          /* The subexpression broken out */
123316: };
123317: 
123318: /*
123319: ** An instance of the following structure keeps track of a mapping
123320: ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
123321: **
123322: ** The VDBE cursor numbers are small integers contained in 
123323: ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
123324: ** clause, the cursor numbers might not begin with 0 and they might
123325: ** contain gaps in the numbering sequence.  But we want to make maximum
123326: ** use of the bits in our bitmasks.  This structure provides a mapping
123327: ** from the sparse cursor numbers into consecutive integers beginning
123328: ** with 0.
123329: **
123330: ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
123331: ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
123332: **
123333: ** For example, if the WHERE clause expression used these VDBE
123334: ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
123335: ** would map those cursor numbers into bits 0 through 5.
123336: **
123337: ** Note that the mapping is not necessarily ordered.  In the example
123338: ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
123339: ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
123340: ** does not really matter.  What is important is that sparse cursor
123341: ** numbers all get mapped into bit numbers that begin with 0 and contain
123342: ** no gaps.
123343: */
123344: struct WhereMaskSet {
123345:   int n;                        /* Number of assigned cursor values */
123346:   int ix[BMS];                  /* Cursor assigned to each bit */
123347: };
123348: 
123349: /*
123350: ** Initialize a WhereMaskSet object
123351: */
123352: #define initMaskSet(P)  (P)->n=0
123353: 
123354: /*
123355: ** This object is a convenience wrapper holding all information needed
123356: ** to construct WhereLoop objects for a particular query.
123357: */
123358: struct WhereLoopBuilder {
123359:   WhereInfo *pWInfo;        /* Information about this WHERE */
123360:   WhereClause *pWC;         /* WHERE clause terms */
123361:   ExprList *pOrderBy;       /* ORDER BY clause */
123362:   WhereLoop *pNew;          /* Template WhereLoop */
123363:   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
123364: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
123365:   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
123366:   int nRecValid;            /* Number of valid fields currently in pRec */
123367: #endif
123368: };
123369: 
123370: /*
123371: ** The WHERE clause processing routine has two halves.  The
123372: ** first part does the start of the WHERE loop and the second
123373: ** half does the tail of the WHERE loop.  An instance of
123374: ** this structure is returned by the first half and passed
123375: ** into the second half to give some continuity.
123376: **
123377: ** An instance of this object holds the complete state of the query
123378: ** planner.
123379: */
123380: struct WhereInfo {
123381:   Parse *pParse;            /* Parsing and code generating context */
123382:   SrcList *pTabList;        /* List of tables in the join */
123383:   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
123384:   ExprList *pDistinctSet;   /* DISTINCT over all these values */
123385:   WhereLoop *pLoops;        /* List of all WhereLoop objects */
123386:   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
123387:   LogEst nRowOut;           /* Estimated number of output rows */
123388:   LogEst iLimit;            /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
123389:   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
123390:   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
123391:   u8 sorted;                /* True if really sorted (not just grouped) */
123392:   u8 eOnePass;              /* ONEPASS_OFF, or _SINGLE, or _MULTI */
123393:   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
123394:   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values */
123395:   u8 nLevel;                /* Number of nested loop */
123396:   u8 bOrderedInnerLoop;     /* True if only the inner-most loop is ordered */
123397:   int iTop;                 /* The very beginning of the WHERE loop */
123398:   int iContinue;            /* Jump here to continue with next record */
123399:   int iBreak;               /* Jump here to break out of the loop */
123400:   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
123401:   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
123402:   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
123403:   WhereClause sWC;          /* Decomposition of the WHERE clause */
123404:   WhereLevel a[1];          /* Information about each nest loop in WHERE */
123405: };
123406: 
123407: /*
123408: ** Private interfaces - callable only by other where.c routines.
123409: **
123410: ** where.c:
123411: */
123412: SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
123413: #ifdef WHERETRACE_ENABLED
123414: SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
123415: #endif
123416: SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
123417:   WhereClause *pWC,     /* The WHERE clause to be searched */
123418:   int iCur,             /* Cursor number of LHS */
123419:   int iColumn,          /* Column number of LHS */
123420:   Bitmask notReady,     /* RHS must not overlap with this mask */
123421:   u32 op,               /* Mask of WO_xx values describing operator */
123422:   Index *pIdx           /* Must be compatible with this index, if not NULL */
123423: );
123424: 
123425: /* wherecode.c: */
123426: #ifndef SQLITE_OMIT_EXPLAIN
123427: SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
123428:   Parse *pParse,                  /* Parse context */
123429:   SrcList *pTabList,              /* Table list this loop refers to */
123430:   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
123431:   int iLevel,                     /* Value for "level" column of output */
123432:   int iFrom,                      /* Value for "from" column of output */
123433:   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
123434: );
123435: #else
123436: # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
123437: #endif /* SQLITE_OMIT_EXPLAIN */
123438: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123439: SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
123440:   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
123441:   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
123442:   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
123443:   int addrExplain                 /* Address of OP_Explain (or 0) */
123444: );
123445: #else
123446: # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
123447: #endif
123448: SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
123449:   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
123450:   int iLevel,          /* Which level of pWInfo->a[] should be coded */
123451:   Bitmask notReady     /* Which tables are currently available */
123452: );
123453: 
123454: /* whereexpr.c: */
123455: SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
123456: SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
123457: SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
123458: SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
123459: SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
123460: SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
123461: SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
123462: 
123463: 
123464: 
123465: 
123466: 
123467: /*
123468: ** Bitmasks for the operators on WhereTerm objects.  These are all
123469: ** operators that are of interest to the query planner.  An
123470: ** OR-ed combination of these values can be used when searching for
123471: ** particular WhereTerms within a WhereClause.
123472: **
123473: ** Value constraints:
123474: **     WO_EQ    == SQLITE_INDEX_CONSTRAINT_EQ
123475: **     WO_LT    == SQLITE_INDEX_CONSTRAINT_LT
123476: **     WO_LE    == SQLITE_INDEX_CONSTRAINT_LE
123477: **     WO_GT    == SQLITE_INDEX_CONSTRAINT_GT
123478: **     WO_GE    == SQLITE_INDEX_CONSTRAINT_GE
123479: **     WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
123480: */
123481: #define WO_IN     0x0001
123482: #define WO_EQ     0x0002
123483: #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
123484: #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
123485: #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
123486: #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
123487: #define WO_MATCH  0x0040
123488: #define WO_IS     0x0080
123489: #define WO_ISNULL 0x0100
123490: #define WO_OR     0x0200       /* Two or more OR-connected terms */
123491: #define WO_AND    0x0400       /* Two or more AND-connected terms */
123492: #define WO_EQUIV  0x0800       /* Of the form A==B, both columns */
123493: #define WO_NOOP   0x1000       /* This term does not restrict search space */
123494: 
123495: #define WO_ALL    0x1fff       /* Mask of all possible WO_* values */
123496: #define WO_SINGLE 0x01ff       /* Mask of all non-compound WO_* values */
123497: 
123498: /*
123499: ** These are definitions of bits in the WhereLoop.wsFlags field.
123500: ** The particular combination of bits in each WhereLoop help to
123501: ** determine the algorithm that WhereLoop represents.
123502: */
123503: #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
123504: #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
123505: #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
123506: #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
123507: #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
123508: #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
123509: #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
123510: #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
123511: #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
123512: #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
123513: #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
123514: #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
123515: #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
123516: #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
123517: #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
123518: #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
123519: #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
123520: #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
123521: #define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
123522: 
123523: /************** End of whereInt.h ********************************************/
123524: /************** Continuing where we left off in wherecode.c ******************/
123525: 
123526: #ifndef SQLITE_OMIT_EXPLAIN
123527: /*
123528: ** This routine is a helper for explainIndexRange() below
123529: **
123530: ** pStr holds the text of an expression that we are building up one term
123531: ** at a time.  This routine adds a new term to the end of the expression.
123532: ** Terms are separated by AND so add the "AND" text for second and subsequent
123533: ** terms only.
123534: */
123535: static void explainAppendTerm(
123536:   StrAccum *pStr,             /* The text expression being built */
123537:   int iTerm,                  /* Index of this term.  First is zero */
123538:   const char *zColumn,        /* Name of the column */
123539:   const char *zOp             /* Name of the operator */
123540: ){
123541:   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
123542:   sqlite3StrAccumAppendAll(pStr, zColumn);
123543:   sqlite3StrAccumAppend(pStr, zOp, 1);
123544:   sqlite3StrAccumAppend(pStr, "?", 1);
123545: }
123546: 
123547: /*
123548: ** Return the name of the i-th column of the pIdx index.
123549: */
123550: static const char *explainIndexColumnName(Index *pIdx, int i){
123551:   i = pIdx->aiColumn[i];
123552:   if( i==XN_EXPR ) return "<expr>";
123553:   if( i==XN_ROWID ) return "rowid";
123554:   return pIdx->pTable->aCol[i].zName;
123555: }
123556: 
123557: /*
123558: ** Argument pLevel describes a strategy for scanning table pTab. This 
123559: ** function appends text to pStr that describes the subset of table
123560: ** rows scanned by the strategy in the form of an SQL expression.
123561: **
123562: ** For example, if the query:
123563: **
123564: **   SELECT * FROM t1 WHERE a=1 AND b>2;
123565: **
123566: ** is run and there is an index on (a, b), then this function returns a
123567: ** string similar to:
123568: **
123569: **   "a=? AND b>?"
123570: */
123571: static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
123572:   Index *pIndex = pLoop->u.btree.pIndex;
123573:   u16 nEq = pLoop->u.btree.nEq;
123574:   u16 nSkip = pLoop->nSkip;
123575:   int i, j;
123576: 
123577:   if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
123578:   sqlite3StrAccumAppend(pStr, " (", 2);
123579:   for(i=0; i<nEq; i++){
123580:     const char *z = explainIndexColumnName(pIndex, i);
123581:     if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
123582:     sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
123583:   }
123584: 
123585:   j = i;
123586:   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
123587:     const char *z = explainIndexColumnName(pIndex, i);
123588:     explainAppendTerm(pStr, i++, z, ">");
123589:   }
123590:   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
123591:     const char *z = explainIndexColumnName(pIndex, j);
123592:     explainAppendTerm(pStr, i, z, "<");
123593:   }
123594:   sqlite3StrAccumAppend(pStr, ")", 1);
123595: }
123596: 
123597: /*
123598: ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
123599: ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
123600: ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 
123601: ** is added to the output to describe the table scan strategy in pLevel.
123602: **
123603: ** If an OP_Explain opcode is added to the VM, its address is returned.
123604: ** Otherwise, if no OP_Explain is coded, zero is returned.
123605: */
123606: SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
123607:   Parse *pParse,                  /* Parse context */
123608:   SrcList *pTabList,              /* Table list this loop refers to */
123609:   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
123610:   int iLevel,                     /* Value for "level" column of output */
123611:   int iFrom,                      /* Value for "from" column of output */
123612:   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
123613: ){
123614:   int ret = 0;
123615: #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
123616:   if( pParse->explain==2 )
123617: #endif
123618:   {
123619:     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
123620:     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
123621:     sqlite3 *db = pParse->db;     /* Database handle */
123622:     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
123623:     int isSearch;                 /* True for a SEARCH. False for SCAN. */
123624:     WhereLoop *pLoop;             /* The controlling WhereLoop object */
123625:     u32 flags;                    /* Flags that describe this loop */
123626:     char *zMsg;                   /* Text to add to EQP output */
123627:     StrAccum str;                 /* EQP output string */
123628:     char zBuf[100];               /* Initial space for EQP output string */
123629: 
123630:     pLoop = pLevel->pWLoop;
123631:     flags = pLoop->wsFlags;
123632:     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
123633: 
123634:     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
123635:             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
123636:             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
123637: 
123638:     sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
123639:     sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
123640:     if( pItem->pSelect ){
123641:       sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
123642:     }else{
123643:       sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
123644:     }
123645: 
123646:     if( pItem->zAlias ){
123647:       sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
123648:     }
123649:     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
123650:       const char *zFmt = 0;
123651:       Index *pIdx;
123652: 
123653:       assert( pLoop->u.btree.pIndex!=0 );
123654:       pIdx = pLoop->u.btree.pIndex;
123655:       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
123656:       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
123657:         if( isSearch ){
123658:           zFmt = "PRIMARY KEY";
123659:         }
123660:       }else if( flags & WHERE_PARTIALIDX ){
123661:         zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
123662:       }else if( flags & WHERE_AUTO_INDEX ){
123663:         zFmt = "AUTOMATIC COVERING INDEX";
123664:       }else if( flags & WHERE_IDX_ONLY ){
123665:         zFmt = "COVERING INDEX %s";
123666:       }else{
123667:         zFmt = "INDEX %s";
123668:       }
123669:       if( zFmt ){
123670:         sqlite3StrAccumAppend(&str, " USING ", 7);
123671:         sqlite3XPrintf(&str, zFmt, pIdx->zName);
123672:         explainIndexRange(&str, pLoop);
123673:       }
123674:     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
123675:       const char *zRangeOp;
123676:       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
123677:         zRangeOp = "=";
123678:       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
123679:         zRangeOp = ">? AND rowid<";
123680:       }else if( flags&WHERE_BTM_LIMIT ){
123681:         zRangeOp = ">";
123682:       }else{
123683:         assert( flags&WHERE_TOP_LIMIT);
123684:         zRangeOp = "<";
123685:       }
123686:       sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
123687:     }
123688: #ifndef SQLITE_OMIT_VIRTUALTABLE
123689:     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
123690:       sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
123691:                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
123692:     }
123693: #endif
123694: #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
123695:     if( pLoop->nOut>=10 ){
123696:       sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
123697:     }else{
123698:       sqlite3StrAccumAppend(&str, " (~1 row)", 9);
123699:     }
123700: #endif
123701:     zMsg = sqlite3StrAccumFinish(&str);
123702:     ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
123703:   }
123704:   return ret;
123705: }
123706: #endif /* SQLITE_OMIT_EXPLAIN */
123707: 
123708: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
123709: /*
123710: ** Configure the VM passed as the first argument with an
123711: ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 
123712: ** implement level pLvl. Argument pSrclist is a pointer to the FROM 
123713: ** clause that the scan reads data from.
123714: **
123715: ** If argument addrExplain is not 0, it must be the address of an 
123716: ** OP_Explain instruction that describes the same loop.
123717: */
123718: SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
123719:   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
123720:   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
123721:   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
123722:   int addrExplain                 /* Address of OP_Explain (or 0) */
123723: ){
123724:   const char *zObj = 0;
123725:   WhereLoop *pLoop = pLvl->pWLoop;
123726:   if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
123727:     zObj = pLoop->u.btree.pIndex->zName;
123728:   }else{
123729:     zObj = pSrclist->a[pLvl->iFrom].zName;
123730:   }
123731:   sqlite3VdbeScanStatus(
123732:       v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
123733:   );
123734: }
123735: #endif
123736: 
123737: 
123738: /*
123739: ** Disable a term in the WHERE clause.  Except, do not disable the term
123740: ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
123741: ** or USING clause of that join.
123742: **
123743: ** Consider the term t2.z='ok' in the following queries:
123744: **
123745: **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
123746: **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
123747: **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
123748: **
123749: ** The t2.z='ok' is disabled in the in (2) because it originates
123750: ** in the ON clause.  The term is disabled in (3) because it is not part
123751: ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
123752: **
123753: ** Disabling a term causes that term to not be tested in the inner loop
123754: ** of the join.  Disabling is an optimization.  When terms are satisfied
123755: ** by indices, we disable them to prevent redundant tests in the inner
123756: ** loop.  We would get the correct results if nothing were ever disabled,
123757: ** but joins might run a little slower.  The trick is to disable as much
123758: ** as we can without disabling too much.  If we disabled in (1), we'd get
123759: ** the wrong answer.  See ticket #813.
123760: **
123761: ** If all the children of a term are disabled, then that term is also
123762: ** automatically disabled.  In this way, terms get disabled if derived
123763: ** virtual terms are tested first.  For example:
123764: **
123765: **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
123766: **      \___________/     \______/     \_____/
123767: **         parent          child1       child2
123768: **
123769: ** Only the parent term was in the original WHERE clause.  The child1
123770: ** and child2 terms were added by the LIKE optimization.  If both of
123771: ** the virtual child terms are valid, then testing of the parent can be 
123772: ** skipped.
123773: **
123774: ** Usually the parent term is marked as TERM_CODED.  But if the parent
123775: ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
123776: ** The TERM_LIKECOND marking indicates that the term should be coded inside
123777: ** a conditional such that is only evaluated on the second pass of a
123778: ** LIKE-optimization loop, when scanning BLOBs instead of strings.
123779: */
123780: static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
123781:   int nLoop = 0;
123782:   while( pTerm
123783:       && (pTerm->wtFlags & TERM_CODED)==0
123784:       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
123785:       && (pLevel->notReady & pTerm->prereqAll)==0
123786:   ){
123787:     if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
123788:       pTerm->wtFlags |= TERM_LIKECOND;
123789:     }else{
123790:       pTerm->wtFlags |= TERM_CODED;
123791:     }
123792:     if( pTerm->iParent<0 ) break;
123793:     pTerm = &pTerm->pWC->a[pTerm->iParent];
123794:     pTerm->nChild--;
123795:     if( pTerm->nChild!=0 ) break;
123796:     nLoop++;
123797:   }
123798: }
123799: 
123800: /*
123801: ** Code an OP_Affinity opcode to apply the column affinity string zAff
123802: ** to the n registers starting at base. 
123803: **
123804: ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
123805: ** beginning and end of zAff are ignored.  If all entries in zAff are
123806: ** SQLITE_AFF_BLOB, then no code gets generated.
123807: **
123808: ** This routine makes its own copy of zAff so that the caller is free
123809: ** to modify zAff after this routine returns.
123810: */
123811: static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
123812:   Vdbe *v = pParse->pVdbe;
123813:   if( zAff==0 ){
123814:     assert( pParse->db->mallocFailed );
123815:     return;
123816:   }
123817:   assert( v!=0 );
123818: 
123819:   /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
123820:   ** and end of the affinity string.
123821:   */
123822:   while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
123823:     n--;
123824:     base++;
123825:     zAff++;
123826:   }
123827:   while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
123828:     n--;
123829:   }
123830: 
123831:   /* Code the OP_Affinity opcode if there is anything left to do. */
123832:   if( n>0 ){
123833:     sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
123834:     sqlite3ExprCacheAffinityChange(pParse, base, n);
123835:   }
123836: }
123837: 
123838: 
123839: /*
123840: ** Generate code for a single equality term of the WHERE clause.  An equality
123841: ** term can be either X=expr or X IN (...).   pTerm is the term to be 
123842: ** coded.
123843: **
123844: ** The current value for the constraint is left in register iReg.
123845: **
123846: ** For a constraint of the form X=expr, the expression is evaluated and its
123847: ** result is left on the stack.  For constraints of the form X IN (...)
123848: ** this routine sets up a loop that will iterate over all values of X.
123849: */
123850: static int codeEqualityTerm(
123851:   Parse *pParse,      /* The parsing context */
123852:   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
123853:   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
123854:   int iEq,            /* Index of the equality term within this level */
123855:   int bRev,           /* True for reverse-order IN operations */
123856:   int iTarget         /* Attempt to leave results in this register */
123857: ){
123858:   Expr *pX = pTerm->pExpr;
123859:   Vdbe *v = pParse->pVdbe;
123860:   int iReg;                  /* Register holding results */
123861: 
123862:   assert( iTarget>0 );
123863:   if( pX->op==TK_EQ || pX->op==TK_IS ){
123864:     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
123865:   }else if( pX->op==TK_ISNULL ){
123866:     iReg = iTarget;
123867:     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
123868: #ifndef SQLITE_OMIT_SUBQUERY
123869:   }else{
123870:     int eType;
123871:     int iTab;
123872:     struct InLoop *pIn;
123873:     WhereLoop *pLoop = pLevel->pWLoop;
123874: 
123875:     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
123876:       && pLoop->u.btree.pIndex!=0
123877:       && pLoop->u.btree.pIndex->aSortOrder[iEq]
123878:     ){
123879:       testcase( iEq==0 );
123880:       testcase( bRev );
123881:       bRev = !bRev;
123882:     }
123883:     assert( pX->op==TK_IN );
123884:     iReg = iTarget;
123885:     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
123886:     if( eType==IN_INDEX_INDEX_DESC ){
123887:       testcase( bRev );
123888:       bRev = !bRev;
123889:     }
123890:     iTab = pX->iTable;
123891:     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
123892:     VdbeCoverageIf(v, bRev);
123893:     VdbeCoverageIf(v, !bRev);
123894:     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
123895:     pLoop->wsFlags |= WHERE_IN_ABLE;
123896:     if( pLevel->u.in.nIn==0 ){
123897:       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
123898:     }
123899:     pLevel->u.in.nIn++;
123900:     pLevel->u.in.aInLoop =
123901:        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
123902:                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
123903:     pIn = pLevel->u.in.aInLoop;
123904:     if( pIn ){
123905:       pIn += pLevel->u.in.nIn - 1;
123906:       pIn->iCur = iTab;
123907:       if( eType==IN_INDEX_ROWID ){
123908:         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
123909:       }else{
123910:         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
123911:       }
123912:       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
123913:       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
123914:     }else{
123915:       pLevel->u.in.nIn = 0;
123916:     }
123917: #endif
123918:   }
123919:   disableTerm(pLevel, pTerm);
123920:   return iReg;
123921: }
123922: 
123923: /*
123924: ** Generate code that will evaluate all == and IN constraints for an
123925: ** index scan.
123926: **
123927: ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
123928: ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
123929: ** The index has as many as three equality constraints, but in this
123930: ** example, the third "c" value is an inequality.  So only two 
123931: ** constraints are coded.  This routine will generate code to evaluate
123932: ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
123933: ** in consecutive registers and the index of the first register is returned.
123934: **
123935: ** In the example above nEq==2.  But this subroutine works for any value
123936: ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
123937: ** The only thing it does is allocate the pLevel->iMem memory cell and
123938: ** compute the affinity string.
123939: **
123940: ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
123941: ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
123942: ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
123943: ** occurs after the nEq quality constraints.
123944: **
123945: ** This routine allocates a range of nEq+nExtraReg memory cells and returns
123946: ** the index of the first memory cell in that range. The code that
123947: ** calls this routine will use that memory range to store keys for
123948: ** start and termination conditions of the loop.
123949: ** key value of the loop.  If one or more IN operators appear, then
123950: ** this routine allocates an additional nEq memory cells for internal
123951: ** use.
123952: **
123953: ** Before returning, *pzAff is set to point to a buffer containing a
123954: ** copy of the column affinity string of the index allocated using
123955: ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
123956: ** with equality constraints that use BLOB or NONE affinity are set to
123957: ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
123958: **
123959: **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
123960: **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
123961: **
123962: ** In the example above, the index on t1(a) has TEXT affinity. But since
123963: ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
123964: ** no conversion should be attempted before using a t2.b value as part of
123965: ** a key to search the index. Hence the first byte in the returned affinity
123966: ** string in this example would be set to SQLITE_AFF_BLOB.
123967: */
123968: static int codeAllEqualityTerms(
123969:   Parse *pParse,        /* Parsing context */
123970:   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
123971:   int bRev,             /* Reverse the order of IN operators */
123972:   int nExtraReg,        /* Number of extra registers to allocate */
123973:   char **pzAff          /* OUT: Set to point to affinity string */
123974: ){
123975:   u16 nEq;                      /* The number of == or IN constraints to code */
123976:   u16 nSkip;                    /* Number of left-most columns to skip */
123977:   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
123978:   Index *pIdx;                  /* The index being used for this loop */
123979:   WhereTerm *pTerm;             /* A single constraint term */
123980:   WhereLoop *pLoop;             /* The WhereLoop object */
123981:   int j;                        /* Loop counter */
123982:   int regBase;                  /* Base register */
123983:   int nReg;                     /* Number of registers to allocate */
123984:   char *zAff;                   /* Affinity string to return */
123985: 
123986:   /* This module is only called on query plans that use an index. */
123987:   pLoop = pLevel->pWLoop;
123988:   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
123989:   nEq = pLoop->u.btree.nEq;
123990:   nSkip = pLoop->nSkip;
123991:   pIdx = pLoop->u.btree.pIndex;
123992:   assert( pIdx!=0 );
123993: 
123994:   /* Figure out how many memory cells we will need then allocate them.
123995:   */
123996:   regBase = pParse->nMem + 1;
123997:   nReg = pLoop->u.btree.nEq + nExtraReg;
123998:   pParse->nMem += nReg;
123999: 
124000:   zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
124001:   assert( zAff!=0 || pParse->db->mallocFailed );
124002: 
124003:   if( nSkip ){
124004:     int iIdxCur = pLevel->iIdxCur;
124005:     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
124006:     VdbeCoverageIf(v, bRev==0);
124007:     VdbeCoverageIf(v, bRev!=0);
124008:     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
124009:     j = sqlite3VdbeAddOp0(v, OP_Goto);
124010:     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
124011:                             iIdxCur, 0, regBase, nSkip);
124012:     VdbeCoverageIf(v, bRev==0);
124013:     VdbeCoverageIf(v, bRev!=0);
124014:     sqlite3VdbeJumpHere(v, j);
124015:     for(j=0; j<nSkip; j++){
124016:       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
124017:       testcase( pIdx->aiColumn[j]==XN_EXPR );
124018:       VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
124019:     }
124020:   }    
124021: 
124022:   /* Evaluate the equality constraints
124023:   */
124024:   assert( zAff==0 || (int)strlen(zAff)>=nEq );
124025:   for(j=nSkip; j<nEq; j++){
124026:     int r1;
124027:     pTerm = pLoop->aLTerm[j];
124028:     assert( pTerm!=0 );
124029:     /* The following testcase is true for indices with redundant columns. 
124030:     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
124031:     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
124032:     testcase( pTerm->wtFlags & TERM_VIRTUAL );
124033:     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
124034:     if( r1!=regBase+j ){
124035:       if( nReg==1 ){
124036:         sqlite3ReleaseTempReg(pParse, regBase);
124037:         regBase = r1;
124038:       }else{
124039:         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
124040:       }
124041:     }
124042:     if( (pTerm->eOperator & WO_IN)!=0 ){
124043:       if( pTerm->pExpr->flags & EP_xIsSelect ){
124044:         /* No affinity ever needs to be (or should be) applied to a value
124045:         ** from the RHS of an "? IN (SELECT ...)" expression. The 
124046:         ** sqlite3FindInIndex() routine has already ensured that the 
124047:         ** affinity of the comparison has been applied to the value.  */
124048:         if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
124049:       }
124050:     }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
124051:       Expr *pRight = pTerm->pExpr->pRight;
124052:       if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
124053:         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
124054:         VdbeCoverage(v);
124055:       }
124056:       if( zAff ){
124057:         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
124058:           zAff[j] = SQLITE_AFF_BLOB;
124059:         }
124060:         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
124061:           zAff[j] = SQLITE_AFF_BLOB;
124062:         }
124063:       }
124064:     }
124065:   }
124066:   *pzAff = zAff;
124067:   return regBase;
124068: }
124069: 
124070: #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124071: /*
124072: ** If the most recently coded instruction is a constant range constraint
124073: ** (a string literal) that originated from the LIKE optimization, then 
124074: ** set P3 and P5 on the OP_String opcode so that the string will be cast
124075: ** to a BLOB at appropriate times.
124076: **
124077: ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
124078: ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
124079: ** scan loop run twice, once for strings and a second time for BLOBs.
124080: ** The OP_String opcodes on the second pass convert the upper and lower
124081: ** bound string constants to blobs.  This routine makes the necessary changes
124082: ** to the OP_String opcodes for that to happen.
124083: **
124084: ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
124085: ** only the one pass through the string space is required, so this routine
124086: ** becomes a no-op.
124087: */
124088: static void whereLikeOptimizationStringFixup(
124089:   Vdbe *v,                /* prepared statement under construction */
124090:   WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
124091:   WhereTerm *pTerm        /* The upper or lower bound just coded */
124092: ){
124093:   if( pTerm->wtFlags & TERM_LIKEOPT ){
124094:     VdbeOp *pOp;
124095:     assert( pLevel->iLikeRepCntr>0 );
124096:     pOp = sqlite3VdbeGetOp(v, -1);
124097:     assert( pOp!=0 );
124098:     assert( pOp->opcode==OP_String8 
124099:             || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
124100:     pOp->p3 = (int)(pLevel->iLikeRepCntr>>1);  /* Register holding counter */
124101:     pOp->p5 = (u8)(pLevel->iLikeRepCntr&1);    /* ASC or DESC */
124102:   }
124103: }
124104: #else
124105: # define whereLikeOptimizationStringFixup(A,B,C)
124106: #endif
124107: 
124108: #ifdef SQLITE_ENABLE_CURSOR_HINTS
124109: /*
124110: ** Information is passed from codeCursorHint() down to individual nodes of
124111: ** the expression tree (by sqlite3WalkExpr()) using an instance of this
124112: ** structure.
124113: */
124114: struct CCurHint {
124115:   int iTabCur;    /* Cursor for the main table */
124116:   int iIdxCur;    /* Cursor for the index, if pIdx!=0.  Unused otherwise */
124117:   Index *pIdx;    /* The index used to access the table */
124118: };
124119: 
124120: /*
124121: ** This function is called for every node of an expression that is a candidate
124122: ** for a cursor hint on an index cursor.  For TK_COLUMN nodes that reference
124123: ** the table CCurHint.iTabCur, verify that the same column can be
124124: ** accessed through the index.  If it cannot, then set pWalker->eCode to 1.
124125: */
124126: static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
124127:   struct CCurHint *pHint = pWalker->u.pCCurHint;
124128:   assert( pHint->pIdx!=0 );
124129:   if( pExpr->op==TK_COLUMN
124130:    && pExpr->iTable==pHint->iTabCur
124131:    && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
124132:   ){
124133:     pWalker->eCode = 1;
124134:   }
124135:   return WRC_Continue;
124136: }
124137: 
124138: /*
124139: ** Test whether or not expression pExpr, which was part of a WHERE clause,
124140: ** should be included in the cursor-hint for a table that is on the rhs
124141: ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 
124142: ** expression is not suitable.
124143: **
124144: ** An expression is unsuitable if it might evaluate to non NULL even if
124145: ** a TK_COLUMN node that does affect the value of the expression is set
124146: ** to NULL. For example:
124147: **
124148: **   col IS NULL
124149: **   col IS NOT NULL
124150: **   coalesce(col, 1)
124151: **   CASE WHEN col THEN 0 ELSE 1 END
124152: */
124153: static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
124154:   if( pExpr->op==TK_IS 
124155:    || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 
124156:    || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 
124157:   ){
124158:     pWalker->eCode = 1;
124159:   }else if( pExpr->op==TK_FUNCTION ){
124160:     int d1;
124161:     char d2[3];
124162:     if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
124163:       pWalker->eCode = 1;
124164:     }
124165:   }
124166: 
124167:   return WRC_Continue;
124168: }
124169: 
124170: 
124171: /*
124172: ** This function is called on every node of an expression tree used as an
124173: ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
124174: ** that accesses any table other than the one identified by
124175: ** CCurHint.iTabCur, then do the following:
124176: **
124177: **   1) allocate a register and code an OP_Column instruction to read 
124178: **      the specified column into the new register, and
124179: **
124180: **   2) transform the expression node to a TK_REGISTER node that reads 
124181: **      from the newly populated register.
124182: **
124183: ** Also, if the node is a TK_COLUMN that does access the table idenified
124184: ** by pCCurHint.iTabCur, and an index is being used (which we will
124185: ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
124186: ** an access of the index rather than the original table.
124187: */
124188: static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
124189:   int rc = WRC_Continue;
124190:   struct CCurHint *pHint = pWalker->u.pCCurHint;
124191:   if( pExpr->op==TK_COLUMN ){
124192:     if( pExpr->iTable!=pHint->iTabCur ){
124193:       Vdbe *v = pWalker->pParse->pVdbe;
124194:       int reg = ++pWalker->pParse->nMem;   /* Register for column value */
124195:       sqlite3ExprCodeGetColumnOfTable(
124196:           v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
124197:       );
124198:       pExpr->op = TK_REGISTER;
124199:       pExpr->iTable = reg;
124200:     }else if( pHint->pIdx!=0 ){
124201:       pExpr->iTable = pHint->iIdxCur;
124202:       pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
124203:       assert( pExpr->iColumn>=0 );
124204:     }
124205:   }else if( pExpr->op==TK_AGG_FUNCTION ){
124206:     /* An aggregate function in the WHERE clause of a query means this must
124207:     ** be a correlated sub-query, and expression pExpr is an aggregate from
124208:     ** the parent context. Do not walk the function arguments in this case.
124209:     **
124210:     ** todo: It should be possible to replace this node with a TK_REGISTER
124211:     ** expression, as the result of the expression must be stored in a 
124212:     ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
124213:     rc = WRC_Prune;
124214:   }
124215:   return rc;
124216: }
124217: 
124218: /*
124219: ** Insert an OP_CursorHint instruction if it is appropriate to do so.
124220: */
124221: static void codeCursorHint(
124222:   struct SrcList_item *pTabItem,  /* FROM clause item */
124223:   WhereInfo *pWInfo,    /* The where clause */
124224:   WhereLevel *pLevel,   /* Which loop to provide hints for */
124225:   WhereTerm *pEndRange  /* Hint this end-of-scan boundary term if not NULL */
124226: ){
124227:   Parse *pParse = pWInfo->pParse;
124228:   sqlite3 *db = pParse->db;
124229:   Vdbe *v = pParse->pVdbe;
124230:   Expr *pExpr = 0;
124231:   WhereLoop *pLoop = pLevel->pWLoop;
124232:   int iCur;
124233:   WhereClause *pWC;
124234:   WhereTerm *pTerm;
124235:   int i, j;
124236:   struct CCurHint sHint;
124237:   Walker sWalker;
124238: 
124239:   if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
124240:   iCur = pLevel->iTabCur;
124241:   assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
124242:   sHint.iTabCur = iCur;
124243:   sHint.iIdxCur = pLevel->iIdxCur;
124244:   sHint.pIdx = pLoop->u.btree.pIndex;
124245:   memset(&sWalker, 0, sizeof(sWalker));
124246:   sWalker.pParse = pParse;
124247:   sWalker.u.pCCurHint = &sHint;
124248:   pWC = &pWInfo->sWC;
124249:   for(i=0; i<pWC->nTerm; i++){
124250:     pTerm = &pWC->a[i];
124251:     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
124252:     if( pTerm->prereqAll & pLevel->notReady ) continue;
124253: 
124254:     /* Any terms specified as part of the ON(...) clause for any LEFT 
124255:     ** JOIN for which the current table is not the rhs are omitted
124256:     ** from the cursor-hint. 
124257:     **
124258:     ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 
124259:     ** that were specified as part of the WHERE clause must be excluded.
124260:     ** This is to address the following:
124261:     **
124262:     **   SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
124263:     **
124264:     ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
124265:     ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 
124266:     ** pushed down to the cursor, this row is filtered out, causing
124267:     ** SQLite to synthesize a row of NULL values. Which does match the
124268:     ** WHERE clause, and so the query returns a row. Which is incorrect.
124269:     **
124270:     ** For the same reason, WHERE terms such as:
124271:     **
124272:     **   WHERE 1 = (t2.c IS NULL)
124273:     **
124274:     ** are also excluded. See codeCursorHintIsOrFunction() for details.
124275:     */
124276:     if( pTabItem->fg.jointype & JT_LEFT ){
124277:       Expr *pExpr = pTerm->pExpr;
124278:       if( !ExprHasProperty(pExpr, EP_FromJoin) 
124279:        || pExpr->iRightJoinTable!=pTabItem->iCursor
124280:       ){
124281:         sWalker.eCode = 0;
124282:         sWalker.xExprCallback = codeCursorHintIsOrFunction;
124283:         sqlite3WalkExpr(&sWalker, pTerm->pExpr);
124284:         if( sWalker.eCode ) continue;
124285:       }
124286:     }else{
124287:       if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
124288:     }
124289: 
124290:     /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
124291:     ** the cursor.  These terms are not needed as hints for a pure range
124292:     ** scan (that has no == terms) so omit them. */
124293:     if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
124294:       for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
124295:       if( j<pLoop->nLTerm ) continue;
124296:     }
124297: 
124298:     /* No subqueries or non-deterministic functions allowed */
124299:     if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
124300: 
124301:     /* For an index scan, make sure referenced columns are actually in
124302:     ** the index. */
124303:     if( sHint.pIdx!=0 ){
124304:       sWalker.eCode = 0;
124305:       sWalker.xExprCallback = codeCursorHintCheckExpr;
124306:       sqlite3WalkExpr(&sWalker, pTerm->pExpr);
124307:       if( sWalker.eCode ) continue;
124308:     }
124309: 
124310:     /* If we survive all prior tests, that means this term is worth hinting */
124311:     pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
124312:   }
124313:   if( pExpr!=0 ){
124314:     sWalker.xExprCallback = codeCursorHintFixExpr;
124315:     sqlite3WalkExpr(&sWalker, pExpr);
124316:     sqlite3VdbeAddOp4(v, OP_CursorHint, 
124317:                       (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
124318:                       (const char*)pExpr, P4_EXPR);
124319:   }
124320: }
124321: #else
124322: # define codeCursorHint(A,B,C,D)  /* No-op */
124323: #endif /* SQLITE_ENABLE_CURSOR_HINTS */
124324: 
124325: /*
124326: ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
124327: ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
124328: ** function generates code to do a deferred seek of cursor iCur to the 
124329: ** rowid stored in register iRowid.
124330: **
124331: ** Normally, this is just:
124332: **
124333: **   OP_Seek $iCur $iRowid
124334: **
124335: ** However, if the scan currently being coded is a branch of an OR-loop and
124336: ** the statement currently being coded is a SELECT, then P3 of the OP_Seek
124337: ** is set to iIdxCur and P4 is set to point to an array of integers
124338: ** containing one entry for each column of the table cursor iCur is open 
124339: ** on. For each table column, if the column is the i'th column of the 
124340: ** index, then the corresponding array entry is set to (i+1). If the column
124341: ** does not appear in the index at all, the array entry is set to 0.
124342: */
124343: static void codeDeferredSeek(
124344:   WhereInfo *pWInfo,              /* Where clause context */
124345:   Index *pIdx,                    /* Index scan is using */
124346:   int iCur,                       /* Cursor for IPK b-tree */
124347:   int iIdxCur                     /* Index cursor */
124348: ){
124349:   Parse *pParse = pWInfo->pParse; /* Parse context */
124350:   Vdbe *v = pParse->pVdbe;        /* Vdbe to generate code within */
124351: 
124352:   assert( iIdxCur>0 );
124353:   assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
124354:   
124355:   sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
124356:   if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
124357:    && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
124358:   ){
124359:     int i;
124360:     Table *pTab = pIdx->pTable;
124361:     int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
124362:     if( ai ){
124363:       ai[0] = pTab->nCol;
124364:       for(i=0; i<pIdx->nColumn-1; i++){
124365:         assert( pIdx->aiColumn[i]<pTab->nCol );
124366:         if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
124367:       }
124368:       sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
124369:     }
124370:   }
124371: }
124372: 
124373: /*
124374: ** Generate code for the start of the iLevel-th loop in the WHERE clause
124375: ** implementation described by pWInfo.
124376: */
124377: SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
124378:   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
124379:   int iLevel,          /* Which level of pWInfo->a[] should be coded */
124380:   Bitmask notReady     /* Which tables are currently available */
124381: ){
124382:   int j, k;            /* Loop counters */
124383:   int iCur;            /* The VDBE cursor for the table */
124384:   int addrNxt;         /* Where to jump to continue with the next IN case */
124385:   int omitTable;       /* True if we use the index only */
124386:   int bRev;            /* True if we need to scan in reverse order */
124387:   WhereLevel *pLevel;  /* The where level to be coded */
124388:   WhereLoop *pLoop;    /* The WhereLoop object being coded */
124389:   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
124390:   WhereTerm *pTerm;               /* A WHERE clause term */
124391:   Parse *pParse;                  /* Parsing context */
124392:   sqlite3 *db;                    /* Database connection */
124393:   Vdbe *v;                        /* The prepared stmt under constructions */
124394:   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
124395:   int addrBrk;                    /* Jump here to break out of the loop */
124396:   int addrCont;                   /* Jump here to continue with next cycle */
124397:   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
124398:   int iReleaseReg = 0;      /* Temp register to free before returning */
124399: 
124400:   pParse = pWInfo->pParse;
124401:   v = pParse->pVdbe;
124402:   pWC = &pWInfo->sWC;
124403:   db = pParse->db;
124404:   pLevel = &pWInfo->a[iLevel];
124405:   pLoop = pLevel->pWLoop;
124406:   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
124407:   iCur = pTabItem->iCursor;
124408:   pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
124409:   bRev = (pWInfo->revMask>>iLevel)&1;
124410:   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 
124411:            && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
124412:   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
124413: 
124414:   /* Create labels for the "break" and "continue" instructions
124415:   ** for the current loop.  Jump to addrBrk to break out of a loop.
124416:   ** Jump to cont to go immediately to the next iteration of the
124417:   ** loop.
124418:   **
124419:   ** When there is an IN operator, we also have a "addrNxt" label that
124420:   ** means to continue with the next IN value combination.  When
124421:   ** there are no IN operators in the constraints, the "addrNxt" label
124422:   ** is the same as "addrBrk".
124423:   */
124424:   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
124425:   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
124426: 
124427:   /* If this is the right table of a LEFT OUTER JOIN, allocate and
124428:   ** initialize a memory cell that records if this table matches any
124429:   ** row of the left table of the join.
124430:   */
124431:   if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
124432:     pLevel->iLeftJoin = ++pParse->nMem;
124433:     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
124434:     VdbeComment((v, "init LEFT JOIN no-match flag"));
124435:   }
124436: 
124437:   /* Special case of a FROM clause subquery implemented as a co-routine */
124438:   if( pTabItem->fg.viaCoroutine ){
124439:     int regYield = pTabItem->regReturn;
124440:     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
124441:     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
124442:     VdbeCoverage(v);
124443:     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
124444:     pLevel->op = OP_Goto;
124445:   }else
124446: 
124447: #ifndef SQLITE_OMIT_VIRTUALTABLE
124448:   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
124449:     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
124450:     **          to access the data.
124451:     */
124452:     int iReg;   /* P3 Value for OP_VFilter */
124453:     int addrNotFound;
124454:     int nConstraint = pLoop->nLTerm;
124455:     int iIn;    /* Counter for IN constraints */
124456: 
124457:     sqlite3ExprCachePush(pParse);
124458:     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
124459:     addrNotFound = pLevel->addrBrk;
124460:     for(j=0; j<nConstraint; j++){
124461:       int iTarget = iReg+j+2;
124462:       pTerm = pLoop->aLTerm[j];
124463:       if( NEVER(pTerm==0) ) continue;
124464:       if( pTerm->eOperator & WO_IN ){
124465:         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
124466:         addrNotFound = pLevel->addrNxt;
124467:       }else{
124468:         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
124469:       }
124470:     }
124471:     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
124472:     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
124473:     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
124474:                       pLoop->u.vtab.idxStr,
124475:                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
124476:     VdbeCoverage(v);
124477:     pLoop->u.vtab.needFree = 0;
124478:     pLevel->p1 = iCur;
124479:     pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
124480:     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
124481:     iIn = pLevel->u.in.nIn;
124482:     for(j=nConstraint-1; j>=0; j--){
124483:       pTerm = pLoop->aLTerm[j];
124484:       if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
124485:         disableTerm(pLevel, pTerm);
124486:       }else if( (pTerm->eOperator & WO_IN)!=0 ){
124487:         Expr *pCompare;  /* The comparison operator */
124488:         Expr *pRight;    /* RHS of the comparison */
124489:         VdbeOp *pOp;     /* Opcode to access the value of the IN constraint */
124490: 
124491:         /* Reload the constraint value into reg[iReg+j+2].  The same value
124492:         ** was loaded into the same register prior to the OP_VFilter, but
124493:         ** the xFilter implementation might have changed the datatype or
124494:         ** encoding of the value in the register, so it *must* be reloaded. */
124495:         assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
124496:         if( !db->mallocFailed ){
124497:           assert( iIn>0 );
124498:           pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
124499:           assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
124500:           assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
124501:           assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
124502:           testcase( pOp->opcode==OP_Rowid );
124503:           sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
124504:         }
124505: 
124506:         /* Generate code that will continue to the next row if 
124507:         ** the IN constraint is not satisfied */
124508:         pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
124509:         assert( pCompare!=0 || db->mallocFailed );
124510:         if( pCompare ){
124511:           pCompare->pLeft = pTerm->pExpr->pLeft;
124512:           pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
124513:           if( pRight ){
124514:             pRight->iTable = iReg+j+2;
124515:             sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
124516:           }
124517:           pCompare->pLeft = 0;
124518:           sqlite3ExprDelete(db, pCompare);
124519:         }
124520:       }
124521:     }
124522:     /* These registers need to be preserved in case there is an IN operator
124523:     ** loop.  So we could deallocate the registers here (and potentially
124524:     ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0.  But it seems
124525:     ** simpler and safer to simply not reuse the registers.
124526:     **
124527:     **    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
124528:     */
124529:     sqlite3ExprCachePop(pParse);
124530:   }else
124531: #endif /* SQLITE_OMIT_VIRTUALTABLE */
124532: 
124533:   if( (pLoop->wsFlags & WHERE_IPK)!=0
124534:    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
124535:   ){
124536:     /* Case 2:  We can directly reference a single row using an
124537:     **          equality comparison against the ROWID field.  Or
124538:     **          we reference multiple rows using a "rowid IN (...)"
124539:     **          construct.
124540:     */
124541:     assert( pLoop->u.btree.nEq==1 );
124542:     pTerm = pLoop->aLTerm[0];
124543:     assert( pTerm!=0 );
124544:     assert( pTerm->pExpr!=0 );
124545:     assert( omitTable==0 );
124546:     testcase( pTerm->wtFlags & TERM_VIRTUAL );
124547:     iReleaseReg = ++pParse->nMem;
124548:     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
124549:     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
124550:     addrNxt = pLevel->addrNxt;
124551:     sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
124552:     VdbeCoverage(v);
124553:     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
124554:     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124555:     VdbeComment((v, "pk"));
124556:     pLevel->op = OP_Noop;
124557:   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
124558:          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
124559:   ){
124560:     /* Case 3:  We have an inequality comparison against the ROWID field.
124561:     */
124562:     int testOp = OP_Noop;
124563:     int start;
124564:     int memEndValue = 0;
124565:     WhereTerm *pStart, *pEnd;
124566: 
124567:     assert( omitTable==0 );
124568:     j = 0;
124569:     pStart = pEnd = 0;
124570:     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
124571:     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
124572:     assert( pStart!=0 || pEnd!=0 );
124573:     if( bRev ){
124574:       pTerm = pStart;
124575:       pStart = pEnd;
124576:       pEnd = pTerm;
124577:     }
124578:     codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
124579:     if( pStart ){
124580:       Expr *pX;             /* The expression that defines the start bound */
124581:       int r1, rTemp;        /* Registers for holding the start boundary */
124582: 
124583:       /* The following constant maps TK_xx codes into corresponding 
124584:       ** seek opcodes.  It depends on a particular ordering of TK_xx
124585:       */
124586:       const u8 aMoveOp[] = {
124587:            /* TK_GT */  OP_SeekGT,
124588:            /* TK_LE */  OP_SeekLE,
124589:            /* TK_LT */  OP_SeekLT,
124590:            /* TK_GE */  OP_SeekGE
124591:       };
124592:       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
124593:       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
124594:       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
124595: 
124596:       assert( (pStart->wtFlags & TERM_VNULL)==0 );
124597:       testcase( pStart->wtFlags & TERM_VIRTUAL );
124598:       pX = pStart->pExpr;
124599:       assert( pX!=0 );
124600:       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
124601:       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
124602:       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
124603:       VdbeComment((v, "pk"));
124604:       VdbeCoverageIf(v, pX->op==TK_GT);
124605:       VdbeCoverageIf(v, pX->op==TK_LE);
124606:       VdbeCoverageIf(v, pX->op==TK_LT);
124607:       VdbeCoverageIf(v, pX->op==TK_GE);
124608:       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
124609:       sqlite3ReleaseTempReg(pParse, rTemp);
124610:       disableTerm(pLevel, pStart);
124611:     }else{
124612:       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
124613:       VdbeCoverageIf(v, bRev==0);
124614:       VdbeCoverageIf(v, bRev!=0);
124615:     }
124616:     if( pEnd ){
124617:       Expr *pX;
124618:       pX = pEnd->pExpr;
124619:       assert( pX!=0 );
124620:       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
124621:       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
124622:       testcase( pEnd->wtFlags & TERM_VIRTUAL );
124623:       memEndValue = ++pParse->nMem;
124624:       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
124625:       if( pX->op==TK_LT || pX->op==TK_GT ){
124626:         testOp = bRev ? OP_Le : OP_Ge;
124627:       }else{
124628:         testOp = bRev ? OP_Lt : OP_Gt;
124629:       }
124630:       disableTerm(pLevel, pEnd);
124631:     }
124632:     start = sqlite3VdbeCurrentAddr(v);
124633:     pLevel->op = bRev ? OP_Prev : OP_Next;
124634:     pLevel->p1 = iCur;
124635:     pLevel->p2 = start;
124636:     assert( pLevel->p5==0 );
124637:     if( testOp!=OP_Noop ){
124638:       iRowidReg = ++pParse->nMem;
124639:       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
124640:       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124641:       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
124642:       VdbeCoverageIf(v, testOp==OP_Le);
124643:       VdbeCoverageIf(v, testOp==OP_Lt);
124644:       VdbeCoverageIf(v, testOp==OP_Ge);
124645:       VdbeCoverageIf(v, testOp==OP_Gt);
124646:       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
124647:     }
124648:   }else if( pLoop->wsFlags & WHERE_INDEXED ){
124649:     /* Case 4: A scan using an index.
124650:     **
124651:     **         The WHERE clause may contain zero or more equality 
124652:     **         terms ("==" or "IN" operators) that refer to the N
124653:     **         left-most columns of the index. It may also contain
124654:     **         inequality constraints (>, <, >= or <=) on the indexed
124655:     **         column that immediately follows the N equalities. Only 
124656:     **         the right-most column can be an inequality - the rest must
124657:     **         use the "==" and "IN" operators. For example, if the 
124658:     **         index is on (x,y,z), then the following clauses are all 
124659:     **         optimized:
124660:     **
124661:     **            x=5
124662:     **            x=5 AND y=10
124663:     **            x=5 AND y<10
124664:     **            x=5 AND y>5 AND y<10
124665:     **            x=5 AND y=5 AND z<=10
124666:     **
124667:     **         The z<10 term of the following cannot be used, only
124668:     **         the x=5 term:
124669:     **
124670:     **            x=5 AND z<10
124671:     **
124672:     **         N may be zero if there are inequality constraints.
124673:     **         If there are no inequality constraints, then N is at
124674:     **         least one.
124675:     **
124676:     **         This case is also used when there are no WHERE clause
124677:     **         constraints but an index is selected anyway, in order
124678:     **         to force the output order to conform to an ORDER BY.
124679:     */  
124680:     static const u8 aStartOp[] = {
124681:       0,
124682:       0,
124683:       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
124684:       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
124685:       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
124686:       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
124687:       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
124688:       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
124689:     };
124690:     static const u8 aEndOp[] = {
124691:       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
124692:       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
124693:       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
124694:       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
124695:     };
124696:     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
124697:     int regBase;                 /* Base register holding constraint values */
124698:     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
124699:     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
124700:     int startEq;                 /* True if range start uses ==, >= or <= */
124701:     int endEq;                   /* True if range end uses ==, >= or <= */
124702:     int start_constraints;       /* Start of range is constrained */
124703:     int nConstraint;             /* Number of constraint terms */
124704:     Index *pIdx;                 /* The index we will be using */
124705:     int iIdxCur;                 /* The VDBE cursor for the index */
124706:     int nExtraReg = 0;           /* Number of extra registers needed */
124707:     int op;                      /* Instruction opcode */
124708:     char *zStartAff;             /* Affinity for start of range constraint */
124709:     char cEndAff = 0;            /* Affinity for end of range constraint */
124710:     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
124711:     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
124712: 
124713:     pIdx = pLoop->u.btree.pIndex;
124714:     iIdxCur = pLevel->iIdxCur;
124715:     assert( nEq>=pLoop->nSkip );
124716: 
124717:     /* If this loop satisfies a sort order (pOrderBy) request that 
124718:     ** was passed to this function to implement a "SELECT min(x) ..." 
124719:     ** query, then the caller will only allow the loop to run for
124720:     ** a single iteration. This means that the first row returned
124721:     ** should not have a NULL value stored in 'x'. If column 'x' is
124722:     ** the first one after the nEq equality constraints in the index,
124723:     ** this requires some special handling.
124724:     */
124725:     assert( pWInfo->pOrderBy==0
124726:          || pWInfo->pOrderBy->nExpr==1
124727:          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
124728:     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
124729:      && pWInfo->nOBSat>0
124730:      && (pIdx->nKeyCol>nEq)
124731:     ){
124732:       assert( pLoop->nSkip==0 );
124733:       bSeekPastNull = 1;
124734:       nExtraReg = 1;
124735:     }
124736: 
124737:     /* Find any inequality constraint terms for the start and end 
124738:     ** of the range. 
124739:     */
124740:     j = nEq;
124741:     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
124742:       pRangeStart = pLoop->aLTerm[j++];
124743:       nExtraReg = 1;
124744:       /* Like optimization range constraints always occur in pairs */
124745:       assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 
124746:               (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
124747:     }
124748:     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
124749:       pRangeEnd = pLoop->aLTerm[j++];
124750:       nExtraReg = 1;
124751: #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124752:       if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
124753:         assert( pRangeStart!=0 );                     /* LIKE opt constraints */
124754:         assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
124755:         pLevel->iLikeRepCntr = (u32)++pParse->nMem;
124756:         sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
124757:         VdbeComment((v, "LIKE loop counter"));
124758:         pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
124759:         /* iLikeRepCntr actually stores 2x the counter register number.  The
124760:         ** bottom bit indicates whether the search order is ASC or DESC. */
124761:         testcase( bRev );
124762:         testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
124763:         assert( (bRev & ~1)==0 );
124764:         pLevel->iLikeRepCntr <<=1;
124765:         pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
124766:       }
124767: #endif
124768:       if( pRangeStart==0
124769:        && (j = pIdx->aiColumn[nEq])>=0 
124770:        && pIdx->pTable->aCol[j].notNull==0
124771:       ){
124772:         bSeekPastNull = 1;
124773:       }
124774:     }
124775:     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
124776: 
124777:     /* If we are doing a reverse order scan on an ascending index, or
124778:     ** a forward order scan on a descending index, interchange the 
124779:     ** start and end terms (pRangeStart and pRangeEnd).
124780:     */
124781:     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
124782:      || (bRev && pIdx->nKeyCol==nEq)
124783:     ){
124784:       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
124785:       SWAP(u8, bSeekPastNull, bStopAtNull);
124786:     }
124787: 
124788:     /* Generate code to evaluate all constraint terms using == or IN
124789:     ** and store the values of those terms in an array of registers
124790:     ** starting at regBase.
124791:     */
124792:     codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
124793:     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
124794:     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
124795:     if( zStartAff ) cEndAff = zStartAff[nEq];
124796:     addrNxt = pLevel->addrNxt;
124797: 
124798:     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
124799:     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
124800:     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
124801:     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
124802:     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
124803:     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
124804:     start_constraints = pRangeStart || nEq>0;
124805: 
124806:     /* Seek the index cursor to the start of the range. */
124807:     nConstraint = nEq;
124808:     if( pRangeStart ){
124809:       Expr *pRight = pRangeStart->pExpr->pRight;
124810:       sqlite3ExprCode(pParse, pRight, regBase+nEq);
124811:       whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
124812:       if( (pRangeStart->wtFlags & TERM_VNULL)==0
124813:        && sqlite3ExprCanBeNull(pRight)
124814:       ){
124815:         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124816:         VdbeCoverage(v);
124817:       }
124818:       if( zStartAff ){
124819:         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
124820:           /* Since the comparison is to be performed with no conversions
124821:           ** applied to the operands, set the affinity to apply to pRight to 
124822:           ** SQLITE_AFF_BLOB.  */
124823:           zStartAff[nEq] = SQLITE_AFF_BLOB;
124824:         }
124825:         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
124826:           zStartAff[nEq] = SQLITE_AFF_BLOB;
124827:         }
124828:       }  
124829:       nConstraint++;
124830:       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
124831:       bSeekPastNull = 0;
124832:     }else if( bSeekPastNull ){
124833:       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124834:       nConstraint++;
124835:       startEq = 0;
124836:       start_constraints = 1;
124837:     }
124838:     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
124839:     if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
124840:       /* The skip-scan logic inside the call to codeAllEqualityConstraints()
124841:       ** above has already left the cursor sitting on the correct row,
124842:       ** so no further seeking is needed */
124843:     }else{
124844:       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
124845:       assert( op!=0 );
124846:       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124847:       VdbeCoverage(v);
124848:       VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
124849:       VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
124850:       VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
124851:       VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
124852:       VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
124853:       VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
124854:     }
124855: 
124856:     /* Load the value for the inequality constraint at the end of the
124857:     ** range (if any).
124858:     */
124859:     nConstraint = nEq;
124860:     if( pRangeEnd ){
124861:       Expr *pRight = pRangeEnd->pExpr->pRight;
124862:       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
124863:       sqlite3ExprCode(pParse, pRight, regBase+nEq);
124864:       whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
124865:       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
124866:        && sqlite3ExprCanBeNull(pRight)
124867:       ){
124868:         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124869:         VdbeCoverage(v);
124870:       }
124871:       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
124872:        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
124873:       ){
124874:         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
124875:       }
124876:       nConstraint++;
124877:       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
124878:     }else if( bStopAtNull ){
124879:       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124880:       endEq = 0;
124881:       nConstraint++;
124882:     }
124883:     sqlite3DbFree(db, zStartAff);
124884: 
124885:     /* Top of the loop body */
124886:     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
124887: 
124888:     /* Check if the index cursor is past the end of the range. */
124889:     if( nConstraint ){
124890:       op = aEndOp[bRev*2 + endEq];
124891:       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124892:       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
124893:       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
124894:       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
124895:       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
124896:     }
124897: 
124898:     /* Seek the table cursor, if required */
124899:     disableTerm(pLevel, pRangeStart);
124900:     disableTerm(pLevel, pRangeEnd);
124901:     if( omitTable ){
124902:       /* pIdx is a covering index.  No need to access the main table. */
124903:     }else if( HasRowid(pIdx->pTable) ){
124904:       if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
124905:         iRowidReg = ++pParse->nMem;
124906:         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
124907:         sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124908:         sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
124909:         VdbeCoverage(v);
124910:       }else{
124911:         codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
124912:       }
124913:     }else if( iCur!=iIdxCur ){
124914:       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
124915:       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
124916:       for(j=0; j<pPk->nKeyCol; j++){
124917:         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
124918:         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
124919:       }
124920:       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
124921:                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
124922:     }
124923: 
124924:     /* Record the instruction used to terminate the loop. Disable 
124925:     ** WHERE clause terms made redundant by the index range scan.
124926:     */
124927:     if( pLoop->wsFlags & WHERE_ONEROW ){
124928:       pLevel->op = OP_Noop;
124929:     }else if( bRev ){
124930:       pLevel->op = OP_Prev;
124931:     }else{
124932:       pLevel->op = OP_Next;
124933:     }
124934:     pLevel->p1 = iIdxCur;
124935:     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
124936:     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
124937:       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
124938:     }else{
124939:       assert( pLevel->p5==0 );
124940:     }
124941:   }else
124942: 
124943: #ifndef SQLITE_OMIT_OR_OPTIMIZATION
124944:   if( pLoop->wsFlags & WHERE_MULTI_OR ){
124945:     /* Case 5:  Two or more separately indexed terms connected by OR
124946:     **
124947:     ** Example:
124948:     **
124949:     **   CREATE TABLE t1(a,b,c,d);
124950:     **   CREATE INDEX i1 ON t1(a);
124951:     **   CREATE INDEX i2 ON t1(b);
124952:     **   CREATE INDEX i3 ON t1(c);
124953:     **
124954:     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
124955:     **
124956:     ** In the example, there are three indexed terms connected by OR.
124957:     ** The top of the loop looks like this:
124958:     **
124959:     **          Null       1                # Zero the rowset in reg 1
124960:     **
124961:     ** Then, for each indexed term, the following. The arguments to
124962:     ** RowSetTest are such that the rowid of the current row is inserted
124963:     ** into the RowSet. If it is already present, control skips the
124964:     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
124965:     **
124966:     **        sqlite3WhereBegin(<term>)
124967:     **          RowSetTest                  # Insert rowid into rowset
124968:     **          Gosub      2 A
124969:     **        sqlite3WhereEnd()
124970:     **
124971:     ** Following the above, code to terminate the loop. Label A, the target
124972:     ** of the Gosub above, jumps to the instruction right after the Goto.
124973:     **
124974:     **          Null       1                # Zero the rowset in reg 1
124975:     **          Goto       B                # The loop is finished.
124976:     **
124977:     **       A: <loop body>                 # Return data, whatever.
124978:     **
124979:     **          Return     2                # Jump back to the Gosub
124980:     **
124981:     **       B: <after the loop>
124982:     **
124983:     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
124984:     ** use an ephemeral index instead of a RowSet to record the primary
124985:     ** keys of the rows we have already seen.
124986:     **
124987:     */
124988:     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
124989:     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
124990:     Index *pCov = 0;             /* Potential covering index (or NULL) */
124991:     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
124992: 
124993:     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
124994:     int regRowset = 0;                        /* Register for RowSet object */
124995:     int regRowid = 0;                         /* Register holding rowid */
124996:     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
124997:     int iRetInit;                             /* Address of regReturn init */
124998:     int untestedTerms = 0;             /* Some terms not completely tested */
124999:     int ii;                            /* Loop counter */
125000:     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
125001:     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
125002:     Table *pTab = pTabItem->pTab;
125003:    
125004:     pTerm = pLoop->aLTerm[0];
125005:     assert( pTerm!=0 );
125006:     assert( pTerm->eOperator & WO_OR );
125007:     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
125008:     pOrWc = &pTerm->u.pOrInfo->wc;
125009:     pLevel->op = OP_Return;
125010:     pLevel->p1 = regReturn;
125011: 
125012:     /* Set up a new SrcList in pOrTab containing the table being scanned
125013:     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
125014:     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
125015:     */
125016:     if( pWInfo->nLevel>1 ){
125017:       int nNotReady;                 /* The number of notReady tables */
125018:       struct SrcList_item *origSrc;     /* Original list of tables */
125019:       nNotReady = pWInfo->nLevel - iLevel - 1;
125020:       pOrTab = sqlite3StackAllocRaw(db,
125021:                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
125022:       if( pOrTab==0 ) return notReady;
125023:       pOrTab->nAlloc = (u8)(nNotReady + 1);
125024:       pOrTab->nSrc = pOrTab->nAlloc;
125025:       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
125026:       origSrc = pWInfo->pTabList->a;
125027:       for(k=1; k<=nNotReady; k++){
125028:         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
125029:       }
125030:     }else{
125031:       pOrTab = pWInfo->pTabList;
125032:     }
125033: 
125034:     /* Initialize the rowset register to contain NULL. An SQL NULL is 
125035:     ** equivalent to an empty rowset.  Or, create an ephemeral index
125036:     ** capable of holding primary keys in the case of a WITHOUT ROWID.
125037:     **
125038:     ** Also initialize regReturn to contain the address of the instruction 
125039:     ** immediately following the OP_Return at the bottom of the loop. This
125040:     ** is required in a few obscure LEFT JOIN cases where control jumps
125041:     ** over the top of the loop into the body of it. In this case the 
125042:     ** correct response for the end-of-loop code (the OP_Return) is to 
125043:     ** fall through to the next instruction, just as an OP_Next does if
125044:     ** called on an uninitialized cursor.
125045:     */
125046:     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
125047:       if( HasRowid(pTab) ){
125048:         regRowset = ++pParse->nMem;
125049:         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
125050:       }else{
125051:         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125052:         regRowset = pParse->nTab++;
125053:         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
125054:         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
125055:       }
125056:       regRowid = ++pParse->nMem;
125057:     }
125058:     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
125059: 
125060:     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
125061:     ** Then for every term xN, evaluate as the subexpression: xN AND z
125062:     ** That way, terms in y that are factored into the disjunction will
125063:     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
125064:     **
125065:     ** Actually, each subexpression is converted to "xN AND w" where w is
125066:     ** the "interesting" terms of z - terms that did not originate in the
125067:     ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
125068:     ** indices.
125069:     **
125070:     ** This optimization also only applies if the (x1 OR x2 OR ...) term
125071:     ** is not contained in the ON clause of a LEFT JOIN.
125072:     ** See ticket http://www.sqlite.org/src/info/f2369304e4
125073:     */
125074:     if( pWC->nTerm>1 ){
125075:       int iTerm;
125076:       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
125077:         Expr *pExpr = pWC->a[iTerm].pExpr;
125078:         if( &pWC->a[iTerm] == pTerm ) continue;
125079:         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
125080:         testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
125081:         testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
125082:         if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
125083:         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
125084:         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
125085:         pExpr = sqlite3ExprDup(db, pExpr, 0);
125086:         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
125087:       }
125088:       if( pAndExpr ){
125089:         pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
125090:       }
125091:     }
125092: 
125093:     /* Run a separate WHERE clause for each term of the OR clause.  After
125094:     ** eliminating duplicates from other WHERE clauses, the action for each
125095:     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
125096:     */
125097:     wctrlFlags =  WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
125098:     for(ii=0; ii<pOrWc->nTerm; ii++){
125099:       WhereTerm *pOrTerm = &pOrWc->a[ii];
125100:       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
125101:         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
125102:         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
125103:         int jmp1 = 0;                   /* Address of jump operation */
125104:         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
125105:           pAndExpr->pLeft = pOrExpr;
125106:           pOrExpr = pAndExpr;
125107:         }
125108:         /* Loop through table entries that match term pOrTerm. */
125109:         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
125110:         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
125111:                                       wctrlFlags, iCovCur);
125112:         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
125113:         if( pSubWInfo ){
125114:           WhereLoop *pSubLoop;
125115:           int addrExplain = sqlite3WhereExplainOneScan(
125116:               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
125117:           );
125118:           sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
125119: 
125120:           /* This is the sub-WHERE clause body.  First skip over
125121:           ** duplicate rows from prior sub-WHERE clauses, and record the
125122:           ** rowid (or PRIMARY KEY) for the current row so that the same
125123:           ** row will be skipped in subsequent sub-WHERE clauses.
125124:           */
125125:           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
125126:             int r;
125127:             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
125128:             if( HasRowid(pTab) ){
125129:               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
125130:               jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
125131:                                            r,iSet);
125132:               VdbeCoverage(v);
125133:             }else{
125134:               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
125135:               int nPk = pPk->nKeyCol;
125136:               int iPk;
125137: 
125138:               /* Read the PK into an array of temp registers. */
125139:               r = sqlite3GetTempRange(pParse, nPk);
125140:               for(iPk=0; iPk<nPk; iPk++){
125141:                 int iCol = pPk->aiColumn[iPk];
125142:                 sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
125143:               }
125144: 
125145:               /* Check if the temp table already contains this key. If so,
125146:               ** the row has already been included in the result set and
125147:               ** can be ignored (by jumping past the Gosub below). Otherwise,
125148:               ** insert the key into the temp table and proceed with processing
125149:               ** the row.
125150:               **
125151:               ** Use some of the same optimizations as OP_RowSetTest: If iSet
125152:               ** is zero, assume that the key cannot already be present in
125153:               ** the temp table. And if iSet is -1, assume that there is no 
125154:               ** need to insert the key into the temp table, as it will never 
125155:               ** be tested for.  */ 
125156:               if( iSet ){
125157:                 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
125158:                 VdbeCoverage(v);
125159:               }
125160:               if( iSet>=0 ){
125161:                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
125162:                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
125163:                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
125164:               }
125165: 
125166:               /* Release the array of temp registers */
125167:               sqlite3ReleaseTempRange(pParse, r, nPk);
125168:             }
125169:           }
125170: 
125171:           /* Invoke the main loop body as a subroutine */
125172:           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
125173: 
125174:           /* Jump here (skipping the main loop body subroutine) if the
125175:           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
125176:           if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
125177: 
125178:           /* The pSubWInfo->untestedTerms flag means that this OR term
125179:           ** contained one or more AND term from a notReady table.  The
125180:           ** terms from the notReady table could not be tested and will
125181:           ** need to be tested later.
125182:           */
125183:           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
125184: 
125185:           /* If all of the OR-connected terms are optimized using the same
125186:           ** index, and the index is opened using the same cursor number
125187:           ** by each call to sqlite3WhereBegin() made by this loop, it may
125188:           ** be possible to use that index as a covering index.
125189:           **
125190:           ** If the call to sqlite3WhereBegin() above resulted in a scan that
125191:           ** uses an index, and this is either the first OR-connected term
125192:           ** processed or the index is the same as that used by all previous
125193:           ** terms, set pCov to the candidate covering index. Otherwise, set 
125194:           ** pCov to NULL to indicate that no candidate covering index will 
125195:           ** be available.
125196:           */
125197:           pSubLoop = pSubWInfo->a[0].pWLoop;
125198:           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
125199:           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
125200:            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
125201:            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
125202:           ){
125203:             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
125204:             pCov = pSubLoop->u.btree.pIndex;
125205:           }else{
125206:             pCov = 0;
125207:           }
125208: 
125209:           /* Finish the loop through table entries that match term pOrTerm. */
125210:           sqlite3WhereEnd(pSubWInfo);
125211:         }
125212:       }
125213:     }
125214:     pLevel->u.pCovidx = pCov;
125215:     if( pCov ) pLevel->iIdxCur = iCovCur;
125216:     if( pAndExpr ){
125217:       pAndExpr->pLeft = 0;
125218:       sqlite3ExprDelete(db, pAndExpr);
125219:     }
125220:     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
125221:     sqlite3VdbeGoto(v, pLevel->addrBrk);
125222:     sqlite3VdbeResolveLabel(v, iLoopBody);
125223: 
125224:     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
125225:     if( !untestedTerms ) disableTerm(pLevel, pTerm);
125226:   }else
125227: #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
125228: 
125229:   {
125230:     /* Case 6:  There is no usable index.  We must do a complete
125231:     **          scan of the entire table.
125232:     */
125233:     static const u8 aStep[] = { OP_Next, OP_Prev };
125234:     static const u8 aStart[] = { OP_Rewind, OP_Last };
125235:     assert( bRev==0 || bRev==1 );
125236:     if( pTabItem->fg.isRecursive ){
125237:       /* Tables marked isRecursive have only a single row that is stored in
125238:       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
125239:       pLevel->op = OP_Noop;
125240:     }else{
125241:       codeCursorHint(pTabItem, pWInfo, pLevel, 0);
125242:       pLevel->op = aStep[bRev];
125243:       pLevel->p1 = iCur;
125244:       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
125245:       VdbeCoverageIf(v, bRev==0);
125246:       VdbeCoverageIf(v, bRev!=0);
125247:       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
125248:     }
125249:   }
125250: 
125251: #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
125252:   pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
125253: #endif
125254: 
125255:   /* Insert code to test every subexpression that can be completely
125256:   ** computed using the current set of tables.
125257:   */
125258:   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
125259:     Expr *pE;
125260:     int skipLikeAddr = 0;
125261:     testcase( pTerm->wtFlags & TERM_VIRTUAL );
125262:     testcase( pTerm->wtFlags & TERM_CODED );
125263:     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125264:     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
125265:       testcase( pWInfo->untestedTerms==0
125266:                && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
125267:       pWInfo->untestedTerms = 1;
125268:       continue;
125269:     }
125270:     pE = pTerm->pExpr;
125271:     assert( pE!=0 );
125272:     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
125273:       continue;
125274:     }
125275:     if( pTerm->wtFlags & TERM_LIKECOND ){
125276:       /* If the TERM_LIKECOND flag is set, that means that the range search
125277:       ** is sufficient to guarantee that the LIKE operator is true, so we
125278:       ** can skip the call to the like(A,B) function.  But this only works
125279:       ** for strings.  So do not skip the call to the function on the pass
125280:       ** that compares BLOBs. */
125281: #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
125282:       continue;
125283: #else
125284:       u32 x = pLevel->iLikeRepCntr;
125285:       assert( x>0 );
125286:       skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
125287:       VdbeCoverage(v);
125288: #endif
125289:     }
125290:     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
125291:     if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
125292:     pTerm->wtFlags |= TERM_CODED;
125293:   }
125294: 
125295:   /* Insert code to test for implied constraints based on transitivity
125296:   ** of the "==" operator.
125297:   **
125298:   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
125299:   ** and we are coding the t1 loop and the t2 loop has not yet coded,
125300:   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
125301:   ** the implied "t1.a=123" constraint.
125302:   */
125303:   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
125304:     Expr *pE, *pEAlt;
125305:     WhereTerm *pAlt;
125306:     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125307:     if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
125308:     if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
125309:     if( pTerm->leftCursor!=iCur ) continue;
125310:     if( pLevel->iLeftJoin ) continue;
125311:     pE = pTerm->pExpr;
125312:     assert( !ExprHasProperty(pE, EP_FromJoin) );
125313:     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
125314:     pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
125315:                     WO_EQ|WO_IN|WO_IS, 0);
125316:     if( pAlt==0 ) continue;
125317:     if( pAlt->wtFlags & (TERM_CODED) ) continue;
125318:     testcase( pAlt->eOperator & WO_EQ );
125319:     testcase( pAlt->eOperator & WO_IS );
125320:     testcase( pAlt->eOperator & WO_IN );
125321:     VdbeModuleComment((v, "begin transitive constraint"));
125322:     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
125323:     if( pEAlt ){
125324:       *pEAlt = *pAlt->pExpr;
125325:       pEAlt->pLeft = pE->pLeft;
125326:       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
125327:       sqlite3StackFree(db, pEAlt);
125328:     }
125329:   }
125330: 
125331:   /* For a LEFT OUTER JOIN, generate code that will record the fact that
125332:   ** at least one row of the right table has matched the left table.  
125333:   */
125334:   if( pLevel->iLeftJoin ){
125335:     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
125336:     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
125337:     VdbeComment((v, "record LEFT JOIN hit"));
125338:     sqlite3ExprCacheClear(pParse);
125339:     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
125340:       testcase( pTerm->wtFlags & TERM_VIRTUAL );
125341:       testcase( pTerm->wtFlags & TERM_CODED );
125342:       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
125343:       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
125344:         assert( pWInfo->untestedTerms );
125345:         continue;
125346:       }
125347:       assert( pTerm->pExpr );
125348:       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
125349:       pTerm->wtFlags |= TERM_CODED;
125350:     }
125351:   }
125352: 
125353:   return pLevel->notReady;
125354: }
125355: 
125356: /************** End of wherecode.c *******************************************/
125357: /************** Begin file whereexpr.c ***************************************/
125358: /*
125359: ** 2015-06-08
125360: **
125361: ** The author disclaims copyright to this source code.  In place of
125362: ** a legal notice, here is a blessing:
125363: **
125364: **    May you do good and not evil.
125365: **    May you find forgiveness for yourself and forgive others.
125366: **    May you share freely, never taking more than you give.
125367: **
125368: *************************************************************************
125369: ** This module contains C code that generates VDBE code used to process
125370: ** the WHERE clause of SQL statements.
125371: **
125372: ** This file was originally part of where.c but was split out to improve
125373: ** readability and editabiliity.  This file contains utility routines for
125374: ** analyzing Expr objects in the WHERE clause.
125375: */
125376: /* #include "sqliteInt.h" */
125377: /* #include "whereInt.h" */
125378: 
125379: /* Forward declarations */
125380: static void exprAnalyze(SrcList*, WhereClause*, int);
125381: 
125382: /*
125383: ** Deallocate all memory associated with a WhereOrInfo object.
125384: */
125385: static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
125386:   sqlite3WhereClauseClear(&p->wc);
125387:   sqlite3DbFree(db, p);
125388: }
125389: 
125390: /*
125391: ** Deallocate all memory associated with a WhereAndInfo object.
125392: */
125393: static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
125394:   sqlite3WhereClauseClear(&p->wc);
125395:   sqlite3DbFree(db, p);
125396: }
125397: 
125398: /*
125399: ** Add a single new WhereTerm entry to the WhereClause object pWC.
125400: ** The new WhereTerm object is constructed from Expr p and with wtFlags.
125401: ** The index in pWC->a[] of the new WhereTerm is returned on success.
125402: ** 0 is returned if the new WhereTerm could not be added due to a memory
125403: ** allocation error.  The memory allocation failure will be recorded in
125404: ** the db->mallocFailed flag so that higher-level functions can detect it.
125405: **
125406: ** This routine will increase the size of the pWC->a[] array as necessary.
125407: **
125408: ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
125409: ** for freeing the expression p is assumed by the WhereClause object pWC.
125410: ** This is true even if this routine fails to allocate a new WhereTerm.
125411: **
125412: ** WARNING:  This routine might reallocate the space used to store
125413: ** WhereTerms.  All pointers to WhereTerms should be invalidated after
125414: ** calling this routine.  Such pointers may be reinitialized by referencing
125415: ** the pWC->a[] array.
125416: */
125417: static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
125418:   WhereTerm *pTerm;
125419:   int idx;
125420:   testcase( wtFlags & TERM_VIRTUAL );
125421:   if( pWC->nTerm>=pWC->nSlot ){
125422:     WhereTerm *pOld = pWC->a;
125423:     sqlite3 *db = pWC->pWInfo->pParse->db;
125424:     pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
125425:     if( pWC->a==0 ){
125426:       if( wtFlags & TERM_DYNAMIC ){
125427:         sqlite3ExprDelete(db, p);
125428:       }
125429:       pWC->a = pOld;
125430:       return 0;
125431:     }
125432:     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
125433:     if( pOld!=pWC->aStatic ){
125434:       sqlite3DbFree(db, pOld);
125435:     }
125436:     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
125437:     memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
125438:   }
125439:   pTerm = &pWC->a[idx = pWC->nTerm++];
125440:   if( p && ExprHasProperty(p, EP_Unlikely) ){
125441:     pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
125442:   }else{
125443:     pTerm->truthProb = 1;
125444:   }
125445:   pTerm->pExpr = sqlite3ExprSkipCollate(p);
125446:   pTerm->wtFlags = wtFlags;
125447:   pTerm->pWC = pWC;
125448:   pTerm->iParent = -1;
125449:   return idx;
125450: }
125451: 
125452: /*
125453: ** Return TRUE if the given operator is one of the operators that is
125454: ** allowed for an indexable WHERE clause term.  The allowed operators are
125455: ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
125456: */
125457: static int allowedOp(int op){
125458:   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
125459:   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
125460:   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
125461:   assert( TK_GE==TK_EQ+4 );
125462:   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
125463: }
125464: 
125465: /*
125466: ** Commute a comparison operator.  Expressions of the form "X op Y"
125467: ** are converted into "Y op X".
125468: **
125469: ** If left/right precedence rules come into play when determining the
125470: ** collating sequence, then COLLATE operators are adjusted to ensure
125471: ** that the collating sequence does not change.  For example:
125472: ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
125473: ** the left hand side of a comparison overrides any collation sequence 
125474: ** attached to the right. For the same reason the EP_Collate flag
125475: ** is not commuted.
125476: */
125477: static void exprCommute(Parse *pParse, Expr *pExpr){
125478:   u16 expRight = (pExpr->pRight->flags & EP_Collate);
125479:   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
125480:   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
125481:   if( expRight==expLeft ){
125482:     /* Either X and Y both have COLLATE operator or neither do */
125483:     if( expRight ){
125484:       /* Both X and Y have COLLATE operators.  Make sure X is always
125485:       ** used by clearing the EP_Collate flag from Y. */
125486:       pExpr->pRight->flags &= ~EP_Collate;
125487:     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
125488:       /* Neither X nor Y have COLLATE operators, but X has a non-default
125489:       ** collating sequence.  So add the EP_Collate marker on X to cause
125490:       ** it to be searched first. */
125491:       pExpr->pLeft->flags |= EP_Collate;
125492:     }
125493:   }
125494:   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
125495:   if( pExpr->op>=TK_GT ){
125496:     assert( TK_LT==TK_GT+2 );
125497:     assert( TK_GE==TK_LE+2 );
125498:     assert( TK_GT>TK_EQ );
125499:     assert( TK_GT<TK_LE );
125500:     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
125501:     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
125502:   }
125503: }
125504: 
125505: /*
125506: ** Translate from TK_xx operator to WO_xx bitmask.
125507: */
125508: static u16 operatorMask(int op){
125509:   u16 c;
125510:   assert( allowedOp(op) );
125511:   if( op==TK_IN ){
125512:     c = WO_IN;
125513:   }else if( op==TK_ISNULL ){
125514:     c = WO_ISNULL;
125515:   }else if( op==TK_IS ){
125516:     c = WO_IS;
125517:   }else{
125518:     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
125519:     c = (u16)(WO_EQ<<(op-TK_EQ));
125520:   }
125521:   assert( op!=TK_ISNULL || c==WO_ISNULL );
125522:   assert( op!=TK_IN || c==WO_IN );
125523:   assert( op!=TK_EQ || c==WO_EQ );
125524:   assert( op!=TK_LT || c==WO_LT );
125525:   assert( op!=TK_LE || c==WO_LE );
125526:   assert( op!=TK_GT || c==WO_GT );
125527:   assert( op!=TK_GE || c==WO_GE );
125528:   assert( op!=TK_IS || c==WO_IS );
125529:   return c;
125530: }
125531: 
125532: 
125533: #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
125534: /*
125535: ** Check to see if the given expression is a LIKE or GLOB operator that
125536: ** can be optimized using inequality constraints.  Return TRUE if it is
125537: ** so and false if not.
125538: **
125539: ** In order for the operator to be optimizible, the RHS must be a string
125540: ** literal that does not begin with a wildcard.  The LHS must be a column
125541: ** that may only be NULL, a string, or a BLOB, never a number. (This means
125542: ** that virtual tables cannot participate in the LIKE optimization.)  The
125543: ** collating sequence for the column on the LHS must be appropriate for
125544: ** the operator.
125545: */
125546: static int isLikeOrGlob(
125547:   Parse *pParse,    /* Parsing and code generating context */
125548:   Expr *pExpr,      /* Test this expression */
125549:   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
125550:   int *pisComplete, /* True if the only wildcard is % in the last character */
125551:   int *pnoCase      /* True if uppercase is equivalent to lowercase */
125552: ){
125553:   const char *z = 0;         /* String on RHS of LIKE operator */
125554:   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
125555:   ExprList *pList;           /* List of operands to the LIKE operator */
125556:   int c;                     /* One character in z[] */
125557:   int cnt;                   /* Number of non-wildcard prefix characters */
125558:   char wc[3];                /* Wildcard characters */
125559:   sqlite3 *db = pParse->db;  /* Database connection */
125560:   sqlite3_value *pVal = 0;
125561:   int op;                    /* Opcode of pRight */
125562:   int rc;                    /* Result code to return */
125563: 
125564:   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
125565:     return 0;
125566:   }
125567: #ifdef SQLITE_EBCDIC
125568:   if( *pnoCase ) return 0;
125569: #endif
125570:   pList = pExpr->x.pList;
125571:   pLeft = pList->a[1].pExpr;
125572:   if( pLeft->op!=TK_COLUMN 
125573:    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
125574:    || IsVirtual(pLeft->pTab)  /* Value might be numeric */
125575:   ){
125576:     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
125577:     ** be the name of an indexed column with TEXT affinity. */
125578:     return 0;
125579:   }
125580:   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
125581: 
125582:   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
125583:   op = pRight->op;
125584:   if( op==TK_VARIABLE ){
125585:     Vdbe *pReprepare = pParse->pReprepare;
125586:     int iCol = pRight->iColumn;
125587:     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
125588:     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
125589:       z = (char *)sqlite3_value_text(pVal);
125590:     }
125591:     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
125592:     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
125593:   }else if( op==TK_STRING ){
125594:     z = pRight->u.zToken;
125595:   }
125596:   if( z ){
125597:     cnt = 0;
125598:     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
125599:       cnt++;
125600:     }
125601:     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
125602:       Expr *pPrefix;
125603:       *pisComplete = c==wc[0] && z[cnt+1]==0;
125604:       pPrefix = sqlite3Expr(db, TK_STRING, z);
125605:       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
125606:       *ppPrefix = pPrefix;
125607:       if( op==TK_VARIABLE ){
125608:         Vdbe *v = pParse->pVdbe;
125609:         sqlite3VdbeSetVarmask(v, pRight->iColumn);
125610:         if( *pisComplete && pRight->u.zToken[1] ){
125611:           /* If the rhs of the LIKE expression is a variable, and the current
125612:           ** value of the variable means there is no need to invoke the LIKE
125613:           ** function, then no OP_Variable will be added to the program.
125614:           ** This causes problems for the sqlite3_bind_parameter_name()
125615:           ** API. To work around them, add a dummy OP_Variable here.
125616:           */ 
125617:           int r1 = sqlite3GetTempReg(pParse);
125618:           sqlite3ExprCodeTarget(pParse, pRight, r1);
125619:           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
125620:           sqlite3ReleaseTempReg(pParse, r1);
125621:         }
125622:       }
125623:     }else{
125624:       z = 0;
125625:     }
125626:   }
125627: 
125628:   rc = (z!=0);
125629:   sqlite3ValueFree(pVal);
125630:   return rc;
125631: }
125632: #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
125633: 
125634: 
125635: #ifndef SQLITE_OMIT_VIRTUALTABLE
125636: /*
125637: ** Check to see if the given expression is of the form
125638: **
125639: **         column OP expr
125640: **
125641: ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a 
125642: ** column of a virtual table.
125643: **
125644: ** If it is then return TRUE.  If not, return FALSE.
125645: */
125646: static int isMatchOfColumn(
125647:   Expr *pExpr,                    /* Test this expression */
125648:   unsigned char *peOp2            /* OUT: 0 for MATCH, or else an op2 value */
125649: ){
125650:   struct Op2 {
125651:     const char *zOp;
125652:     unsigned char eOp2;
125653:   } aOp[] = {
125654:     { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
125655:     { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
125656:     { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
125657:     { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
125658:   };
125659:   ExprList *pList;
125660:   Expr *pCol;                     /* Column reference */
125661:   int i;
125662: 
125663:   if( pExpr->op!=TK_FUNCTION ){
125664:     return 0;
125665:   }
125666:   pList = pExpr->x.pList;
125667:   if( pList==0 || pList->nExpr!=2 ){
125668:     return 0;
125669:   }
125670:   pCol = pList->a[1].pExpr;
125671:   if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
125672:     return 0;
125673:   }
125674:   for(i=0; i<ArraySize(aOp); i++){
125675:     if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
125676:       *peOp2 = aOp[i].eOp2;
125677:       return 1;
125678:     }
125679:   }
125680:   return 0;
125681: }
125682: #endif /* SQLITE_OMIT_VIRTUALTABLE */
125683: 
125684: /*
125685: ** If the pBase expression originated in the ON or USING clause of
125686: ** a join, then transfer the appropriate markings over to derived.
125687: */
125688: static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
125689:   if( pDerived ){
125690:     pDerived->flags |= pBase->flags & EP_FromJoin;
125691:     pDerived->iRightJoinTable = pBase->iRightJoinTable;
125692:   }
125693: }
125694: 
125695: /*
125696: ** Mark term iChild as being a child of term iParent
125697: */
125698: static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
125699:   pWC->a[iChild].iParent = iParent;
125700:   pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
125701:   pWC->a[iParent].nChild++;
125702: }
125703: 
125704: /*
125705: ** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
125706: ** a conjunction, then return just pTerm when N==0.  If N is exceeds
125707: ** the number of available subterms, return NULL.
125708: */
125709: static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
125710:   if( pTerm->eOperator!=WO_AND ){
125711:     return N==0 ? pTerm : 0;
125712:   }
125713:   if( N<pTerm->u.pAndInfo->wc.nTerm ){
125714:     return &pTerm->u.pAndInfo->wc.a[N];
125715:   }
125716:   return 0;
125717: }
125718: 
125719: /*
125720: ** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
125721: ** two subterms are in disjunction - they are OR-ed together.
125722: **
125723: ** If these two terms are both of the form:  "A op B" with the same
125724: ** A and B values but different operators and if the operators are
125725: ** compatible (if one is = and the other is <, for example) then
125726: ** add a new virtual AND term to pWC that is the combination of the
125727: ** two.
125728: **
125729: ** Some examples:
125730: **
125731: **    x<y OR x=y    -->     x<=y
125732: **    x=y OR x=y    -->     x=y
125733: **    x<=y OR x<y   -->     x<=y
125734: **
125735: ** The following is NOT generated:
125736: **
125737: **    x<y OR x>y    -->     x!=y     
125738: */
125739: static void whereCombineDisjuncts(
125740:   SrcList *pSrc,         /* the FROM clause */
125741:   WhereClause *pWC,      /* The complete WHERE clause */
125742:   WhereTerm *pOne,       /* First disjunct */
125743:   WhereTerm *pTwo        /* Second disjunct */
125744: ){
125745:   u16 eOp = pOne->eOperator | pTwo->eOperator;
125746:   sqlite3 *db;           /* Database connection (for malloc) */
125747:   Expr *pNew;            /* New virtual expression */
125748:   int op;                /* Operator for the combined expression */
125749:   int idxNew;            /* Index in pWC of the next virtual term */
125750: 
125751:   if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
125752:   if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
125753:   if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
125754:    && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
125755:   assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
125756:   assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
125757:   if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
125758:   if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
125759:   /* If we reach this point, it means the two subterms can be combined */
125760:   if( (eOp & (eOp-1))!=0 ){
125761:     if( eOp & (WO_LT|WO_LE) ){
125762:       eOp = WO_LE;
125763:     }else{
125764:       assert( eOp & (WO_GT|WO_GE) );
125765:       eOp = WO_GE;
125766:     }
125767:   }
125768:   db = pWC->pWInfo->pParse->db;
125769:   pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
125770:   if( pNew==0 ) return;
125771:   for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
125772:   pNew->op = op;
125773:   idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
125774:   exprAnalyze(pSrc, pWC, idxNew);
125775: }
125776: 
125777: #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
125778: /*
125779: ** Analyze a term that consists of two or more OR-connected
125780: ** subterms.  So in:
125781: **
125782: **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
125783: **                          ^^^^^^^^^^^^^^^^^^^^
125784: **
125785: ** This routine analyzes terms such as the middle term in the above example.
125786: ** A WhereOrTerm object is computed and attached to the term under
125787: ** analysis, regardless of the outcome of the analysis.  Hence:
125788: **
125789: **     WhereTerm.wtFlags   |=  TERM_ORINFO
125790: **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
125791: **
125792: ** The term being analyzed must have two or more of OR-connected subterms.
125793: ** A single subterm might be a set of AND-connected sub-subterms.
125794: ** Examples of terms under analysis:
125795: **
125796: **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
125797: **     (B)     x=expr1 OR expr2=x OR x=expr3
125798: **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
125799: **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
125800: **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
125801: **     (F)     x>A OR (x=A AND y>=B)
125802: **
125803: ** CASE 1:
125804: **
125805: ** If all subterms are of the form T.C=expr for some single column of C and
125806: ** a single table T (as shown in example B above) then create a new virtual
125807: ** term that is an equivalent IN expression.  In other words, if the term
125808: ** being analyzed is:
125809: **
125810: **      x = expr1  OR  expr2 = x  OR  x = expr3
125811: **
125812: ** then create a new virtual term like this:
125813: **
125814: **      x IN (expr1,expr2,expr3)
125815: **
125816: ** CASE 2:
125817: **
125818: ** If there are exactly two disjuncts and one side has x>A and the other side
125819: ** has x=A (for the same x and A) then add a new virtual conjunct term to the
125820: ** WHERE clause of the form "x>=A".  Example:
125821: **
125822: **      x>A OR (x=A AND y>B)    adds:    x>=A
125823: **
125824: ** The added conjunct can sometimes be helpful in query planning.
125825: **
125826: ** CASE 3:
125827: **
125828: ** If all subterms are indexable by a single table T, then set
125829: **
125830: **     WhereTerm.eOperator              =  WO_OR
125831: **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
125832: **
125833: ** A subterm is "indexable" if it is of the form
125834: ** "T.C <op> <expr>" where C is any column of table T and 
125835: ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
125836: ** A subterm is also indexable if it is an AND of two or more
125837: ** subsubterms at least one of which is indexable.  Indexable AND 
125838: ** subterms have their eOperator set to WO_AND and they have
125839: ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
125840: **
125841: ** From another point of view, "indexable" means that the subterm could
125842: ** potentially be used with an index if an appropriate index exists.
125843: ** This analysis does not consider whether or not the index exists; that
125844: ** is decided elsewhere.  This analysis only looks at whether subterms
125845: ** appropriate for indexing exist.
125846: **
125847: ** All examples A through E above satisfy case 3.  But if a term
125848: ** also satisfies case 1 (such as B) we know that the optimizer will
125849: ** always prefer case 1, so in that case we pretend that case 3 is not
125850: ** satisfied.
125851: **
125852: ** It might be the case that multiple tables are indexable.  For example,
125853: ** (E) above is indexable on tables P, Q, and R.
125854: **
125855: ** Terms that satisfy case 3 are candidates for lookup by using
125856: ** separate indices to find rowids for each subterm and composing
125857: ** the union of all rowids using a RowSet object.  This is similar
125858: ** to "bitmap indices" in other database engines.
125859: **
125860: ** OTHERWISE:
125861: **
125862: ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
125863: ** zero.  This term is not useful for search.
125864: */
125865: static void exprAnalyzeOrTerm(
125866:   SrcList *pSrc,            /* the FROM clause */
125867:   WhereClause *pWC,         /* the complete WHERE clause */
125868:   int idxTerm               /* Index of the OR-term to be analyzed */
125869: ){
125870:   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
125871:   Parse *pParse = pWInfo->pParse;         /* Parser context */
125872:   sqlite3 *db = pParse->db;               /* Database connection */
125873:   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
125874:   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
125875:   int i;                                  /* Loop counters */
125876:   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
125877:   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
125878:   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
125879:   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
125880:   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
125881: 
125882:   /*
125883:   ** Break the OR clause into its separate subterms.  The subterms are
125884:   ** stored in a WhereClause structure containing within the WhereOrInfo
125885:   ** object that is attached to the original OR clause term.
125886:   */
125887:   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
125888:   assert( pExpr->op==TK_OR );
125889:   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
125890:   if( pOrInfo==0 ) return;
125891:   pTerm->wtFlags |= TERM_ORINFO;
125892:   pOrWc = &pOrInfo->wc;
125893:   memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
125894:   sqlite3WhereClauseInit(pOrWc, pWInfo);
125895:   sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
125896:   sqlite3WhereExprAnalyze(pSrc, pOrWc);
125897:   if( db->mallocFailed ) return;
125898:   assert( pOrWc->nTerm>=2 );
125899: 
125900:   /*
125901:   ** Compute the set of tables that might satisfy cases 1 or 3.
125902:   */
125903:   indexable = ~(Bitmask)0;
125904:   chngToIN = ~(Bitmask)0;
125905:   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
125906:     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
125907:       WhereAndInfo *pAndInfo;
125908:       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
125909:       chngToIN = 0;
125910:       pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
125911:       if( pAndInfo ){
125912:         WhereClause *pAndWC;
125913:         WhereTerm *pAndTerm;
125914:         int j;
125915:         Bitmask b = 0;
125916:         pOrTerm->u.pAndInfo = pAndInfo;
125917:         pOrTerm->wtFlags |= TERM_ANDINFO;
125918:         pOrTerm->eOperator = WO_AND;
125919:         pAndWC = &pAndInfo->wc;
125920:         memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
125921:         sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
125922:         sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
125923:         sqlite3WhereExprAnalyze(pSrc, pAndWC);
125924:         pAndWC->pOuter = pWC;
125925:         if( !db->mallocFailed ){
125926:           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
125927:             assert( pAndTerm->pExpr );
125928:             if( allowedOp(pAndTerm->pExpr->op) 
125929:              || pAndTerm->eOperator==WO_MATCH 
125930:             ){
125931:               b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
125932:             }
125933:           }
125934:         }
125935:         indexable &= b;
125936:       }
125937:     }else if( pOrTerm->wtFlags & TERM_COPIED ){
125938:       /* Skip this term for now.  We revisit it when we process the
125939:       ** corresponding TERM_VIRTUAL term */
125940:     }else{
125941:       Bitmask b;
125942:       b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
125943:       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
125944:         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
125945:         b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
125946:       }
125947:       indexable &= b;
125948:       if( (pOrTerm->eOperator & WO_EQ)==0 ){
125949:         chngToIN = 0;
125950:       }else{
125951:         chngToIN &= b;
125952:       }
125953:     }
125954:   }
125955: 
125956:   /*
125957:   ** Record the set of tables that satisfy case 3.  The set might be
125958:   ** empty.
125959:   */
125960:   pOrInfo->indexable = indexable;
125961:   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
125962: 
125963:   /* For a two-way OR, attempt to implementation case 2.
125964:   */
125965:   if( indexable && pOrWc->nTerm==2 ){
125966:     int iOne = 0;
125967:     WhereTerm *pOne;
125968:     while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
125969:       int iTwo = 0;
125970:       WhereTerm *pTwo;
125971:       while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
125972:         whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
125973:       }
125974:     }
125975:   }
125976: 
125977:   /*
125978:   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
125979:   ** we have to do some additional checking to see if case 1 really
125980:   ** is satisfied.
125981:   **
125982:   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
125983:   ** that there is no possibility of transforming the OR clause into an
125984:   ** IN operator because one or more terms in the OR clause contain
125985:   ** something other than == on a column in the single table.  The 1-bit
125986:   ** case means that every term of the OR clause is of the form
125987:   ** "table.column=expr" for some single table.  The one bit that is set
125988:   ** will correspond to the common table.  We still need to check to make
125989:   ** sure the same column is used on all terms.  The 2-bit case is when
125990:   ** the all terms are of the form "table1.column=table2.column".  It
125991:   ** might be possible to form an IN operator with either table1.column
125992:   ** or table2.column as the LHS if either is common to every term of
125993:   ** the OR clause.
125994:   **
125995:   ** Note that terms of the form "table.column1=table.column2" (the
125996:   ** same table on both sizes of the ==) cannot be optimized.
125997:   */
125998:   if( chngToIN ){
125999:     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
126000:     int iColumn = -1;         /* Column index on lhs of IN operator */
126001:     int iCursor = -1;         /* Table cursor common to all terms */
126002:     int j = 0;                /* Loop counter */
126003: 
126004:     /* Search for a table and column that appears on one side or the
126005:     ** other of the == operator in every subterm.  That table and column
126006:     ** will be recorded in iCursor and iColumn.  There might not be any
126007:     ** such table and column.  Set okToChngToIN if an appropriate table
126008:     ** and column is found but leave okToChngToIN false if not found.
126009:     */
126010:     for(j=0; j<2 && !okToChngToIN; j++){
126011:       pOrTerm = pOrWc->a;
126012:       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
126013:         assert( pOrTerm->eOperator & WO_EQ );
126014:         pOrTerm->wtFlags &= ~TERM_OR_OK;
126015:         if( pOrTerm->leftCursor==iCursor ){
126016:           /* This is the 2-bit case and we are on the second iteration and
126017:           ** current term is from the first iteration.  So skip this term. */
126018:           assert( j==1 );
126019:           continue;
126020:         }
126021:         if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
126022:                                             pOrTerm->leftCursor))==0 ){
126023:           /* This term must be of the form t1.a==t2.b where t2 is in the
126024:           ** chngToIN set but t1 is not.  This term will be either preceded
126025:           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
126026:           ** and use its inversion. */
126027:           testcase( pOrTerm->wtFlags & TERM_COPIED );
126028:           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
126029:           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
126030:           continue;
126031:         }
126032:         iColumn = pOrTerm->u.leftColumn;
126033:         iCursor = pOrTerm->leftCursor;
126034:         break;
126035:       }
126036:       if( i<0 ){
126037:         /* No candidate table+column was found.  This can only occur
126038:         ** on the second iteration */
126039:         assert( j==1 );
126040:         assert( IsPowerOfTwo(chngToIN) );
126041:         assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
126042:         break;
126043:       }
126044:       testcase( j==1 );
126045: 
126046:       /* We have found a candidate table and column.  Check to see if that
126047:       ** table and column is common to every term in the OR clause */
126048:       okToChngToIN = 1;
126049:       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
126050:         assert( pOrTerm->eOperator & WO_EQ );
126051:         if( pOrTerm->leftCursor!=iCursor ){
126052:           pOrTerm->wtFlags &= ~TERM_OR_OK;
126053:         }else if( pOrTerm->u.leftColumn!=iColumn ){
126054:           okToChngToIN = 0;
126055:         }else{
126056:           int affLeft, affRight;
126057:           /* If the right-hand side is also a column, then the affinities
126058:           ** of both right and left sides must be such that no type
126059:           ** conversions are required on the right.  (Ticket #2249)
126060:           */
126061:           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
126062:           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
126063:           if( affRight!=0 && affRight!=affLeft ){
126064:             okToChngToIN = 0;
126065:           }else{
126066:             pOrTerm->wtFlags |= TERM_OR_OK;
126067:           }
126068:         }
126069:       }
126070:     }
126071: 
126072:     /* At this point, okToChngToIN is true if original pTerm satisfies
126073:     ** case 1.  In that case, construct a new virtual term that is 
126074:     ** pTerm converted into an IN operator.
126075:     */
126076:     if( okToChngToIN ){
126077:       Expr *pDup;            /* A transient duplicate expression */
126078:       ExprList *pList = 0;   /* The RHS of the IN operator */
126079:       Expr *pLeft = 0;       /* The LHS of the IN operator */
126080:       Expr *pNew;            /* The complete IN operator */
126081: 
126082:       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
126083:         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
126084:         assert( pOrTerm->eOperator & WO_EQ );
126085:         assert( pOrTerm->leftCursor==iCursor );
126086:         assert( pOrTerm->u.leftColumn==iColumn );
126087:         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
126088:         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
126089:         pLeft = pOrTerm->pExpr->pLeft;
126090:       }
126091:       assert( pLeft!=0 );
126092:       pDup = sqlite3ExprDup(db, pLeft, 0);
126093:       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
126094:       if( pNew ){
126095:         int idxNew;
126096:         transferJoinMarkings(pNew, pExpr);
126097:         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
126098:         pNew->x.pList = pList;
126099:         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
126100:         testcase( idxNew==0 );
126101:         exprAnalyze(pSrc, pWC, idxNew);
126102:         pTerm = &pWC->a[idxTerm];
126103:         markTermAsChild(pWC, idxNew, idxTerm);
126104:       }else{
126105:         sqlite3ExprListDelete(db, pList);
126106:       }
126107:       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
126108:     }
126109:   }
126110: }
126111: #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
126112: 
126113: /*
126114: ** We already know that pExpr is a binary operator where both operands are
126115: ** column references.  This routine checks to see if pExpr is an equivalence
126116: ** relation:
126117: **   1.  The SQLITE_Transitive optimization must be enabled
126118: **   2.  Must be either an == or an IS operator
126119: **   3.  Not originating in the ON clause of an OUTER JOIN
126120: **   4.  The affinities of A and B must be compatible
126121: **   5a. Both operands use the same collating sequence OR
126122: **   5b. The overall collating sequence is BINARY
126123: ** If this routine returns TRUE, that means that the RHS can be substituted
126124: ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
126125: ** This is an optimization.  No harm comes from returning 0.  But if 1 is
126126: ** returned when it should not be, then incorrect answers might result.
126127: */
126128: static int termIsEquivalence(Parse *pParse, Expr *pExpr){
126129:   char aff1, aff2;
126130:   CollSeq *pColl;
126131:   const char *zColl1, *zColl2;
126132:   if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
126133:   if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
126134:   if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
126135:   aff1 = sqlite3ExprAffinity(pExpr->pLeft);
126136:   aff2 = sqlite3ExprAffinity(pExpr->pRight);
126137:   if( aff1!=aff2
126138:    && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
126139:   ){
126140:     return 0;
126141:   }
126142:   pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
126143:   if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
126144:   pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
126145:   zColl1 = pColl ? pColl->zName : 0;
126146:   pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
126147:   zColl2 = pColl ? pColl->zName : 0;
126148:   return sqlite3_stricmp(zColl1, zColl2)==0;
126149: }
126150: 
126151: /*
126152: ** Recursively walk the expressions of a SELECT statement and generate
126153: ** a bitmask indicating which tables are used in that expression
126154: ** tree.
126155: */
126156: static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
126157:   Bitmask mask = 0;
126158:   while( pS ){
126159:     SrcList *pSrc = pS->pSrc;
126160:     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
126161:     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
126162:     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
126163:     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
126164:     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
126165:     if( ALWAYS(pSrc!=0) ){
126166:       int i;
126167:       for(i=0; i<pSrc->nSrc; i++){
126168:         mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
126169:         mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
126170:       }
126171:     }
126172:     pS = pS->pPrior;
126173:   }
126174:   return mask;
126175: }
126176: 
126177: /*
126178: ** Expression pExpr is one operand of a comparison operator that might
126179: ** be useful for indexing.  This routine checks to see if pExpr appears
126180: ** in any index.  Return TRUE (1) if pExpr is an indexed term and return
126181: ** FALSE (0) if not.  If TRUE is returned, also set *piCur to the cursor
126182: ** number of the table that is indexed and *piColumn to the column number
126183: ** of the column that is indexed, or -2 if an expression is being indexed.
126184: **
126185: ** If pExpr is a TK_COLUMN column reference, then this routine always returns
126186: ** true even if that particular column is not indexed, because the column
126187: ** might be added to an automatic index later.
126188: */
126189: static int exprMightBeIndexed(
126190:   SrcList *pFrom,        /* The FROM clause */
126191:   Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
126192:   Expr *pExpr,           /* An operand of a comparison operator */
126193:   int *piCur,            /* Write the referenced table cursor number here */
126194:   int *piColumn          /* Write the referenced table column number here */
126195: ){
126196:   Index *pIdx;
126197:   int i;
126198:   int iCur;
126199:   if( pExpr->op==TK_COLUMN ){
126200:     *piCur = pExpr->iTable;
126201:     *piColumn = pExpr->iColumn;
126202:     return 1;
126203:   }
126204:   if( mPrereq==0 ) return 0;                 /* No table references */
126205:   if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
126206:   for(i=0; mPrereq>1; i++, mPrereq>>=1){}
126207:   iCur = pFrom->a[i].iCursor;
126208:   for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
126209:     if( pIdx->aColExpr==0 ) continue;
126210:     for(i=0; i<pIdx->nKeyCol; i++){
126211:       if( pIdx->aiColumn[i]!=(-2) ) continue;
126212:       if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
126213:         *piCur = iCur;
126214:         *piColumn = -2;
126215:         return 1;
126216:       }
126217:     }
126218:   }
126219:   return 0;
126220: }
126221: 
126222: /*
126223: ** The input to this routine is an WhereTerm structure with only the
126224: ** "pExpr" field filled in.  The job of this routine is to analyze the
126225: ** subexpression and populate all the other fields of the WhereTerm
126226: ** structure.
126227: **
126228: ** If the expression is of the form "<expr> <op> X" it gets commuted
126229: ** to the standard form of "X <op> <expr>".
126230: **
126231: ** If the expression is of the form "X <op> Y" where both X and Y are
126232: ** columns, then the original expression is unchanged and a new virtual
126233: ** term of the form "Y <op> X" is added to the WHERE clause and
126234: ** analyzed separately.  The original term is marked with TERM_COPIED
126235: ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
126236: ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
126237: ** is a commuted copy of a prior term.)  The original term has nChild=1
126238: ** and the copy has idxParent set to the index of the original term.
126239: */
126240: static void exprAnalyze(
126241:   SrcList *pSrc,            /* the FROM clause */
126242:   WhereClause *pWC,         /* the WHERE clause */
126243:   int idxTerm               /* Index of the term to be analyzed */
126244: ){
126245:   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
126246:   WhereTerm *pTerm;                /* The term to be analyzed */
126247:   WhereMaskSet *pMaskSet;          /* Set of table index masks */
126248:   Expr *pExpr;                     /* The expression to be analyzed */
126249:   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
126250:   Bitmask prereqAll;               /* Prerequesites of pExpr */
126251:   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
126252:   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
126253:   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
126254:   int noCase = 0;                  /* uppercase equivalent to lowercase */
126255:   int op;                          /* Top-level operator.  pExpr->op */
126256:   Parse *pParse = pWInfo->pParse;  /* Parsing context */
126257:   sqlite3 *db = pParse->db;        /* Database connection */
126258:   unsigned char eOp2;              /* op2 value for LIKE/REGEXP/GLOB */
126259: 
126260:   if( db->mallocFailed ){
126261:     return;
126262:   }
126263:   pTerm = &pWC->a[idxTerm];
126264:   pMaskSet = &pWInfo->sMaskSet;
126265:   pExpr = pTerm->pExpr;
126266:   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
126267:   prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
126268:   op = pExpr->op;
126269:   if( op==TK_IN ){
126270:     assert( pExpr->pRight==0 );
126271:     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
126272:       pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
126273:     }else{
126274:       pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
126275:     }
126276:   }else if( op==TK_ISNULL ){
126277:     pTerm->prereqRight = 0;
126278:   }else{
126279:     pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
126280:   }
126281:   prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
126282:   if( ExprHasProperty(pExpr, EP_FromJoin) ){
126283:     Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
126284:     prereqAll |= x;
126285:     extraRight = x-1;  /* ON clause terms may not be used with an index
126286:                        ** on left table of a LEFT JOIN.  Ticket #3015 */
126287:   }
126288:   pTerm->prereqAll = prereqAll;
126289:   pTerm->leftCursor = -1;
126290:   pTerm->iParent = -1;
126291:   pTerm->eOperator = 0;
126292:   if( allowedOp(op) ){
126293:     int iCur, iColumn;
126294:     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
126295:     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
126296:     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
126297:     if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
126298:       pTerm->leftCursor = iCur;
126299:       pTerm->u.leftColumn = iColumn;
126300:       pTerm->eOperator = operatorMask(op) & opMask;
126301:     }
126302:     if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
126303:     if( pRight 
126304:      && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
126305:     ){
126306:       WhereTerm *pNew;
126307:       Expr *pDup;
126308:       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
126309:       if( pTerm->leftCursor>=0 ){
126310:         int idxNew;
126311:         pDup = sqlite3ExprDup(db, pExpr, 0);
126312:         if( db->mallocFailed ){
126313:           sqlite3ExprDelete(db, pDup);
126314:           return;
126315:         }
126316:         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
126317:         if( idxNew==0 ) return;
126318:         pNew = &pWC->a[idxNew];
126319:         markTermAsChild(pWC, idxNew, idxTerm);
126320:         if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
126321:         pTerm = &pWC->a[idxTerm];
126322:         pTerm->wtFlags |= TERM_COPIED;
126323: 
126324:         if( termIsEquivalence(pParse, pDup) ){
126325:           pTerm->eOperator |= WO_EQUIV;
126326:           eExtraOp = WO_EQUIV;
126327:         }
126328:       }else{
126329:         pDup = pExpr;
126330:         pNew = pTerm;
126331:       }
126332:       exprCommute(pParse, pDup);
126333:       pNew->leftCursor = iCur;
126334:       pNew->u.leftColumn = iColumn;
126335:       testcase( (prereqLeft | extraRight) != prereqLeft );
126336:       pNew->prereqRight = prereqLeft | extraRight;
126337:       pNew->prereqAll = prereqAll;
126338:       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
126339:     }
126340:   }
126341: 
126342: #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
126343:   /* If a term is the BETWEEN operator, create two new virtual terms
126344:   ** that define the range that the BETWEEN implements.  For example:
126345:   **
126346:   **      a BETWEEN b AND c
126347:   **
126348:   ** is converted into:
126349:   **
126350:   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
126351:   **
126352:   ** The two new terms are added onto the end of the WhereClause object.
126353:   ** The new terms are "dynamic" and are children of the original BETWEEN
126354:   ** term.  That means that if the BETWEEN term is coded, the children are
126355:   ** skipped.  Or, if the children are satisfied by an index, the original
126356:   ** BETWEEN term is skipped.
126357:   */
126358:   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
126359:     ExprList *pList = pExpr->x.pList;
126360:     int i;
126361:     static const u8 ops[] = {TK_GE, TK_LE};
126362:     assert( pList!=0 );
126363:     assert( pList->nExpr==2 );
126364:     for(i=0; i<2; i++){
126365:       Expr *pNewExpr;
126366:       int idxNew;
126367:       pNewExpr = sqlite3PExpr(pParse, ops[i], 
126368:                              sqlite3ExprDup(db, pExpr->pLeft, 0),
126369:                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
126370:       transferJoinMarkings(pNewExpr, pExpr);
126371:       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
126372:       testcase( idxNew==0 );
126373:       exprAnalyze(pSrc, pWC, idxNew);
126374:       pTerm = &pWC->a[idxTerm];
126375:       markTermAsChild(pWC, idxNew, idxTerm);
126376:     }
126377:   }
126378: #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
126379: 
126380: #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
126381:   /* Analyze a term that is composed of two or more subterms connected by
126382:   ** an OR operator.
126383:   */
126384:   else if( pExpr->op==TK_OR ){
126385:     assert( pWC->op==TK_AND );
126386:     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
126387:     pTerm = &pWC->a[idxTerm];
126388:   }
126389: #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
126390: 
126391: #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
126392:   /* Add constraints to reduce the search space on a LIKE or GLOB
126393:   ** operator.
126394:   **
126395:   ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
126396:   **
126397:   **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
126398:   **
126399:   ** The last character of the prefix "abc" is incremented to form the
126400:   ** termination condition "abd".  If case is not significant (the default
126401:   ** for LIKE) then the lower-bound is made all uppercase and the upper-
126402:   ** bound is made all lowercase so that the bounds also work when comparing
126403:   ** BLOBs.
126404:   */
126405:   if( pWC->op==TK_AND 
126406:    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
126407:   ){
126408:     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
126409:     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
126410:     Expr *pNewExpr1;
126411:     Expr *pNewExpr2;
126412:     int idxNew1;
126413:     int idxNew2;
126414:     const char *zCollSeqName;     /* Name of collating sequence */
126415:     const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
126416: 
126417:     pLeft = pExpr->x.pList->a[1].pExpr;
126418:     pStr2 = sqlite3ExprDup(db, pStr1, 0);
126419: 
126420:     /* Convert the lower bound to upper-case and the upper bound to
126421:     ** lower-case (upper-case is less than lower-case in ASCII) so that
126422:     ** the range constraints also work for BLOBs
126423:     */
126424:     if( noCase && !pParse->db->mallocFailed ){
126425:       int i;
126426:       char c;
126427:       pTerm->wtFlags |= TERM_LIKE;
126428:       for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
126429:         pStr1->u.zToken[i] = sqlite3Toupper(c);
126430:         pStr2->u.zToken[i] = sqlite3Tolower(c);
126431:       }
126432:     }
126433: 
126434:     if( !db->mallocFailed ){
126435:       u8 c, *pC;       /* Last character before the first wildcard */
126436:       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
126437:       c = *pC;
126438:       if( noCase ){
126439:         /* The point is to increment the last character before the first
126440:         ** wildcard.  But if we increment '@', that will push it into the
126441:         ** alphabetic range where case conversions will mess up the 
126442:         ** inequality.  To avoid this, make sure to also run the full
126443:         ** LIKE on all candidate expressions by clearing the isComplete flag
126444:         */
126445:         if( c=='A'-1 ) isComplete = 0;
126446:         c = sqlite3UpperToLower[c];
126447:       }
126448:       *pC = c + 1;
126449:     }
126450:     zCollSeqName = noCase ? "NOCASE" : "BINARY";
126451:     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
126452:     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
126453:            sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
126454:            pStr1, 0);
126455:     transferJoinMarkings(pNewExpr1, pExpr);
126456:     idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
126457:     testcase( idxNew1==0 );
126458:     exprAnalyze(pSrc, pWC, idxNew1);
126459:     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
126460:     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
126461:            sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
126462:            pStr2, 0);
126463:     transferJoinMarkings(pNewExpr2, pExpr);
126464:     idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
126465:     testcase( idxNew2==0 );
126466:     exprAnalyze(pSrc, pWC, idxNew2);
126467:     pTerm = &pWC->a[idxTerm];
126468:     if( isComplete ){
126469:       markTermAsChild(pWC, idxNew1, idxTerm);
126470:       markTermAsChild(pWC, idxNew2, idxTerm);
126471:     }
126472:   }
126473: #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
126474: 
126475: #ifndef SQLITE_OMIT_VIRTUALTABLE
126476:   /* Add a WO_MATCH auxiliary term to the constraint set if the
126477:   ** current expression is of the form:  column MATCH expr.
126478:   ** This information is used by the xBestIndex methods of
126479:   ** virtual tables.  The native query optimizer does not attempt
126480:   ** to do anything with MATCH functions.
126481:   */
126482:   if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
126483:     int idxNew;
126484:     Expr *pRight, *pLeft;
126485:     WhereTerm *pNewTerm;
126486:     Bitmask prereqColumn, prereqExpr;
126487: 
126488:     pRight = pExpr->x.pList->a[0].pExpr;
126489:     pLeft = pExpr->x.pList->a[1].pExpr;
126490:     prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
126491:     prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
126492:     if( (prereqExpr & prereqColumn)==0 ){
126493:       Expr *pNewExpr;
126494:       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
126495:                               0, sqlite3ExprDup(db, pRight, 0), 0);
126496:       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
126497:       testcase( idxNew==0 );
126498:       pNewTerm = &pWC->a[idxNew];
126499:       pNewTerm->prereqRight = prereqExpr;
126500:       pNewTerm->leftCursor = pLeft->iTable;
126501:       pNewTerm->u.leftColumn = pLeft->iColumn;
126502:       pNewTerm->eOperator = WO_MATCH;
126503:       pNewTerm->eMatchOp = eOp2;
126504:       markTermAsChild(pWC, idxNew, idxTerm);
126505:       pTerm = &pWC->a[idxTerm];
126506:       pTerm->wtFlags |= TERM_COPIED;
126507:       pNewTerm->prereqAll = pTerm->prereqAll;
126508:     }
126509:   }
126510: #endif /* SQLITE_OMIT_VIRTUALTABLE */
126511: 
126512: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
126513:   /* When sqlite_stat3 histogram data is available an operator of the
126514:   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
126515:   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
126516:   ** virtual term of that form.
126517:   **
126518:   ** Note that the virtual term must be tagged with TERM_VNULL.
126519:   */
126520:   if( pExpr->op==TK_NOTNULL
126521:    && pExpr->pLeft->op==TK_COLUMN
126522:    && pExpr->pLeft->iColumn>=0
126523:    && OptimizationEnabled(db, SQLITE_Stat34)
126524:   ){
126525:     Expr *pNewExpr;
126526:     Expr *pLeft = pExpr->pLeft;
126527:     int idxNew;
126528:     WhereTerm *pNewTerm;
126529: 
126530:     pNewExpr = sqlite3PExpr(pParse, TK_GT,
126531:                             sqlite3ExprDup(db, pLeft, 0),
126532:                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
126533: 
126534:     idxNew = whereClauseInsert(pWC, pNewExpr,
126535:                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
126536:     if( idxNew ){
126537:       pNewTerm = &pWC->a[idxNew];
126538:       pNewTerm->prereqRight = 0;
126539:       pNewTerm->leftCursor = pLeft->iTable;
126540:       pNewTerm->u.leftColumn = pLeft->iColumn;
126541:       pNewTerm->eOperator = WO_GT;
126542:       markTermAsChild(pWC, idxNew, idxTerm);
126543:       pTerm = &pWC->a[idxTerm];
126544:       pTerm->wtFlags |= TERM_COPIED;
126545:       pNewTerm->prereqAll = pTerm->prereqAll;
126546:     }
126547:   }
126548: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
126549: 
126550:   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
126551:   ** an index for tables to the left of the join.
126552:   */
126553:   pTerm->prereqRight |= extraRight;
126554: }
126555: 
126556: /***************************************************************************
126557: ** Routines with file scope above.  Interface to the rest of the where.c
126558: ** subsystem follows.
126559: ***************************************************************************/
126560: 
126561: /*
126562: ** This routine identifies subexpressions in the WHERE clause where
126563: ** each subexpression is separated by the AND operator or some other
126564: ** operator specified in the op parameter.  The WhereClause structure
126565: ** is filled with pointers to subexpressions.  For example:
126566: **
126567: **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
126568: **           \________/     \_______________/     \________________/
126569: **            slot[0]            slot[1]               slot[2]
126570: **
126571: ** The original WHERE clause in pExpr is unaltered.  All this routine
126572: ** does is make slot[] entries point to substructure within pExpr.
126573: **
126574: ** In the previous sentence and in the diagram, "slot[]" refers to
126575: ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
126576: ** all terms of the WHERE clause.
126577: */
126578: SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
126579:   Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
126580:   pWC->op = op;
126581:   if( pE2==0 ) return;
126582:   if( pE2->op!=op ){
126583:     whereClauseInsert(pWC, pExpr, 0);
126584:   }else{
126585:     sqlite3WhereSplit(pWC, pE2->pLeft, op);
126586:     sqlite3WhereSplit(pWC, pE2->pRight, op);
126587:   }
126588: }
126589: 
126590: /*
126591: ** Initialize a preallocated WhereClause structure.
126592: */
126593: SQLITE_PRIVATE void sqlite3WhereClauseInit(
126594:   WhereClause *pWC,        /* The WhereClause to be initialized */
126595:   WhereInfo *pWInfo        /* The WHERE processing context */
126596: ){
126597:   pWC->pWInfo = pWInfo;
126598:   pWC->pOuter = 0;
126599:   pWC->nTerm = 0;
126600:   pWC->nSlot = ArraySize(pWC->aStatic);
126601:   pWC->a = pWC->aStatic;
126602: }
126603: 
126604: /*
126605: ** Deallocate a WhereClause structure.  The WhereClause structure
126606: ** itself is not freed.  This routine is the inverse of
126607: ** sqlite3WhereClauseInit().
126608: */
126609: SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
126610:   int i;
126611:   WhereTerm *a;
126612:   sqlite3 *db = pWC->pWInfo->pParse->db;
126613:   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
126614:     if( a->wtFlags & TERM_DYNAMIC ){
126615:       sqlite3ExprDelete(db, a->pExpr);
126616:     }
126617:     if( a->wtFlags & TERM_ORINFO ){
126618:       whereOrInfoDelete(db, a->u.pOrInfo);
126619:     }else if( a->wtFlags & TERM_ANDINFO ){
126620:       whereAndInfoDelete(db, a->u.pAndInfo);
126621:     }
126622:   }
126623:   if( pWC->a!=pWC->aStatic ){
126624:     sqlite3DbFree(db, pWC->a);
126625:   }
126626: }
126627: 
126628: 
126629: /*
126630: ** These routines walk (recursively) an expression tree and generate
126631: ** a bitmask indicating which tables are used in that expression
126632: ** tree.
126633: */
126634: SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
126635:   Bitmask mask = 0;
126636:   if( p==0 ) return 0;
126637:   if( p->op==TK_COLUMN ){
126638:     mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
126639:     return mask;
126640:   }
126641:   mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
126642:   if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
126643:   if( ExprHasProperty(p, EP_xIsSelect) ){
126644:     mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
126645:   }else if( p->x.pList ){
126646:     mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
126647:   }
126648:   return mask;
126649: }
126650: SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
126651:   int i;
126652:   Bitmask mask = 0;
126653:   if( pList ){
126654:     for(i=0; i<pList->nExpr; i++){
126655:       mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
126656:     }
126657:   }
126658:   return mask;
126659: }
126660: 
126661: 
126662: /*
126663: ** Call exprAnalyze on all terms in a WHERE clause.  
126664: **
126665: ** Note that exprAnalyze() might add new virtual terms onto the
126666: ** end of the WHERE clause.  We do not want to analyze these new
126667: ** virtual terms, so start analyzing at the end and work forward
126668: ** so that the added virtual terms are never processed.
126669: */
126670: SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
126671:   SrcList *pTabList,       /* the FROM clause */
126672:   WhereClause *pWC         /* the WHERE clause to be analyzed */
126673: ){
126674:   int i;
126675:   for(i=pWC->nTerm-1; i>=0; i--){
126676:     exprAnalyze(pTabList, pWC, i);
126677:   }
126678: }
126679: 
126680: /*
126681: ** For table-valued-functions, transform the function arguments into
126682: ** new WHERE clause terms.  
126683: **
126684: ** Each function argument translates into an equality constraint against
126685: ** a HIDDEN column in the table.
126686: */
126687: SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
126688:   Parse *pParse,                    /* Parsing context */
126689:   struct SrcList_item *pItem,       /* The FROM clause term to process */
126690:   WhereClause *pWC                  /* Xfer function arguments to here */
126691: ){
126692:   Table *pTab;
126693:   int j, k;
126694:   ExprList *pArgs;
126695:   Expr *pColRef;
126696:   Expr *pTerm;
126697:   if( pItem->fg.isTabFunc==0 ) return;
126698:   pTab = pItem->pTab;
126699:   assert( pTab!=0 );
126700:   pArgs = pItem->u1.pFuncArg;
126701:   if( pArgs==0 ) return;
126702:   for(j=k=0; j<pArgs->nExpr; j++){
126703:     while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
126704:     if( k>=pTab->nCol ){
126705:       sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
126706:                       pTab->zName, j);
126707:       return;
126708:     }
126709:     pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
126710:     if( pColRef==0 ) return;
126711:     pColRef->iTable = pItem->iCursor;
126712:     pColRef->iColumn = k++;
126713:     pColRef->pTab = pTab;
126714:     pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
126715:                          sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
126716:     whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
126717:   }
126718: }
126719: 
126720: /************** End of whereexpr.c *******************************************/
126721: /************** Begin file where.c *******************************************/
126722: /*
126723: ** 2001 September 15
126724: **
126725: ** The author disclaims copyright to this source code.  In place of
126726: ** a legal notice, here is a blessing:
126727: **
126728: **    May you do good and not evil.
126729: **    May you find forgiveness for yourself and forgive others.
126730: **    May you share freely, never taking more than you give.
126731: **
126732: *************************************************************************
126733: ** This module contains C code that generates VDBE code used to process
126734: ** the WHERE clause of SQL statements.  This module is responsible for
126735: ** generating the code that loops through a table looking for applicable
126736: ** rows.  Indices are selected and used to speed the search when doing
126737: ** so is applicable.  Because this module is responsible for selecting
126738: ** indices, you might also think of this module as the "query optimizer".
126739: */
126740: /* #include "sqliteInt.h" */
126741: /* #include "whereInt.h" */
126742: 
126743: /* Forward declaration of methods */
126744: static int whereLoopResize(sqlite3*, WhereLoop*, int);
126745: 
126746: /* Test variable that can be set to enable WHERE tracing */
126747: #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
126748: /***/ int sqlite3WhereTrace = 0;
126749: #endif
126750: 
126751: 
126752: /*
126753: ** Return the estimated number of output rows from a WHERE clause
126754: */
126755: SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
126756:   return pWInfo->nRowOut;
126757: }
126758: 
126759: /*
126760: ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
126761: ** WHERE clause returns outputs for DISTINCT processing.
126762: */
126763: SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
126764:   return pWInfo->eDistinct;
126765: }
126766: 
126767: /*
126768: ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
126769: ** Return FALSE if the output needs to be sorted.
126770: */
126771: SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
126772:   return pWInfo->nOBSat;
126773: }
126774: 
126775: /*
126776: ** Return TRUE if the innermost loop of the WHERE clause implementation
126777: ** returns rows in ORDER BY order for complete run of the inner loop.
126778: **
126779: ** Across multiple iterations of outer loops, the output rows need not be
126780: ** sorted.  As long as rows are sorted for just the innermost loop, this
126781: ** routine can return TRUE.
126782: */
126783: SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
126784:   return pWInfo->bOrderedInnerLoop;
126785: }
126786: 
126787: /*
126788: ** Return the VDBE address or label to jump to in order to continue
126789: ** immediately with the next row of a WHERE clause.
126790: */
126791: SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
126792:   assert( pWInfo->iContinue!=0 );
126793:   return pWInfo->iContinue;
126794: }
126795: 
126796: /*
126797: ** Return the VDBE address or label to jump to in order to break
126798: ** out of a WHERE loop.
126799: */
126800: SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
126801:   return pWInfo->iBreak;
126802: }
126803: 
126804: /*
126805: ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
126806: ** operate directly on the rowis returned by a WHERE clause.  Return
126807: ** ONEPASS_SINGLE (1) if the statement can operation directly because only
126808: ** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
126809: ** optimization can be used on multiple 
126810: **
126811: ** If the ONEPASS optimization is used (if this routine returns true)
126812: ** then also write the indices of open cursors used by ONEPASS
126813: ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
126814: ** table and iaCur[1] gets the cursor used by an auxiliary index.
126815: ** Either value may be -1, indicating that cursor is not used.
126816: ** Any cursors returned will have been opened for writing.
126817: **
126818: ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
126819: ** unable to use the ONEPASS optimization.
126820: */
126821: SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
126822:   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
126823: #ifdef WHERETRACE_ENABLED
126824:   if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
126825:     sqlite3DebugPrintf("%s cursors: %d %d\n",
126826:          pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
126827:          aiCur[0], aiCur[1]);
126828:   }
126829: #endif
126830:   return pWInfo->eOnePass;
126831: }
126832: 
126833: /*
126834: ** Move the content of pSrc into pDest
126835: */
126836: static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
126837:   pDest->n = pSrc->n;
126838:   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
126839: }
126840: 
126841: /*
126842: ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
126843: **
126844: ** The new entry might overwrite an existing entry, or it might be
126845: ** appended, or it might be discarded.  Do whatever is the right thing
126846: ** so that pSet keeps the N_OR_COST best entries seen so far.
126847: */
126848: static int whereOrInsert(
126849:   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
126850:   Bitmask prereq,        /* Prerequisites of the new entry */
126851:   LogEst rRun,           /* Run-cost of the new entry */
126852:   LogEst nOut            /* Number of outputs for the new entry */
126853: ){
126854:   u16 i;
126855:   WhereOrCost *p;
126856:   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
126857:     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
126858:       goto whereOrInsert_done;
126859:     }
126860:     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
126861:       return 0;
126862:     }
126863:   }
126864:   if( pSet->n<N_OR_COST ){
126865:     p = &pSet->a[pSet->n++];
126866:     p->nOut = nOut;
126867:   }else{
126868:     p = pSet->a;
126869:     for(i=1; i<pSet->n; i++){
126870:       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
126871:     }
126872:     if( p->rRun<=rRun ) return 0;
126873:   }
126874: whereOrInsert_done:
126875:   p->prereq = prereq;
126876:   p->rRun = rRun;
126877:   if( p->nOut>nOut ) p->nOut = nOut;
126878:   return 1;
126879: }
126880: 
126881: /*
126882: ** Return the bitmask for the given cursor number.  Return 0 if
126883: ** iCursor is not in the set.
126884: */
126885: SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
126886:   int i;
126887:   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
126888:   for(i=0; i<pMaskSet->n; i++){
126889:     if( pMaskSet->ix[i]==iCursor ){
126890:       return MASKBIT(i);
126891:     }
126892:   }
126893:   return 0;
126894: }
126895: 
126896: /*
126897: ** Create a new mask for cursor iCursor.
126898: **
126899: ** There is one cursor per table in the FROM clause.  The number of
126900: ** tables in the FROM clause is limited by a test early in the
126901: ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
126902: ** array will never overflow.
126903: */
126904: static void createMask(WhereMaskSet *pMaskSet, int iCursor){
126905:   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
126906:   pMaskSet->ix[pMaskSet->n++] = iCursor;
126907: }
126908: 
126909: /*
126910: ** Advance to the next WhereTerm that matches according to the criteria
126911: ** established when the pScan object was initialized by whereScanInit().
126912: ** Return NULL if there are no more matching WhereTerms.
126913: */
126914: static WhereTerm *whereScanNext(WhereScan *pScan){
126915:   int iCur;            /* The cursor on the LHS of the term */
126916:   i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
126917:   Expr *pX;            /* An expression being tested */
126918:   WhereClause *pWC;    /* Shorthand for pScan->pWC */
126919:   WhereTerm *pTerm;    /* The term being tested */
126920:   int k = pScan->k;    /* Where to start scanning */
126921: 
126922:   while( pScan->iEquiv<=pScan->nEquiv ){
126923:     iCur = pScan->aiCur[pScan->iEquiv-1];
126924:     iColumn = pScan->aiColumn[pScan->iEquiv-1];
126925:     if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
126926:     while( (pWC = pScan->pWC)!=0 ){
126927:       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
126928:         if( pTerm->leftCursor==iCur
126929:          && pTerm->u.leftColumn==iColumn
126930:          && (iColumn!=XN_EXPR
126931:              || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
126932:          && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
126933:         ){
126934:           if( (pTerm->eOperator & WO_EQUIV)!=0
126935:            && pScan->nEquiv<ArraySize(pScan->aiCur)
126936:            && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
126937:           ){
126938:             int j;
126939:             for(j=0; j<pScan->nEquiv; j++){
126940:               if( pScan->aiCur[j]==pX->iTable
126941:                && pScan->aiColumn[j]==pX->iColumn ){
126942:                   break;
126943:               }
126944:             }
126945:             if( j==pScan->nEquiv ){
126946:               pScan->aiCur[j] = pX->iTable;
126947:               pScan->aiColumn[j] = pX->iColumn;
126948:               pScan->nEquiv++;
126949:             }
126950:           }
126951:           if( (pTerm->eOperator & pScan->opMask)!=0 ){
126952:             /* Verify the affinity and collating sequence match */
126953:             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
126954:               CollSeq *pColl;
126955:               Parse *pParse = pWC->pWInfo->pParse;
126956:               pX = pTerm->pExpr;
126957:               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
126958:                 continue;
126959:               }
126960:               assert(pX->pLeft);
126961:               pColl = sqlite3BinaryCompareCollSeq(pParse,
126962:                                                   pX->pLeft, pX->pRight);
126963:               if( pColl==0 ) pColl = pParse->db->pDfltColl;
126964:               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
126965:                 continue;
126966:               }
126967:             }
126968:             if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
126969:              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
126970:              && pX->iTable==pScan->aiCur[0]
126971:              && pX->iColumn==pScan->aiColumn[0]
126972:             ){
126973:               testcase( pTerm->eOperator & WO_IS );
126974:               continue;
126975:             }
126976:             pScan->k = k+1;
126977:             return pTerm;
126978:           }
126979:         }
126980:       }
126981:       pScan->pWC = pScan->pWC->pOuter;
126982:       k = 0;
126983:     }
126984:     pScan->pWC = pScan->pOrigWC;
126985:     k = 0;
126986:     pScan->iEquiv++;
126987:   }
126988:   return 0;
126989: }
126990: 
126991: /*
126992: ** Initialize a WHERE clause scanner object.  Return a pointer to the
126993: ** first match.  Return NULL if there are no matches.
126994: **
126995: ** The scanner will be searching the WHERE clause pWC.  It will look
126996: ** for terms of the form "X <op> <expr>" where X is column iColumn of table
126997: ** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
126998: ** must be one of the indexes of table iCur.
126999: **
127000: ** The <op> must be one of the operators described by opMask.
127001: **
127002: ** If the search is for X and the WHERE clause contains terms of the
127003: ** form X=Y then this routine might also return terms of the form
127004: ** "Y <op> <expr>".  The number of levels of transitivity is limited,
127005: ** but is enough to handle most commonly occurring SQL statements.
127006: **
127007: ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
127008: ** index pIdx.
127009: */
127010: static WhereTerm *whereScanInit(
127011:   WhereScan *pScan,       /* The WhereScan object being initialized */
127012:   WhereClause *pWC,       /* The WHERE clause to be scanned */
127013:   int iCur,               /* Cursor to scan for */
127014:   int iColumn,            /* Column to scan for */
127015:   u32 opMask,             /* Operator(s) to scan for */
127016:   Index *pIdx             /* Must be compatible with this index */
127017: ){
127018:   int j = 0;
127019: 
127020:   /* memset(pScan, 0, sizeof(*pScan)); */
127021:   pScan->pOrigWC = pWC;
127022:   pScan->pWC = pWC;
127023:   pScan->pIdxExpr = 0;
127024:   if( pIdx ){
127025:     j = iColumn;
127026:     iColumn = pIdx->aiColumn[j];
127027:     if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
127028:     if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
127029:   }
127030:   if( pIdx && iColumn>=0 ){
127031:     pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
127032:     pScan->zCollName = pIdx->azColl[j];
127033:   }else{
127034:     pScan->idxaff = 0;
127035:     pScan->zCollName = 0;
127036:   }
127037:   pScan->opMask = opMask;
127038:   pScan->k = 0;
127039:   pScan->aiCur[0] = iCur;
127040:   pScan->aiColumn[0] = iColumn;
127041:   pScan->nEquiv = 1;
127042:   pScan->iEquiv = 1;
127043:   return whereScanNext(pScan);
127044: }
127045: 
127046: /*
127047: ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
127048: ** where X is a reference to the iColumn of table iCur or of index pIdx
127049: ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
127050: ** the op parameter.  Return a pointer to the term.  Return 0 if not found.
127051: **
127052: ** If pIdx!=0 then it must be one of the indexes of table iCur.  
127053: ** Search for terms matching the iColumn-th column of pIdx
127054: ** rather than the iColumn-th column of table iCur.
127055: **
127056: ** The term returned might by Y=<expr> if there is another constraint in
127057: ** the WHERE clause that specifies that X=Y.  Any such constraints will be
127058: ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
127059: ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
127060: ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
127061: ** other equivalent values.  Hence a search for X will return <expr> if X=A1
127062: ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
127063: **
127064: ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
127065: ** then try for the one with no dependencies on <expr> - in other words where
127066: ** <expr> is a constant expression of some kind.  Only return entries of
127067: ** the form "X <op> Y" where Y is a column in another table if no terms of
127068: ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
127069: ** exist, try to return a term that does not use WO_EQUIV.
127070: */
127071: SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
127072:   WhereClause *pWC,     /* The WHERE clause to be searched */
127073:   int iCur,             /* Cursor number of LHS */
127074:   int iColumn,          /* Column number of LHS */
127075:   Bitmask notReady,     /* RHS must not overlap with this mask */
127076:   u32 op,               /* Mask of WO_xx values describing operator */
127077:   Index *pIdx           /* Must be compatible with this index, if not NULL */
127078: ){
127079:   WhereTerm *pResult = 0;
127080:   WhereTerm *p;
127081:   WhereScan scan;
127082: 
127083:   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
127084:   op &= WO_EQ|WO_IS;
127085:   while( p ){
127086:     if( (p->prereqRight & notReady)==0 ){
127087:       if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
127088:         testcase( p->eOperator & WO_IS );
127089:         return p;
127090:       }
127091:       if( pResult==0 ) pResult = p;
127092:     }
127093:     p = whereScanNext(&scan);
127094:   }
127095:   return pResult;
127096: }
127097: 
127098: /*
127099: ** This function searches pList for an entry that matches the iCol-th column
127100: ** of index pIdx.
127101: **
127102: ** If such an expression is found, its index in pList->a[] is returned. If
127103: ** no expression is found, -1 is returned.
127104: */
127105: static int findIndexCol(
127106:   Parse *pParse,                  /* Parse context */
127107:   ExprList *pList,                /* Expression list to search */
127108:   int iBase,                      /* Cursor for table associated with pIdx */
127109:   Index *pIdx,                    /* Index to match column of */
127110:   int iCol                        /* Column of index to match */
127111: ){
127112:   int i;
127113:   const char *zColl = pIdx->azColl[iCol];
127114: 
127115:   for(i=0; i<pList->nExpr; i++){
127116:     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
127117:     if( p->op==TK_COLUMN
127118:      && p->iColumn==pIdx->aiColumn[iCol]
127119:      && p->iTable==iBase
127120:     ){
127121:       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
127122:       if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
127123:         return i;
127124:       }
127125:     }
127126:   }
127127: 
127128:   return -1;
127129: }
127130: 
127131: /*
127132: ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
127133: */
127134: static int indexColumnNotNull(Index *pIdx, int iCol){
127135:   int j;
127136:   assert( pIdx!=0 );
127137:   assert( iCol>=0 && iCol<pIdx->nColumn );
127138:   j = pIdx->aiColumn[iCol];
127139:   if( j>=0 ){
127140:     return pIdx->pTable->aCol[j].notNull;
127141:   }else if( j==(-1) ){
127142:     return 1;
127143:   }else{
127144:     assert( j==(-2) );
127145:     return 0;  /* Assume an indexed expression can always yield a NULL */
127146: 
127147:   }
127148: }
127149: 
127150: /*
127151: ** Return true if the DISTINCT expression-list passed as the third argument
127152: ** is redundant.
127153: **
127154: ** A DISTINCT list is redundant if any subset of the columns in the
127155: ** DISTINCT list are collectively unique and individually non-null.
127156: */
127157: static int isDistinctRedundant(
127158:   Parse *pParse,            /* Parsing context */
127159:   SrcList *pTabList,        /* The FROM clause */
127160:   WhereClause *pWC,         /* The WHERE clause */
127161:   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
127162: ){
127163:   Table *pTab;
127164:   Index *pIdx;
127165:   int i;                          
127166:   int iBase;
127167: 
127168:   /* If there is more than one table or sub-select in the FROM clause of
127169:   ** this query, then it will not be possible to show that the DISTINCT 
127170:   ** clause is redundant. */
127171:   if( pTabList->nSrc!=1 ) return 0;
127172:   iBase = pTabList->a[0].iCursor;
127173:   pTab = pTabList->a[0].pTab;
127174: 
127175:   /* If any of the expressions is an IPK column on table iBase, then return 
127176:   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
127177:   ** current SELECT is a correlated sub-query.
127178:   */
127179:   for(i=0; i<pDistinct->nExpr; i++){
127180:     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
127181:     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
127182:   }
127183: 
127184:   /* Loop through all indices on the table, checking each to see if it makes
127185:   ** the DISTINCT qualifier redundant. It does so if:
127186:   **
127187:   **   1. The index is itself UNIQUE, and
127188:   **
127189:   **   2. All of the columns in the index are either part of the pDistinct
127190:   **      list, or else the WHERE clause contains a term of the form "col=X",
127191:   **      where X is a constant value. The collation sequences of the
127192:   **      comparison and select-list expressions must match those of the index.
127193:   **
127194:   **   3. All of those index columns for which the WHERE clause does not
127195:   **      contain a "col=X" term are subject to a NOT NULL constraint.
127196:   */
127197:   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127198:     if( !IsUniqueIndex(pIdx) ) continue;
127199:     for(i=0; i<pIdx->nKeyCol; i++){
127200:       if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
127201:         if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
127202:         if( indexColumnNotNull(pIdx, i)==0 ) break;
127203:       }
127204:     }
127205:     if( i==pIdx->nKeyCol ){
127206:       /* This index implies that the DISTINCT qualifier is redundant. */
127207:       return 1;
127208:     }
127209:   }
127210: 
127211:   return 0;
127212: }
127213: 
127214: 
127215: /*
127216: ** Estimate the logarithm of the input value to base 2.
127217: */
127218: static LogEst estLog(LogEst N){
127219:   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
127220: }
127221: 
127222: /*
127223: ** Convert OP_Column opcodes to OP_Copy in previously generated code.
127224: **
127225: ** This routine runs over generated VDBE code and translates OP_Column
127226: ** opcodes into OP_Copy when the table is being accessed via co-routine 
127227: ** instead of via table lookup.
127228: **
127229: ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
127230: ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
127231: ** then each OP_Rowid is transformed into an instruction to increment the
127232: ** value stored in its output register.
127233: */
127234: static void translateColumnToCopy(
127235:   Vdbe *v,            /* The VDBE containing code to translate */
127236:   int iStart,         /* Translate from this opcode to the end */
127237:   int iTabCur,        /* OP_Column/OP_Rowid references to this table */
127238:   int iRegister,      /* The first column is in this register */
127239:   int bIncrRowid      /* If non-zero, transform OP_rowid to OP_AddImm(1) */
127240: ){
127241:   VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
127242:   int iEnd = sqlite3VdbeCurrentAddr(v);
127243:   for(; iStart<iEnd; iStart++, pOp++){
127244:     if( pOp->p1!=iTabCur ) continue;
127245:     if( pOp->opcode==OP_Column ){
127246:       pOp->opcode = OP_Copy;
127247:       pOp->p1 = pOp->p2 + iRegister;
127248:       pOp->p2 = pOp->p3;
127249:       pOp->p3 = 0;
127250:     }else if( pOp->opcode==OP_Rowid ){
127251:       if( bIncrRowid ){
127252:         /* Increment the value stored in the P2 operand of the OP_Rowid. */
127253:         pOp->opcode = OP_AddImm;
127254:         pOp->p1 = pOp->p2;
127255:         pOp->p2 = 1;
127256:       }else{
127257:         pOp->opcode = OP_Null;
127258:         pOp->p1 = 0;
127259:         pOp->p3 = 0;
127260:       }
127261:     }
127262:   }
127263: }
127264: 
127265: /*
127266: ** Two routines for printing the content of an sqlite3_index_info
127267: ** structure.  Used for testing and debugging only.  If neither
127268: ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
127269: ** are no-ops.
127270: */
127271: #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
127272: static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
127273:   int i;
127274:   if( !sqlite3WhereTrace ) return;
127275:   for(i=0; i<p->nConstraint; i++){
127276:     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
127277:        i,
127278:        p->aConstraint[i].iColumn,
127279:        p->aConstraint[i].iTermOffset,
127280:        p->aConstraint[i].op,
127281:        p->aConstraint[i].usable);
127282:   }
127283:   for(i=0; i<p->nOrderBy; i++){
127284:     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
127285:        i,
127286:        p->aOrderBy[i].iColumn,
127287:        p->aOrderBy[i].desc);
127288:   }
127289: }
127290: static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
127291:   int i;
127292:   if( !sqlite3WhereTrace ) return;
127293:   for(i=0; i<p->nConstraint; i++){
127294:     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
127295:        i,
127296:        p->aConstraintUsage[i].argvIndex,
127297:        p->aConstraintUsage[i].omit);
127298:   }
127299:   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
127300:   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
127301:   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
127302:   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
127303:   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
127304: }
127305: #else
127306: #define TRACE_IDX_INPUTS(A)
127307: #define TRACE_IDX_OUTPUTS(A)
127308: #endif
127309: 
127310: #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
127311: /*
127312: ** Return TRUE if the WHERE clause term pTerm is of a form where it
127313: ** could be used with an index to access pSrc, assuming an appropriate
127314: ** index existed.
127315: */
127316: static int termCanDriveIndex(
127317:   WhereTerm *pTerm,              /* WHERE clause term to check */
127318:   struct SrcList_item *pSrc,     /* Table we are trying to access */
127319:   Bitmask notReady               /* Tables in outer loops of the join */
127320: ){
127321:   char aff;
127322:   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
127323:   if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
127324:   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
127325:   if( pTerm->u.leftColumn<0 ) return 0;
127326:   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
127327:   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
127328:   testcase( pTerm->pExpr->op==TK_IS );
127329:   return 1;
127330: }
127331: #endif
127332: 
127333: 
127334: #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
127335: /*
127336: ** Generate code to construct the Index object for an automatic index
127337: ** and to set up the WhereLevel object pLevel so that the code generator
127338: ** makes use of the automatic index.
127339: */
127340: static void constructAutomaticIndex(
127341:   Parse *pParse,              /* The parsing context */
127342:   WhereClause *pWC,           /* The WHERE clause */
127343:   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
127344:   Bitmask notReady,           /* Mask of cursors that are not available */
127345:   WhereLevel *pLevel          /* Write new index here */
127346: ){
127347:   int nKeyCol;                /* Number of columns in the constructed index */
127348:   WhereTerm *pTerm;           /* A single term of the WHERE clause */
127349:   WhereTerm *pWCEnd;          /* End of pWC->a[] */
127350:   Index *pIdx;                /* Object describing the transient index */
127351:   Vdbe *v;                    /* Prepared statement under construction */
127352:   int addrInit;               /* Address of the initialization bypass jump */
127353:   Table *pTable;              /* The table being indexed */
127354:   int addrTop;                /* Top of the index fill loop */
127355:   int regRecord;              /* Register holding an index record */
127356:   int n;                      /* Column counter */
127357:   int i;                      /* Loop counter */
127358:   int mxBitCol;               /* Maximum column in pSrc->colUsed */
127359:   CollSeq *pColl;             /* Collating sequence to on a column */
127360:   WhereLoop *pLoop;           /* The Loop object */
127361:   char *zNotUsed;             /* Extra space on the end of pIdx */
127362:   Bitmask idxCols;            /* Bitmap of columns used for indexing */
127363:   Bitmask extraCols;          /* Bitmap of additional columns */
127364:   u8 sentWarning = 0;         /* True if a warnning has been issued */
127365:   Expr *pPartial = 0;         /* Partial Index Expression */
127366:   int iContinue = 0;          /* Jump here to skip excluded rows */
127367:   struct SrcList_item *pTabItem;  /* FROM clause term being indexed */
127368:   int addrCounter = 0;        /* Address where integer counter is initialized */
127369:   int regBase;                /* Array of registers where record is assembled */
127370: 
127371:   /* Generate code to skip over the creation and initialization of the
127372:   ** transient index on 2nd and subsequent iterations of the loop. */
127373:   v = pParse->pVdbe;
127374:   assert( v!=0 );
127375:   addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
127376: 
127377:   /* Count the number of columns that will be added to the index
127378:   ** and used to match WHERE clause constraints */
127379:   nKeyCol = 0;
127380:   pTable = pSrc->pTab;
127381:   pWCEnd = &pWC->a[pWC->nTerm];
127382:   pLoop = pLevel->pWLoop;
127383:   idxCols = 0;
127384:   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
127385:     Expr *pExpr = pTerm->pExpr;
127386:     assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
127387:          || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
127388:          || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
127389:     if( pLoop->prereq==0
127390:      && (pTerm->wtFlags & TERM_VIRTUAL)==0
127391:      && !ExprHasProperty(pExpr, EP_FromJoin)
127392:      && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
127393:       pPartial = sqlite3ExprAnd(pParse->db, pPartial,
127394:                                 sqlite3ExprDup(pParse->db, pExpr, 0));
127395:     }
127396:     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
127397:       int iCol = pTerm->u.leftColumn;
127398:       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
127399:       testcase( iCol==BMS );
127400:       testcase( iCol==BMS-1 );
127401:       if( !sentWarning ){
127402:         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
127403:             "automatic index on %s(%s)", pTable->zName,
127404:             pTable->aCol[iCol].zName);
127405:         sentWarning = 1;
127406:       }
127407:       if( (idxCols & cMask)==0 ){
127408:         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
127409:           goto end_auto_index_create;
127410:         }
127411:         pLoop->aLTerm[nKeyCol++] = pTerm;
127412:         idxCols |= cMask;
127413:       }
127414:     }
127415:   }
127416:   assert( nKeyCol>0 );
127417:   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
127418:   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
127419:                      | WHERE_AUTO_INDEX;
127420: 
127421:   /* Count the number of additional columns needed to create a
127422:   ** covering index.  A "covering index" is an index that contains all
127423:   ** columns that are needed by the query.  With a covering index, the
127424:   ** original table never needs to be accessed.  Automatic indices must
127425:   ** be a covering index because the index will not be updated if the
127426:   ** original table changes and the index and table cannot both be used
127427:   ** if they go out of sync.
127428:   */
127429:   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
127430:   mxBitCol = MIN(BMS-1,pTable->nCol);
127431:   testcase( pTable->nCol==BMS-1 );
127432:   testcase( pTable->nCol==BMS-2 );
127433:   for(i=0; i<mxBitCol; i++){
127434:     if( extraCols & MASKBIT(i) ) nKeyCol++;
127435:   }
127436:   if( pSrc->colUsed & MASKBIT(BMS-1) ){
127437:     nKeyCol += pTable->nCol - BMS + 1;
127438:   }
127439: 
127440:   /* Construct the Index object to describe this index */
127441:   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
127442:   if( pIdx==0 ) goto end_auto_index_create;
127443:   pLoop->u.btree.pIndex = pIdx;
127444:   pIdx->zName = "auto-index";
127445:   pIdx->pTable = pTable;
127446:   n = 0;
127447:   idxCols = 0;
127448:   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
127449:     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
127450:       int iCol = pTerm->u.leftColumn;
127451:       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
127452:       testcase( iCol==BMS-1 );
127453:       testcase( iCol==BMS );
127454:       if( (idxCols & cMask)==0 ){
127455:         Expr *pX = pTerm->pExpr;
127456:         idxCols |= cMask;
127457:         pIdx->aiColumn[n] = pTerm->u.leftColumn;
127458:         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
127459:         pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
127460:         n++;
127461:       }
127462:     }
127463:   }
127464:   assert( (u32)n==pLoop->u.btree.nEq );
127465: 
127466:   /* Add additional columns needed to make the automatic index into
127467:   ** a covering index */
127468:   for(i=0; i<mxBitCol; i++){
127469:     if( extraCols & MASKBIT(i) ){
127470:       pIdx->aiColumn[n] = i;
127471:       pIdx->azColl[n] = sqlite3StrBINARY;
127472:       n++;
127473:     }
127474:   }
127475:   if( pSrc->colUsed & MASKBIT(BMS-1) ){
127476:     for(i=BMS-1; i<pTable->nCol; i++){
127477:       pIdx->aiColumn[n] = i;
127478:       pIdx->azColl[n] = sqlite3StrBINARY;
127479:       n++;
127480:     }
127481:   }
127482:   assert( n==nKeyCol );
127483:   pIdx->aiColumn[n] = XN_ROWID;
127484:   pIdx->azColl[n] = sqlite3StrBINARY;
127485: 
127486:   /* Create the automatic index */
127487:   assert( pLevel->iIdxCur>=0 );
127488:   pLevel->iIdxCur = pParse->nTab++;
127489:   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
127490:   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
127491:   VdbeComment((v, "for %s", pTable->zName));
127492: 
127493:   /* Fill the automatic index with content */
127494:   sqlite3ExprCachePush(pParse);
127495:   pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
127496:   if( pTabItem->fg.viaCoroutine ){
127497:     int regYield = pTabItem->regReturn;
127498:     addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
127499:     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
127500:     addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
127501:     VdbeCoverage(v);
127502:     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
127503:   }else{
127504:     addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
127505:   }
127506:   if( pPartial ){
127507:     iContinue = sqlite3VdbeMakeLabel(v);
127508:     sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
127509:     pLoop->wsFlags |= WHERE_PARTIALIDX;
127510:   }
127511:   regRecord = sqlite3GetTempReg(pParse);
127512:   regBase = sqlite3GenerateIndexKey(
127513:       pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
127514:   );
127515:   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
127516:   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
127517:   if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
127518:   if( pTabItem->fg.viaCoroutine ){
127519:     sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
127520:     translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
127521:     sqlite3VdbeGoto(v, addrTop);
127522:     pTabItem->fg.viaCoroutine = 0;
127523:   }else{
127524:     sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
127525:   }
127526:   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
127527:   sqlite3VdbeJumpHere(v, addrTop);
127528:   sqlite3ReleaseTempReg(pParse, regRecord);
127529:   sqlite3ExprCachePop(pParse);
127530:   
127531:   /* Jump here when skipping the initialization */
127532:   sqlite3VdbeJumpHere(v, addrInit);
127533: 
127534: end_auto_index_create:
127535:   sqlite3ExprDelete(pParse->db, pPartial);
127536: }
127537: #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
127538: 
127539: #ifndef SQLITE_OMIT_VIRTUALTABLE
127540: /*
127541: ** Allocate and populate an sqlite3_index_info structure. It is the 
127542: ** responsibility of the caller to eventually release the structure
127543: ** by passing the pointer returned by this function to sqlite3_free().
127544: */
127545: static sqlite3_index_info *allocateIndexInfo(
127546:   Parse *pParse,
127547:   WhereClause *pWC,
127548:   Bitmask mUnusable,              /* Ignore terms with these prereqs */
127549:   struct SrcList_item *pSrc,
127550:   ExprList *pOrderBy
127551: ){
127552:   int i, j;
127553:   int nTerm;
127554:   struct sqlite3_index_constraint *pIdxCons;
127555:   struct sqlite3_index_orderby *pIdxOrderBy;
127556:   struct sqlite3_index_constraint_usage *pUsage;
127557:   WhereTerm *pTerm;
127558:   int nOrderBy;
127559:   sqlite3_index_info *pIdxInfo;
127560: 
127561:   /* Count the number of possible WHERE clause constraints referring
127562:   ** to this virtual table */
127563:   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
127564:     if( pTerm->leftCursor != pSrc->iCursor ) continue;
127565:     if( pTerm->prereqRight & mUnusable ) continue;
127566:     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
127567:     testcase( pTerm->eOperator & WO_IN );
127568:     testcase( pTerm->eOperator & WO_ISNULL );
127569:     testcase( pTerm->eOperator & WO_IS );
127570:     testcase( pTerm->eOperator & WO_ALL );
127571:     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
127572:     if( pTerm->wtFlags & TERM_VNULL ) continue;
127573:     assert( pTerm->u.leftColumn>=(-1) );
127574:     nTerm++;
127575:   }
127576: 
127577:   /* If the ORDER BY clause contains only columns in the current 
127578:   ** virtual table then allocate space for the aOrderBy part of
127579:   ** the sqlite3_index_info structure.
127580:   */
127581:   nOrderBy = 0;
127582:   if( pOrderBy ){
127583:     int n = pOrderBy->nExpr;
127584:     for(i=0; i<n; i++){
127585:       Expr *pExpr = pOrderBy->a[i].pExpr;
127586:       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
127587:     }
127588:     if( i==n){
127589:       nOrderBy = n;
127590:     }
127591:   }
127592: 
127593:   /* Allocate the sqlite3_index_info structure
127594:   */
127595:   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
127596:                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
127597:                            + sizeof(*pIdxOrderBy)*nOrderBy );
127598:   if( pIdxInfo==0 ){
127599:     sqlite3ErrorMsg(pParse, "out of memory");
127600:     return 0;
127601:   }
127602: 
127603:   /* Initialize the structure.  The sqlite3_index_info structure contains
127604:   ** many fields that are declared "const" to prevent xBestIndex from
127605:   ** changing them.  We have to do some funky casting in order to
127606:   ** initialize those fields.
127607:   */
127608:   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
127609:   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
127610:   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
127611:   *(int*)&pIdxInfo->nConstraint = nTerm;
127612:   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
127613:   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
127614:   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
127615:   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
127616:                                                                    pUsage;
127617: 
127618:   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
127619:     u8 op;
127620:     if( pTerm->leftCursor != pSrc->iCursor ) continue;
127621:     if( pTerm->prereqRight & mUnusable ) continue;
127622:     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
127623:     testcase( pTerm->eOperator & WO_IN );
127624:     testcase( pTerm->eOperator & WO_IS );
127625:     testcase( pTerm->eOperator & WO_ISNULL );
127626:     testcase( pTerm->eOperator & WO_ALL );
127627:     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
127628:     if( pTerm->wtFlags & TERM_VNULL ) continue;
127629:     assert( pTerm->u.leftColumn>=(-1) );
127630:     pIdxCons[j].iColumn = pTerm->u.leftColumn;
127631:     pIdxCons[j].iTermOffset = i;
127632:     op = (u8)pTerm->eOperator & WO_ALL;
127633:     if( op==WO_IN ) op = WO_EQ;
127634:     if( op==WO_MATCH ){
127635:       op = pTerm->eMatchOp;
127636:     }
127637:     pIdxCons[j].op = op;
127638:     /* The direct assignment in the previous line is possible only because
127639:     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
127640:     ** following asserts verify this fact. */
127641:     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
127642:     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
127643:     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
127644:     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
127645:     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
127646:     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
127647:     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
127648:     j++;
127649:   }
127650:   for(i=0; i<nOrderBy; i++){
127651:     Expr *pExpr = pOrderBy->a[i].pExpr;
127652:     pIdxOrderBy[i].iColumn = pExpr->iColumn;
127653:     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
127654:   }
127655: 
127656:   return pIdxInfo;
127657: }
127658: 
127659: /*
127660: ** The table object reference passed as the second argument to this function
127661: ** must represent a virtual table. This function invokes the xBestIndex()
127662: ** method of the virtual table with the sqlite3_index_info object that
127663: ** comes in as the 3rd argument to this function.
127664: **
127665: ** If an error occurs, pParse is populated with an error message and a
127666: ** non-zero value is returned. Otherwise, 0 is returned and the output
127667: ** part of the sqlite3_index_info structure is left populated.
127668: **
127669: ** Whether or not an error is returned, it is the responsibility of the
127670: ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
127671: ** that this is required.
127672: */
127673: static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
127674:   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
127675:   int rc;
127676: 
127677:   TRACE_IDX_INPUTS(p);
127678:   rc = pVtab->pModule->xBestIndex(pVtab, p);
127679:   TRACE_IDX_OUTPUTS(p);
127680: 
127681:   if( rc!=SQLITE_OK ){
127682:     if( rc==SQLITE_NOMEM ){
127683:       sqlite3OomFault(pParse->db);
127684:     }else if( !pVtab->zErrMsg ){
127685:       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
127686:     }else{
127687:       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
127688:     }
127689:   }
127690:   sqlite3_free(pVtab->zErrMsg);
127691:   pVtab->zErrMsg = 0;
127692: 
127693: #if 0
127694:   /* This error is now caught by the caller.
127695:   ** Search for "xBestIndex malfunction" below */
127696:   for(i=0; i<p->nConstraint; i++){
127697:     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
127698:       sqlite3ErrorMsg(pParse, 
127699:           "table %s: xBestIndex returned an invalid plan", pTab->zName);
127700:     }
127701:   }
127702: #endif
127703: 
127704:   return pParse->nErr;
127705: }
127706: #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
127707: 
127708: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127709: /*
127710: ** Estimate the location of a particular key among all keys in an
127711: ** index.  Store the results in aStat as follows:
127712: **
127713: **    aStat[0]      Est. number of rows less than pRec
127714: **    aStat[1]      Est. number of rows equal to pRec
127715: **
127716: ** Return the index of the sample that is the smallest sample that
127717: ** is greater than or equal to pRec. Note that this index is not an index
127718: ** into the aSample[] array - it is an index into a virtual set of samples
127719: ** based on the contents of aSample[] and the number of fields in record 
127720: ** pRec. 
127721: */
127722: static int whereKeyStats(
127723:   Parse *pParse,              /* Database connection */
127724:   Index *pIdx,                /* Index to consider domain of */
127725:   UnpackedRecord *pRec,       /* Vector of values to consider */
127726:   int roundUp,                /* Round up if true.  Round down if false */
127727:   tRowcnt *aStat              /* OUT: stats written here */
127728: ){
127729:   IndexSample *aSample = pIdx->aSample;
127730:   int iCol;                   /* Index of required stats in anEq[] etc. */
127731:   int i;                      /* Index of first sample >= pRec */
127732:   int iSample;                /* Smallest sample larger than or equal to pRec */
127733:   int iMin = 0;               /* Smallest sample not yet tested */
127734:   int iTest;                  /* Next sample to test */
127735:   int res;                    /* Result of comparison operation */
127736:   int nField;                 /* Number of fields in pRec */
127737:   tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
127738: 
127739: #ifndef SQLITE_DEBUG
127740:   UNUSED_PARAMETER( pParse );
127741: #endif
127742:   assert( pRec!=0 );
127743:   assert( pIdx->nSample>0 );
127744:   assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
127745: 
127746:   /* Do a binary search to find the first sample greater than or equal
127747:   ** to pRec. If pRec contains a single field, the set of samples to search
127748:   ** is simply the aSample[] array. If the samples in aSample[] contain more
127749:   ** than one fields, all fields following the first are ignored.
127750:   **
127751:   ** If pRec contains N fields, where N is more than one, then as well as the
127752:   ** samples in aSample[] (truncated to N fields), the search also has to
127753:   ** consider prefixes of those samples. For example, if the set of samples
127754:   ** in aSample is:
127755:   **
127756:   **     aSample[0] = (a, 5) 
127757:   **     aSample[1] = (a, 10) 
127758:   **     aSample[2] = (b, 5) 
127759:   **     aSample[3] = (c, 100) 
127760:   **     aSample[4] = (c, 105)
127761:   **
127762:   ** Then the search space should ideally be the samples above and the 
127763:   ** unique prefixes [a], [b] and [c]. But since that is hard to organize, 
127764:   ** the code actually searches this set:
127765:   **
127766:   **     0: (a) 
127767:   **     1: (a, 5) 
127768:   **     2: (a, 10) 
127769:   **     3: (a, 10) 
127770:   **     4: (b) 
127771:   **     5: (b, 5) 
127772:   **     6: (c) 
127773:   **     7: (c, 100) 
127774:   **     8: (c, 105)
127775:   **     9: (c, 105)
127776:   **
127777:   ** For each sample in the aSample[] array, N samples are present in the
127778:   ** effective sample array. In the above, samples 0 and 1 are based on 
127779:   ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
127780:   **
127781:   ** Often, sample i of each block of N effective samples has (i+1) fields.
127782:   ** Except, each sample may be extended to ensure that it is greater than or
127783:   ** equal to the previous sample in the array. For example, in the above, 
127784:   ** sample 2 is the first sample of a block of N samples, so at first it 
127785:   ** appears that it should be 1 field in size. However, that would make it 
127786:   ** smaller than sample 1, so the binary search would not work. As a result, 
127787:   ** it is extended to two fields. The duplicates that this creates do not 
127788:   ** cause any problems.
127789:   */
127790:   nField = pRec->nField;
127791:   iCol = 0;
127792:   iSample = pIdx->nSample * nField;
127793:   do{
127794:     int iSamp;                    /* Index in aSample[] of test sample */
127795:     int n;                        /* Number of fields in test sample */
127796: 
127797:     iTest = (iMin+iSample)/2;
127798:     iSamp = iTest / nField;
127799:     if( iSamp>0 ){
127800:       /* The proposed effective sample is a prefix of sample aSample[iSamp].
127801:       ** Specifically, the shortest prefix of at least (1 + iTest%nField) 
127802:       ** fields that is greater than the previous effective sample.  */
127803:       for(n=(iTest % nField) + 1; n<nField; n++){
127804:         if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
127805:       }
127806:     }else{
127807:       n = iTest + 1;
127808:     }
127809: 
127810:     pRec->nField = n;
127811:     res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
127812:     if( res<0 ){
127813:       iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
127814:       iMin = iTest+1;
127815:     }else if( res==0 && n<nField ){
127816:       iLower = aSample[iSamp].anLt[n-1];
127817:       iMin = iTest+1;
127818:       res = -1;
127819:     }else{
127820:       iSample = iTest;
127821:       iCol = n-1;
127822:     }
127823:   }while( res && iMin<iSample );
127824:   i = iSample / nField;
127825: 
127826: #ifdef SQLITE_DEBUG
127827:   /* The following assert statements check that the binary search code
127828:   ** above found the right answer. This block serves no purpose other
127829:   ** than to invoke the asserts.  */
127830:   if( pParse->db->mallocFailed==0 ){
127831:     if( res==0 ){
127832:       /* If (res==0) is true, then pRec must be equal to sample i. */
127833:       assert( i<pIdx->nSample );
127834:       assert( iCol==nField-1 );
127835:       pRec->nField = nField;
127836:       assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) 
127837:            || pParse->db->mallocFailed 
127838:       );
127839:     }else{
127840:       /* Unless i==pIdx->nSample, indicating that pRec is larger than
127841:       ** all samples in the aSample[] array, pRec must be smaller than the
127842:       ** (iCol+1) field prefix of sample i.  */
127843:       assert( i<=pIdx->nSample && i>=0 );
127844:       pRec->nField = iCol+1;
127845:       assert( i==pIdx->nSample 
127846:            || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
127847:            || pParse->db->mallocFailed );
127848: 
127849:       /* if i==0 and iCol==0, then record pRec is smaller than all samples
127850:       ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
127851:       ** be greater than or equal to the (iCol) field prefix of sample i.
127852:       ** If (i>0), then pRec must also be greater than sample (i-1).  */
127853:       if( iCol>0 ){
127854:         pRec->nField = iCol;
127855:         assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
127856:              || pParse->db->mallocFailed );
127857:       }
127858:       if( i>0 ){
127859:         pRec->nField = nField;
127860:         assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
127861:              || pParse->db->mallocFailed );
127862:       }
127863:     }
127864:   }
127865: #endif /* ifdef SQLITE_DEBUG */
127866: 
127867:   if( res==0 ){
127868:     /* Record pRec is equal to sample i */
127869:     assert( iCol==nField-1 );
127870:     aStat[0] = aSample[i].anLt[iCol];
127871:     aStat[1] = aSample[i].anEq[iCol];
127872:   }else{
127873:     /* At this point, the (iCol+1) field prefix of aSample[i] is the first 
127874:     ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
127875:     ** is larger than all samples in the array. */
127876:     tRowcnt iUpper, iGap;
127877:     if( i>=pIdx->nSample ){
127878:       iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
127879:     }else{
127880:       iUpper = aSample[i].anLt[iCol];
127881:     }
127882: 
127883:     if( iLower>=iUpper ){
127884:       iGap = 0;
127885:     }else{
127886:       iGap = iUpper - iLower;
127887:     }
127888:     if( roundUp ){
127889:       iGap = (iGap*2)/3;
127890:     }else{
127891:       iGap = iGap/3;
127892:     }
127893:     aStat[0] = iLower + iGap;
127894:     aStat[1] = pIdx->aAvgEq[iCol];
127895:   }
127896: 
127897:   /* Restore the pRec->nField value before returning.  */
127898:   pRec->nField = nField;
127899:   return i;
127900: }
127901: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127902: 
127903: /*
127904: ** If it is not NULL, pTerm is a term that provides an upper or lower
127905: ** bound on a range scan. Without considering pTerm, it is estimated 
127906: ** that the scan will visit nNew rows. This function returns the number
127907: ** estimated to be visited after taking pTerm into account.
127908: **
127909: ** If the user explicitly specified a likelihood() value for this term,
127910: ** then the return value is the likelihood multiplied by the number of
127911: ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
127912: ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
127913: */
127914: static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
127915:   LogEst nRet = nNew;
127916:   if( pTerm ){
127917:     if( pTerm->truthProb<=0 ){
127918:       nRet += pTerm->truthProb;
127919:     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
127920:       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
127921:     }
127922:   }
127923:   return nRet;
127924: }
127925: 
127926: 
127927: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127928: /*
127929: ** Return the affinity for a single column of an index.
127930: */
127931: static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
127932:   assert( iCol>=0 && iCol<pIdx->nColumn );
127933:   if( !pIdx->zColAff ){
127934:     if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
127935:   }
127936:   return pIdx->zColAff[iCol];
127937: }
127938: #endif
127939: 
127940: 
127941: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127942: /* 
127943: ** This function is called to estimate the number of rows visited by a
127944: ** range-scan on a skip-scan index. For example:
127945: **
127946: **   CREATE INDEX i1 ON t1(a, b, c);
127947: **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
127948: **
127949: ** Value pLoop->nOut is currently set to the estimated number of rows 
127950: ** visited for scanning (a=? AND b=?). This function reduces that estimate 
127951: ** by some factor to account for the (c BETWEEN ? AND ?) expression based
127952: ** on the stat4 data for the index. this scan will be peformed multiple 
127953: ** times (once for each (a,b) combination that matches a=?) is dealt with 
127954: ** by the caller.
127955: **
127956: ** It does this by scanning through all stat4 samples, comparing values
127957: ** extracted from pLower and pUpper with the corresponding column in each
127958: ** sample. If L and U are the number of samples found to be less than or
127959: ** equal to the values extracted from pLower and pUpper respectively, and
127960: ** N is the total number of samples, the pLoop->nOut value is adjusted
127961: ** as follows:
127962: **
127963: **   nOut = nOut * ( min(U - L, 1) / N )
127964: **
127965: ** If pLower is NULL, or a value cannot be extracted from the term, L is
127966: ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
127967: ** U is set to N.
127968: **
127969: ** Normally, this function sets *pbDone to 1 before returning. However,
127970: ** if no value can be extracted from either pLower or pUpper (and so the
127971: ** estimate of the number of rows delivered remains unchanged), *pbDone
127972: ** is left as is.
127973: **
127974: ** If an error occurs, an SQLite error code is returned. Otherwise, 
127975: ** SQLITE_OK.
127976: */
127977: static int whereRangeSkipScanEst(
127978:   Parse *pParse,       /* Parsing & code generating context */
127979:   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
127980:   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
127981:   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
127982:   int *pbDone          /* Set to true if at least one expr. value extracted */
127983: ){
127984:   Index *p = pLoop->u.btree.pIndex;
127985:   int nEq = pLoop->u.btree.nEq;
127986:   sqlite3 *db = pParse->db;
127987:   int nLower = -1;
127988:   int nUpper = p->nSample+1;
127989:   int rc = SQLITE_OK;
127990:   u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
127991:   CollSeq *pColl;
127992:   
127993:   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
127994:   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
127995:   sqlite3_value *pVal = 0;        /* Value extracted from record */
127996: 
127997:   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
127998:   if( pLower ){
127999:     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
128000:     nLower = 0;
128001:   }
128002:   if( pUpper && rc==SQLITE_OK ){
128003:     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
128004:     nUpper = p2 ? 0 : p->nSample;
128005:   }
128006: 
128007:   if( p1 || p2 ){
128008:     int i;
128009:     int nDiff;
128010:     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
128011:       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
128012:       if( rc==SQLITE_OK && p1 ){
128013:         int res = sqlite3MemCompare(p1, pVal, pColl);
128014:         if( res>=0 ) nLower++;
128015:       }
128016:       if( rc==SQLITE_OK && p2 ){
128017:         int res = sqlite3MemCompare(p2, pVal, pColl);
128018:         if( res>=0 ) nUpper++;
128019:       }
128020:     }
128021:     nDiff = (nUpper - nLower);
128022:     if( nDiff<=0 ) nDiff = 1;
128023: 
128024:     /* If there is both an upper and lower bound specified, and the 
128025:     ** comparisons indicate that they are close together, use the fallback
128026:     ** method (assume that the scan visits 1/64 of the rows) for estimating
128027:     ** the number of rows visited. Otherwise, estimate the number of rows
128028:     ** using the method described in the header comment for this function. */
128029:     if( nDiff!=1 || pUpper==0 || pLower==0 ){
128030:       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
128031:       pLoop->nOut -= nAdjust;
128032:       *pbDone = 1;
128033:       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
128034:                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
128035:     }
128036: 
128037:   }else{
128038:     assert( *pbDone==0 );
128039:   }
128040: 
128041:   sqlite3ValueFree(p1);
128042:   sqlite3ValueFree(p2);
128043:   sqlite3ValueFree(pVal);
128044: 
128045:   return rc;
128046: }
128047: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128048: 
128049: /*
128050: ** This function is used to estimate the number of rows that will be visited
128051: ** by scanning an index for a range of values. The range may have an upper
128052: ** bound, a lower bound, or both. The WHERE clause terms that set the upper
128053: ** and lower bounds are represented by pLower and pUpper respectively. For
128054: ** example, assuming that index p is on t1(a):
128055: **
128056: **   ... FROM t1 WHERE a > ? AND a < ? ...
128057: **                    |_____|   |_____|
128058: **                       |         |
128059: **                     pLower    pUpper
128060: **
128061: ** If either of the upper or lower bound is not present, then NULL is passed in
128062: ** place of the corresponding WhereTerm.
128063: **
128064: ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
128065: ** column subject to the range constraint. Or, equivalently, the number of
128066: ** equality constraints optimized by the proposed index scan. For example,
128067: ** assuming index p is on t1(a, b), and the SQL query is:
128068: **
128069: **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
128070: **
128071: ** then nEq is set to 1 (as the range restricted column, b, is the second 
128072: ** left-most column of the index). Or, if the query is:
128073: **
128074: **   ... FROM t1 WHERE a > ? AND a < ? ...
128075: **
128076: ** then nEq is set to 0.
128077: **
128078: ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
128079: ** number of rows that the index scan is expected to visit without 
128080: ** considering the range constraints. If nEq is 0, then *pnOut is the number of 
128081: ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
128082: ** to account for the range constraints pLower and pUpper.
128083: ** 
128084: ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
128085: ** used, a single range inequality reduces the search space by a factor of 4. 
128086: ** and a pair of constraints (x>? AND x<?) reduces the expected number of
128087: ** rows visited by a factor of 64.
128088: */
128089: static int whereRangeScanEst(
128090:   Parse *pParse,       /* Parsing & code generating context */
128091:   WhereLoopBuilder *pBuilder,
128092:   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
128093:   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
128094:   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
128095: ){
128096:   int rc = SQLITE_OK;
128097:   int nOut = pLoop->nOut;
128098:   LogEst nNew;
128099: 
128100: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128101:   Index *p = pLoop->u.btree.pIndex;
128102:   int nEq = pLoop->u.btree.nEq;
128103: 
128104:   if( p->nSample>0 && nEq<p->nSampleCol ){
128105:     if( nEq==pBuilder->nRecValid ){
128106:       UnpackedRecord *pRec = pBuilder->pRec;
128107:       tRowcnt a[2];
128108:       u8 aff;
128109: 
128110:       /* Variable iLower will be set to the estimate of the number of rows in 
128111:       ** the index that are less than the lower bound of the range query. The
128112:       ** lower bound being the concatenation of $P and $L, where $P is the
128113:       ** key-prefix formed by the nEq values matched against the nEq left-most
128114:       ** columns of the index, and $L is the value in pLower.
128115:       **
128116:       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
128117:       ** is not a simple variable or literal value), the lower bound of the
128118:       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
128119:       ** if $L is available, whereKeyStats() is called for both ($P) and 
128120:       ** ($P:$L) and the larger of the two returned values is used.
128121:       **
128122:       ** Similarly, iUpper is to be set to the estimate of the number of rows
128123:       ** less than the upper bound of the range query. Where the upper bound
128124:       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
128125:       ** of iUpper are requested of whereKeyStats() and the smaller used.
128126:       **
128127:       ** The number of rows between the two bounds is then just iUpper-iLower.
128128:       */
128129:       tRowcnt iLower;     /* Rows less than the lower bound */
128130:       tRowcnt iUpper;     /* Rows less than the upper bound */
128131:       int iLwrIdx = -2;   /* aSample[] for the lower bound */
128132:       int iUprIdx = -1;   /* aSample[] for the upper bound */
128133: 
128134:       if( pRec ){
128135:         testcase( pRec->nField!=pBuilder->nRecValid );
128136:         pRec->nField = pBuilder->nRecValid;
128137:       }
128138:       aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
128139:       assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
128140:       /* Determine iLower and iUpper using ($P) only. */
128141:       if( nEq==0 ){
128142:         iLower = 0;
128143:         iUpper = p->nRowEst0;
128144:       }else{
128145:         /* Note: this call could be optimized away - since the same values must 
128146:         ** have been requested when testing key $P in whereEqualScanEst().  */
128147:         whereKeyStats(pParse, p, pRec, 0, a);
128148:         iLower = a[0];
128149:         iUpper = a[0] + a[1];
128150:       }
128151: 
128152:       assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
128153:       assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
128154:       assert( p->aSortOrder!=0 );
128155:       if( p->aSortOrder[nEq] ){
128156:         /* The roles of pLower and pUpper are swapped for a DESC index */
128157:         SWAP(WhereTerm*, pLower, pUpper);
128158:       }
128159: 
128160:       /* If possible, improve on the iLower estimate using ($P:$L). */
128161:       if( pLower ){
128162:         int bOk;                    /* True if value is extracted from pExpr */
128163:         Expr *pExpr = pLower->pExpr->pRight;
128164:         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
128165:         if( rc==SQLITE_OK && bOk ){
128166:           tRowcnt iNew;
128167:           iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
128168:           iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
128169:           if( iNew>iLower ) iLower = iNew;
128170:           nOut--;
128171:           pLower = 0;
128172:         }
128173:       }
128174: 
128175:       /* If possible, improve on the iUpper estimate using ($P:$U). */
128176:       if( pUpper ){
128177:         int bOk;                    /* True if value is extracted from pExpr */
128178:         Expr *pExpr = pUpper->pExpr->pRight;
128179:         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
128180:         if( rc==SQLITE_OK && bOk ){
128181:           tRowcnt iNew;
128182:           iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
128183:           iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
128184:           if( iNew<iUpper ) iUpper = iNew;
128185:           nOut--;
128186:           pUpper = 0;
128187:         }
128188:       }
128189: 
128190:       pBuilder->pRec = pRec;
128191:       if( rc==SQLITE_OK ){
128192:         if( iUpper>iLower ){
128193:           nNew = sqlite3LogEst(iUpper - iLower);
128194:           /* TUNING:  If both iUpper and iLower are derived from the same
128195:           ** sample, then assume they are 4x more selective.  This brings
128196:           ** the estimated selectivity more in line with what it would be
128197:           ** if estimated without the use of STAT3/4 tables. */
128198:           if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
128199:         }else{
128200:           nNew = 10;        assert( 10==sqlite3LogEst(2) );
128201:         }
128202:         if( nNew<nOut ){
128203:           nOut = nNew;
128204:         }
128205:         WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
128206:                            (u32)iLower, (u32)iUpper, nOut));
128207:       }
128208:     }else{
128209:       int bDone = 0;
128210:       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
128211:       if( bDone ) return rc;
128212:     }
128213:   }
128214: #else
128215:   UNUSED_PARAMETER(pParse);
128216:   UNUSED_PARAMETER(pBuilder);
128217:   assert( pLower || pUpper );
128218: #endif
128219:   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
128220:   nNew = whereRangeAdjust(pLower, nOut);
128221:   nNew = whereRangeAdjust(pUpper, nNew);
128222: 
128223:   /* TUNING: If there is both an upper and lower limit and neither limit
128224:   ** has an application-defined likelihood(), assume the range is
128225:   ** reduced by an additional 75%. This means that, by default, an open-ended
128226:   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
128227:   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
128228:   ** match 1/64 of the index. */ 
128229:   if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
128230:     nNew -= 20;
128231:   }
128232: 
128233:   nOut -= (pLower!=0) + (pUpper!=0);
128234:   if( nNew<10 ) nNew = 10;
128235:   if( nNew<nOut ) nOut = nNew;
128236: #if defined(WHERETRACE_ENABLED)
128237:   if( pLoop->nOut>nOut ){
128238:     WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
128239:                     pLoop->nOut, nOut));
128240:   }
128241: #endif
128242:   pLoop->nOut = (LogEst)nOut;
128243:   return rc;
128244: }
128245: 
128246: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128247: /*
128248: ** Estimate the number of rows that will be returned based on
128249: ** an equality constraint x=VALUE and where that VALUE occurs in
128250: ** the histogram data.  This only works when x is the left-most
128251: ** column of an index and sqlite_stat3 histogram data is available
128252: ** for that index.  When pExpr==NULL that means the constraint is
128253: ** "x IS NULL" instead of "x=VALUE".
128254: **
128255: ** Write the estimated row count into *pnRow and return SQLITE_OK. 
128256: ** If unable to make an estimate, leave *pnRow unchanged and return
128257: ** non-zero.
128258: **
128259: ** This routine can fail if it is unable to load a collating sequence
128260: ** required for string comparison, or if unable to allocate memory
128261: ** for a UTF conversion required for comparison.  The error is stored
128262: ** in the pParse structure.
128263: */
128264: static int whereEqualScanEst(
128265:   Parse *pParse,       /* Parsing & code generating context */
128266:   WhereLoopBuilder *pBuilder,
128267:   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
128268:   tRowcnt *pnRow       /* Write the revised row estimate here */
128269: ){
128270:   Index *p = pBuilder->pNew->u.btree.pIndex;
128271:   int nEq = pBuilder->pNew->u.btree.nEq;
128272:   UnpackedRecord *pRec = pBuilder->pRec;
128273:   u8 aff;                   /* Column affinity */
128274:   int rc;                   /* Subfunction return code */
128275:   tRowcnt a[2];             /* Statistics */
128276:   int bOk;
128277: 
128278:   assert( nEq>=1 );
128279:   assert( nEq<=p->nColumn );
128280:   assert( p->aSample!=0 );
128281:   assert( p->nSample>0 );
128282:   assert( pBuilder->nRecValid<nEq );
128283: 
128284:   /* If values are not available for all fields of the index to the left
128285:   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
128286:   if( pBuilder->nRecValid<(nEq-1) ){
128287:     return SQLITE_NOTFOUND;
128288:   }
128289: 
128290:   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
128291:   ** below would return the same value.  */
128292:   if( nEq>=p->nColumn ){
128293:     *pnRow = 1;
128294:     return SQLITE_OK;
128295:   }
128296: 
128297:   aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
128298:   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
128299:   pBuilder->pRec = pRec;
128300:   if( rc!=SQLITE_OK ) return rc;
128301:   if( bOk==0 ) return SQLITE_NOTFOUND;
128302:   pBuilder->nRecValid = nEq;
128303: 
128304:   whereKeyStats(pParse, p, pRec, 0, a);
128305:   WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
128306:                    p->zName, nEq-1, (int)a[1]));
128307:   *pnRow = a[1];
128308:   
128309:   return rc;
128310: }
128311: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128312: 
128313: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128314: /*
128315: ** Estimate the number of rows that will be returned based on
128316: ** an IN constraint where the right-hand side of the IN operator
128317: ** is a list of values.  Example:
128318: **
128319: **        WHERE x IN (1,2,3,4)
128320: **
128321: ** Write the estimated row count into *pnRow and return SQLITE_OK. 
128322: ** If unable to make an estimate, leave *pnRow unchanged and return
128323: ** non-zero.
128324: **
128325: ** This routine can fail if it is unable to load a collating sequence
128326: ** required for string comparison, or if unable to allocate memory
128327: ** for a UTF conversion required for comparison.  The error is stored
128328: ** in the pParse structure.
128329: */
128330: static int whereInScanEst(
128331:   Parse *pParse,       /* Parsing & code generating context */
128332:   WhereLoopBuilder *pBuilder,
128333:   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
128334:   tRowcnt *pnRow       /* Write the revised row estimate here */
128335: ){
128336:   Index *p = pBuilder->pNew->u.btree.pIndex;
128337:   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
128338:   int nRecValid = pBuilder->nRecValid;
128339:   int rc = SQLITE_OK;     /* Subfunction return code */
128340:   tRowcnt nEst;           /* Number of rows for a single term */
128341:   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
128342:   int i;                  /* Loop counter */
128343: 
128344:   assert( p->aSample!=0 );
128345:   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
128346:     nEst = nRow0;
128347:     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
128348:     nRowEst += nEst;
128349:     pBuilder->nRecValid = nRecValid;
128350:   }
128351: 
128352:   if( rc==SQLITE_OK ){
128353:     if( nRowEst > nRow0 ) nRowEst = nRow0;
128354:     *pnRow = nRowEst;
128355:     WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
128356:   }
128357:   assert( pBuilder->nRecValid==nRecValid );
128358:   return rc;
128359: }
128360: #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
128361: 
128362: 
128363: #ifdef WHERETRACE_ENABLED
128364: /*
128365: ** Print the content of a WhereTerm object
128366: */
128367: static void whereTermPrint(WhereTerm *pTerm, int iTerm){
128368:   if( pTerm==0 ){
128369:     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
128370:   }else{
128371:     char zType[4];
128372:     char zLeft[50];
128373:     memcpy(zType, "...", 4);
128374:     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
128375:     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
128376:     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
128377:     if( pTerm->eOperator & WO_SINGLE ){
128378:       sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
128379:                        pTerm->leftCursor, pTerm->u.leftColumn);
128380:     }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
128381:       sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld", 
128382:                        pTerm->u.pOrInfo->indexable);
128383:     }else{
128384:       sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
128385:     }
128386:     sqlite3DebugPrintf(
128387:        "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x\n",
128388:        iTerm, pTerm, zType, zLeft, pTerm->truthProb,
128389:        pTerm->eOperator, pTerm->wtFlags);
128390:     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
128391:   }
128392: }
128393: #endif
128394: 
128395: #ifdef WHERETRACE_ENABLED
128396: /*
128397: ** Show the complete content of a WhereClause
128398: */
128399: SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
128400:   int i;
128401:   for(i=0; i<pWC->nTerm; i++){
128402:     whereTermPrint(&pWC->a[i], i);
128403:   }
128404: }
128405: #endif
128406: 
128407: #ifdef WHERETRACE_ENABLED
128408: /*
128409: ** Print a WhereLoop object for debugging purposes
128410: */
128411: static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
128412:   WhereInfo *pWInfo = pWC->pWInfo;
128413:   int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
128414:   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
128415:   Table *pTab = pItem->pTab;
128416:   Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
128417:   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
128418:                      p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
128419:   sqlite3DebugPrintf(" %12s",
128420:                      pItem->zAlias ? pItem->zAlias : pTab->zName);
128421:   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
128422:     const char *zName;
128423:     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
128424:       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
128425:         int i = sqlite3Strlen30(zName) - 1;
128426:         while( zName[i]!='_' ) i--;
128427:         zName += i;
128428:       }
128429:       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
128430:     }else{
128431:       sqlite3DebugPrintf("%20s","");
128432:     }
128433:   }else{
128434:     char *z;
128435:     if( p->u.vtab.idxStr ){
128436:       z = sqlite3_mprintf("(%d,\"%s\",%x)",
128437:                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
128438:     }else{
128439:       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
128440:     }
128441:     sqlite3DebugPrintf(" %-19s", z);
128442:     sqlite3_free(z);
128443:   }
128444:   if( p->wsFlags & WHERE_SKIPSCAN ){
128445:     sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
128446:   }else{
128447:     sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
128448:   }
128449:   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
128450:   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
128451:     int i;
128452:     for(i=0; i<p->nLTerm; i++){
128453:       whereTermPrint(p->aLTerm[i], i);
128454:     }
128455:   }
128456: }
128457: #endif
128458: 
128459: /*
128460: ** Convert bulk memory into a valid WhereLoop that can be passed
128461: ** to whereLoopClear harmlessly.
128462: */
128463: static void whereLoopInit(WhereLoop *p){
128464:   p->aLTerm = p->aLTermSpace;
128465:   p->nLTerm = 0;
128466:   p->nLSlot = ArraySize(p->aLTermSpace);
128467:   p->wsFlags = 0;
128468: }
128469: 
128470: /*
128471: ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
128472: */
128473: static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
128474:   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
128475:     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
128476:       sqlite3_free(p->u.vtab.idxStr);
128477:       p->u.vtab.needFree = 0;
128478:       p->u.vtab.idxStr = 0;
128479:     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
128480:       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
128481:       sqlite3DbFree(db, p->u.btree.pIndex);
128482:       p->u.btree.pIndex = 0;
128483:     }
128484:   }
128485: }
128486: 
128487: /*
128488: ** Deallocate internal memory used by a WhereLoop object
128489: */
128490: static void whereLoopClear(sqlite3 *db, WhereLoop *p){
128491:   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
128492:   whereLoopClearUnion(db, p);
128493:   whereLoopInit(p);
128494: }
128495: 
128496: /*
128497: ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
128498: */
128499: static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
128500:   WhereTerm **paNew;
128501:   if( p->nLSlot>=n ) return SQLITE_OK;
128502:   n = (n+7)&~7;
128503:   paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
128504:   if( paNew==0 ) return SQLITE_NOMEM_BKPT;
128505:   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
128506:   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
128507:   p->aLTerm = paNew;
128508:   p->nLSlot = n;
128509:   return SQLITE_OK;
128510: }
128511: 
128512: /*
128513: ** Transfer content from the second pLoop into the first.
128514: */
128515: static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
128516:   whereLoopClearUnion(db, pTo);
128517:   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
128518:     memset(&pTo->u, 0, sizeof(pTo->u));
128519:     return SQLITE_NOMEM_BKPT;
128520:   }
128521:   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
128522:   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
128523:   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
128524:     pFrom->u.vtab.needFree = 0;
128525:   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
128526:     pFrom->u.btree.pIndex = 0;
128527:   }
128528:   return SQLITE_OK;
128529: }
128530: 
128531: /*
128532: ** Delete a WhereLoop object
128533: */
128534: static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
128535:   whereLoopClear(db, p);
128536:   sqlite3DbFree(db, p);
128537: }
128538: 
128539: /*
128540: ** Free a WhereInfo structure
128541: */
128542: static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
128543:   if( ALWAYS(pWInfo) ){
128544:     int i;
128545:     for(i=0; i<pWInfo->nLevel; i++){
128546:       WhereLevel *pLevel = &pWInfo->a[i];
128547:       if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
128548:         sqlite3DbFree(db, pLevel->u.in.aInLoop);
128549:       }
128550:     }
128551:     sqlite3WhereClauseClear(&pWInfo->sWC);
128552:     while( pWInfo->pLoops ){
128553:       WhereLoop *p = pWInfo->pLoops;
128554:       pWInfo->pLoops = p->pNextLoop;
128555:       whereLoopDelete(db, p);
128556:     }
128557:     sqlite3DbFree(db, pWInfo);
128558:   }
128559: }
128560: 
128561: /*
128562: ** Return TRUE if all of the following are true:
128563: **
128564: **   (1)  X has the same or lower cost that Y
128565: **   (2)  X is a proper subset of Y
128566: **   (3)  X skips at least as many columns as Y
128567: **
128568: ** By "proper subset" we mean that X uses fewer WHERE clause terms
128569: ** than Y and that every WHERE clause term used by X is also used
128570: ** by Y.
128571: **
128572: ** If X is a proper subset of Y then Y is a better choice and ought
128573: ** to have a lower cost.  This routine returns TRUE when that cost 
128574: ** relationship is inverted and needs to be adjusted.  The third rule
128575: ** was added because if X uses skip-scan less than Y it still might
128576: ** deserve a lower cost even if it is a proper subset of Y.
128577: */
128578: static int whereLoopCheaperProperSubset(
128579:   const WhereLoop *pX,       /* First WhereLoop to compare */
128580:   const WhereLoop *pY        /* Compare against this WhereLoop */
128581: ){
128582:   int i, j;
128583:   if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
128584:     return 0; /* X is not a subset of Y */
128585:   }
128586:   if( pY->nSkip > pX->nSkip ) return 0;
128587:   if( pX->rRun >= pY->rRun ){
128588:     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
128589:     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
128590:   }
128591:   for(i=pX->nLTerm-1; i>=0; i--){
128592:     if( pX->aLTerm[i]==0 ) continue;
128593:     for(j=pY->nLTerm-1; j>=0; j--){
128594:       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
128595:     }
128596:     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
128597:   }
128598:   return 1;  /* All conditions meet */
128599: }
128600: 
128601: /*
128602: ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
128603: ** that:
128604: **
128605: **   (1) pTemplate costs less than any other WhereLoops that are a proper
128606: **       subset of pTemplate
128607: **
128608: **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
128609: **       is a proper subset.
128610: **
128611: ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
128612: ** WHERE clause terms than Y and that every WHERE clause term used by X is
128613: ** also used by Y.
128614: */
128615: static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
128616:   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
128617:   for(; p; p=p->pNextLoop){
128618:     if( p->iTab!=pTemplate->iTab ) continue;
128619:     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
128620:     if( whereLoopCheaperProperSubset(p, pTemplate) ){
128621:       /* Adjust pTemplate cost downward so that it is cheaper than its 
128622:       ** subset p. */
128623:       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
128624:                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
128625:       pTemplate->rRun = p->rRun;
128626:       pTemplate->nOut = p->nOut - 1;
128627:     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
128628:       /* Adjust pTemplate cost upward so that it is costlier than p since
128629:       ** pTemplate is a proper subset of p */
128630:       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
128631:                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
128632:       pTemplate->rRun = p->rRun;
128633:       pTemplate->nOut = p->nOut + 1;
128634:     }
128635:   }
128636: }
128637: 
128638: /*
128639: ** Search the list of WhereLoops in *ppPrev looking for one that can be
128640: ** supplanted by pTemplate.
128641: **
128642: ** Return NULL if the WhereLoop list contains an entry that can supplant
128643: ** pTemplate, in other words if pTemplate does not belong on the list.
128644: **
128645: ** If pX is a WhereLoop that pTemplate can supplant, then return the
128646: ** link that points to pX.
128647: **
128648: ** If pTemplate cannot supplant any existing element of the list but needs
128649: ** to be added to the list, then return a pointer to the tail of the list.
128650: */
128651: static WhereLoop **whereLoopFindLesser(
128652:   WhereLoop **ppPrev,
128653:   const WhereLoop *pTemplate
128654: ){
128655:   WhereLoop *p;
128656:   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
128657:     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
128658:       /* If either the iTab or iSortIdx values for two WhereLoop are different
128659:       ** then those WhereLoops need to be considered separately.  Neither is
128660:       ** a candidate to replace the other. */
128661:       continue;
128662:     }
128663:     /* In the current implementation, the rSetup value is either zero
128664:     ** or the cost of building an automatic index (NlogN) and the NlogN
128665:     ** is the same for compatible WhereLoops. */
128666:     assert( p->rSetup==0 || pTemplate->rSetup==0 
128667:                  || p->rSetup==pTemplate->rSetup );
128668: 
128669:     /* whereLoopAddBtree() always generates and inserts the automatic index
128670:     ** case first.  Hence compatible candidate WhereLoops never have a larger
128671:     ** rSetup. Call this SETUP-INVARIANT */
128672:     assert( p->rSetup>=pTemplate->rSetup );
128673: 
128674:     /* Any loop using an appliation-defined index (or PRIMARY KEY or
128675:     ** UNIQUE constraint) with one or more == constraints is better
128676:     ** than an automatic index. Unless it is a skip-scan. */
128677:     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
128678:      && (pTemplate->nSkip)==0
128679:      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
128680:      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
128681:      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
128682:     ){
128683:       break;
128684:     }
128685: 
128686:     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
128687:     ** discarded.  WhereLoop p is better if:
128688:     **   (1)  p has no more dependencies than pTemplate, and
128689:     **   (2)  p has an equal or lower cost than pTemplate
128690:     */
128691:     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
128692:      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
128693:      && p->rRun<=pTemplate->rRun                      /* (2b) */
128694:      && p->nOut<=pTemplate->nOut                      /* (2c) */
128695:     ){
128696:       return 0;  /* Discard pTemplate */
128697:     }
128698: 
128699:     /* If pTemplate is always better than p, then cause p to be overwritten
128700:     ** with pTemplate.  pTemplate is better than p if:
128701:     **   (1)  pTemplate has no more dependences than p, and
128702:     **   (2)  pTemplate has an equal or lower cost than p.
128703:     */
128704:     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
128705:      && p->rRun>=pTemplate->rRun                             /* (2a) */
128706:      && p->nOut>=pTemplate->nOut                             /* (2b) */
128707:     ){
128708:       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
128709:       break;   /* Cause p to be overwritten by pTemplate */
128710:     }
128711:   }
128712:   return ppPrev;
128713: }
128714: 
128715: /*
128716: ** Insert or replace a WhereLoop entry using the template supplied.
128717: **
128718: ** An existing WhereLoop entry might be overwritten if the new template
128719: ** is better and has fewer dependencies.  Or the template will be ignored
128720: ** and no insert will occur if an existing WhereLoop is faster and has
128721: ** fewer dependencies than the template.  Otherwise a new WhereLoop is
128722: ** added based on the template.
128723: **
128724: ** If pBuilder->pOrSet is not NULL then we care about only the
128725: ** prerequisites and rRun and nOut costs of the N best loops.  That
128726: ** information is gathered in the pBuilder->pOrSet object.  This special
128727: ** processing mode is used only for OR clause processing.
128728: **
128729: ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
128730: ** still might overwrite similar loops with the new template if the
128731: ** new template is better.  Loops may be overwritten if the following 
128732: ** conditions are met:
128733: **
128734: **    (1)  They have the same iTab.
128735: **    (2)  They have the same iSortIdx.
128736: **    (3)  The template has same or fewer dependencies than the current loop
128737: **    (4)  The template has the same or lower cost than the current loop
128738: */
128739: static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
128740:   WhereLoop **ppPrev, *p;
128741:   WhereInfo *pWInfo = pBuilder->pWInfo;
128742:   sqlite3 *db = pWInfo->pParse->db;
128743:   int rc;
128744: 
128745:   /* If pBuilder->pOrSet is defined, then only keep track of the costs
128746:   ** and prereqs.
128747:   */
128748:   if( pBuilder->pOrSet!=0 ){
128749:     if( pTemplate->nLTerm ){
128750: #if WHERETRACE_ENABLED
128751:       u16 n = pBuilder->pOrSet->n;
128752:       int x =
128753: #endif
128754:       whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
128755:                                     pTemplate->nOut);
128756: #if WHERETRACE_ENABLED /* 0x8 */
128757:       if( sqlite3WhereTrace & 0x8 ){
128758:         sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
128759:         whereLoopPrint(pTemplate, pBuilder->pWC);
128760:       }
128761: #endif
128762:     }
128763:     return SQLITE_OK;
128764:   }
128765: 
128766:   /* Look for an existing WhereLoop to replace with pTemplate
128767:   */
128768:   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
128769:   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
128770: 
128771:   if( ppPrev==0 ){
128772:     /* There already exists a WhereLoop on the list that is better
128773:     ** than pTemplate, so just ignore pTemplate */
128774: #if WHERETRACE_ENABLED /* 0x8 */
128775:     if( sqlite3WhereTrace & 0x8 ){
128776:       sqlite3DebugPrintf("   skip: ");
128777:       whereLoopPrint(pTemplate, pBuilder->pWC);
128778:     }
128779: #endif
128780:     return SQLITE_OK;  
128781:   }else{
128782:     p = *ppPrev;
128783:   }
128784: 
128785:   /* If we reach this point it means that either p[] should be overwritten
128786:   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
128787:   ** WhereLoop and insert it.
128788:   */
128789: #if WHERETRACE_ENABLED /* 0x8 */
128790:   if( sqlite3WhereTrace & 0x8 ){
128791:     if( p!=0 ){
128792:       sqlite3DebugPrintf("replace: ");
128793:       whereLoopPrint(p, pBuilder->pWC);
128794:     }
128795:     sqlite3DebugPrintf("    add: ");
128796:     whereLoopPrint(pTemplate, pBuilder->pWC);
128797:   }
128798: #endif
128799:   if( p==0 ){
128800:     /* Allocate a new WhereLoop to add to the end of the list */
128801:     *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
128802:     if( p==0 ) return SQLITE_NOMEM_BKPT;
128803:     whereLoopInit(p);
128804:     p->pNextLoop = 0;
128805:   }else{
128806:     /* We will be overwriting WhereLoop p[].  But before we do, first
128807:     ** go through the rest of the list and delete any other entries besides
128808:     ** p[] that are also supplated by pTemplate */
128809:     WhereLoop **ppTail = &p->pNextLoop;
128810:     WhereLoop *pToDel;
128811:     while( *ppTail ){
128812:       ppTail = whereLoopFindLesser(ppTail, pTemplate);
128813:       if( ppTail==0 ) break;
128814:       pToDel = *ppTail;
128815:       if( pToDel==0 ) break;
128816:       *ppTail = pToDel->pNextLoop;
128817: #if WHERETRACE_ENABLED /* 0x8 */
128818:       if( sqlite3WhereTrace & 0x8 ){
128819:         sqlite3DebugPrintf(" delete: ");
128820:         whereLoopPrint(pToDel, pBuilder->pWC);
128821:       }
128822: #endif
128823:       whereLoopDelete(db, pToDel);
128824:     }
128825:   }
128826:   rc = whereLoopXfer(db, p, pTemplate);
128827:   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
128828:     Index *pIndex = p->u.btree.pIndex;
128829:     if( pIndex && pIndex->tnum==0 ){
128830:       p->u.btree.pIndex = 0;
128831:     }
128832:   }
128833:   return rc;
128834: }
128835: 
128836: /*
128837: ** Adjust the WhereLoop.nOut value downward to account for terms of the
128838: ** WHERE clause that reference the loop but which are not used by an
128839: ** index.
128840: *
128841: ** For every WHERE clause term that is not used by the index
128842: ** and which has a truth probability assigned by one of the likelihood(),
128843: ** likely(), or unlikely() SQL functions, reduce the estimated number
128844: ** of output rows by the probability specified.
128845: **
128846: ** TUNING:  For every WHERE clause term that is not used by the index
128847: ** and which does not have an assigned truth probability, heuristics
128848: ** described below are used to try to estimate the truth probability.
128849: ** TODO --> Perhaps this is something that could be improved by better
128850: ** table statistics.
128851: **
128852: ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
128853: ** value corresponds to -1 in LogEst notation, so this means decrement
128854: ** the WhereLoop.nOut field for every such WHERE clause term.
128855: **
128856: ** Heuristic 2:  If there exists one or more WHERE clause terms of the
128857: ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
128858: ** final output row estimate is no greater than 1/4 of the total number
128859: ** of rows in the table.  In other words, assume that x==EXPR will filter
128860: ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
128861: ** "x" column is boolean or else -1 or 0 or 1 is a common default value
128862: ** on the "x" column and so in that case only cap the output row estimate
128863: ** at 1/2 instead of 1/4.
128864: */
128865: static void whereLoopOutputAdjust(
128866:   WhereClause *pWC,      /* The WHERE clause */
128867:   WhereLoop *pLoop,      /* The loop to adjust downward */
128868:   LogEst nRow            /* Number of rows in the entire table */
128869: ){
128870:   WhereTerm *pTerm, *pX;
128871:   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
128872:   int i, j, k;
128873:   LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
128874: 
128875:   assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
128876:   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
128877:     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
128878:     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
128879:     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
128880:     for(j=pLoop->nLTerm-1; j>=0; j--){
128881:       pX = pLoop->aLTerm[j];
128882:       if( pX==0 ) continue;
128883:       if( pX==pTerm ) break;
128884:       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
128885:     }
128886:     if( j<0 ){
128887:       if( pTerm->truthProb<=0 ){
128888:         /* If a truth probability is specified using the likelihood() hints,
128889:         ** then use the probability provided by the application. */
128890:         pLoop->nOut += pTerm->truthProb;
128891:       }else{
128892:         /* In the absence of explicit truth probabilities, use heuristics to
128893:         ** guess a reasonable truth probability. */
128894:         pLoop->nOut--;
128895:         if( pTerm->eOperator&(WO_EQ|WO_IS) ){
128896:           Expr *pRight = pTerm->pExpr->pRight;
128897:           testcase( pTerm->pExpr->op==TK_IS );
128898:           if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
128899:             k = 10;
128900:           }else{
128901:             k = 20;
128902:           }
128903:           if( iReduce<k ) iReduce = k;
128904:         }
128905:       }
128906:     }
128907:   }
128908:   if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
128909: }
128910: 
128911: /*
128912: ** Adjust the cost C by the costMult facter T.  This only occurs if
128913: ** compiled with -DSQLITE_ENABLE_COSTMULT
128914: */
128915: #ifdef SQLITE_ENABLE_COSTMULT
128916: # define ApplyCostMultiplier(C,T)  C += T
128917: #else
128918: # define ApplyCostMultiplier(C,T)
128919: #endif
128920: 
128921: /*
128922: ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 
128923: ** index pIndex. Try to match one more.
128924: **
128925: ** When this function is called, pBuilder->pNew->nOut contains the 
128926: ** number of rows expected to be visited by filtering using the nEq 
128927: ** terms only. If it is modified, this value is restored before this 
128928: ** function returns.
128929: **
128930: ** If pProbe->tnum==0, that means pIndex is a fake index used for the
128931: ** INTEGER PRIMARY KEY.
128932: */
128933: static int whereLoopAddBtreeIndex(
128934:   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
128935:   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
128936:   Index *pProbe,                  /* An index on pSrc */
128937:   LogEst nInMul                   /* log(Number of iterations due to IN) */
128938: ){
128939:   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
128940:   Parse *pParse = pWInfo->pParse;        /* Parsing context */
128941:   sqlite3 *db = pParse->db;       /* Database connection malloc context */
128942:   WhereLoop *pNew;                /* Template WhereLoop under construction */
128943:   WhereTerm *pTerm;               /* A WhereTerm under consideration */
128944:   int opMask;                     /* Valid operators for constraints */
128945:   WhereScan scan;                 /* Iterator for WHERE terms */
128946:   Bitmask saved_prereq;           /* Original value of pNew->prereq */
128947:   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
128948:   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
128949:   u16 saved_nSkip;                /* Original value of pNew->nSkip */
128950:   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
128951:   LogEst saved_nOut;              /* Original value of pNew->nOut */
128952:   int rc = SQLITE_OK;             /* Return code */
128953:   LogEst rSize;                   /* Number of rows in the table */
128954:   LogEst rLogSize;                /* Logarithm of table size */
128955:   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
128956: 
128957:   pNew = pBuilder->pNew;
128958:   if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
128959: 
128960:   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
128961:   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
128962:   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
128963:     opMask = WO_LT|WO_LE;
128964:   }else{
128965:     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
128966:   }
128967:   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
128968: 
128969:   assert( pNew->u.btree.nEq<pProbe->nColumn );
128970: 
128971:   saved_nEq = pNew->u.btree.nEq;
128972:   saved_nSkip = pNew->nSkip;
128973:   saved_nLTerm = pNew->nLTerm;
128974:   saved_wsFlags = pNew->wsFlags;
128975:   saved_prereq = pNew->prereq;
128976:   saved_nOut = pNew->nOut;
128977:   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
128978:                         opMask, pProbe);
128979:   pNew->rSetup = 0;
128980:   rSize = pProbe->aiRowLogEst[0];
128981:   rLogSize = estLog(rSize);
128982:   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
128983:     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
128984:     LogEst rCostIdx;
128985:     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
128986:     int nIn = 0;
128987: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128988:     int nRecValid = pBuilder->nRecValid;
128989: #endif
128990:     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
128991:      && indexColumnNotNull(pProbe, saved_nEq)
128992:     ){
128993:       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
128994:     }
128995:     if( pTerm->prereqRight & pNew->maskSelf ) continue;
128996: 
128997:     /* Do not allow the upper bound of a LIKE optimization range constraint
128998:     ** to mix with a lower range bound from some other source */
128999:     if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
129000: 
129001:     /* Do not allow IS constraints from the WHERE clause to be used by the
129002:     ** right table of a LEFT JOIN.  Only constraints in the ON clause are
129003:     ** allowed */
129004:     if( (pSrc->fg.jointype & JT_LEFT)!=0
129005:      && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
129006:      && (eOp & (WO_IS|WO_ISNULL))!=0
129007:     ){
129008:       testcase( eOp & WO_IS );
129009:       testcase( eOp & WO_ISNULL );
129010:       continue;
129011:     }
129012: 
129013:     pNew->wsFlags = saved_wsFlags;
129014:     pNew->u.btree.nEq = saved_nEq;
129015:     pNew->nLTerm = saved_nLTerm;
129016:     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
129017:     pNew->aLTerm[pNew->nLTerm++] = pTerm;
129018:     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
129019: 
129020:     assert( nInMul==0
129021:         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 
129022:         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 
129023:         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 
129024:     );
129025: 
129026:     if( eOp & WO_IN ){
129027:       Expr *pExpr = pTerm->pExpr;
129028:       pNew->wsFlags |= WHERE_COLUMN_IN;
129029:       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
129030:         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
129031:         nIn = 46;  assert( 46==sqlite3LogEst(25) );
129032:       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
129033:         /* "x IN (value, value, ...)" */
129034:         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
129035:       }
129036:       assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
129037:                         ** changes "x IN (?)" into "x=?". */
129038: 
129039:     }else if( eOp & (WO_EQ|WO_IS) ){
129040:       int iCol = pProbe->aiColumn[saved_nEq];
129041:       pNew->wsFlags |= WHERE_COLUMN_EQ;
129042:       assert( saved_nEq==pNew->u.btree.nEq );
129043:       if( iCol==XN_ROWID 
129044:        || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
129045:       ){
129046:         if( iCol>=0 && pProbe->uniqNotNull==0 ){
129047:           pNew->wsFlags |= WHERE_UNQ_WANTED;
129048:         }else{
129049:           pNew->wsFlags |= WHERE_ONEROW;
129050:         }
129051:       }
129052:     }else if( eOp & WO_ISNULL ){
129053:       pNew->wsFlags |= WHERE_COLUMN_NULL;
129054:     }else if( eOp & (WO_GT|WO_GE) ){
129055:       testcase( eOp & WO_GT );
129056:       testcase( eOp & WO_GE );
129057:       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
129058:       pBtm = pTerm;
129059:       pTop = 0;
129060:       if( pTerm->wtFlags & TERM_LIKEOPT ){
129061:         /* Range contraints that come from the LIKE optimization are
129062:         ** always used in pairs. */
129063:         pTop = &pTerm[1];
129064:         assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
129065:         assert( pTop->wtFlags & TERM_LIKEOPT );
129066:         assert( pTop->eOperator==WO_LT );
129067:         if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
129068:         pNew->aLTerm[pNew->nLTerm++] = pTop;
129069:         pNew->wsFlags |= WHERE_TOP_LIMIT;
129070:       }
129071:     }else{
129072:       assert( eOp & (WO_LT|WO_LE) );
129073:       testcase( eOp & WO_LT );
129074:       testcase( eOp & WO_LE );
129075:       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
129076:       pTop = pTerm;
129077:       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
129078:                      pNew->aLTerm[pNew->nLTerm-2] : 0;
129079:     }
129080: 
129081:     /* At this point pNew->nOut is set to the number of rows expected to
129082:     ** be visited by the index scan before considering term pTerm, or the
129083:     ** values of nIn and nInMul. In other words, assuming that all 
129084:     ** "x IN(...)" terms are replaced with "x = ?". This block updates
129085:     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
129086:     assert( pNew->nOut==saved_nOut );
129087:     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
129088:       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
129089:       ** data, using some other estimate.  */
129090:       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
129091:     }else{
129092:       int nEq = ++pNew->u.btree.nEq;
129093:       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
129094: 
129095:       assert( pNew->nOut==saved_nOut );
129096:       if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
129097:         assert( (eOp & WO_IN) || nIn==0 );
129098:         testcase( eOp & WO_IN );
129099:         pNew->nOut += pTerm->truthProb;
129100:         pNew->nOut -= nIn;
129101:       }else{
129102: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129103:         tRowcnt nOut = 0;
129104:         if( nInMul==0 
129105:          && pProbe->nSample 
129106:          && pNew->u.btree.nEq<=pProbe->nSampleCol
129107:          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
129108:         ){
129109:           Expr *pExpr = pTerm->pExpr;
129110:           if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
129111:             testcase( eOp & WO_EQ );
129112:             testcase( eOp & WO_IS );
129113:             testcase( eOp & WO_ISNULL );
129114:             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
129115:           }else{
129116:             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
129117:           }
129118:           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
129119:           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
129120:           if( nOut ){
129121:             pNew->nOut = sqlite3LogEst(nOut);
129122:             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
129123:             pNew->nOut -= nIn;
129124:           }
129125:         }
129126:         if( nOut==0 )
129127: #endif
129128:         {
129129:           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
129130:           if( eOp & WO_ISNULL ){
129131:             /* TUNING: If there is no likelihood() value, assume that a 
129132:             ** "col IS NULL" expression matches twice as many rows 
129133:             ** as (col=?). */
129134:             pNew->nOut += 10;
129135:           }
129136:         }
129137:       }
129138:     }
129139: 
129140:     /* Set rCostIdx to the cost of visiting selected rows in index. Add
129141:     ** it to pNew->rRun, which is currently set to the cost of the index
129142:     ** seek only. Then, if this is a non-covering index, add the cost of
129143:     ** visiting the rows in the main table.  */
129144:     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
129145:     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
129146:     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
129147:       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
129148:     }
129149:     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
129150: 
129151:     nOutUnadjusted = pNew->nOut;
129152:     pNew->rRun += nInMul + nIn;
129153:     pNew->nOut += nInMul + nIn;
129154:     whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
129155:     rc = whereLoopInsert(pBuilder, pNew);
129156: 
129157:     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
129158:       pNew->nOut = saved_nOut;
129159:     }else{
129160:       pNew->nOut = nOutUnadjusted;
129161:     }
129162: 
129163:     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
129164:      && pNew->u.btree.nEq<pProbe->nColumn
129165:     ){
129166:       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
129167:     }
129168:     pNew->nOut = saved_nOut;
129169: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129170:     pBuilder->nRecValid = nRecValid;
129171: #endif
129172:   }
129173:   pNew->prereq = saved_prereq;
129174:   pNew->u.btree.nEq = saved_nEq;
129175:   pNew->nSkip = saved_nSkip;
129176:   pNew->wsFlags = saved_wsFlags;
129177:   pNew->nOut = saved_nOut;
129178:   pNew->nLTerm = saved_nLTerm;
129179: 
129180:   /* Consider using a skip-scan if there are no WHERE clause constraints
129181:   ** available for the left-most terms of the index, and if the average
129182:   ** number of repeats in the left-most terms is at least 18. 
129183:   **
129184:   ** The magic number 18 is selected on the basis that scanning 17 rows
129185:   ** is almost always quicker than an index seek (even though if the index
129186:   ** contains fewer than 2^17 rows we assume otherwise in other parts of
129187:   ** the code). And, even if it is not, it should not be too much slower. 
129188:   ** On the other hand, the extra seeks could end up being significantly
129189:   ** more expensive.  */
129190:   assert( 42==sqlite3LogEst(18) );
129191:   if( saved_nEq==saved_nSkip
129192:    && saved_nEq+1<pProbe->nKeyCol
129193:    && pProbe->noSkipScan==0
129194:    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
129195:    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
129196:   ){
129197:     LogEst nIter;
129198:     pNew->u.btree.nEq++;
129199:     pNew->nSkip++;
129200:     pNew->aLTerm[pNew->nLTerm++] = 0;
129201:     pNew->wsFlags |= WHERE_SKIPSCAN;
129202:     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
129203:     pNew->nOut -= nIter;
129204:     /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
129205:     ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
129206:     nIter += 5;
129207:     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
129208:     pNew->nOut = saved_nOut;
129209:     pNew->u.btree.nEq = saved_nEq;
129210:     pNew->nSkip = saved_nSkip;
129211:     pNew->wsFlags = saved_wsFlags;
129212:   }
129213: 
129214:   return rc;
129215: }
129216: 
129217: /*
129218: ** Return True if it is possible that pIndex might be useful in
129219: ** implementing the ORDER BY clause in pBuilder.
129220: **
129221: ** Return False if pBuilder does not contain an ORDER BY clause or
129222: ** if there is no way for pIndex to be useful in implementing that
129223: ** ORDER BY clause.
129224: */
129225: static int indexMightHelpWithOrderBy(
129226:   WhereLoopBuilder *pBuilder,
129227:   Index *pIndex,
129228:   int iCursor
129229: ){
129230:   ExprList *pOB;
129231:   ExprList *aColExpr;
129232:   int ii, jj;
129233: 
129234:   if( pIndex->bUnordered ) return 0;
129235:   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
129236:   for(ii=0; ii<pOB->nExpr; ii++){
129237:     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
129238:     if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
129239:       if( pExpr->iColumn<0 ) return 1;
129240:       for(jj=0; jj<pIndex->nKeyCol; jj++){
129241:         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
129242:       }
129243:     }else if( (aColExpr = pIndex->aColExpr)!=0 ){
129244:       for(jj=0; jj<pIndex->nKeyCol; jj++){
129245:         if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
129246:         if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
129247:           return 1;
129248:         }
129249:       }
129250:     }
129251:   }
129252:   return 0;
129253: }
129254: 
129255: /*
129256: ** Return a bitmask where 1s indicate that the corresponding column of
129257: ** the table is used by an index.  Only the first 63 columns are considered.
129258: */
129259: static Bitmask columnsInIndex(Index *pIdx){
129260:   Bitmask m = 0;
129261:   int j;
129262:   for(j=pIdx->nColumn-1; j>=0; j--){
129263:     int x = pIdx->aiColumn[j];
129264:     if( x>=0 ){
129265:       testcase( x==BMS-1 );
129266:       testcase( x==BMS-2 );
129267:       if( x<BMS-1 ) m |= MASKBIT(x);
129268:     }
129269:   }
129270:   return m;
129271: }
129272: 
129273: /* Check to see if a partial index with pPartIndexWhere can be used
129274: ** in the current query.  Return true if it can be and false if not.
129275: */
129276: static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
129277:   int i;
129278:   WhereTerm *pTerm;
129279:   while( pWhere->op==TK_AND ){
129280:     if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
129281:     pWhere = pWhere->pRight;
129282:   }
129283:   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
129284:     Expr *pExpr = pTerm->pExpr;
129285:     if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab) 
129286:      && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
129287:     ){
129288:       return 1;
129289:     }
129290:   }
129291:   return 0;
129292: }
129293: 
129294: /*
129295: ** Add all WhereLoop objects for a single table of the join where the table
129296: ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
129297: ** a b-tree table, not a virtual table.
129298: **
129299: ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
129300: ** are calculated as follows:
129301: **
129302: ** For a full scan, assuming the table (or index) contains nRow rows:
129303: **
129304: **     cost = nRow * 3.0                    // full-table scan
129305: **     cost = nRow * K                      // scan of covering index
129306: **     cost = nRow * (K+3.0)                // scan of non-covering index
129307: **
129308: ** where K is a value between 1.1 and 3.0 set based on the relative 
129309: ** estimated average size of the index and table records.
129310: **
129311: ** For an index scan, where nVisit is the number of index rows visited
129312: ** by the scan, and nSeek is the number of seek operations required on 
129313: ** the index b-tree:
129314: **
129315: **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
129316: **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
129317: **
129318: ** Normally, nSeek is 1. nSeek values greater than 1 come about if the 
129319: ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 
129320: ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
129321: **
129322: ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
129323: ** of uncertainty.  For this reason, scoring is designed to pick plans that
129324: ** "do the least harm" if the estimates are inaccurate.  For example, a
129325: ** log(nRow) factor is omitted from a non-covering index scan in order to
129326: ** bias the scoring in favor of using an index, since the worst-case
129327: ** performance of using an index is far better than the worst-case performance
129328: ** of a full table scan.
129329: */
129330: static int whereLoopAddBtree(
129331:   WhereLoopBuilder *pBuilder, /* WHERE clause information */
129332:   Bitmask mPrereq             /* Extra prerequesites for using this table */
129333: ){
129334:   WhereInfo *pWInfo;          /* WHERE analysis context */
129335:   Index *pProbe;              /* An index we are evaluating */
129336:   Index sPk;                  /* A fake index object for the primary key */
129337:   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
129338:   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
129339:   SrcList *pTabList;          /* The FROM clause */
129340:   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
129341:   WhereLoop *pNew;            /* Template WhereLoop object */
129342:   int rc = SQLITE_OK;         /* Return code */
129343:   int iSortIdx = 1;           /* Index number */
129344:   int b;                      /* A boolean value */
129345:   LogEst rSize;               /* number of rows in the table */
129346:   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
129347:   WhereClause *pWC;           /* The parsed WHERE clause */
129348:   Table *pTab;                /* Table being queried */
129349:   
129350:   pNew = pBuilder->pNew;
129351:   pWInfo = pBuilder->pWInfo;
129352:   pTabList = pWInfo->pTabList;
129353:   pSrc = pTabList->a + pNew->iTab;
129354:   pTab = pSrc->pTab;
129355:   pWC = pBuilder->pWC;
129356:   assert( !IsVirtual(pSrc->pTab) );
129357: 
129358:   if( pSrc->pIBIndex ){
129359:     /* An INDEXED BY clause specifies a particular index to use */
129360:     pProbe = pSrc->pIBIndex;
129361:   }else if( !HasRowid(pTab) ){
129362:     pProbe = pTab->pIndex;
129363:   }else{
129364:     /* There is no INDEXED BY clause.  Create a fake Index object in local
129365:     ** variable sPk to represent the rowid primary key index.  Make this
129366:     ** fake index the first in a chain of Index objects with all of the real
129367:     ** indices to follow */
129368:     Index *pFirst;                  /* First of real indices on the table */
129369:     memset(&sPk, 0, sizeof(Index));
129370:     sPk.nKeyCol = 1;
129371:     sPk.nColumn = 1;
129372:     sPk.aiColumn = &aiColumnPk;
129373:     sPk.aiRowLogEst = aiRowEstPk;
129374:     sPk.onError = OE_Replace;
129375:     sPk.pTable = pTab;
129376:     sPk.szIdxRow = pTab->szTabRow;
129377:     aiRowEstPk[0] = pTab->nRowLogEst;
129378:     aiRowEstPk[1] = 0;
129379:     pFirst = pSrc->pTab->pIndex;
129380:     if( pSrc->fg.notIndexed==0 ){
129381:       /* The real indices of the table are only considered if the
129382:       ** NOT INDEXED qualifier is omitted from the FROM clause */
129383:       sPk.pNext = pFirst;
129384:     }
129385:     pProbe = &sPk;
129386:   }
129387:   rSize = pTab->nRowLogEst;
129388:   rLogSize = estLog(rSize);
129389: 
129390: #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
129391:   /* Automatic indexes */
129392:   if( !pBuilder->pOrSet      /* Not part of an OR optimization */
129393:    && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
129394:    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
129395:    && pSrc->pIBIndex==0      /* Has no INDEXED BY clause */
129396:    && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
129397:    && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
129398:    && !pSrc->fg.isCorrelated /* Not a correlated subquery */
129399:    && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
129400:   ){
129401:     /* Generate auto-index WhereLoops */
129402:     WhereTerm *pTerm;
129403:     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
129404:     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
129405:       if( pTerm->prereqRight & pNew->maskSelf ) continue;
129406:       if( termCanDriveIndex(pTerm, pSrc, 0) ){
129407:         pNew->u.btree.nEq = 1;
129408:         pNew->nSkip = 0;
129409:         pNew->u.btree.pIndex = 0;
129410:         pNew->nLTerm = 1;
129411:         pNew->aLTerm[0] = pTerm;
129412:         /* TUNING: One-time cost for computing the automatic index is
129413:         ** estimated to be X*N*log2(N) where N is the number of rows in
129414:         ** the table being indexed and where X is 7 (LogEst=28) for normal
129415:         ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
129416:         ** of X is smaller for views and subqueries so that the query planner
129417:         ** will be more aggressive about generating automatic indexes for
129418:         ** those objects, since there is no opportunity to add schema
129419:         ** indexes on subqueries and views. */
129420:         pNew->rSetup = rLogSize + rSize + 4;
129421:         if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
129422:           pNew->rSetup += 24;
129423:         }
129424:         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
129425:         if( pNew->rSetup<0 ) pNew->rSetup = 0;
129426:         /* TUNING: Each index lookup yields 20 rows in the table.  This
129427:         ** is more than the usual guess of 10 rows, since we have no way
129428:         ** of knowing how selective the index will ultimately be.  It would
129429:         ** not be unreasonable to make this value much larger. */
129430:         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
129431:         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
129432:         pNew->wsFlags = WHERE_AUTO_INDEX;
129433:         pNew->prereq = mPrereq | pTerm->prereqRight;
129434:         rc = whereLoopInsert(pBuilder, pNew);
129435:       }
129436:     }
129437:   }
129438: #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
129439: 
129440:   /* Loop over all indices
129441:   */
129442:   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
129443:     if( pProbe->pPartIdxWhere!=0
129444:      && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
129445:       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
129446:       continue;  /* Partial index inappropriate for this query */
129447:     }
129448:     rSize = pProbe->aiRowLogEst[0];
129449:     pNew->u.btree.nEq = 0;
129450:     pNew->nSkip = 0;
129451:     pNew->nLTerm = 0;
129452:     pNew->iSortIdx = 0;
129453:     pNew->rSetup = 0;
129454:     pNew->prereq = mPrereq;
129455:     pNew->nOut = rSize;
129456:     pNew->u.btree.pIndex = pProbe;
129457:     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
129458:     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
129459:     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
129460:     if( pProbe->tnum<=0 ){
129461:       /* Integer primary key index */
129462:       pNew->wsFlags = WHERE_IPK;
129463: 
129464:       /* Full table scan */
129465:       pNew->iSortIdx = b ? iSortIdx : 0;
129466:       /* TUNING: Cost of full table scan is (N*3.0). */
129467:       pNew->rRun = rSize + 16;
129468:       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
129469:       whereLoopOutputAdjust(pWC, pNew, rSize);
129470:       rc = whereLoopInsert(pBuilder, pNew);
129471:       pNew->nOut = rSize;
129472:       if( rc ) break;
129473:     }else{
129474:       Bitmask m;
129475:       if( pProbe->isCovering ){
129476:         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
129477:         m = 0;
129478:       }else{
129479:         m = pSrc->colUsed & ~columnsInIndex(pProbe);
129480:         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
129481:       }
129482: 
129483:       /* Full scan via index */
129484:       if( b
129485:        || !HasRowid(pTab)
129486:        || pProbe->pPartIdxWhere!=0
129487:        || ( m==0
129488:          && pProbe->bUnordered==0
129489:          && (pProbe->szIdxRow<pTab->szTabRow)
129490:          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
129491:          && sqlite3GlobalConfig.bUseCis
129492:          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
129493:           )
129494:       ){
129495:         pNew->iSortIdx = b ? iSortIdx : 0;
129496: 
129497:         /* The cost of visiting the index rows is N*K, where K is
129498:         ** between 1.1 and 3.0, depending on the relative sizes of the
129499:         ** index and table rows. */
129500:         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
129501:         if( m!=0 ){
129502:           /* If this is a non-covering index scan, add in the cost of
129503:           ** doing table lookups.  The cost will be 3x the number of
129504:           ** lookups.  Take into account WHERE clause terms that can be
129505:           ** satisfied using just the index, and that do not require a
129506:           ** table lookup. */
129507:           LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
129508:           int ii;
129509:           int iCur = pSrc->iCursor;
129510:           WhereClause *pWC2 = &pWInfo->sWC;
129511:           for(ii=0; ii<pWC2->nTerm; ii++){
129512:             WhereTerm *pTerm = &pWC2->a[ii];
129513:             if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
129514:               break;
129515:             }
129516:             /* pTerm can be evaluated using just the index.  So reduce
129517:             ** the expected number of table lookups accordingly */
129518:             if( pTerm->truthProb<=0 ){
129519:               nLookup += pTerm->truthProb;
129520:             }else{
129521:               nLookup--;
129522:               if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
129523:             }
129524:           }
129525:           
129526:           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
129527:         }
129528:         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
129529:         whereLoopOutputAdjust(pWC, pNew, rSize);
129530:         rc = whereLoopInsert(pBuilder, pNew);
129531:         pNew->nOut = rSize;
129532:         if( rc ) break;
129533:       }
129534:     }
129535: 
129536:     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
129537: #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
129538:     sqlite3Stat4ProbeFree(pBuilder->pRec);
129539:     pBuilder->nRecValid = 0;
129540:     pBuilder->pRec = 0;
129541: #endif
129542: 
129543:     /* If there was an INDEXED BY clause, then only that one index is
129544:     ** considered. */
129545:     if( pSrc->pIBIndex ) break;
129546:   }
129547:   return rc;
129548: }
129549: 
129550: #ifndef SQLITE_OMIT_VIRTUALTABLE
129551: 
129552: /*
129553: ** Argument pIdxInfo is already populated with all constraints that may
129554: ** be used by the virtual table identified by pBuilder->pNew->iTab. This
129555: ** function marks a subset of those constraints usable, invokes the
129556: ** xBestIndex method and adds the returned plan to pBuilder.
129557: **
129558: ** A constraint is marked usable if:
129559: **
129560: **   * Argument mUsable indicates that its prerequisites are available, and
129561: **
129562: **   * It is not one of the operators specified in the mExclude mask passed
129563: **     as the fourth argument (which in practice is either WO_IN or 0).
129564: **
129565: ** Argument mPrereq is a mask of tables that must be scanned before the
129566: ** virtual table in question. These are added to the plans prerequisites
129567: ** before it is added to pBuilder.
129568: **
129569: ** Output parameter *pbIn is set to true if the plan added to pBuilder
129570: ** uses one or more WO_IN terms, or false otherwise.
129571: */
129572: static int whereLoopAddVirtualOne(
129573:   WhereLoopBuilder *pBuilder,
129574:   Bitmask mPrereq,                /* Mask of tables that must be used. */
129575:   Bitmask mUsable,                /* Mask of usable tables */
129576:   u16 mExclude,                   /* Exclude terms using these operators */
129577:   sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
129578:   int *pbIn                       /* OUT: True if plan uses an IN(...) op */
129579: ){
129580:   WhereClause *pWC = pBuilder->pWC;
129581:   struct sqlite3_index_constraint *pIdxCons;
129582:   struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
129583:   int i;
129584:   int mxTerm;
129585:   int rc = SQLITE_OK;
129586:   WhereLoop *pNew = pBuilder->pNew;
129587:   Parse *pParse = pBuilder->pWInfo->pParse;
129588:   struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
129589:   int nConstraint = pIdxInfo->nConstraint;
129590: 
129591:   assert( (mUsable & mPrereq)==mPrereq );
129592:   *pbIn = 0;
129593:   pNew->prereq = mPrereq;
129594: 
129595:   /* Set the usable flag on the subset of constraints identified by 
129596:   ** arguments mUsable and mExclude. */
129597:   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
129598:   for(i=0; i<nConstraint; i++, pIdxCons++){
129599:     WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
129600:     pIdxCons->usable = 0;
129601:     if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight 
129602:      && (pTerm->eOperator & mExclude)==0
129603:     ){
129604:       pIdxCons->usable = 1;
129605:     }
129606:   }
129607: 
129608:   /* Initialize the output fields of the sqlite3_index_info structure */
129609:   memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
129610:   assert( pIdxInfo->needToFreeIdxStr==0 );
129611:   pIdxInfo->idxStr = 0;
129612:   pIdxInfo->idxNum = 0;
129613:   pIdxInfo->orderByConsumed = 0;
129614:   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
129615:   pIdxInfo->estimatedRows = 25;
129616:   pIdxInfo->idxFlags = 0;
129617:   pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
129618: 
129619:   /* Invoke the virtual table xBestIndex() method */
129620:   rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
129621:   if( rc ) return rc;
129622: 
129623:   mxTerm = -1;
129624:   assert( pNew->nLSlot>=nConstraint );
129625:   for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
129626:   pNew->u.vtab.omitMask = 0;
129627:   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
129628:   for(i=0; i<nConstraint; i++, pIdxCons++){
129629:     int iTerm;
129630:     if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
129631:       WhereTerm *pTerm;
129632:       int j = pIdxCons->iTermOffset;
129633:       if( iTerm>=nConstraint
129634:        || j<0
129635:        || j>=pWC->nTerm
129636:        || pNew->aLTerm[iTerm]!=0
129637:        || pIdxCons->usable==0
129638:       ){
129639:         rc = SQLITE_ERROR;
129640:         sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
129641:         return rc;
129642:       }
129643:       testcase( iTerm==nConstraint-1 );
129644:       testcase( j==0 );
129645:       testcase( j==pWC->nTerm-1 );
129646:       pTerm = &pWC->a[j];
129647:       pNew->prereq |= pTerm->prereqRight;
129648:       assert( iTerm<pNew->nLSlot );
129649:       pNew->aLTerm[iTerm] = pTerm;
129650:       if( iTerm>mxTerm ) mxTerm = iTerm;
129651:       testcase( iTerm==15 );
129652:       testcase( iTerm==16 );
129653:       if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
129654:       if( (pTerm->eOperator & WO_IN)!=0 ){
129655:         /* A virtual table that is constrained by an IN clause may not
129656:         ** consume the ORDER BY clause because (1) the order of IN terms
129657:         ** is not necessarily related to the order of output terms and
129658:         ** (2) Multiple outputs from a single IN value will not merge
129659:         ** together.  */
129660:         pIdxInfo->orderByConsumed = 0;
129661:         pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
129662:         *pbIn = 1; assert( (mExclude & WO_IN)==0 );
129663:       }
129664:     }
129665:   }
129666: 
129667:   pNew->nLTerm = mxTerm+1;
129668:   assert( pNew->nLTerm<=pNew->nLSlot );
129669:   pNew->u.vtab.idxNum = pIdxInfo->idxNum;
129670:   pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
129671:   pIdxInfo->needToFreeIdxStr = 0;
129672:   pNew->u.vtab.idxStr = pIdxInfo->idxStr;
129673:   pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
129674:       pIdxInfo->nOrderBy : 0);
129675:   pNew->rSetup = 0;
129676:   pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
129677:   pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
129678: 
129679:   /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
129680:   ** that the scan will visit at most one row. Clear it otherwise. */
129681:   if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
129682:     pNew->wsFlags |= WHERE_ONEROW;
129683:   }else{
129684:     pNew->wsFlags &= ~WHERE_ONEROW;
129685:   }
129686:   rc = whereLoopInsert(pBuilder, pNew);
129687:   if( pNew->u.vtab.needFree ){
129688:     sqlite3_free(pNew->u.vtab.idxStr);
129689:     pNew->u.vtab.needFree = 0;
129690:   }
129691:   WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
129692:                       *pbIn, (sqlite3_uint64)mPrereq,
129693:                       (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
129694: 
129695:   return rc;
129696: }
129697: 
129698: 
129699: /*
129700: ** Add all WhereLoop objects for a table of the join identified by
129701: ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
129702: **
129703: ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
129704: ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
129705: ** entries that occur before the virtual table in the FROM clause and are
129706: ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
129707: ** mUnusable mask contains all FROM clause entries that occur after the
129708: ** virtual table and are separated from it by at least one LEFT or 
129709: ** CROSS JOIN. 
129710: **
129711: ** For example, if the query were:
129712: **
129713: **   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
129714: **
129715: ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
129716: **
129717: ** All the tables in mPrereq must be scanned before the current virtual 
129718: ** table. So any terms for which all prerequisites are satisfied by 
129719: ** mPrereq may be specified as "usable" in all calls to xBestIndex. 
129720: ** Conversely, all tables in mUnusable must be scanned after the current
129721: ** virtual table, so any terms for which the prerequisites overlap with
129722: ** mUnusable should always be configured as "not-usable" for xBestIndex.
129723: */
129724: static int whereLoopAddVirtual(
129725:   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
129726:   Bitmask mPrereq,             /* Tables that must be scanned before this one */
129727:   Bitmask mUnusable            /* Tables that must be scanned after this one */
129728: ){
129729:   int rc = SQLITE_OK;          /* Return code */
129730:   WhereInfo *pWInfo;           /* WHERE analysis context */
129731:   Parse *pParse;               /* The parsing context */
129732:   WhereClause *pWC;            /* The WHERE clause */
129733:   struct SrcList_item *pSrc;   /* The FROM clause term to search */
129734:   sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
129735:   int nConstraint;             /* Number of constraints in p */
129736:   int bIn;                     /* True if plan uses IN(...) operator */
129737:   WhereLoop *pNew;
129738:   Bitmask mBest;               /* Tables used by best possible plan */
129739: 
129740:   assert( (mPrereq & mUnusable)==0 );
129741:   pWInfo = pBuilder->pWInfo;
129742:   pParse = pWInfo->pParse;
129743:   pWC = pBuilder->pWC;
129744:   pNew = pBuilder->pNew;
129745:   pSrc = &pWInfo->pTabList->a[pNew->iTab];
129746:   assert( IsVirtual(pSrc->pTab) );
129747:   p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy);
129748:   if( p==0 ) return SQLITE_NOMEM_BKPT;
129749:   pNew->rSetup = 0;
129750:   pNew->wsFlags = WHERE_VIRTUALTABLE;
129751:   pNew->nLTerm = 0;
129752:   pNew->u.vtab.needFree = 0;
129753:   nConstraint = p->nConstraint;
129754:   if( whereLoopResize(pParse->db, pNew, nConstraint) ){
129755:     sqlite3DbFree(pParse->db, p);
129756:     return SQLITE_NOMEM_BKPT;
129757:   }
129758: 
129759:   /* First call xBestIndex() with all constraints usable. */
129760:   WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
129761:   rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, &bIn);
129762: 
129763:   /* If the call to xBestIndex() with all terms enabled produced a plan
129764:   ** that does not require any source tables (IOW: a plan with mBest==0),
129765:   ** then there is no point in making any further calls to xBestIndex() 
129766:   ** since they will all return the same result (if the xBestIndex()
129767:   ** implementation is sane). */
129768:   if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
129769:     int seenZero = 0;             /* True if a plan with no prereqs seen */
129770:     int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
129771:     Bitmask mPrev = 0;
129772:     Bitmask mBestNoIn = 0;
129773: 
129774:     /* If the plan produced by the earlier call uses an IN(...) term, call
129775:     ** xBestIndex again, this time with IN(...) terms disabled. */
129776:     if( bIn ){
129777:       WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
129778:       rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, WO_IN, p, &bIn);
129779:       assert( bIn==0 );
129780:       mBestNoIn = pNew->prereq & ~mPrereq;
129781:       if( mBestNoIn==0 ){
129782:         seenZero = 1;
129783:         seenZeroNoIN = 1;
129784:       }
129785:     }
129786: 
129787:     /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq) 
129788:     ** in the set of terms that apply to the current virtual table.  */
129789:     while( rc==SQLITE_OK ){
129790:       int i;
129791:       Bitmask mNext = ALLBITS;
129792:       assert( mNext>0 );
129793:       for(i=0; i<nConstraint; i++){
129794:         Bitmask mThis = (
129795:             pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
129796:         );
129797:         if( mThis>mPrev && mThis<mNext ) mNext = mThis;
129798:       }
129799:       mPrev = mNext;
129800:       if( mNext==ALLBITS ) break;
129801:       if( mNext==mBest || mNext==mBestNoIn ) continue;
129802:       WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
129803:                        (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
129804:       rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mNext|mPrereq, 0, p, &bIn);
129805:       if( pNew->prereq==mPrereq ){
129806:         seenZero = 1;
129807:         if( bIn==0 ) seenZeroNoIN = 1;
129808:       }
129809:     }
129810: 
129811:     /* If the calls to xBestIndex() in the above loop did not find a plan
129812:     ** that requires no source tables at all (i.e. one guaranteed to be
129813:     ** usable), make a call here with all source tables disabled */
129814:     if( rc==SQLITE_OK && seenZero==0 ){
129815:       WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
129816:       rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, 0, p, &bIn);
129817:       if( bIn==0 ) seenZeroNoIN = 1;
129818:     }
129819: 
129820:     /* If the calls to xBestIndex() have so far failed to find a plan
129821:     ** that requires no source tables at all and does not use an IN(...)
129822:     ** operator, make a final call to obtain one here.  */
129823:     if( rc==SQLITE_OK && seenZeroNoIN==0 ){
129824:       WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
129825:       rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, WO_IN, p, &bIn);
129826:     }
129827:   }
129828: 
129829:   if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
129830:   sqlite3DbFree(pParse->db, p);
129831:   return rc;
129832: }
129833: #endif /* SQLITE_OMIT_VIRTUALTABLE */
129834: 
129835: /*
129836: ** Add WhereLoop entries to handle OR terms.  This works for either
129837: ** btrees or virtual tables.
129838: */
129839: static int whereLoopAddOr(
129840:   WhereLoopBuilder *pBuilder, 
129841:   Bitmask mPrereq, 
129842:   Bitmask mUnusable
129843: ){
129844:   WhereInfo *pWInfo = pBuilder->pWInfo;
129845:   WhereClause *pWC;
129846:   WhereLoop *pNew;
129847:   WhereTerm *pTerm, *pWCEnd;
129848:   int rc = SQLITE_OK;
129849:   int iCur;
129850:   WhereClause tempWC;
129851:   WhereLoopBuilder sSubBuild;
129852:   WhereOrSet sSum, sCur;
129853:   struct SrcList_item *pItem;
129854:   
129855:   pWC = pBuilder->pWC;
129856:   pWCEnd = pWC->a + pWC->nTerm;
129857:   pNew = pBuilder->pNew;
129858:   memset(&sSum, 0, sizeof(sSum));
129859:   pItem = pWInfo->pTabList->a + pNew->iTab;
129860:   iCur = pItem->iCursor;
129861: 
129862:   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
129863:     if( (pTerm->eOperator & WO_OR)!=0
129864:      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 
129865:     ){
129866:       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
129867:       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
129868:       WhereTerm *pOrTerm;
129869:       int once = 1;
129870:       int i, j;
129871:     
129872:       sSubBuild = *pBuilder;
129873:       sSubBuild.pOrderBy = 0;
129874:       sSubBuild.pOrSet = &sCur;
129875: 
129876:       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
129877:       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
129878:         if( (pOrTerm->eOperator & WO_AND)!=0 ){
129879:           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
129880:         }else if( pOrTerm->leftCursor==iCur ){
129881:           tempWC.pWInfo = pWC->pWInfo;
129882:           tempWC.pOuter = pWC;
129883:           tempWC.op = TK_AND;
129884:           tempWC.nTerm = 1;
129885:           tempWC.a = pOrTerm;
129886:           sSubBuild.pWC = &tempWC;
129887:         }else{
129888:           continue;
129889:         }
129890:         sCur.n = 0;
129891: #ifdef WHERETRACE_ENABLED
129892:         WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", 
129893:                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
129894:         if( sqlite3WhereTrace & 0x400 ){
129895:           sqlite3WhereClausePrint(sSubBuild.pWC);
129896:         }
129897: #endif
129898: #ifndef SQLITE_OMIT_VIRTUALTABLE
129899:         if( IsVirtual(pItem->pTab) ){
129900:           rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
129901:         }else
129902: #endif
129903:         {
129904:           rc = whereLoopAddBtree(&sSubBuild, mPrereq);
129905:         }
129906:         if( rc==SQLITE_OK ){
129907:           rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
129908:         }
129909:         assert( rc==SQLITE_OK || sCur.n==0 );
129910:         if( sCur.n==0 ){
129911:           sSum.n = 0;
129912:           break;
129913:         }else if( once ){
129914:           whereOrMove(&sSum, &sCur);
129915:           once = 0;
129916:         }else{
129917:           WhereOrSet sPrev;
129918:           whereOrMove(&sPrev, &sSum);
129919:           sSum.n = 0;
129920:           for(i=0; i<sPrev.n; i++){
129921:             for(j=0; j<sCur.n; j++){
129922:               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
129923:                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
129924:                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
129925:             }
129926:           }
129927:         }
129928:       }
129929:       pNew->nLTerm = 1;
129930:       pNew->aLTerm[0] = pTerm;
129931:       pNew->wsFlags = WHERE_MULTI_OR;
129932:       pNew->rSetup = 0;
129933:       pNew->iSortIdx = 0;
129934:       memset(&pNew->u, 0, sizeof(pNew->u));
129935:       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
129936:         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
129937:         ** of all sub-scans required by the OR-scan. However, due to rounding
129938:         ** errors, it may be that the cost of the OR-scan is equal to its
129939:         ** most expensive sub-scan. Add the smallest possible penalty 
129940:         ** (equivalent to multiplying the cost by 1.07) to ensure that 
129941:         ** this does not happen. Otherwise, for WHERE clauses such as the
129942:         ** following where there is an index on "y":
129943:         **
129944:         **     WHERE likelihood(x=?, 0.99) OR y=?
129945:         **
129946:         ** the planner may elect to "OR" together a full-table scan and an
129947:         ** index lookup. And other similarly odd results.  */
129948:         pNew->rRun = sSum.a[i].rRun + 1;
129949:         pNew->nOut = sSum.a[i].nOut;
129950:         pNew->prereq = sSum.a[i].prereq;
129951:         rc = whereLoopInsert(pBuilder, pNew);
129952:       }
129953:       WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
129954:     }
129955:   }
129956:   return rc;
129957: }
129958: 
129959: /*
129960: ** Add all WhereLoop objects for all tables 
129961: */
129962: static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
129963:   WhereInfo *pWInfo = pBuilder->pWInfo;
129964:   Bitmask mPrereq = 0;
129965:   Bitmask mPrior = 0;
129966:   int iTab;
129967:   SrcList *pTabList = pWInfo->pTabList;
129968:   struct SrcList_item *pItem;
129969:   struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
129970:   sqlite3 *db = pWInfo->pParse->db;
129971:   int rc = SQLITE_OK;
129972:   WhereLoop *pNew;
129973:   u8 priorJointype = 0;
129974: 
129975:   /* Loop over the tables in the join, from left to right */
129976:   pNew = pBuilder->pNew;
129977:   whereLoopInit(pNew);
129978:   for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
129979:     Bitmask mUnusable = 0;
129980:     pNew->iTab = iTab;
129981:     pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
129982:     if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
129983:       /* This condition is true when pItem is the FROM clause term on the
129984:       ** right-hand-side of a LEFT or CROSS JOIN.  */
129985:       mPrereq = mPrior;
129986:     }
129987:     priorJointype = pItem->fg.jointype;
129988: #ifndef SQLITE_OMIT_VIRTUALTABLE
129989:     if( IsVirtual(pItem->pTab) ){
129990:       struct SrcList_item *p;
129991:       for(p=&pItem[1]; p<pEnd; p++){
129992:         if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
129993:           mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
129994:         }
129995:       }
129996:       rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
129997:     }else
129998: #endif /* SQLITE_OMIT_VIRTUALTABLE */
129999:     {
130000:       rc = whereLoopAddBtree(pBuilder, mPrereq);
130001:     }
130002:     if( rc==SQLITE_OK ){
130003:       rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
130004:     }
130005:     mPrior |= pNew->maskSelf;
130006:     if( rc || db->mallocFailed ) break;
130007:   }
130008: 
130009:   whereLoopClear(db, pNew);
130010:   return rc;
130011: }
130012: 
130013: /*
130014: ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
130015: ** parameters) to see if it outputs rows in the requested ORDER BY
130016: ** (or GROUP BY) without requiring a separate sort operation.  Return N:
130017: ** 
130018: **   N>0:   N terms of the ORDER BY clause are satisfied
130019: **   N==0:  No terms of the ORDER BY clause are satisfied
130020: **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.   
130021: **
130022: ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
130023: ** strict.  With GROUP BY and DISTINCT the only requirement is that
130024: ** equivalent rows appear immediately adjacent to one another.  GROUP BY
130025: ** and DISTINCT do not require rows to appear in any particular order as long
130026: ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
130027: ** the pOrderBy terms can be matched in any order.  With ORDER BY, the 
130028: ** pOrderBy terms must be matched in strict left-to-right order.
130029: */
130030: static i8 wherePathSatisfiesOrderBy(
130031:   WhereInfo *pWInfo,    /* The WHERE clause */
130032:   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
130033:   WherePath *pPath,     /* The WherePath to check */
130034:   u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
130035:   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
130036:   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
130037:   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
130038: ){
130039:   u8 revSet;            /* True if rev is known */
130040:   u8 rev;               /* Composite sort order */
130041:   u8 revIdx;            /* Index sort order */
130042:   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
130043:   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
130044:   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
130045:   u16 eqOpMask;         /* Allowed equality operators */
130046:   u16 nKeyCol;          /* Number of key columns in pIndex */
130047:   u16 nColumn;          /* Total number of ordered columns in the index */
130048:   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
130049:   int iLoop;            /* Index of WhereLoop in pPath being processed */
130050:   int i, j;             /* Loop counters */
130051:   int iCur;             /* Cursor number for current WhereLoop */
130052:   int iColumn;          /* A column number within table iCur */
130053:   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
130054:   WhereTerm *pTerm;     /* A single term of the WHERE clause */
130055:   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
130056:   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
130057:   Index *pIndex;        /* The index associated with pLoop */
130058:   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
130059:   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
130060:   Bitmask obDone;       /* Mask of all ORDER BY terms */
130061:   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
130062:   Bitmask ready;              /* Mask of inner loops */
130063: 
130064:   /*
130065:   ** We say the WhereLoop is "one-row" if it generates no more than one
130066:   ** row of output.  A WhereLoop is one-row if all of the following are true:
130067:   **  (a) All index columns match with WHERE_COLUMN_EQ.
130068:   **  (b) The index is unique
130069:   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
130070:   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
130071:   **
130072:   ** We say the WhereLoop is "order-distinct" if the set of columns from
130073:   ** that WhereLoop that are in the ORDER BY clause are different for every
130074:   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
130075:   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
130076:   ** is not order-distinct. To be order-distinct is not quite the same as being
130077:   ** UNIQUE since a UNIQUE column or index can have multiple rows that 
130078:   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
130079:   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
130080:   **
130081:   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
130082:   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
130083:   ** automatically order-distinct.
130084:   */
130085: 
130086:   assert( pOrderBy!=0 );
130087:   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
130088: 
130089:   nOrderBy = pOrderBy->nExpr;
130090:   testcase( nOrderBy==BMS-1 );
130091:   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
130092:   isOrderDistinct = 1;
130093:   obDone = MASKBIT(nOrderBy)-1;
130094:   orderDistinctMask = 0;
130095:   ready = 0;
130096:   eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
130097:   if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
130098:   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
130099:     if( iLoop>0 ) ready |= pLoop->maskSelf;
130100:     if( iLoop<nLoop ){
130101:       pLoop = pPath->aLoop[iLoop];
130102:       if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
130103:     }else{
130104:       pLoop = pLast;
130105:     }
130106:     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
130107:       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
130108:       break;
130109:     }
130110:     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
130111: 
130112:     /* Mark off any ORDER BY term X that is a column in the table of
130113:     ** the current loop for which there is term in the WHERE
130114:     ** clause of the form X IS NULL or X=? that reference only outer
130115:     ** loops.
130116:     */
130117:     for(i=0; i<nOrderBy; i++){
130118:       if( MASKBIT(i) & obSat ) continue;
130119:       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
130120:       if( pOBExpr->op!=TK_COLUMN ) continue;
130121:       if( pOBExpr->iTable!=iCur ) continue;
130122:       pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
130123:                        ~ready, eqOpMask, 0);
130124:       if( pTerm==0 ) continue;
130125:       if( pTerm->eOperator==WO_IN ){
130126:         /* IN terms are only valid for sorting in the ORDER BY LIMIT 
130127:         ** optimization, and then only if they are actually used
130128:         ** by the query plan */
130129:         assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
130130:         for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
130131:         if( j>=pLoop->nLTerm ) continue;
130132:       }
130133:       if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
130134:         const char *z1, *z2;
130135:         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
130136:         if( !pColl ) pColl = db->pDfltColl;
130137:         z1 = pColl->zName;
130138:         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
130139:         if( !pColl ) pColl = db->pDfltColl;
130140:         z2 = pColl->zName;
130141:         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
130142:         testcase( pTerm->pExpr->op==TK_IS );
130143:       }
130144:       obSat |= MASKBIT(i);
130145:     }
130146: 
130147:     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
130148:       if( pLoop->wsFlags & WHERE_IPK ){
130149:         pIndex = 0;
130150:         nKeyCol = 0;
130151:         nColumn = 1;
130152:       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
130153:         return 0;
130154:       }else{
130155:         nKeyCol = pIndex->nKeyCol;
130156:         nColumn = pIndex->nColumn;
130157:         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
130158:         assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
130159:                           || !HasRowid(pIndex->pTable));
130160:         isOrderDistinct = IsUniqueIndex(pIndex);
130161:       }
130162: 
130163:       /* Loop through all columns of the index and deal with the ones
130164:       ** that are not constrained by == or IN.
130165:       */
130166:       rev = revSet = 0;
130167:       distinctColumns = 0;
130168:       for(j=0; j<nColumn; j++){
130169:         u8 bOnce;   /* True to run the ORDER BY search loop */
130170: 
130171:         /* Skip over == and IS and ISNULL terms.
130172:         ** (Also skip IN terms when doing WHERE_ORDERBY_LIMIT processing)
130173:         */
130174:         if( j<pLoop->u.btree.nEq
130175:          && pLoop->nSkip==0
130176:          && ((i = pLoop->aLTerm[j]->eOperator) & eqOpMask)!=0
130177:         ){
130178:           if( i & WO_ISNULL ){
130179:             testcase( isOrderDistinct );
130180:             isOrderDistinct = 0;
130181:           }
130182:           continue;  
130183:         }
130184: 
130185:         /* Get the column number in the table (iColumn) and sort order
130186:         ** (revIdx) for the j-th column of the index.
130187:         */
130188:         if( pIndex ){
130189:           iColumn = pIndex->aiColumn[j];
130190:           revIdx = pIndex->aSortOrder[j];
130191:           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
130192:         }else{
130193:           iColumn = XN_ROWID;
130194:           revIdx = 0;
130195:         }
130196: 
130197:         /* An unconstrained column that might be NULL means that this
130198:         ** WhereLoop is not well-ordered
130199:         */
130200:         if( isOrderDistinct
130201:          && iColumn>=0
130202:          && j>=pLoop->u.btree.nEq
130203:          && pIndex->pTable->aCol[iColumn].notNull==0
130204:         ){
130205:           isOrderDistinct = 0;
130206:         }
130207: 
130208:         /* Find the ORDER BY term that corresponds to the j-th column
130209:         ** of the index and mark that ORDER BY term off 
130210:         */
130211:         bOnce = 1;
130212:         isMatch = 0;
130213:         for(i=0; bOnce && i<nOrderBy; i++){
130214:           if( MASKBIT(i) & obSat ) continue;
130215:           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
130216:           testcase( wctrlFlags & WHERE_GROUPBY );
130217:           testcase( wctrlFlags & WHERE_DISTINCTBY );
130218:           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
130219:           if( iColumn>=(-1) ){
130220:             if( pOBExpr->op!=TK_COLUMN ) continue;
130221:             if( pOBExpr->iTable!=iCur ) continue;
130222:             if( pOBExpr->iColumn!=iColumn ) continue;
130223:           }else{
130224:             if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
130225:               continue;
130226:             }
130227:           }
130228:           if( iColumn>=0 ){
130229:             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
130230:             if( !pColl ) pColl = db->pDfltColl;
130231:             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
130232:           }
130233:           isMatch = 1;
130234:           break;
130235:         }
130236:         if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
130237:           /* Make sure the sort order is compatible in an ORDER BY clause.
130238:           ** Sort order is irrelevant for a GROUP BY clause. */
130239:           if( revSet ){
130240:             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
130241:           }else{
130242:             rev = revIdx ^ pOrderBy->a[i].sortOrder;
130243:             if( rev ) *pRevMask |= MASKBIT(iLoop);
130244:             revSet = 1;
130245:           }
130246:         }
130247:         if( isMatch ){
130248:           if( iColumn<0 ){
130249:             testcase( distinctColumns==0 );
130250:             distinctColumns = 1;
130251:           }
130252:           obSat |= MASKBIT(i);
130253:         }else{
130254:           /* No match found */
130255:           if( j==0 || j<nKeyCol ){
130256:             testcase( isOrderDistinct!=0 );
130257:             isOrderDistinct = 0;
130258:           }
130259:           break;
130260:         }
130261:       } /* end Loop over all index columns */
130262:       if( distinctColumns ){
130263:         testcase( isOrderDistinct==0 );
130264:         isOrderDistinct = 1;
130265:       }
130266:     } /* end-if not one-row */
130267: 
130268:     /* Mark off any other ORDER BY terms that reference pLoop */
130269:     if( isOrderDistinct ){
130270:       orderDistinctMask |= pLoop->maskSelf;
130271:       for(i=0; i<nOrderBy; i++){
130272:         Expr *p;
130273:         Bitmask mTerm;
130274:         if( MASKBIT(i) & obSat ) continue;
130275:         p = pOrderBy->a[i].pExpr;
130276:         mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
130277:         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
130278:         if( (mTerm&~orderDistinctMask)==0 ){
130279:           obSat |= MASKBIT(i);
130280:         }
130281:       }
130282:     }
130283:   } /* End the loop over all WhereLoops from outer-most down to inner-most */
130284:   if( obSat==obDone ) return (i8)nOrderBy;
130285:   if( !isOrderDistinct ){
130286:     for(i=nOrderBy-1; i>0; i--){
130287:       Bitmask m = MASKBIT(i) - 1;
130288:       if( (obSat&m)==m ) return i;
130289:     }
130290:     return 0;
130291:   }
130292:   return -1;
130293: }
130294: 
130295: 
130296: /*
130297: ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
130298: ** the planner assumes that the specified pOrderBy list is actually a GROUP
130299: ** BY clause - and so any order that groups rows as required satisfies the
130300: ** request.
130301: **
130302: ** Normally, in this case it is not possible for the caller to determine
130303: ** whether or not the rows are really being delivered in sorted order, or
130304: ** just in some other order that provides the required grouping. However,
130305: ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
130306: ** this function may be called on the returned WhereInfo object. It returns
130307: ** true if the rows really will be sorted in the specified order, or false
130308: ** otherwise.
130309: **
130310: ** For example, assuming:
130311: **
130312: **   CREATE INDEX i1 ON t1(x, Y);
130313: **
130314: ** then
130315: **
130316: **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
130317: **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
130318: */
130319: SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
130320:   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
130321:   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
130322:   return pWInfo->sorted;
130323: }
130324: 
130325: #ifdef WHERETRACE_ENABLED
130326: /* For debugging use only: */
130327: static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
130328:   static char zName[65];
130329:   int i;
130330:   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
130331:   if( pLast ) zName[i++] = pLast->cId;
130332:   zName[i] = 0;
130333:   return zName;
130334: }
130335: #endif
130336: 
130337: /*
130338: ** Return the cost of sorting nRow rows, assuming that the keys have 
130339: ** nOrderby columns and that the first nSorted columns are already in
130340: ** order.
130341: */
130342: static LogEst whereSortingCost(
130343:   WhereInfo *pWInfo,
130344:   LogEst nRow,
130345:   int nOrderBy,
130346:   int nSorted
130347: ){
130348:   /* TUNING: Estimated cost of a full external sort, where N is 
130349:   ** the number of rows to sort is:
130350:   **
130351:   **   cost = (3.0 * N * log(N)).
130352:   ** 
130353:   ** Or, if the order-by clause has X terms but only the last Y 
130354:   ** terms are out of order, then block-sorting will reduce the 
130355:   ** sorting cost to:
130356:   **
130357:   **   cost = (3.0 * N * log(N)) * (Y/X)
130358:   **
130359:   ** The (Y/X) term is implemented using stack variable rScale
130360:   ** below.  */
130361:   LogEst rScale, rSortCost;
130362:   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
130363:   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
130364:   rSortCost = nRow + rScale + 16;
130365: 
130366:   /* Multiple by log(M) where M is the number of output rows.
130367:   ** Use the LIMIT for M if it is smaller */
130368:   if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
130369:     nRow = pWInfo->iLimit;
130370:   }
130371:   rSortCost += estLog(nRow);
130372:   return rSortCost;
130373: }
130374: 
130375: /*
130376: ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
130377: ** attempts to find the lowest cost path that visits each WhereLoop
130378: ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
130379: **
130380: ** Assume that the total number of output rows that will need to be sorted
130381: ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
130382: ** costs if nRowEst==0.
130383: **
130384: ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
130385: ** error occurs.
130386: */
130387: static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
130388:   int mxChoice;             /* Maximum number of simultaneous paths tracked */
130389:   int nLoop;                /* Number of terms in the join */
130390:   Parse *pParse;            /* Parsing context */
130391:   sqlite3 *db;              /* The database connection */
130392:   int iLoop;                /* Loop counter over the terms of the join */
130393:   int ii, jj;               /* Loop counters */
130394:   int mxI = 0;              /* Index of next entry to replace */
130395:   int nOrderBy;             /* Number of ORDER BY clause terms */
130396:   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
130397:   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
130398:   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
130399:   WherePath *aFrom;         /* All nFrom paths at the previous level */
130400:   WherePath *aTo;           /* The nTo best paths at the current level */
130401:   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
130402:   WherePath *pTo;           /* An element of aTo[] that we are working on */
130403:   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
130404:   WhereLoop **pX;           /* Used to divy up the pSpace memory */
130405:   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
130406:   char *pSpace;             /* Temporary memory used by this routine */
130407:   int nSpace;               /* Bytes of space allocated at pSpace */
130408: 
130409:   pParse = pWInfo->pParse;
130410:   db = pParse->db;
130411:   nLoop = pWInfo->nLevel;
130412:   /* TUNING: For simple queries, only the best path is tracked.
130413:   ** For 2-way joins, the 5 best paths are followed.
130414:   ** For joins of 3 or more tables, track the 10 best paths */
130415:   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
130416:   assert( nLoop<=pWInfo->pTabList->nSrc );
130417:   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
130418: 
130419:   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
130420:   ** case the purpose of this call is to estimate the number of rows returned
130421:   ** by the overall query. Once this estimate has been obtained, the caller
130422:   ** will invoke this function a second time, passing the estimate as the
130423:   ** nRowEst parameter.  */
130424:   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
130425:     nOrderBy = 0;
130426:   }else{
130427:     nOrderBy = pWInfo->pOrderBy->nExpr;
130428:   }
130429: 
130430:   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
130431:   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
130432:   nSpace += sizeof(LogEst) * nOrderBy;
130433:   pSpace = sqlite3DbMallocRawNN(db, nSpace);
130434:   if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
130435:   aTo = (WherePath*)pSpace;
130436:   aFrom = aTo+mxChoice;
130437:   memset(aFrom, 0, sizeof(aFrom[0]));
130438:   pX = (WhereLoop**)(aFrom+mxChoice);
130439:   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
130440:     pFrom->aLoop = pX;
130441:   }
130442:   if( nOrderBy ){
130443:     /* If there is an ORDER BY clause and it is not being ignored, set up
130444:     ** space for the aSortCost[] array. Each element of the aSortCost array
130445:     ** is either zero - meaning it has not yet been initialized - or the
130446:     ** cost of sorting nRowEst rows of data where the first X terms of
130447:     ** the ORDER BY clause are already in order, where X is the array 
130448:     ** index.  */
130449:     aSortCost = (LogEst*)pX;
130450:     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
130451:   }
130452:   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
130453:   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
130454: 
130455:   /* Seed the search with a single WherePath containing zero WhereLoops.
130456:   **
130457:   ** TUNING: Do not let the number of iterations go above 28.  If the cost
130458:   ** of computing an automatic index is not paid back within the first 28
130459:   ** rows, then do not use the automatic index. */
130460:   aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
130461:   nFrom = 1;
130462:   assert( aFrom[0].isOrdered==0 );
130463:   if( nOrderBy ){
130464:     /* If nLoop is zero, then there are no FROM terms in the query. Since
130465:     ** in this case the query may return a maximum of one row, the results
130466:     ** are already in the requested order. Set isOrdered to nOrderBy to
130467:     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
130468:     ** -1, indicating that the result set may or may not be ordered, 
130469:     ** depending on the loops added to the current plan.  */
130470:     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
130471:   }
130472: 
130473:   /* Compute successively longer WherePaths using the previous generation
130474:   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
130475:   ** best paths at each generation */
130476:   for(iLoop=0; iLoop<nLoop; iLoop++){
130477:     nTo = 0;
130478:     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
130479:       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
130480:         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
130481:         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
130482:         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
130483:         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
130484:         Bitmask maskNew;                  /* Mask of src visited by (..) */
130485:         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
130486: 
130487:         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
130488:         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
130489:         if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
130490:           /* Do not use an automatic index if the this loop is expected
130491:           ** to run less than 2 times. */
130492:           assert( 10==sqlite3LogEst(2) );
130493:           continue;
130494:         }
130495:         /* At this point, pWLoop is a candidate to be the next loop. 
130496:         ** Compute its cost */
130497:         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
130498:         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
130499:         nOut = pFrom->nRow + pWLoop->nOut;
130500:         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
130501:         if( isOrdered<0 ){
130502:           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
130503:                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
130504:                        iLoop, pWLoop, &revMask);
130505:         }else{
130506:           revMask = pFrom->revLoop;
130507:         }
130508:         if( isOrdered>=0 && isOrdered<nOrderBy ){
130509:           if( aSortCost[isOrdered]==0 ){
130510:             aSortCost[isOrdered] = whereSortingCost(
130511:                 pWInfo, nRowEst, nOrderBy, isOrdered
130512:             );
130513:           }
130514:           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
130515: 
130516:           WHERETRACE(0x002,
130517:               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
130518:                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, 
130519:                rUnsorted, rCost));
130520:         }else{
130521:           rCost = rUnsorted;
130522:         }
130523: 
130524:         /* Check to see if pWLoop should be added to the set of
130525:         ** mxChoice best-so-far paths.
130526:         **
130527:         ** First look for an existing path among best-so-far paths
130528:         ** that covers the same set of loops and has the same isOrdered
130529:         ** setting as the current path candidate.
130530:         **
130531:         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
130532:         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
130533:         ** of legal values for isOrdered, -1..64.
130534:         */
130535:         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
130536:           if( pTo->maskLoop==maskNew
130537:            && ((pTo->isOrdered^isOrdered)&0x80)==0
130538:           ){
130539:             testcase( jj==nTo-1 );
130540:             break;
130541:           }
130542:         }
130543:         if( jj>=nTo ){
130544:           /* None of the existing best-so-far paths match the candidate. */
130545:           if( nTo>=mxChoice
130546:            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
130547:           ){
130548:             /* The current candidate is no better than any of the mxChoice
130549:             ** paths currently in the best-so-far buffer.  So discard
130550:             ** this candidate as not viable. */
130551: #ifdef WHERETRACE_ENABLED /* 0x4 */
130552:             if( sqlite3WhereTrace&0x4 ){
130553:               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
130554:                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130555:                   isOrdered>=0 ? isOrdered+'0' : '?');
130556:             }
130557: #endif
130558:             continue;
130559:           }
130560:           /* If we reach this points it means that the new candidate path
130561:           ** needs to be added to the set of best-so-far paths. */
130562:           if( nTo<mxChoice ){
130563:             /* Increase the size of the aTo set by one */
130564:             jj = nTo++;
130565:           }else{
130566:             /* New path replaces the prior worst to keep count below mxChoice */
130567:             jj = mxI;
130568:           }
130569:           pTo = &aTo[jj];
130570: #ifdef WHERETRACE_ENABLED /* 0x4 */
130571:           if( sqlite3WhereTrace&0x4 ){
130572:             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
130573:                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130574:                 isOrdered>=0 ? isOrdered+'0' : '?');
130575:           }
130576: #endif
130577:         }else{
130578:           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
130579:           ** same set of loops and has the sam isOrdered setting as the
130580:           ** candidate path.  Check to see if the candidate should replace
130581:           ** pTo or if the candidate should be skipped */
130582:           if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
130583: #ifdef WHERETRACE_ENABLED /* 0x4 */
130584:             if( sqlite3WhereTrace&0x4 ){
130585:               sqlite3DebugPrintf(
130586:                   "Skip   %s cost=%-3d,%3d order=%c",
130587:                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130588:                   isOrdered>=0 ? isOrdered+'0' : '?');
130589:               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
130590:                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130591:                   pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
130592:             }
130593: #endif
130594:             /* Discard the candidate path from further consideration */
130595:             testcase( pTo->rCost==rCost );
130596:             continue;
130597:           }
130598:           testcase( pTo->rCost==rCost+1 );
130599:           /* Control reaches here if the candidate path is better than the
130600:           ** pTo path.  Replace pTo with the candidate. */
130601: #ifdef WHERETRACE_ENABLED /* 0x4 */
130602:           if( sqlite3WhereTrace&0x4 ){
130603:             sqlite3DebugPrintf(
130604:                 "Update %s cost=%-3d,%3d order=%c",
130605:                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
130606:                 isOrdered>=0 ? isOrdered+'0' : '?');
130607:             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
130608:                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130609:                 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
130610:           }
130611: #endif
130612:         }
130613:         /* pWLoop is a winner.  Add it to the set of best so far */
130614:         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
130615:         pTo->revLoop = revMask;
130616:         pTo->nRow = nOut;
130617:         pTo->rCost = rCost;
130618:         pTo->rUnsorted = rUnsorted;
130619:         pTo->isOrdered = isOrdered;
130620:         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
130621:         pTo->aLoop[iLoop] = pWLoop;
130622:         if( nTo>=mxChoice ){
130623:           mxI = 0;
130624:           mxCost = aTo[0].rCost;
130625:           mxUnsorted = aTo[0].nRow;
130626:           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
130627:             if( pTo->rCost>mxCost 
130628:              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) 
130629:             ){
130630:               mxCost = pTo->rCost;
130631:               mxUnsorted = pTo->rUnsorted;
130632:               mxI = jj;
130633:             }
130634:           }
130635:         }
130636:       }
130637:     }
130638: 
130639: #ifdef WHERETRACE_ENABLED  /* >=2 */
130640:     if( sqlite3WhereTrace & 0x02 ){
130641:       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
130642:       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
130643:         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
130644:            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
130645:            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
130646:         if( pTo->isOrdered>0 ){
130647:           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
130648:         }else{
130649:           sqlite3DebugPrintf("\n");
130650:         }
130651:       }
130652:     }
130653: #endif
130654: 
130655:     /* Swap the roles of aFrom and aTo for the next generation */
130656:     pFrom = aTo;
130657:     aTo = aFrom;
130658:     aFrom = pFrom;
130659:     nFrom = nTo;
130660:   }
130661: 
130662:   if( nFrom==0 ){
130663:     sqlite3ErrorMsg(pParse, "no query solution");
130664:     sqlite3DbFree(db, pSpace);
130665:     return SQLITE_ERROR;
130666:   }
130667:   
130668:   /* Find the lowest cost path.  pFrom will be left pointing to that path */
130669:   pFrom = aFrom;
130670:   for(ii=1; ii<nFrom; ii++){
130671:     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
130672:   }
130673:   assert( pWInfo->nLevel==nLoop );
130674:   /* Load the lowest cost path into pWInfo */
130675:   for(iLoop=0; iLoop<nLoop; iLoop++){
130676:     WhereLevel *pLevel = pWInfo->a + iLoop;
130677:     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
130678:     pLevel->iFrom = pWLoop->iTab;
130679:     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
130680:   }
130681:   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
130682:    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
130683:    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
130684:    && nRowEst
130685:   ){
130686:     Bitmask notUsed;
130687:     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
130688:                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
130689:     if( rc==pWInfo->pDistinctSet->nExpr ){
130690:       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
130691:     }
130692:   }
130693:   if( pWInfo->pOrderBy ){
130694:     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
130695:       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
130696:         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
130697:       }
130698:     }else{
130699:       pWInfo->nOBSat = pFrom->isOrdered;
130700:       pWInfo->revMask = pFrom->revLoop;
130701:       if( pWInfo->nOBSat<=0 ){
130702:         pWInfo->nOBSat = 0;
130703:         if( nLoop>0 && (pFrom->aLoop[nLoop-1]->wsFlags & WHERE_ONEROW)==0 ){
130704:           Bitmask m = 0;
130705:           int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
130706:                       WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
130707:           if( rc==pWInfo->pOrderBy->nExpr ){
130708:             pWInfo->bOrderedInnerLoop = 1;
130709:             pWInfo->revMask = m;
130710:           }
130711:         }
130712:       }
130713:     }
130714:     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
130715:         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
130716:     ){
130717:       Bitmask revMask = 0;
130718:       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 
130719:           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
130720:       );
130721:       assert( pWInfo->sorted==0 );
130722:       if( nOrder==pWInfo->pOrderBy->nExpr ){
130723:         pWInfo->sorted = 1;
130724:         pWInfo->revMask = revMask;
130725:       }
130726:     }
130727:   }
130728: 
130729: 
130730:   pWInfo->nRowOut = pFrom->nRow;
130731: 
130732:   /* Free temporary memory and return success */
130733:   sqlite3DbFree(db, pSpace);
130734:   return SQLITE_OK;
130735: }
130736: 
130737: /*
130738: ** Most queries use only a single table (they are not joins) and have
130739: ** simple == constraints against indexed fields.  This routine attempts
130740: ** to plan those simple cases using much less ceremony than the
130741: ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
130742: ** times for the common case.
130743: **
130744: ** Return non-zero on success, if this query can be handled by this
130745: ** no-frills query planner.  Return zero if this query needs the 
130746: ** general-purpose query planner.
130747: */
130748: static int whereShortCut(WhereLoopBuilder *pBuilder){
130749:   WhereInfo *pWInfo;
130750:   struct SrcList_item *pItem;
130751:   WhereClause *pWC;
130752:   WhereTerm *pTerm;
130753:   WhereLoop *pLoop;
130754:   int iCur;
130755:   int j;
130756:   Table *pTab;
130757:   Index *pIdx;
130758: 
130759:   pWInfo = pBuilder->pWInfo;
130760:   if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
130761:   assert( pWInfo->pTabList->nSrc>=1 );
130762:   pItem = pWInfo->pTabList->a;
130763:   pTab = pItem->pTab;
130764:   if( IsVirtual(pTab) ) return 0;
130765:   if( pItem->fg.isIndexedBy ) return 0;
130766:   iCur = pItem->iCursor;
130767:   pWC = &pWInfo->sWC;
130768:   pLoop = pBuilder->pNew;
130769:   pLoop->wsFlags = 0;
130770:   pLoop->nSkip = 0;
130771:   pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
130772:   if( pTerm ){
130773:     testcase( pTerm->eOperator & WO_IS );
130774:     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
130775:     pLoop->aLTerm[0] = pTerm;
130776:     pLoop->nLTerm = 1;
130777:     pLoop->u.btree.nEq = 1;
130778:     /* TUNING: Cost of a rowid lookup is 10 */
130779:     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
130780:   }else{
130781:     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
130782:       int opMask;
130783:       assert( pLoop->aLTermSpace==pLoop->aLTerm );
130784:       if( !IsUniqueIndex(pIdx)
130785:        || pIdx->pPartIdxWhere!=0 
130786:        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 
130787:       ) continue;
130788:       opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
130789:       for(j=0; j<pIdx->nKeyCol; j++){
130790:         pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
130791:         if( pTerm==0 ) break;
130792:         testcase( pTerm->eOperator & WO_IS );
130793:         pLoop->aLTerm[j] = pTerm;
130794:       }
130795:       if( j!=pIdx->nKeyCol ) continue;
130796:       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
130797:       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
130798:         pLoop->wsFlags |= WHERE_IDX_ONLY;
130799:       }
130800:       pLoop->nLTerm = j;
130801:       pLoop->u.btree.nEq = j;
130802:       pLoop->u.btree.pIndex = pIdx;
130803:       /* TUNING: Cost of a unique index lookup is 15 */
130804:       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
130805:       break;
130806:     }
130807:   }
130808:   if( pLoop->wsFlags ){
130809:     pLoop->nOut = (LogEst)1;
130810:     pWInfo->a[0].pWLoop = pLoop;
130811:     pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
130812:     pWInfo->a[0].iTabCur = iCur;
130813:     pWInfo->nRowOut = 1;
130814:     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
130815:     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
130816:       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
130817:     }
130818: #ifdef SQLITE_DEBUG
130819:     pLoop->cId = '0';
130820: #endif
130821:     return 1;
130822:   }
130823:   return 0;
130824: }
130825: 
130826: /*
130827: ** Generate the beginning of the loop used for WHERE clause processing.
130828: ** The return value is a pointer to an opaque structure that contains
130829: ** information needed to terminate the loop.  Later, the calling routine
130830: ** should invoke sqlite3WhereEnd() with the return value of this function
130831: ** in order to complete the WHERE clause processing.
130832: **
130833: ** If an error occurs, this routine returns NULL.
130834: **
130835: ** The basic idea is to do a nested loop, one loop for each table in
130836: ** the FROM clause of a select.  (INSERT and UPDATE statements are the
130837: ** same as a SELECT with only a single table in the FROM clause.)  For
130838: ** example, if the SQL is this:
130839: **
130840: **       SELECT * FROM t1, t2, t3 WHERE ...;
130841: **
130842: ** Then the code generated is conceptually like the following:
130843: **
130844: **      foreach row1 in t1 do       \    Code generated
130845: **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
130846: **          foreach row3 in t3 do   /
130847: **            ...
130848: **          end                     \    Code generated
130849: **        end                        |-- by sqlite3WhereEnd()
130850: **      end                         /
130851: **
130852: ** Note that the loops might not be nested in the order in which they
130853: ** appear in the FROM clause if a different order is better able to make
130854: ** use of indices.  Note also that when the IN operator appears in
130855: ** the WHERE clause, it might result in additional nested loops for
130856: ** scanning through all values on the right-hand side of the IN.
130857: **
130858: ** There are Btree cursors associated with each table.  t1 uses cursor
130859: ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
130860: ** And so forth.  This routine generates code to open those VDBE cursors
130861: ** and sqlite3WhereEnd() generates the code to close them.
130862: **
130863: ** The code that sqlite3WhereBegin() generates leaves the cursors named
130864: ** in pTabList pointing at their appropriate entries.  The [...] code
130865: ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
130866: ** data from the various tables of the loop.
130867: **
130868: ** If the WHERE clause is empty, the foreach loops must each scan their
130869: ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
130870: ** the tables have indices and there are terms in the WHERE clause that
130871: ** refer to those indices, a complete table scan can be avoided and the
130872: ** code will run much faster.  Most of the work of this routine is checking
130873: ** to see if there are indices that can be used to speed up the loop.
130874: **
130875: ** Terms of the WHERE clause are also used to limit which rows actually
130876: ** make it to the "..." in the middle of the loop.  After each "foreach",
130877: ** terms of the WHERE clause that use only terms in that loop and outer
130878: ** loops are evaluated and if false a jump is made around all subsequent
130879: ** inner loops (or around the "..." if the test occurs within the inner-
130880: ** most loop)
130881: **
130882: ** OUTER JOINS
130883: **
130884: ** An outer join of tables t1 and t2 is conceptally coded as follows:
130885: **
130886: **    foreach row1 in t1 do
130887: **      flag = 0
130888: **      foreach row2 in t2 do
130889: **        start:
130890: **          ...
130891: **          flag = 1
130892: **      end
130893: **      if flag==0 then
130894: **        move the row2 cursor to a null row
130895: **        goto start
130896: **      fi
130897: **    end
130898: **
130899: ** ORDER BY CLAUSE PROCESSING
130900: **
130901: ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
130902: ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
130903: ** if there is one.  If there is no ORDER BY clause or if this routine
130904: ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
130905: **
130906: ** The iIdxCur parameter is the cursor number of an index.  If 
130907: ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
130908: ** to use for OR clause processing.  The WHERE clause should use this
130909: ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
130910: ** the first cursor in an array of cursors for all indices.  iIdxCur should
130911: ** be used to compute the appropriate cursor depending on which index is
130912: ** used.
130913: */
130914: SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
130915:   Parse *pParse,          /* The parser context */
130916:   SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
130917:   Expr *pWhere,           /* The WHERE clause */
130918:   ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
130919:   ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
130920:   u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
130921:   int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
130922:                           ** If WHERE_USE_LIMIT, then the limit amount */
130923: ){
130924:   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
130925:   int nTabList;              /* Number of elements in pTabList */
130926:   WhereInfo *pWInfo;         /* Will become the return value of this function */
130927:   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
130928:   Bitmask notReady;          /* Cursors that are not yet positioned */
130929:   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
130930:   WhereMaskSet *pMaskSet;    /* The expression mask set */
130931:   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
130932:   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
130933:   int ii;                    /* Loop counter */
130934:   sqlite3 *db;               /* Database connection */
130935:   int rc;                    /* Return code */
130936:   u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
130937: 
130938:   assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
130939:         (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 
130940:      && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 
130941:   ));
130942: 
130943:   /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
130944:   assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
130945:             || (wctrlFlags & WHERE_USE_LIMIT)==0 );
130946: 
130947:   /* Variable initialization */
130948:   db = pParse->db;
130949:   memset(&sWLB, 0, sizeof(sWLB));
130950: 
130951:   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
130952:   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
130953:   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
130954:   sWLB.pOrderBy = pOrderBy;
130955: 
130956:   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
130957:   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
130958:   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
130959:     wctrlFlags &= ~WHERE_WANT_DISTINCT;
130960:   }
130961: 
130962:   /* The number of tables in the FROM clause is limited by the number of
130963:   ** bits in a Bitmask 
130964:   */
130965:   testcase( pTabList->nSrc==BMS );
130966:   if( pTabList->nSrc>BMS ){
130967:     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
130968:     return 0;
130969:   }
130970: 
130971:   /* This function normally generates a nested loop for all tables in 
130972:   ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
130973:   ** only generate code for the first table in pTabList and assume that
130974:   ** any cursors associated with subsequent tables are uninitialized.
130975:   */
130976:   nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
130977: 
130978:   /* Allocate and initialize the WhereInfo structure that will become the
130979:   ** return value. A single allocation is used to store the WhereInfo
130980:   ** struct, the contents of WhereInfo.a[], the WhereClause structure
130981:   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
130982:   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
130983:   ** some architectures. Hence the ROUND8() below.
130984:   */
130985:   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
130986:   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
130987:   if( db->mallocFailed ){
130988:     sqlite3DbFree(db, pWInfo);
130989:     pWInfo = 0;
130990:     goto whereBeginError;
130991:   }
130992:   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
130993:   pWInfo->nLevel = nTabList;
130994:   pWInfo->pParse = pParse;
130995:   pWInfo->pTabList = pTabList;
130996:   pWInfo->pOrderBy = pOrderBy;
130997:   pWInfo->pDistinctSet = pDistinctSet;
130998:   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
130999:   pWInfo->wctrlFlags = wctrlFlags;
131000:   pWInfo->iLimit = iAuxArg;
131001:   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
131002:   assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
131003:   pMaskSet = &pWInfo->sMaskSet;
131004:   sWLB.pWInfo = pWInfo;
131005:   sWLB.pWC = &pWInfo->sWC;
131006:   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
131007:   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
131008:   whereLoopInit(sWLB.pNew);
131009: #ifdef SQLITE_DEBUG
131010:   sWLB.pNew->cId = '*';
131011: #endif
131012: 
131013:   /* Split the WHERE clause into separate subexpressions where each
131014:   ** subexpression is separated by an AND operator.
131015:   */
131016:   initMaskSet(pMaskSet);
131017:   sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
131018:   sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
131019:     
131020:   /* Special case: a WHERE clause that is constant.  Evaluate the
131021:   ** expression and either jump over all of the code or fall thru.
131022:   */
131023:   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
131024:     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
131025:       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
131026:                          SQLITE_JUMPIFNULL);
131027:       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
131028:     }
131029:   }
131030: 
131031:   /* Special case: No FROM clause
131032:   */
131033:   if( nTabList==0 ){
131034:     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
131035:     if( wctrlFlags & WHERE_WANT_DISTINCT ){
131036:       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
131037:     }
131038:   }
131039: 
131040:   /* Assign a bit from the bitmask to every term in the FROM clause.
131041:   **
131042:   ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
131043:   **
131044:   ** The rule of the previous sentence ensures thta if X is the bitmask for
131045:   ** a table T, then X-1 is the bitmask for all other tables to the left of T.
131046:   ** Knowing the bitmask for all tables to the left of a left join is
131047:   ** important.  Ticket #3015.
131048:   **
131049:   ** Note that bitmasks are created for all pTabList->nSrc tables in
131050:   ** pTabList, not just the first nTabList tables.  nTabList is normally
131051:   ** equal to pTabList->nSrc but might be shortened to 1 if the
131052:   ** WHERE_OR_SUBCLAUSE flag is set.
131053:   */
131054:   for(ii=0; ii<pTabList->nSrc; ii++){
131055:     createMask(pMaskSet, pTabList->a[ii].iCursor);
131056:     sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
131057:   }
131058: #ifdef SQLITE_DEBUG
131059:   for(ii=0; ii<pTabList->nSrc; ii++){
131060:     Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
131061:     assert( m==MASKBIT(ii) );
131062:   }
131063: #endif
131064: 
131065:   /* Analyze all of the subexpressions. */
131066:   sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
131067:   if( db->mallocFailed ) goto whereBeginError;
131068: 
131069:   if( wctrlFlags & WHERE_WANT_DISTINCT ){
131070:     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
131071:       /* The DISTINCT marking is pointless.  Ignore it. */
131072:       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
131073:     }else if( pOrderBy==0 ){
131074:       /* Try to ORDER BY the result set to make distinct processing easier */
131075:       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
131076:       pWInfo->pOrderBy = pDistinctSet;
131077:     }
131078:   }
131079: 
131080:   /* Construct the WhereLoop objects */
131081: #if defined(WHERETRACE_ENABLED)
131082:   if( sqlite3WhereTrace & 0xffff ){
131083:     sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
131084:     if( wctrlFlags & WHERE_USE_LIMIT ){
131085:       sqlite3DebugPrintf(", limit: %d", iAuxArg);
131086:     }
131087:     sqlite3DebugPrintf(")\n");
131088:   }
131089:   if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
131090:     sqlite3WhereClausePrint(sWLB.pWC);
131091:   }
131092: #endif
131093: 
131094:   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
131095:     rc = whereLoopAddAll(&sWLB);
131096:     if( rc ) goto whereBeginError;
131097:   
131098: #ifdef WHERETRACE_ENABLED
131099:     if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
131100:       WhereLoop *p;
131101:       int i;
131102:       static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
131103:                                              "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
131104:       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
131105:         p->cId = zLabel[i%sizeof(zLabel)];
131106:         whereLoopPrint(p, sWLB.pWC);
131107:       }
131108:     }
131109: #endif
131110:   
131111:     wherePathSolver(pWInfo, 0);
131112:     if( db->mallocFailed ) goto whereBeginError;
131113:     if( pWInfo->pOrderBy ){
131114:        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
131115:        if( db->mallocFailed ) goto whereBeginError;
131116:     }
131117:   }
131118:   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
131119:      pWInfo->revMask = ALLBITS;
131120:   }
131121:   if( pParse->nErr || NEVER(db->mallocFailed) ){
131122:     goto whereBeginError;
131123:   }
131124: #ifdef WHERETRACE_ENABLED
131125:   if( sqlite3WhereTrace ){
131126:     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
131127:     if( pWInfo->nOBSat>0 ){
131128:       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
131129:     }
131130:     switch( pWInfo->eDistinct ){
131131:       case WHERE_DISTINCT_UNIQUE: {
131132:         sqlite3DebugPrintf("  DISTINCT=unique");
131133:         break;
131134:       }
131135:       case WHERE_DISTINCT_ORDERED: {
131136:         sqlite3DebugPrintf("  DISTINCT=ordered");
131137:         break;
131138:       }
131139:       case WHERE_DISTINCT_UNORDERED: {
131140:         sqlite3DebugPrintf("  DISTINCT=unordered");
131141:         break;
131142:       }
131143:     }
131144:     sqlite3DebugPrintf("\n");
131145:     for(ii=0; ii<pWInfo->nLevel; ii++){
131146:       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
131147:     }
131148:   }
131149: #endif
131150:   /* Attempt to omit tables from the join that do not effect the result */
131151:   if( pWInfo->nLevel>=2
131152:    && pDistinctSet!=0
131153:    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
131154:   ){
131155:     Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
131156:     if( sWLB.pOrderBy ){
131157:       tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
131158:     }
131159:     while( pWInfo->nLevel>=2 ){
131160:       WhereTerm *pTerm, *pEnd;
131161:       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
131162:       if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
131163:       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
131164:        && (pLoop->wsFlags & WHERE_ONEROW)==0
131165:       ){
131166:         break;
131167:       }
131168:       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
131169:       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
131170:       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
131171:         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
131172:          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
131173:         ){
131174:           break;
131175:         }
131176:       }
131177:       if( pTerm<pEnd ) break;
131178:       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
131179:       pWInfo->nLevel--;
131180:       nTabList--;
131181:     }
131182:   }
131183:   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
131184:   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
131185: 
131186:   /* If the caller is an UPDATE or DELETE statement that is requesting
131187:   ** to use a one-pass algorithm, determine if this is appropriate.
131188:   */
131189:   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
131190:   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
131191:     int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
131192:     int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
131193:     if( bOnerow
131194:      || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
131195:            && 0==(wsFlags & WHERE_VIRTUALTABLE))
131196:     ){
131197:       pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
131198:       if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
131199:         if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
131200:           bFordelete = OPFLAG_FORDELETE;
131201:         }
131202:         pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
131203:       }
131204:     }
131205:   }
131206: 
131207:   /* Open all tables in the pTabList and any indices selected for
131208:   ** searching those tables.
131209:   */
131210:   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
131211:     Table *pTab;     /* Table to open */
131212:     int iDb;         /* Index of database containing table/index */
131213:     struct SrcList_item *pTabItem;
131214: 
131215:     pTabItem = &pTabList->a[pLevel->iFrom];
131216:     pTab = pTabItem->pTab;
131217:     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
131218:     pLoop = pLevel->pWLoop;
131219:     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
131220:       /* Do nothing */
131221:     }else
131222: #ifndef SQLITE_OMIT_VIRTUALTABLE
131223:     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
131224:       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
131225:       int iCur = pTabItem->iCursor;
131226:       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
131227:     }else if( IsVirtual(pTab) ){
131228:       /* noop */
131229:     }else
131230: #endif
131231:     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
131232:          && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
131233:       int op = OP_OpenRead;
131234:       if( pWInfo->eOnePass!=ONEPASS_OFF ){
131235:         op = OP_OpenWrite;
131236:         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
131237:       };
131238:       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
131239:       assert( pTabItem->iCursor==pLevel->iTabCur );
131240:       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
131241:       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
131242:       if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
131243:         Bitmask b = pTabItem->colUsed;
131244:         int n = 0;
131245:         for(; b; b=b>>1, n++){}
131246:         sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
131247:         assert( n<=pTab->nCol );
131248:       }
131249: #ifdef SQLITE_ENABLE_CURSOR_HINTS
131250:       if( pLoop->u.btree.pIndex!=0 ){
131251:         sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
131252:       }else
131253: #endif
131254:       {
131255:         sqlite3VdbeChangeP5(v, bFordelete);
131256:       }
131257: #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
131258:       sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
131259:                             (const u8*)&pTabItem->colUsed, P4_INT64);
131260: #endif
131261:     }else{
131262:       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
131263:     }
131264:     if( pLoop->wsFlags & WHERE_INDEXED ){
131265:       Index *pIx = pLoop->u.btree.pIndex;
131266:       int iIndexCur;
131267:       int op = OP_OpenRead;
131268:       /* iAuxArg is always set if to a positive value if ONEPASS is possible */
131269:       assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
131270:       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
131271:        && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
131272:       ){
131273:         /* This is one term of an OR-optimization using the PRIMARY KEY of a
131274:         ** WITHOUT ROWID table.  No need for a separate index */
131275:         iIndexCur = pLevel->iTabCur;
131276:         op = 0;
131277:       }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
131278:         Index *pJ = pTabItem->pTab->pIndex;
131279:         iIndexCur = iAuxArg;
131280:         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
131281:         while( ALWAYS(pJ) && pJ!=pIx ){
131282:           iIndexCur++;
131283:           pJ = pJ->pNext;
131284:         }
131285:         op = OP_OpenWrite;
131286:         pWInfo->aiCurOnePass[1] = iIndexCur;
131287:       }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
131288:         iIndexCur = iAuxArg;
131289:         op = OP_ReopenIdx;
131290:       }else{
131291:         iIndexCur = pParse->nTab++;
131292:       }
131293:       pLevel->iIdxCur = iIndexCur;
131294:       assert( pIx->pSchema==pTab->pSchema );
131295:       assert( iIndexCur>=0 );
131296:       if( op ){
131297:         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
131298:         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
131299:         if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
131300:          && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
131301:          && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
131302:         ){
131303:           sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
131304:         }
131305:         VdbeComment((v, "%s", pIx->zName));
131306: #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
131307:         {
131308:           u64 colUsed = 0;
131309:           int ii, jj;
131310:           for(ii=0; ii<pIx->nColumn; ii++){
131311:             jj = pIx->aiColumn[ii];
131312:             if( jj<0 ) continue;
131313:             if( jj>63 ) jj = 63;
131314:             if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
131315:             colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
131316:           }
131317:           sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
131318:                                 (u8*)&colUsed, P4_INT64);
131319:         }
131320: #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
131321:       }
131322:     }
131323:     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
131324:   }
131325:   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
131326:   if( db->mallocFailed ) goto whereBeginError;
131327: 
131328:   /* Generate the code to do the search.  Each iteration of the for
131329:   ** loop below generates code for a single nested loop of the VM
131330:   ** program.
131331:   */
131332:   notReady = ~(Bitmask)0;
131333:   for(ii=0; ii<nTabList; ii++){
131334:     int addrExplain;
131335:     int wsFlags;
131336:     pLevel = &pWInfo->a[ii];
131337:     wsFlags = pLevel->pWLoop->wsFlags;
131338: #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
131339:     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
131340:       constructAutomaticIndex(pParse, &pWInfo->sWC,
131341:                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
131342:       if( db->mallocFailed ) goto whereBeginError;
131343:     }
131344: #endif
131345:     addrExplain = sqlite3WhereExplainOneScan(
131346:         pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
131347:     );
131348:     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
131349:     notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
131350:     pWInfo->iContinue = pLevel->addrCont;
131351:     if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
131352:       sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
131353:     }
131354:   }
131355: 
131356:   /* Done. */
131357:   VdbeModuleComment((v, "Begin WHERE-core"));
131358:   return pWInfo;
131359: 
131360:   /* Jump here if malloc fails */
131361: whereBeginError:
131362:   if( pWInfo ){
131363:     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
131364:     whereInfoFree(db, pWInfo);
131365:   }
131366:   return 0;
131367: }
131368: 
131369: /*
131370: ** Generate the end of the WHERE loop.  See comments on 
131371: ** sqlite3WhereBegin() for additional information.
131372: */
131373: SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
131374:   Parse *pParse = pWInfo->pParse;
131375:   Vdbe *v = pParse->pVdbe;
131376:   int i;
131377:   WhereLevel *pLevel;
131378:   WhereLoop *pLoop;
131379:   SrcList *pTabList = pWInfo->pTabList;
131380:   sqlite3 *db = pParse->db;
131381: 
131382:   /* Generate loop termination code.
131383:   */
131384:   VdbeModuleComment((v, "End WHERE-core"));
131385:   sqlite3ExprCacheClear(pParse);
131386:   for(i=pWInfo->nLevel-1; i>=0; i--){
131387:     int addr;
131388:     pLevel = &pWInfo->a[i];
131389:     pLoop = pLevel->pWLoop;
131390:     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
131391:     if( pLevel->op!=OP_Noop ){
131392:       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
131393:       sqlite3VdbeChangeP5(v, pLevel->p5);
131394:       VdbeCoverage(v);
131395:       VdbeCoverageIf(v, pLevel->op==OP_Next);
131396:       VdbeCoverageIf(v, pLevel->op==OP_Prev);
131397:       VdbeCoverageIf(v, pLevel->op==OP_VNext);
131398:     }
131399:     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
131400:       struct InLoop *pIn;
131401:       int j;
131402:       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
131403:       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
131404:         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
131405:         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
131406:         VdbeCoverage(v);
131407:         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
131408:         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
131409:         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
131410:       }
131411:     }
131412:     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
131413:     if( pLevel->addrSkip ){
131414:       sqlite3VdbeGoto(v, pLevel->addrSkip);
131415:       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
131416:       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
131417:       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
131418:     }
131419: #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
131420:     if( pLevel->addrLikeRep ){
131421:       sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
131422:                         pLevel->addrLikeRep);
131423:       VdbeCoverage(v);
131424:     }
131425: #endif
131426:     if( pLevel->iLeftJoin ){
131427:       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
131428:       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
131429:            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
131430:       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
131431:         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
131432:       }
131433:       if( pLoop->wsFlags & WHERE_INDEXED ){
131434:         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
131435:       }
131436:       if( pLevel->op==OP_Return ){
131437:         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
131438:       }else{
131439:         sqlite3VdbeGoto(v, pLevel->addrFirst);
131440:       }
131441:       sqlite3VdbeJumpHere(v, addr);
131442:     }
131443:     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
131444:                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
131445:   }
131446: 
131447:   /* The "break" point is here, just past the end of the outer loop.
131448:   ** Set it.
131449:   */
131450:   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
131451: 
131452:   assert( pWInfo->nLevel<=pTabList->nSrc );
131453:   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
131454:     int k, last;
131455:     VdbeOp *pOp;
131456:     Index *pIdx = 0;
131457:     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
131458:     Table *pTab = pTabItem->pTab;
131459:     assert( pTab!=0 );
131460:     pLoop = pLevel->pWLoop;
131461: 
131462:     /* For a co-routine, change all OP_Column references to the table of
131463:     ** the co-routine into OP_Copy of result contained in a register.
131464:     ** OP_Rowid becomes OP_Null.
131465:     */
131466:     if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
131467:       translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
131468:                             pTabItem->regResult, 0);
131469:       continue;
131470:     }
131471: 
131472:     /* Close all of the cursors that were opened by sqlite3WhereBegin.
131473:     ** Except, do not close cursors that will be reused by the OR optimization
131474:     ** (WHERE_OR_SUBCLAUSE).  And do not close the OP_OpenWrite cursors
131475:     ** created for the ONEPASS optimization.
131476:     */
131477:     if( (pTab->tabFlags & TF_Ephemeral)==0
131478:      && pTab->pSelect==0
131479:      && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
131480:     ){
131481:       int ws = pLoop->wsFlags;
131482:       if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
131483:         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
131484:       }
131485:       if( (ws & WHERE_INDEXED)!=0
131486:        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 
131487:        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
131488:       ){
131489:         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
131490:       }
131491:     }
131492: 
131493:     /* If this scan uses an index, make VDBE code substitutions to read data
131494:     ** from the index instead of from the table where possible.  In some cases
131495:     ** this optimization prevents the table from ever being read, which can
131496:     ** yield a significant performance boost.
131497:     ** 
131498:     ** Calls to the code generator in between sqlite3WhereBegin and
131499:     ** sqlite3WhereEnd will have created code that references the table
131500:     ** directly.  This loop scans all that code looking for opcodes
131501:     ** that reference the table and converts them into opcodes that
131502:     ** reference the index.
131503:     */
131504:     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
131505:       pIdx = pLoop->u.btree.pIndex;
131506:     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
131507:       pIdx = pLevel->u.pCovidx;
131508:     }
131509:     if( pIdx
131510:      && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
131511:      && !db->mallocFailed
131512:     ){
131513:       last = sqlite3VdbeCurrentAddr(v);
131514:       k = pLevel->addrBody;
131515:       pOp = sqlite3VdbeGetOp(v, k);
131516:       for(; k<last; k++, pOp++){
131517:         if( pOp->p1!=pLevel->iTabCur ) continue;
131518:         if( pOp->opcode==OP_Column ){
131519:           int x = pOp->p2;
131520:           assert( pIdx->pTable==pTab );
131521:           if( !HasRowid(pTab) ){
131522:             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
131523:             x = pPk->aiColumn[x];
131524:             assert( x>=0 );
131525:           }
131526:           x = sqlite3ColumnOfIndex(pIdx, x);
131527:           if( x>=0 ){
131528:             pOp->p2 = x;
131529:             pOp->p1 = pLevel->iIdxCur;
131530:           }
131531:           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
131532:         }else if( pOp->opcode==OP_Rowid ){
131533:           pOp->p1 = pLevel->iIdxCur;
131534:           pOp->opcode = OP_IdxRowid;
131535:         }
131536:       }
131537:     }
131538:   }
131539: 
131540:   /* Final cleanup
131541:   */
131542:   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
131543:   whereInfoFree(db, pWInfo);
131544:   return;
131545: }
131546: 
131547: /************** End of where.c ***********************************************/
131548: /************** Begin file parse.c *******************************************/
131549: /*
131550: ** 2000-05-29
131551: **
131552: ** The author disclaims copyright to this source code.  In place of
131553: ** a legal notice, here is a blessing:
131554: **
131555: **    May you do good and not evil.
131556: **    May you find forgiveness for yourself and forgive others.
131557: **    May you share freely, never taking more than you give.
131558: **
131559: *************************************************************************
131560: ** Driver template for the LEMON parser generator.
131561: **
131562: ** The "lemon" program processes an LALR(1) input grammar file, then uses
131563: ** this template to construct a parser.  The "lemon" program inserts text
131564: ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
131565: ** interstitial "-" characters) contained in this template is changed into
131566: ** the value of the %name directive from the grammar.  Otherwise, the content
131567: ** of this template is copied straight through into the generate parser
131568: ** source file.
131569: **
131570: ** The following is the concatenation of all %include directives from the
131571: ** input grammar file:
131572: */
131573: /* #include <stdio.h> */
131574: /************ Begin %include sections from the grammar ************************/
131575: 
131576: /* #include "sqliteInt.h" */
131577: 
131578: /*
131579: ** Disable all error recovery processing in the parser push-down
131580: ** automaton.
131581: */
131582: #define YYNOERRORRECOVERY 1
131583: 
131584: /*
131585: ** Make yytestcase() the same as testcase()
131586: */
131587: #define yytestcase(X) testcase(X)
131588: 
131589: /*
131590: ** Indicate that sqlite3ParserFree() will never be called with a null
131591: ** pointer.
131592: */
131593: #define YYPARSEFREENEVERNULL 1
131594: 
131595: /*
131596: ** Alternative datatype for the argument to the malloc() routine passed
131597: ** into sqlite3ParserAlloc().  The default is size_t.
131598: */
131599: #define YYMALLOCARGTYPE  u64
131600: 
131601: /*
131602: ** An instance of this structure holds information about the
131603: ** LIMIT clause of a SELECT statement.
131604: */
131605: struct LimitVal {
131606:   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
131607:   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
131608: };
131609: 
131610: /*
131611: ** An instance of this structure is used to store the LIKE,
131612: ** GLOB, NOT LIKE, and NOT GLOB operators.
131613: */
131614: struct LikeOp {
131615:   Token eOperator;  /* "like" or "glob" or "regexp" */
131616:   int bNot;         /* True if the NOT keyword is present */
131617: };
131618: 
131619: /*
131620: ** An instance of the following structure describes the event of a
131621: ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
131622: ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
131623: **
131624: **      UPDATE ON (a,b,c)
131625: **
131626: ** Then the "b" IdList records the list "a,b,c".
131627: */
131628: struct TrigEvent { int a; IdList * b; };
131629: 
131630: /*
131631: ** An instance of this structure holds the ATTACH key and the key type.
131632: */
131633: struct AttachKey { int type;  Token key; };
131634: 
131635: /*
131636: ** Disable lookaside memory allocation for objects that might be
131637: ** shared across database connections.
131638: */
131639: static void disableLookaside(Parse *pParse){
131640:   pParse->disableLookaside++;
131641:   pParse->db->lookaside.bDisable++;
131642: }
131643: 
131644: 
131645:   /*
131646:   ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
131647:   ** all elements in the list.  And make sure list length does not exceed
131648:   ** SQLITE_LIMIT_COMPOUND_SELECT.
131649:   */
131650:   static void parserDoubleLinkSelect(Parse *pParse, Select *p){
131651:     if( p->pPrior ){
131652:       Select *pNext = 0, *pLoop;
131653:       int mxSelect, cnt = 0;
131654:       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
131655:         pLoop->pNext = pNext;
131656:         pLoop->selFlags |= SF_Compound;
131657:       }
131658:       if( (p->selFlags & SF_MultiValue)==0 && 
131659:         (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
131660:         cnt>mxSelect
131661:       ){
131662:         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
131663:       }
131664:     }
131665:   }
131666: 
131667:   /* This is a utility routine used to set the ExprSpan.zStart and
131668:   ** ExprSpan.zEnd values of pOut so that the span covers the complete
131669:   ** range of text beginning with pStart and going to the end of pEnd.
131670:   */
131671:   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
131672:     pOut->zStart = pStart->z;
131673:     pOut->zEnd = &pEnd->z[pEnd->n];
131674:   }
131675: 
131676:   /* Construct a new Expr object from a single identifier.  Use the
131677:   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
131678:   ** that created the expression.
131679:   */
131680:   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
131681:     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, &t);
131682:     pOut->zStart = t.z;
131683:     pOut->zEnd = &t.z[t.n];
131684:   }
131685: 
131686:   /* This routine constructs a binary expression node out of two ExprSpan
131687:   ** objects and uses the result to populate a new ExprSpan object.
131688:   */
131689:   static void spanBinaryExpr(
131690:     Parse *pParse,      /* The parsing context.  Errors accumulate here */
131691:     int op,             /* The binary operation */
131692:     ExprSpan *pLeft,    /* The left operand, and output */
131693:     ExprSpan *pRight    /* The right operand */
131694:   ){
131695:     pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
131696:     pLeft->zEnd = pRight->zEnd;
131697:   }
131698: 
131699:   /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
131700:   ** outside of *ppExpr.
131701:   */
131702:   static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
131703:     if( doNot ){
131704:       pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0);
131705:     }
131706:   }
131707: 
131708:   /* Construct an expression node for a unary postfix operator
131709:   */
131710:   static void spanUnaryPostfix(
131711:     Parse *pParse,         /* Parsing context to record errors */
131712:     int op,                /* The operator */
131713:     ExprSpan *pOperand,    /* The operand, and output */
131714:     Token *pPostOp         /* The operand token for setting the span */
131715:   ){
131716:     pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
131717:     pOperand->zEnd = &pPostOp->z[pPostOp->n];
131718:   }                           
131719: 
131720:   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
131721:   ** unary TK_ISNULL or TK_NOTNULL expression. */
131722:   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
131723:     sqlite3 *db = pParse->db;
131724:     if( pA && pY && pY->op==TK_NULL ){
131725:       pA->op = (u8)op;
131726:       sqlite3ExprDelete(db, pA->pRight);
131727:       pA->pRight = 0;
131728:     }
131729:   }
131730: 
131731:   /* Construct an expression node for a unary prefix operator
131732:   */
131733:   static void spanUnaryPrefix(
131734:     ExprSpan *pOut,        /* Write the new expression node here */
131735:     Parse *pParse,         /* Parsing context to record errors */
131736:     int op,                /* The operator */
131737:     ExprSpan *pOperand,    /* The operand */
131738:     Token *pPreOp         /* The operand token for setting the span */
131739:   ){
131740:     pOut->zStart = pPreOp->z;
131741:     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
131742:     pOut->zEnd = pOperand->zEnd;
131743:   }
131744: 
131745:   /* Add a single new term to an ExprList that is used to store a
131746:   ** list of identifiers.  Report an error if the ID list contains
131747:   ** a COLLATE clause or an ASC or DESC keyword, except ignore the
131748:   ** error while parsing a legacy schema.
131749:   */
131750:   static ExprList *parserAddExprIdListTerm(
131751:     Parse *pParse,
131752:     ExprList *pPrior,
131753:     Token *pIdToken,
131754:     int hasCollate,
131755:     int sortOrder
131756:   ){
131757:     ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
131758:     if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
131759:         && pParse->db->init.busy==0
131760:     ){
131761:       sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
131762:                          pIdToken->n, pIdToken->z);
131763:     }
131764:     sqlite3ExprListSetName(pParse, p, pIdToken, 1);
131765:     return p;
131766:   }
131767: /**************** End of %include directives **********************************/
131768: /* These constants specify the various numeric values for terminal symbols
131769: ** in a format understandable to "makeheaders".  This section is blank unless
131770: ** "lemon" is run with the "-m" command-line option.
131771: ***************** Begin makeheaders token definitions *************************/
131772: /**************** End makeheaders token definitions ***************************/
131773: 
131774: /* The next sections is a series of control #defines.
131775: ** various aspects of the generated parser.
131776: **    YYCODETYPE         is the data type used to store the integer codes
131777: **                       that represent terminal and non-terminal symbols.
131778: **                       "unsigned char" is used if there are fewer than
131779: **                       256 symbols.  Larger types otherwise.
131780: **    YYNOCODE           is a number of type YYCODETYPE that is not used for
131781: **                       any terminal or nonterminal symbol.
131782: **    YYFALLBACK         If defined, this indicates that one or more tokens
131783: **                       (also known as: "terminal symbols") have fall-back
131784: **                       values which should be used if the original symbol
131785: **                       would not parse.  This permits keywords to sometimes
131786: **                       be used as identifiers, for example.
131787: **    YYACTIONTYPE       is the data type used for "action codes" - numbers
131788: **                       that indicate what to do in response to the next
131789: **                       token.
131790: **    sqlite3ParserTOKENTYPE     is the data type used for minor type for terminal
131791: **                       symbols.  Background: A "minor type" is a semantic
131792: **                       value associated with a terminal or non-terminal
131793: **                       symbols.  For example, for an "ID" terminal symbol,
131794: **                       the minor type might be the name of the identifier.
131795: **                       Each non-terminal can have a different minor type.
131796: **                       Terminal symbols all have the same minor type, though.
131797: **                       This macros defines the minor type for terminal 
131798: **                       symbols.
131799: **    YYMINORTYPE        is the data type used for all minor types.
131800: **                       This is typically a union of many types, one of
131801: **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
131802: **                       for terminal symbols is called "yy0".
131803: **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
131804: **                       zero the stack is dynamically sized using realloc()
131805: **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
131806: **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
131807: **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
131808: **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
131809: **    YYERRORSYMBOL      is the code number of the error symbol.  If not
131810: **                       defined, then do no error processing.
131811: **    YYNSTATE           the combined number of states.
131812: **    YYNRULE            the number of rules in the grammar
131813: **    YY_MAX_SHIFT       Maximum value for shift actions
131814: **    YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
131815: **    YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
131816: **    YY_MIN_REDUCE      Maximum value for reduce actions
131817: **    YY_ERROR_ACTION    The yy_action[] code for syntax error
131818: **    YY_ACCEPT_ACTION   The yy_action[] code for accept
131819: **    YY_NO_ACTION       The yy_action[] code for no-op
131820: */
131821: #ifndef INTERFACE
131822: # define INTERFACE 1
131823: #endif
131824: /************* Begin control #defines *****************************************/
131825: #define YYCODETYPE unsigned char
131826: #define YYNOCODE 252
131827: #define YYACTIONTYPE unsigned short int
131828: #define YYWILDCARD 96
131829: #define sqlite3ParserTOKENTYPE Token
131830: typedef union {
131831:   int yyinit;
131832:   sqlite3ParserTOKENTYPE yy0;
131833:   Expr* yy72;
131834:   TriggerStep* yy145;
131835:   ExprList* yy148;
131836:   SrcList* yy185;
131837:   ExprSpan yy190;
131838:   int yy194;
131839:   Select* yy243;
131840:   IdList* yy254;
131841:   With* yy285;
131842:   struct TrigEvent yy332;
131843:   struct LimitVal yy354;
131844:   struct LikeOp yy392;
131845:   struct {int value; int mask;} yy497;
131846: } YYMINORTYPE;
131847: #ifndef YYSTACKDEPTH
131848: #define YYSTACKDEPTH 100
131849: #endif
131850: #define sqlite3ParserARG_SDECL Parse *pParse;
131851: #define sqlite3ParserARG_PDECL ,Parse *pParse
131852: #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
131853: #define sqlite3ParserARG_STORE yypParser->pParse = pParse
131854: #define YYFALLBACK 1
131855: #define YYNSTATE             443
131856: #define YYNRULE              328
131857: #define YY_MAX_SHIFT         442
131858: #define YY_MIN_SHIFTREDUCE   653
131859: #define YY_MAX_SHIFTREDUCE   980
131860: #define YY_MIN_REDUCE        981
131861: #define YY_MAX_REDUCE        1308
131862: #define YY_ERROR_ACTION      1309
131863: #define YY_ACCEPT_ACTION     1310
131864: #define YY_NO_ACTION         1311
131865: /************* End control #defines *******************************************/
131866: 
131867: /* Define the yytestcase() macro to be a no-op if is not already defined
131868: ** otherwise.
131869: **
131870: ** Applications can choose to define yytestcase() in the %include section
131871: ** to a macro that can assist in verifying code coverage.  For production
131872: ** code the yytestcase() macro should be turned off.  But it is useful
131873: ** for testing.
131874: */
131875: #ifndef yytestcase
131876: # define yytestcase(X)
131877: #endif
131878: 
131879: 
131880: /* Next are the tables used to determine what action to take based on the
131881: ** current state and lookahead token.  These tables are used to implement
131882: ** functions that take a state number and lookahead value and return an
131883: ** action integer.  
131884: **
131885: ** Suppose the action integer is N.  Then the action is determined as
131886: ** follows
131887: **
131888: **   0 <= N <= YY_MAX_SHIFT             Shift N.  That is, push the lookahead
131889: **                                      token onto the stack and goto state N.
131890: **
131891: **   N between YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
131892: **     and YY_MAX_SHIFTREDUCE           reduce by rule N-YY_MIN_SHIFTREDUCE.
131893: **
131894: **   N between YY_MIN_REDUCE            Reduce by rule N-YY_MIN_REDUCE
131895: **     and YY_MAX_REDUCE
131896: 
131897: **   N == YY_ERROR_ACTION               A syntax error has occurred.
131898: **
131899: **   N == YY_ACCEPT_ACTION              The parser accepts its input.
131900: **
131901: **   N == YY_NO_ACTION                  No such action.  Denotes unused
131902: **                                      slots in the yy_action[] table.
131903: **
131904: ** The action table is constructed as a single large table named yy_action[].
131905: ** Given state S and lookahead X, the action is computed as
131906: **
131907: **      yy_action[ yy_shift_ofst[S] + X ]
131908: **
131909: ** If the index value yy_shift_ofst[S]+X is out of range or if the value
131910: ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
131911: ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
131912: ** and that yy_default[S] should be used instead.  
131913: **
131914: ** The formula above is for computing the action when the lookahead is
131915: ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
131916: ** a reduce action) then the yy_reduce_ofst[] array is used in place of
131917: ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
131918: ** YY_SHIFT_USE_DFLT.
131919: **
131920: ** The following are the tables generated in this section:
131921: **
131922: **  yy_action[]        A single table containing all actions.
131923: **  yy_lookahead[]     A table containing the lookahead for each entry in
131924: **                     yy_action.  Used to detect hash collisions.
131925: **  yy_shift_ofst[]    For each state, the offset into yy_action for
131926: **                     shifting terminals.
131927: **  yy_reduce_ofst[]   For each state, the offset into yy_action for
131928: **                     shifting non-terminals after a reduce.
131929: **  yy_default[]       Default action for each state.
131930: **
131931: *********** Begin parsing tables **********************************************/
131932: #define YY_ACTTAB_COUNT (1507)
131933: static const YYACTIONTYPE yy_action[] = {
131934:  /*     0 */   317,  814,  341,  808,    5,  195,  195,  802,   93,   94,
131935:  /*    10 */    84,  823,  823,  835,  838,  827,  827,   91,   91,   92,
131936:  /*    20 */    92,   92,   92,  293,   90,   90,   90,   90,   89,   89,
131937:  /*    30 */    88,   88,   88,   87,  341,  317,  958,  958,  807,  807,
131938:  /*    40 */   807,  928,  344,   93,   94,   84,  823,  823,  835,  838,
131939:  /*    50 */   827,  827,   91,   91,   92,   92,   92,   92,  328,   90,
131940:  /*    60 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  341,
131941:  /*    70 */    89,   89,   88,   88,   88,   87,  341,  776,  958,  958,
131942:  /*    80 */   317,   88,   88,   88,   87,  341,  777,   69,   93,   94,
131943:  /*    90 */    84,  823,  823,  835,  838,  827,  827,   91,   91,   92,
131944:  /*   100 */    92,   92,   92,  437,   90,   90,   90,   90,   89,   89,
131945:  /*   110 */    88,   88,   88,   87,  341, 1310,  147,  147,    2,  317,
131946:  /*   120 */    76,   25,   74,   49,   49,   87,  341,   93,   94,   84,
131947:  /*   130 */   823,  823,  835,  838,  827,  827,   91,   91,   92,   92,
131948:  /*   140 */    92,   92,   95,   90,   90,   90,   90,   89,   89,   88,
131949:  /*   150 */    88,   88,   87,  341,  939,  939,  317,  260,  415,  400,
131950:  /*   160 */   398,   58,  737,  737,   93,   94,   84,  823,  823,  835,
131951:  /*   170 */   838,  827,  827,   91,   91,   92,   92,   92,   92,   57,
131952:  /*   180 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131953:  /*   190 */   341,  317, 1253,  928,  344,  269,  940,  941,  242,   93,
131954:  /*   200 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131955:  /*   210 */    92,   92,   92,   92,  293,   90,   90,   90,   90,   89,
131956:  /*   220 */    89,   88,   88,   88,   87,  341,  317,  919, 1303,  793,
131957:  /*   230 */   691, 1303,  724,  724,   93,   94,   84,  823,  823,  835,
131958:  /*   240 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  337,
131959:  /*   250 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131960:  /*   260 */   341,  317,  114,  919, 1304,  684,  395, 1304,  124,   93,
131961:  /*   270 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131962:  /*   280 */    92,   92,   92,   92,  683,   90,   90,   90,   90,   89,
131963:  /*   290 */    89,   88,   88,   88,   87,  341,  317,   86,   83,  169,
131964:  /*   300 */   801,  917,  234,  399,   93,   94,   84,  823,  823,  835,
131965:  /*   310 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  686,
131966:  /*   320 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131967:  /*   330 */   341,  317,  436,  742,   86,   83,  169,  917,  741,   93,
131968:  /*   340 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131969:  /*   350 */    92,   92,   92,   92,  902,   90,   90,   90,   90,   89,
131970:  /*   360 */    89,   88,   88,   88,   87,  341,  317,  321,  434,  434,
131971:  /*   370 */   434,    1,  722,  722,   93,   94,   84,  823,  823,  835,
131972:  /*   380 */   838,  827,  827,   91,   91,   92,   92,   92,   92,  190,
131973:  /*   390 */    90,   90,   90,   90,   89,   89,   88,   88,   88,   87,
131974:  /*   400 */   341,  317,  685,  292,  939,  939,  150,  977,  310,   93,
131975:  /*   410 */    94,   84,  823,  823,  835,  838,  827,  827,   91,   91,
131976:  /*   420 */    92,   92,   92,   92,  437,   90,   90,   90,   90,   89,
131977:  /*   430 */    89,   88,   88,   88,   87,  341,  926,    2,  372,  719,
131978:  /*   440 */   698,  369,  950,  317,   49,   49,  940,  941,  719,  177,
131979:  /*   450 */    72,   93,   94,   84,  823,  823,  835,  838,  827,  827,
131980:  /*   460 */    91,   91,   92,   92,   92,   92,  322,   90,   90,   90,
131981:  /*   470 */    90,   89,   89,   88,   88,   88,   87,  341,  317,  415,
131982:  /*   480 */   405,  824,  824,  836,  839,   75,   93,   82,   84,  823,
131983:  /*   490 */   823,  835,  838,  827,  827,   91,   91,   92,   92,   92,
131984:  /*   500 */    92,  430,   90,   90,   90,   90,   89,   89,   88,   88,
131985:  /*   510 */    88,   87,  341,  317,  340,  340,  340,  658,  659,  660,
131986:  /*   520 */   333,  288,   94,   84,  823,  823,  835,  838,  827,  827,
131987:  /*   530 */    91,   91,   92,   92,   92,   92,  437,   90,   90,   90,
131988:  /*   540 */    90,   89,   89,   88,   88,   88,   87,  341,  317,  882,
131989:  /*   550 */   882,  375,  828,   66,  330,  409,   49,   49,   84,  823,
131990:  /*   560 */   823,  835,  838,  827,  827,   91,   91,   92,   92,   92,
131991:  /*   570 */    92,  351,   90,   90,   90,   90,   89,   89,   88,   88,
131992:  /*   580 */    88,   87,  341,   80,  432,  742,    3, 1180,  351,  350,
131993:  /*   590 */   741,  334,  796,  939,  939,  761,   80,  432,  278,    3,
131994:  /*   600 */   204,  161,  279,  393,  274,  392,  191,  362,  437,  277,
131995:  /*   610 */   745,   77,   78,  272,  800,  254,  355,  243,   79,  342,
131996:  /*   620 */   342,   86,   83,  169,   77,   78,  234,  399,   49,   49,
131997:  /*   630 */   435,   79,  342,  342,  437,  940,  941,  186,  442,  655,
131998:  /*   640 */   390,  387,  386,  435,  235,  213,  108,  421,  761,  351,
131999:  /*   650 */   437,  385,  167,  732,   10,   10,  124,  124,  671,  814,
132000:  /*   660 */   421,  439,  438,  415,  414,  802,  362,  168,  327,  124,
132001:  /*   670 */    49,   49,  814,  219,  439,  438,  800,  186,  802,  326,
132002:  /*   680 */   390,  387,  386,  437, 1248, 1248,   23,  939,  939,   80,
132003:  /*   690 */   432,  385,    3,  761,  416,  876,  807,  807,  807,  809,
132004:  /*   700 */    19,  290,  149,   49,   49,  415,  396,  260,  910,  807,
132005:  /*   710 */   807,  807,  809,   19,  312,  237,  145,   77,   78,  746,
132006:  /*   720 */   168,  702,  437,  149,   79,  342,  342,  114,  358,  940,
132007:  /*   730 */   941,  302,  223,  397,  345,  313,  435,  260,  415,  417,
132008:  /*   740 */   858,  374,   31,   31,   80,  432,  761,    3,  348,   92,
132009:  /*   750 */    92,   92,   92,  421,   90,   90,   90,   90,   89,   89,
132010:  /*   760 */    88,   88,   88,   87,  341,  814,  114,  439,  438,  796,
132011:  /*   770 */   367,  802,   77,   78,  701,  796,  124, 1187,  220,   79,
132012:  /*   780 */   342,  342,  124,  747,  734,  939,  939,  775,  404,  939,
132013:  /*   790 */   939,  435,  254,  360,  253,  402,  895,  346,  254,  360,
132014:  /*   800 */   253,  774,  807,  807,  807,  809,   19,  800,  421,   90,
132015:  /*   810 */    90,   90,   90,   89,   89,   88,   88,   88,   87,  341,
132016:  /*   820 */   814,  114,  439,  438,  939,  939,  802,  940,  941,  114,
132017:  /*   830 */   437,  940,  941,   86,   83,  169,  192,  166,  309,  979,
132018:  /*   840 */    70,  432,  700,    3,  382,  870,  238,   86,   83,  169,
132019:  /*   850 */    10,   10,  361,  406,  763,  190,  222,  807,  807,  807,
132020:  /*   860 */   809,   19,  870,  872,  329,   24,  940,  941,   77,   78,
132021:  /*   870 */   359,  437,  335,  260,  218,   79,  342,  342,  437,  307,
132022:  /*   880 */   306,  305,  207,  303,  339,  338,  668,  435,  339,  338,
132023:  /*   890 */   407,   10,   10,  762,  216,  216,  939,  939,   49,   49,
132024:  /*   900 */   437,  260,   97,  241,  421,  225,  402,  189,  188,  187,
132025:  /*   910 */   309,  918,  980,  149,  221,  898,  814,  868,  439,  438,
132026:  /*   920 */    10,   10,  802,  870,  915,  316,  898,  163,  162,  171,
132027:  /*   930 */   249,  240,  322,  410,  412,  687,  687,  272,  940,  941,
132028:  /*   940 */   239,  965,  901,  437,  226,  403,  226,  437,  963,  367,
132029:  /*   950 */   964,  173,  248,  807,  807,  807,  809,   19,  174,  367,
132030:  /*   960 */   899,  124,  172,   48,   48,    9,    9,   35,   35,  966,
132031:  /*   970 */   966,  899,  363,  966,  966,  814,  900,  808,  725,  939,
132032:  /*   980 */   939,  802,  895,  318,  980,  324,  125,  900,  726,  420,
132033:  /*   990 */    92,   92,   92,   92,   85,   90,   90,   90,   90,   89,
132034:  /*  1000 */    89,   88,   88,   88,   87,  341,  216,  216,  437,  946,
132035:  /*  1010 */   349,  292,  807,  807,  807,  114,  291,  693,  402,  705,
132036:  /*  1020 */   890,  940,  941,  437,  245,  889,  247,  437,   36,   36,
132037:  /*  1030 */   437,  353,  391,  437,  260,  252,  260,  437,  361,  437,
132038:  /*  1040 */   706,  437,  370,   12,   12,  224,  437,   27,   27,  437,
132039:  /*  1050 */    37,   37,  437,   38,   38,  752,  368,   39,   39,   28,
132040:  /*  1060 */    28,   29,   29,  215,  166,  331,   40,   40,  437,   41,
132041:  /*  1070 */    41,  437,   42,   42,  437,  866,  246,  731,  437,  879,
132042:  /*  1080 */   437,  256,  437,  878,  437,  267,  437,  261,   11,   11,
132043:  /*  1090 */   437,   43,   43,  437,   99,   99,  437,  373,   44,   44,
132044:  /*  1100 */    45,   45,   32,   32,   46,   46,   47,   47,  437,  426,
132045:  /*  1110 */    33,   33,  776,  116,  116,  437,  117,  117,  437,  124,
132046:  /*  1120 */   437,  777,  437,  260,  437,  957,  437,  352,  118,  118,
132047:  /*  1130 */   437,  195,  437,  111,  437,   53,   53,  264,   34,   34,
132048:  /*  1140 */   100,  100,   50,   50,  101,  101,  102,  102,  437,  260,
132049:  /*  1150 */    98,   98,  115,  115,  113,  113,  437,  262,  437,  265,
132050:  /*  1160 */   437,  943,  958,  437,  727,  437,  681,  437,  106,  106,
132051:  /*  1170 */    68,  437,  893,  730,  437,  365,  105,  105,  103,  103,
132052:  /*  1180 */   104,  104,  217,   52,   52,   54,   54,   51,   51,  694,
132053:  /*  1190 */   259,   26,   26,  266,   30,   30,  677,  323,  433,  323,
132054:  /*  1200 */   674,  423,  427,  943,  958,  114,  114,  431,  681,  865,
132055:  /*  1210 */  1277,  233,  366,  714,  112,   20,  154,  704,  703,  810,
132056:  /*  1220 */   914,   55,  159,  311,  798,  255,  383,  194,   68,  200,
132057:  /*  1230 */    21,  694,  268,  114,  114,  114,  270,  711,  712,   68,
132058:  /*  1240 */   114,  739,  770,  715,   71,  194,  861,  875,  875,  200,
132059:  /*  1250 */   696,  865,  874,  874,  679,  699,  273,  110,  229,  419,
132060:  /*  1260 */   768,  810,  799,  378,  748,  759,  418,  210,  294,  281,
132061:  /*  1270 */   295,  806,  283,  682,  676,  665,  664,  666,  933,  151,
132062:  /*  1280 */   285,    7, 1267,  308,  251,  790,  354,  244,  892,  364,
132063:  /*  1290 */   287,  422,  300,  164,  160,  936,  974,  127,  197,  137,
132064:  /*  1300 */   909,  907,  971,  388,  276,  863,  862,   56,  698,  325,
132065:  /*  1310 */   148,   59,  122,   66,  356,  381,  357,  176,  152,   62,
132066:  /*  1320 */   371,  130,  877,  181,  377,  760,  211,  182,  132,  133,
132067:  /*  1330 */   134,  135,  258,  146,  140,  795,  787,  263,  183,  379,
132068:  /*  1340 */   667,  394,  184,  332,  894,  314,  718,  717,  857,  716,
132069:  /*  1350 */   696,  315,  709,  690,   65,  196,    6,  408,  289,  708,
132070:  /*  1360 */   275,  689,  688,  948,  756,  757,  280,  282,  425,  755,
132071:  /*  1370 */   284,  336,   73,   67,  754,  429,  411,   96,  286,  413,
132072:  /*  1380 */   205,  934,  673,   22,  209,  440,  119,  120,  109,  206,
132073:  /*  1390 */   208,  441,  662,  661,  656,  843,  654,  343,  158,  236,
132074:  /*  1400 */   170,  347,  107,  227,  121,  738,  873,  298,  296,  297,
132075:  /*  1410 */   299,  871,  794,  128,  129,  728,  230,  131,  175,  250,
132076:  /*  1420 */   888,  136,  138,  231,  232,  139,   60,   61,  891,  178,
132077:  /*  1430 */   179,  887,    8,   13,  180,  257,  880,  968,  194,  141,
132078:  /*  1440 */   142,  376,  153,  670,  380,  185,  143,  277,   63,  384,
132079:  /*  1450 */    14,  707,  271,   15,  389,   64,  319,  320,  126,  228,
132080:  /*  1460 */   813,  812,  841,  736,  123,   16,  401,  740,    4,  769,
132081:  /*  1470 */   165,  212,  214,  193,  144,  764,   71,   68,   17,   18,
132082:  /*  1480 */   856,  842,  840,  897,  845,  896,  199,  198,  923,  155,
132083:  /*  1490 */   424,  929,  924,  156,  201,  202,  428,  844,  157,  203,
132084:  /*  1500 */   811,  680,   81, 1269, 1268,  301,  304,
132085: };
132086: static const YYCODETYPE yy_lookahead[] = {
132087:  /*     0 */    19,   95,   53,   97,   22,   24,   24,  101,   27,   28,
132088:  /*    10 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
132089:  /*    20 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
132090:  /*    30 */    49,   50,   51,   52,   53,   19,   55,   55,  132,  133,
132091:  /*    40 */   134,    1,    2,   27,   28,   29,   30,   31,   32,   33,
132092:  /*    50 */    34,   35,   36,   37,   38,   39,   40,   41,  187,   43,
132093:  /*    60 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
132094:  /*    70 */    47,   48,   49,   50,   51,   52,   53,   61,   97,   97,
132095:  /*    80 */    19,   49,   50,   51,   52,   53,   70,   26,   27,   28,
132096:  /*    90 */    29,   30,   31,   32,   33,   34,   35,   36,   37,   38,
132097:  /*   100 */    39,   40,   41,  152,   43,   44,   45,   46,   47,   48,
132098:  /*   110 */    49,   50,   51,   52,   53,  144,  145,  146,  147,   19,
132099:  /*   120 */   137,   22,  139,  172,  173,   52,   53,   27,   28,   29,
132100:  /*   130 */    30,   31,   32,   33,   34,   35,   36,   37,   38,   39,
132101:  /*   140 */    40,   41,   81,   43,   44,   45,   46,   47,   48,   49,
132102:  /*   150 */    50,   51,   52,   53,   55,   56,   19,  152,  207,  208,
132103:  /*   160 */   115,   24,  117,  118,   27,   28,   29,   30,   31,   32,
132104:  /*   170 */    33,   34,   35,   36,   37,   38,   39,   40,   41,   79,
132105:  /*   180 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132106:  /*   190 */    53,   19,    0,    1,    2,   23,   97,   98,  193,   27,
132107:  /*   200 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132108:  /*   210 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
132109:  /*   220 */    48,   49,   50,   51,   52,   53,   19,   22,   23,  163,
132110:  /*   230 */    23,   26,  190,  191,   27,   28,   29,   30,   31,   32,
132111:  /*   240 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  187,
132112:  /*   250 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132113:  /*   260 */    53,   19,  196,   22,   23,   23,   49,   26,   92,   27,
132114:  /*   270 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132115:  /*   280 */    38,   39,   40,   41,  172,   43,   44,   45,   46,   47,
132116:  /*   290 */    48,   49,   50,   51,   52,   53,   19,  221,  222,  223,
132117:  /*   300 */    23,   96,  119,  120,   27,   28,   29,   30,   31,   32,
132118:  /*   310 */    33,   34,   35,   36,   37,   38,   39,   40,   41,  172,
132119:  /*   320 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132120:  /*   330 */    53,   19,  152,  116,  221,  222,  223,   96,  121,   27,
132121:  /*   340 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132122:  /*   350 */    38,   39,   40,   41,  241,   43,   44,   45,   46,   47,
132123:  /*   360 */    48,   49,   50,   51,   52,   53,   19,  157,  168,  169,
132124:  /*   370 */   170,   22,  190,  191,   27,   28,   29,   30,   31,   32,
132125:  /*   380 */    33,   34,   35,   36,   37,   38,   39,   40,   41,   30,
132126:  /*   390 */    43,   44,   45,   46,   47,   48,   49,   50,   51,   52,
132127:  /*   400 */    53,   19,  172,  152,   55,   56,   24,  247,  248,   27,
132128:  /*   410 */    28,   29,   30,   31,   32,   33,   34,   35,   36,   37,
132129:  /*   420 */    38,   39,   40,   41,  152,   43,   44,   45,   46,   47,
132130:  /*   430 */    48,   49,   50,   51,   52,   53,  146,  147,  228,  179,
132131:  /*   440 */   180,  231,  185,   19,  172,  173,   97,   98,  188,   26,
132132:  /*   450 */   138,   27,   28,   29,   30,   31,   32,   33,   34,   35,
132133:  /*   460 */    36,   37,   38,   39,   40,   41,  107,   43,   44,   45,
132134:  /*   470 */    46,   47,   48,   49,   50,   51,   52,   53,   19,  207,
132135:  /*   480 */   208,   30,   31,   32,   33,  138,   27,   28,   29,   30,
132136:  /*   490 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
132137:  /*   500 */    41,  250,   43,   44,   45,   46,   47,   48,   49,   50,
132138:  /*   510 */    51,   52,   53,   19,  168,  169,  170,    7,    8,    9,
132139:  /*   520 */    19,  152,   28,   29,   30,   31,   32,   33,   34,   35,
132140:  /*   530 */    36,   37,   38,   39,   40,   41,  152,   43,   44,   45,
132141:  /*   540 */    46,   47,   48,   49,   50,   51,   52,   53,   19,  108,
132142:  /*   550 */   109,  110,  101,  130,   53,  152,  172,  173,   29,   30,
132143:  /*   560 */    31,   32,   33,   34,   35,   36,   37,   38,   39,   40,
132144:  /*   570 */    41,  152,   43,   44,   45,   46,   47,   48,   49,   50,
132145:  /*   580 */    51,   52,   53,   19,   20,  116,   22,   23,  169,  170,
132146:  /*   590 */   121,  207,   85,   55,   56,   26,   19,   20,  101,   22,
132147:  /*   600 */    99,  100,  101,  102,  103,  104,  105,  152,  152,  112,
132148:  /*   610 */   210,   47,   48,  112,  152,  108,  109,  110,   54,   55,
132149:  /*   620 */    56,  221,  222,  223,   47,   48,  119,  120,  172,  173,
132150:  /*   630 */    66,   54,   55,   56,  152,   97,   98,   99,  148,  149,
132151:  /*   640 */   102,  103,  104,   66,  154,   23,  156,   83,   26,  230,
132152:  /*   650 */   152,  113,  152,  163,  172,  173,   92,   92,   21,   95,
132153:  /*   660 */    83,   97,   98,  207,  208,  101,  152,   98,  186,   92,
132154:  /*   670 */   172,  173,   95,  218,   97,   98,  152,   99,  101,  217,
132155:  /*   680 */   102,  103,  104,  152,  119,  120,  196,   55,   56,   19,
132156:  /*   690 */    20,  113,   22,  124,  163,   11,  132,  133,  134,  135,
132157:  /*   700 */   136,  152,  152,  172,  173,  207,  208,  152,  152,  132,
132158:  /*   710 */   133,  134,  135,  136,  164,  152,   84,   47,   48,   49,
132159:  /*   720 */    98,  181,  152,  152,   54,   55,   56,  196,   91,   97,
132160:  /*   730 */    98,  160,  218,  163,  244,  164,   66,  152,  207,  208,
132161:  /*   740 */   103,  217,  172,  173,   19,   20,  124,   22,  193,   38,
132162:  /*   750 */    39,   40,   41,   83,   43,   44,   45,   46,   47,   48,
132163:  /*   760 */    49,   50,   51,   52,   53,   95,  196,   97,   98,   85,
132164:  /*   770 */   152,  101,   47,   48,  181,   85,   92,  140,  193,   54,
132165:  /*   780 */    55,   56,   92,   49,  195,   55,   56,  175,  163,   55,
132166:  /*   790 */    56,   66,  108,  109,  110,  206,  163,  242,  108,  109,
132167:  /*   800 */   110,  175,  132,  133,  134,  135,  136,  152,   83,   43,
132168:  /*   810 */    44,   45,   46,   47,   48,   49,   50,   51,   52,   53,
132169:  /*   820 */    95,  196,   97,   98,   55,   56,  101,   97,   98,  196,
132170:  /*   830 */   152,   97,   98,  221,  222,  223,  211,  212,   22,   23,
132171:  /*   840 */    19,   20,  181,   22,   19,  152,  152,  221,  222,  223,
132172:  /*   850 */   172,  173,  219,   19,  124,   30,  238,  132,  133,  134,
132173:  /*   860 */   135,  136,  169,  170,  186,  232,   97,   98,   47,   48,
132174:  /*   870 */   237,  152,  217,  152,    5,   54,   55,   56,  152,   10,
132175:  /*   880 */    11,   12,   13,   14,   47,   48,   17,   66,   47,   48,
132176:  /*   890 */    56,  172,  173,  124,  194,  195,   55,   56,  172,  173,
132177:  /*   900 */   152,  152,   22,  152,   83,  186,  206,  108,  109,  110,
132178:  /*   910 */    22,   23,   96,  152,  193,   12,   95,  152,   97,   98,
132179:  /*   920 */   172,  173,  101,  230,  152,  164,   12,   47,   48,   60,
132180:  /*   930 */   152,   62,  107,  207,  186,   55,   56,  112,   97,   98,
132181:  /*   940 */    71,  100,  193,  152,  183,  152,  185,  152,  107,  152,
132182:  /*   950 */   109,   82,   16,  132,  133,  134,  135,  136,   89,  152,
132183:  /*   960 */    57,   92,   93,  172,  173,  172,  173,  172,  173,  132,
132184:  /*   970 */   133,   57,  152,  132,  133,   95,   73,   97,   75,   55,
132185:  /*   980 */    56,  101,  163,  114,   96,  245,  246,   73,   85,   75,
132186:  /*   990 */    38,   39,   40,   41,   42,   43,   44,   45,   46,   47,
132187:  /*  1000 */    48,   49,   50,   51,   52,   53,  194,  195,  152,  171,
132188:  /*  1010 */   141,  152,  132,  133,  134,  196,  225,  179,  206,   65,
132189:  /*  1020 */   152,   97,   98,  152,   88,  152,   90,  152,  172,  173,
132190:  /*  1030 */   152,  219,   78,  152,  152,  238,  152,  152,  219,  152,
132191:  /*  1040 */    86,  152,  152,  172,  173,  238,  152,  172,  173,  152,
132192:  /*  1050 */   172,  173,  152,  172,  173,  213,  237,  172,  173,  172,
132193:  /*  1060 */   173,  172,  173,  211,  212,  111,  172,  173,  152,  172,
132194:  /*  1070 */   173,  152,  172,  173,  152,  193,  140,  193,  152,   59,
132195:  /*  1080 */   152,  152,  152,   63,  152,   16,  152,  152,  172,  173,
132196:  /*  1090 */   152,  172,  173,  152,  172,  173,  152,   77,  172,  173,
132197:  /*  1100 */   172,  173,  172,  173,  172,  173,  172,  173,  152,  250,
132198:  /*  1110 */   172,  173,   61,  172,  173,  152,  172,  173,  152,   92,
132199:  /*  1120 */   152,   70,  152,  152,  152,   26,  152,  100,  172,  173,
132200:  /*  1130 */   152,   24,  152,   22,  152,  172,  173,  152,  172,  173,
132201:  /*  1140 */   172,  173,  172,  173,  172,  173,  172,  173,  152,  152,
132202:  /*  1150 */   172,  173,  172,  173,  172,  173,  152,   88,  152,   90,
132203:  /*  1160 */   152,   55,   55,  152,  193,  152,   55,  152,  172,  173,
132204:  /*  1170 */    26,  152,  163,  163,  152,   19,  172,  173,  172,  173,
132205:  /*  1180 */   172,  173,   22,  172,  173,  172,  173,  172,  173,   55,
132206:  /*  1190 */   193,  172,  173,  152,  172,  173,  166,  167,  166,  167,
132207:  /*  1200 */   163,  163,  163,   97,   97,  196,  196,  163,   97,   55,
132208:  /*  1210 */    23,  199,   56,   26,   22,   22,   24,  100,  101,   55,
132209:  /*  1220 */    23,  209,  123,   26,   23,   23,   23,   26,   26,   26,
132210:  /*  1230 */    37,   97,  152,  196,  196,  196,   23,    7,    8,   26,
132211:  /*  1240 */   196,   23,   23,  152,   26,   26,   23,  132,  133,   26,
132212:  /*  1250 */   106,   97,  132,  133,   23,  152,  152,   26,  210,  191,
132213:  /*  1260 */   152,   97,  152,  234,  152,  152,  152,  233,  152,  210,
132214:  /*  1270 */   152,  152,  210,  152,  152,  152,  152,  152,  152,  197,
132215:  /*  1280 */   210,  198,  122,  150,  239,  201,  214,  214,  201,  239,
132216:  /*  1290 */   214,  227,  200,  184,  198,  155,   67,  243,  122,   22,
132217:  /*  1300 */   159,  159,   69,  176,  175,  175,  175,  240,  180,  159,
132218:  /*  1310 */   220,  240,   27,  130,   18,   18,  159,  158,  220,  137,
132219:  /*  1320 */   159,  189,  236,  158,   74,  159,  159,  158,  192,  192,
132220:  /*  1330 */   192,  192,  235,   22,  189,  189,  201,  159,  158,  177,
132221:  /*  1340 */   159,  107,  158,   76,  201,  177,  174,  174,  201,  174,
132222:  /*  1350 */   106,  177,  182,  174,  107,  159,   22,  125,  159,  182,
132223:  /*  1360 */   174,  176,  174,  174,  216,  216,  215,  215,  177,  216,
132224:  /*  1370 */   215,   53,  137,  128,  216,  177,  127,  129,  215,  126,
132225:  /*  1380 */    25,   13,  162,   26,    6,  161,  165,  165,  178,  153,
132226:  /*  1390 */   153,  151,  151,  151,  151,  224,    4,    3,   22,  142,
132227:  /*  1400 */    15,   94,   16,  178,  165,  205,   23,  202,  204,  203,
132228:  /*  1410 */   201,   23,  120,  131,  111,   20,  226,  123,  125,   16,
132229:  /*  1420 */     1,  123,  131,  229,  229,  111,   37,   37,   56,   64,
132230:  /*  1430 */   122,    1,    5,   22,  107,  140,   80,   87,   26,   80,
132231:  /*  1440 */   107,   72,   24,   20,   19,  105,   22,  112,   22,   79,
132232:  /*  1450 */    22,   58,   23,   22,   79,   22,  249,  249,  246,   79,
132233:  /*  1460 */    23,   23,   23,  116,   68,   22,   26,   23,   22,   56,
132234:  /*  1470 */   122,   23,   23,   64,   22,  124,   26,   26,   64,   64,
132235:  /*  1480 */    23,   23,   23,   23,   11,   23,   22,   26,   23,   22,
132236:  /*  1490 */    24,    1,   23,   22,   26,  122,   24,   23,   22,  122,
132237:  /*  1500 */    23,   23,   22,  122,  122,   23,   15,
132238: };
132239: #define YY_SHIFT_USE_DFLT (-95)
132240: #define YY_SHIFT_COUNT (442)
132241: #define YY_SHIFT_MIN   (-94)
132242: #define YY_SHIFT_MAX   (1491)
132243: static const short yy_shift_ofst[] = {
132244:  /*     0 */    40,  564,  869,  577,  725,  725,  725,  725,  690,  -19,
132245:  /*    10 */    16,   16,  100,  725,  725,  725,  725,  725,  725,  725,
132246:  /*    20 */   841,  841,  538,  507,  684,  565,   61,  137,  172,  207,
132247:  /*    30 */   242,  277,  312,  347,  382,  424,  424,  424,  424,  424,
132248:  /*    40 */   424,  424,  424,  424,  424,  424,  424,  424,  424,  424,
132249:  /*    50 */   459,  424,  494,  529,  529,  670,  725,  725,  725,  725,
132250:  /*    60 */   725,  725,  725,  725,  725,  725,  725,  725,  725,  725,
132251:  /*    70 */   725,  725,  725,  725,  725,  725,  725,  725,  725,  725,
132252:  /*    80 */   725,  725,  725,  725,  821,  725,  725,  725,  725,  725,
132253:  /*    90 */   725,  725,  725,  725,  725,  725,  725,  725,  952,  711,
132254:  /*   100 */   711,  711,  711,  711,  766,   23,   32,  924,  637,  825,
132255:  /*   110 */   837,  837,  924,   73,  183,  -51,  -95,  -95,  -95,  501,
132256:  /*   120 */   501,  501,  903,  903,  632,  205,  241,  924,  924,  924,
132257:  /*   130 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132258:  /*   140 */   924,  924,  924,  924,  924,  924,  924,  192, 1027, 1106,
132259:  /*   150 */  1106,  183,  176,  176,  176,  176,  176,  176,  -95,  -95,
132260:  /*   160 */   -95,  880,  -94,  -94,  578,  734,   99,  730,  769,  349,
132261:  /*   170 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132262:  /*   180 */   924,  924,  924,  924,  924,  924,  924,  954,  954,  954,
132263:  /*   190 */   924,  924,  622,  924,  924,  924,  -18,  924,  924,  914,
132264:  /*   200 */   924,  924,  924,  924,  924,  924,  924,  924,  924,  924,
132265:  /*   210 */   441, 1020, 1107, 1107, 1107,  569,   45,  217,  510,  423,
132266:  /*   220 */   834,  834, 1156,  423, 1156, 1144, 1187,  359, 1051,  834,
132267:  /*   230 */   -17, 1051, 1051, 1099,  469, 1192, 1229, 1176, 1176, 1233,
132268:  /*   240 */  1233, 1176, 1277, 1285, 1183, 1296, 1296, 1296, 1296, 1176,
132269:  /*   250 */  1297, 1183, 1277, 1285, 1285, 1183, 1176, 1297, 1182, 1250,
132270:  /*   260 */  1176, 1176, 1297, 1311, 1176, 1297, 1176, 1297, 1311, 1234,
132271:  /*   270 */  1234, 1234, 1267, 1311, 1234, 1244, 1234, 1267, 1234, 1234,
132272:  /*   280 */  1232, 1247, 1232, 1247, 1232, 1247, 1232, 1247, 1176, 1334,
132273:  /*   290 */  1176, 1235, 1311, 1318, 1318, 1311, 1248, 1253, 1245, 1249,
132274:  /*   300 */  1183, 1355, 1357, 1368, 1368, 1378, 1378, 1378, 1378,  -95,
132275:  /*   310 */   -95,  -95,  -95,  -95,  -95,  -95,  -95,  451,  936,  816,
132276:  /*   320 */   888, 1069,  799, 1111, 1197, 1193, 1201, 1202, 1203, 1213,
132277:  /*   330 */  1134, 1117, 1230,  497, 1218, 1219, 1154, 1223, 1115, 1120,
132278:  /*   340 */  1231, 1164, 1160, 1392, 1394, 1376, 1257, 1385, 1307, 1386,
132279:  /*   350 */  1383, 1388, 1292, 1282, 1303, 1294, 1395, 1293, 1403, 1419,
132280:  /*   360 */  1298, 1291, 1389, 1390, 1314, 1372, 1365, 1308, 1430, 1427,
132281:  /*   370 */  1411, 1327, 1295, 1356, 1412, 1359, 1350, 1369, 1333, 1418,
132282:  /*   380 */  1423, 1425, 1335, 1340, 1424, 1370, 1426, 1428, 1429, 1431,
132283:  /*   390 */  1375, 1393, 1433, 1380, 1396, 1437, 1438, 1439, 1347, 1443,
132284:  /*   400 */  1444, 1446, 1440, 1348, 1448, 1449, 1413, 1409, 1452, 1351,
132285:  /*   410 */  1450, 1414, 1451, 1415, 1457, 1450, 1458, 1459, 1460, 1461,
132286:  /*   420 */  1462, 1464, 1473, 1465, 1467, 1466, 1468, 1469, 1471, 1472,
132287:  /*   430 */  1468, 1474, 1476, 1477, 1478, 1480, 1373, 1377, 1381, 1382,
132288:  /*   440 */  1482, 1491, 1490,
132289: };
132290: #define YY_REDUCE_USE_DFLT (-130)
132291: #define YY_REDUCE_COUNT (316)
132292: #define YY_REDUCE_MIN   (-129)
132293: #define YY_REDUCE_MAX   (1243)
132294: static const short yy_reduce_ofst[] = {
132295:  /*     0 */   -29,  531,  490,  570,  -49,  272,  456,  498,  633,  400,
132296:  /*    10 */   612,  626,  113,  482,  678,  719,  384,  726,  748,  791,
132297:  /*    20 */   419,  693,  761,  812,  819,  625,   76,   76,   76,   76,
132298:  /*    30 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
132299:  /*    40 */    76,   76,   76,   76,   76,   76,   76,   76,   76,   76,
132300:  /*    50 */    76,   76,   76,   76,   76,  793,  795,  856,  871,  875,
132301:  /*    60 */   878,  881,  885,  887,  889,  894,  897,  900,  916,  919,
132302:  /*    70 */   922,  926,  928,  930,  932,  934,  938,  941,  944,  956,
132303:  /*    80 */   963,  966,  968,  970,  972,  974,  978,  980,  982,  996,
132304:  /*    90 */  1004, 1006, 1008, 1011, 1013, 1015, 1019, 1022,   76,   76,
132305:  /*   100 */    76,   76,   76,   76,   76,   76,   76,  555,  210,  260,
132306:  /*   110 */   200,  346,  571,   76,  700,   76,   76,   76,   76,  838,
132307:  /*   120 */   838,  838,   42,  182,  251,  160,  160,  550,    5,  455,
132308:  /*   130 */   585,  721,  749,  882,  884,  971,  618,  462,  797,  514,
132309:  /*   140 */   807,  524,  997, -129,  655,  859,   62,  290,   66, 1030,
132310:  /*   150 */  1032,  589, 1009, 1010, 1037, 1038, 1039, 1044,  740,  852,
132311:  /*   160 */  1012,  112,  147,  230,  257,  180,  369,  403,  500,  549,
132312:  /*   170 */   556,  563,  694,  751,  765,  772,  778,  820,  868,  873,
132313:  /*   180 */   890,  929,  935,  985, 1041, 1080, 1091,  540,  593,  661,
132314:  /*   190 */  1103, 1104,  842, 1108, 1110, 1112, 1048, 1113, 1114, 1068,
132315:  /*   200 */  1116, 1118, 1119,  180, 1121, 1122, 1123, 1124, 1125, 1126,
132316:  /*   210 */  1029, 1034, 1059, 1062, 1070,  842, 1082, 1083, 1133, 1084,
132317:  /*   220 */  1072, 1073, 1045, 1087, 1050, 1127, 1109, 1128, 1129, 1076,
132318:  /*   230 */  1064, 1130, 1131, 1092, 1096, 1140, 1054, 1141, 1142, 1067,
132319:  /*   240 */  1071, 1150, 1090, 1132, 1135, 1136, 1137, 1138, 1139, 1157,
132320:  /*   250 */  1159, 1143, 1098, 1145, 1146, 1147, 1161, 1165, 1086, 1097,
132321:  /*   260 */  1166, 1167, 1169, 1162, 1178, 1180, 1181, 1184, 1168, 1172,
132322:  /*   270 */  1173, 1175, 1170, 1174, 1179, 1185, 1186, 1177, 1188, 1189,
132323:  /*   280 */  1148, 1151, 1149, 1152, 1153, 1155, 1158, 1163, 1196, 1171,
132324:  /*   290 */  1199, 1190, 1191, 1194, 1195, 1198, 1200, 1204, 1206, 1205,
132325:  /*   300 */  1209, 1220, 1224, 1236, 1237, 1240, 1241, 1242, 1243, 1207,
132326:  /*   310 */  1208, 1212, 1221, 1222, 1210, 1225, 1239,
132327: };
132328: static const YYACTIONTYPE yy_default[] = {
132329:  /*     0 */  1258, 1248, 1248, 1248, 1180, 1180, 1180, 1180, 1248, 1077,
132330:  /*    10 */  1106, 1106, 1232, 1309, 1309, 1309, 1309, 1309, 1309, 1179,
132331:  /*    20 */  1309, 1309, 1309, 1309, 1248, 1081, 1112, 1309, 1309, 1309,
132332:  /*    30 */  1309, 1309, 1309, 1309, 1309, 1231, 1233, 1120, 1119, 1214,
132333:  /*    40 */  1093, 1117, 1110, 1114, 1181, 1175, 1176, 1174, 1178, 1182,
132334:  /*    50 */  1309, 1113, 1144, 1159, 1143, 1309, 1309, 1309, 1309, 1309,
132335:  /*    60 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132336:  /*    70 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132337:  /*    80 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132338:  /*    90 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1153, 1158,
132339:  /*   100 */  1165, 1157, 1154, 1146, 1145, 1147, 1148, 1309, 1000, 1048,
132340:  /*   110 */  1309, 1309, 1309, 1149, 1309, 1150, 1162, 1161, 1160, 1239,
132341:  /*   120 */  1266, 1265, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132342:  /*   130 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132343:  /*   140 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1258, 1248, 1006,
132344:  /*   150 */  1006, 1309, 1248, 1248, 1248, 1248, 1248, 1248, 1244, 1081,
132345:  /*   160 */  1072, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132346:  /*   170 */  1309, 1236, 1234, 1309, 1195, 1309, 1309, 1309, 1309, 1309,
132347:  /*   180 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132348:  /*   190 */  1309, 1309, 1309, 1309, 1309, 1309, 1077, 1309, 1309, 1309,
132349:  /*   200 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1260,
132350:  /*   210 */  1309, 1209, 1077, 1077, 1077, 1079, 1061, 1071,  985, 1116,
132351:  /*   220 */  1095, 1095, 1298, 1116, 1298, 1023, 1280, 1020, 1106, 1095,
132352:  /*   230 */  1177, 1106, 1106, 1078, 1071, 1309, 1301, 1086, 1086, 1300,
132353:  /*   240 */  1300, 1086, 1125, 1051, 1116, 1057, 1057, 1057, 1057, 1086,
132354:  /*   250 */   997, 1116, 1125, 1051, 1051, 1116, 1086,  997, 1213, 1295,
132355:  /*   260 */  1086, 1086,  997, 1188, 1086,  997, 1086,  997, 1188, 1049,
132356:  /*   270 */  1049, 1049, 1038, 1188, 1049, 1023, 1049, 1038, 1049, 1049,
132357:  /*   280 */  1099, 1094, 1099, 1094, 1099, 1094, 1099, 1094, 1086, 1183,
132358:  /*   290 */  1086, 1309, 1188, 1192, 1192, 1188, 1111, 1100, 1109, 1107,
132359:  /*   300 */  1116, 1003, 1041, 1263, 1263, 1259, 1259, 1259, 1259, 1306,
132360:  /*   310 */  1306, 1244, 1275, 1275, 1025, 1025, 1275, 1309, 1309, 1309,
132361:  /*   320 */  1309, 1309, 1309, 1270, 1309, 1197, 1309, 1309, 1309, 1309,
132362:  /*   330 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132363:  /*   340 */  1309, 1309, 1131, 1309,  981, 1241, 1309, 1309, 1240, 1309,
132364:  /*   350 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132365:  /*   360 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1297, 1309, 1309,
132366:  /*   370 */  1309, 1309, 1309, 1309, 1212, 1211, 1309, 1309, 1309, 1309,
132367:  /*   380 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132368:  /*   390 */  1309, 1309, 1309, 1309, 1309, 1309, 1309, 1309, 1063, 1309,
132369:  /*   400 */  1309, 1309, 1284, 1309, 1309, 1309, 1309, 1309, 1309, 1309,
132370:  /*   410 */  1108, 1309, 1101, 1309, 1309, 1288, 1309, 1309, 1309, 1309,
132371:  /*   420 */  1309, 1309, 1309, 1309, 1309, 1309, 1250, 1309, 1309, 1309,
132372:  /*   430 */  1249, 1309, 1309, 1309, 1309, 1309, 1133, 1309, 1132, 1136,
132373:  /*   440 */  1309,  991, 1309,
132374: };
132375: /********** End of lemon-generated parsing tables *****************************/
132376: 
132377: /* The next table maps tokens (terminal symbols) into fallback tokens.  
132378: ** If a construct like the following:
132379: ** 
132380: **      %fallback ID X Y Z.
132381: **
132382: ** appears in the grammar, then ID becomes a fallback token for X, Y,
132383: ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
132384: ** but it does not parse, the type of the token is changed to ID and
132385: ** the parse is retried before an error is thrown.
132386: **
132387: ** This feature can be used, for example, to cause some keywords in a language
132388: ** to revert to identifiers if they keyword does not apply in the context where
132389: ** it appears.
132390: */
132391: #ifdef YYFALLBACK
132392: static const YYCODETYPE yyFallback[] = {
132393:     0,  /*          $ => nothing */
132394:     0,  /*       SEMI => nothing */
132395:    55,  /*    EXPLAIN => ID */
132396:    55,  /*      QUERY => ID */
132397:    55,  /*       PLAN => ID */
132398:    55,  /*      BEGIN => ID */
132399:     0,  /* TRANSACTION => nothing */
132400:    55,  /*   DEFERRED => ID */
132401:    55,  /*  IMMEDIATE => ID */
132402:    55,  /*  EXCLUSIVE => ID */
132403:     0,  /*     COMMIT => nothing */
132404:    55,  /*        END => ID */
132405:    55,  /*   ROLLBACK => ID */
132406:    55,  /*  SAVEPOINT => ID */
132407:    55,  /*    RELEASE => ID */
132408:     0,  /*         TO => nothing */
132409:     0,  /*      TABLE => nothing */
132410:     0,  /*     CREATE => nothing */
132411:    55,  /*         IF => ID */
132412:     0,  /*        NOT => nothing */
132413:     0,  /*     EXISTS => nothing */
132414:    55,  /*       TEMP => ID */
132415:     0,  /*         LP => nothing */
132416:     0,  /*         RP => nothing */
132417:     0,  /*         AS => nothing */
132418:    55,  /*    WITHOUT => ID */
132419:     0,  /*      COMMA => nothing */
132420:     0,  /*         OR => nothing */
132421:     0,  /*        AND => nothing */
132422:     0,  /*         IS => nothing */
132423:    55,  /*      MATCH => ID */
132424:    55,  /*    LIKE_KW => ID */
132425:     0,  /*    BETWEEN => nothing */
132426:     0,  /*         IN => nothing */
132427:     0,  /*     ISNULL => nothing */
132428:     0,  /*    NOTNULL => nothing */
132429:     0,  /*         NE => nothing */
132430:     0,  /*         EQ => nothing */
132431:     0,  /*         GT => nothing */
132432:     0,  /*         LE => nothing */
132433:     0,  /*         LT => nothing */
132434:     0,  /*         GE => nothing */
132435:     0,  /*     ESCAPE => nothing */
132436:     0,  /*     BITAND => nothing */
132437:     0,  /*      BITOR => nothing */
132438:     0,  /*     LSHIFT => nothing */
132439:     0,  /*     RSHIFT => nothing */
132440:     0,  /*       PLUS => nothing */
132441:     0,  /*      MINUS => nothing */
132442:     0,  /*       STAR => nothing */
132443:     0,  /*      SLASH => nothing */
132444:     0,  /*        REM => nothing */
132445:     0,  /*     CONCAT => nothing */
132446:     0,  /*    COLLATE => nothing */
132447:     0,  /*     BITNOT => nothing */
132448:     0,  /*         ID => nothing */
132449:     0,  /*    INDEXED => nothing */
132450:    55,  /*      ABORT => ID */
132451:    55,  /*     ACTION => ID */
132452:    55,  /*      AFTER => ID */
132453:    55,  /*    ANALYZE => ID */
132454:    55,  /*        ASC => ID */
132455:    55,  /*     ATTACH => ID */
132456:    55,  /*     BEFORE => ID */
132457:    55,  /*         BY => ID */
132458:    55,  /*    CASCADE => ID */
132459:    55,  /*       CAST => ID */
132460:    55,  /*   COLUMNKW => ID */
132461:    55,  /*   CONFLICT => ID */
132462:    55,  /*   DATABASE => ID */
132463:    55,  /*       DESC => ID */
132464:    55,  /*     DETACH => ID */
132465:    55,  /*       EACH => ID */
132466:    55,  /*       FAIL => ID */
132467:    55,  /*        FOR => ID */
132468:    55,  /*     IGNORE => ID */
132469:    55,  /*  INITIALLY => ID */
132470:    55,  /*    INSTEAD => ID */
132471:    55,  /*         NO => ID */
132472:    55,  /*        KEY => ID */
132473:    55,  /*         OF => ID */
132474:    55,  /*     OFFSET => ID */
132475:    55,  /*     PRAGMA => ID */
132476:    55,  /*      RAISE => ID */
132477:    55,  /*  RECURSIVE => ID */
132478:    55,  /*    REPLACE => ID */
132479:    55,  /*   RESTRICT => ID */
132480:    55,  /*        ROW => ID */
132481:    55,  /*    TRIGGER => ID */
132482:    55,  /*     VACUUM => ID */
132483:    55,  /*       VIEW => ID */
132484:    55,  /*    VIRTUAL => ID */
132485:    55,  /*       WITH => ID */
132486:    55,  /*    REINDEX => ID */
132487:    55,  /*     RENAME => ID */
132488:    55,  /*   CTIME_KW => ID */
132489: };
132490: #endif /* YYFALLBACK */
132491: 
132492: /* The following structure represents a single element of the
132493: ** parser's stack.  Information stored includes:
132494: **
132495: **   +  The state number for the parser at this level of the stack.
132496: **
132497: **   +  The value of the token stored at this level of the stack.
132498: **      (In other words, the "major" token.)
132499: **
132500: **   +  The semantic value stored at this level of the stack.  This is
132501: **      the information used by the action routines in the grammar.
132502: **      It is sometimes called the "minor" token.
132503: **
132504: ** After the "shift" half of a SHIFTREDUCE action, the stateno field
132505: ** actually contains the reduce action for the second half of the
132506: ** SHIFTREDUCE.
132507: */
132508: struct yyStackEntry {
132509:   YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
132510:   YYCODETYPE major;      /* The major token value.  This is the code
132511:                          ** number for the token at this stack level */
132512:   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
132513:                          ** is the value of the token  */
132514: };
132515: typedef struct yyStackEntry yyStackEntry;
132516: 
132517: /* The state of the parser is completely contained in an instance of
132518: ** the following structure */
132519: struct yyParser {
132520:   yyStackEntry *yytos;          /* Pointer to top element of the stack */
132521: #ifdef YYTRACKMAXSTACKDEPTH
132522:   int yyhwm;                    /* High-water mark of the stack */
132523: #endif
132524: #ifndef YYNOERRORRECOVERY
132525:   int yyerrcnt;                 /* Shifts left before out of the error */
132526: #endif
132527:   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
132528: #if YYSTACKDEPTH<=0
132529:   int yystksz;                  /* Current side of the stack */
132530:   yyStackEntry *yystack;        /* The parser's stack */
132531:   yyStackEntry yystk0;          /* First stack entry */
132532: #else
132533:   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
132534: #endif
132535: };
132536: typedef struct yyParser yyParser;
132537: 
132538: #ifndef NDEBUG
132539: /* #include <stdio.h> */
132540: static FILE *yyTraceFILE = 0;
132541: static char *yyTracePrompt = 0;
132542: #endif /* NDEBUG */
132543: 
132544: #ifndef NDEBUG
132545: /* 
132546: ** Turn parser tracing on by giving a stream to which to write the trace
132547: ** and a prompt to preface each trace message.  Tracing is turned off
132548: ** by making either argument NULL 
132549: **
132550: ** Inputs:
132551: ** <ul>
132552: ** <li> A FILE* to which trace output should be written.
132553: **      If NULL, then tracing is turned off.
132554: ** <li> A prefix string written at the beginning of every
132555: **      line of trace output.  If NULL, then tracing is
132556: **      turned off.
132557: ** </ul>
132558: **
132559: ** Outputs:
132560: ** None.
132561: */
132562: SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
132563:   yyTraceFILE = TraceFILE;
132564:   yyTracePrompt = zTracePrompt;
132565:   if( yyTraceFILE==0 ) yyTracePrompt = 0;
132566:   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
132567: }
132568: #endif /* NDEBUG */
132569: 
132570: #ifndef NDEBUG
132571: /* For tracing shifts, the names of all terminals and nonterminals
132572: ** are required.  The following table supplies these names */
132573: static const char *const yyTokenName[] = { 
132574:   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
132575:   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
132576:   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
132577:   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
132578:   "TABLE",         "CREATE",        "IF",            "NOT",         
132579:   "EXISTS",        "TEMP",          "LP",            "RP",          
132580:   "AS",            "WITHOUT",       "COMMA",         "OR",          
132581:   "AND",           "IS",            "MATCH",         "LIKE_KW",     
132582:   "BETWEEN",       "IN",            "ISNULL",        "NOTNULL",     
132583:   "NE",            "EQ",            "GT",            "LE",          
132584:   "LT",            "GE",            "ESCAPE",        "BITAND",      
132585:   "BITOR",         "LSHIFT",        "RSHIFT",        "PLUS",        
132586:   "MINUS",         "STAR",          "SLASH",         "REM",         
132587:   "CONCAT",        "COLLATE",       "BITNOT",        "ID",          
132588:   "INDEXED",       "ABORT",         "ACTION",        "AFTER",       
132589:   "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",      
132590:   "BY",            "CASCADE",       "CAST",          "COLUMNKW",    
132591:   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
132592:   "EACH",          "FAIL",          "FOR",           "IGNORE",      
132593:   "INITIALLY",     "INSTEAD",       "NO",            "KEY",         
132594:   "OF",            "OFFSET",        "PRAGMA",        "RAISE",       
132595:   "RECURSIVE",     "REPLACE",       "RESTRICT",      "ROW",         
132596:   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
132597:   "WITH",          "REINDEX",       "RENAME",        "CTIME_KW",    
132598:   "ANY",           "STRING",        "JOIN_KW",       "CONSTRAINT",  
132599:   "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",      
132600:   "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",          
132601:   "INSERT",        "DELETE",        "UPDATE",        "SET",         
132602:   "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",       
132603:   "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",      
132604:   "VALUES",        "DISTINCT",      "DOT",           "FROM",        
132605:   "JOIN",          "USING",         "ORDER",         "GROUP",       
132606:   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
132607:   "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",    
132608:   "CASE",          "WHEN",          "THEN",          "ELSE",        
132609:   "INDEX",         "ALTER",         "ADD",           "error",       
132610:   "input",         "cmdlist",       "ecmd",          "explain",     
132611:   "cmdx",          "cmd",           "transtype",     "trans_opt",   
132612:   "nm",            "savepoint_opt",  "create_table",  "create_table_args",
132613:   "createkw",      "temp",          "ifnotexists",   "dbnm",        
132614:   "columnlist",    "conslist_opt",  "table_options",  "select",      
132615:   "columnname",    "carglist",      "typetoken",     "typename",    
132616:   "signed",        "plus_num",      "minus_num",     "ccons",       
132617:   "term",          "expr",          "onconf",        "sortorder",   
132618:   "autoinc",       "eidlist_opt",   "refargs",       "defer_subclause",
132619:   "refarg",        "refact",        "init_deferred_pred_opt",  "conslist",    
132620:   "tconscomma",    "tcons",         "sortlist",      "eidlist",     
132621:   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
132622:   "ifexists",      "fullname",      "selectnowith",  "oneselect",   
132623:   "with",          "multiselect_op",  "distinct",      "selcollist",  
132624:   "from",          "where_opt",     "groupby_opt",   "having_opt",  
132625:   "orderby_opt",   "limit_opt",     "values",        "nexprlist",   
132626:   "exprlist",      "sclp",          "as",            "seltablist",  
132627:   "stl_prefix",    "joinop",        "indexed_opt",   "on_opt",      
132628:   "using_opt",     "idlist",        "setlist",       "insert_cmd",  
132629:   "idlist_opt",    "likeop",        "between_op",    "in_op",       
132630:   "paren_exprlist",  "case_operand",  "case_exprlist",  "case_else",   
132631:   "uniqueflag",    "collate",       "nmnum",         "trigger_decl",
132632:   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
132633:   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",     
132634:   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
132635:   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
132636:   "lp",            "anylist",       "wqlist",      
132637: };
132638: #endif /* NDEBUG */
132639: 
132640: #ifndef NDEBUG
132641: /* For tracing reduce actions, the names of all rules are required.
132642: */
132643: static const char *const yyRuleName[] = {
132644:  /*   0 */ "explain ::= EXPLAIN",
132645:  /*   1 */ "explain ::= EXPLAIN QUERY PLAN",
132646:  /*   2 */ "cmdx ::= cmd",
132647:  /*   3 */ "cmd ::= BEGIN transtype trans_opt",
132648:  /*   4 */ "transtype ::=",
132649:  /*   5 */ "transtype ::= DEFERRED",
132650:  /*   6 */ "transtype ::= IMMEDIATE",
132651:  /*   7 */ "transtype ::= EXCLUSIVE",
132652:  /*   8 */ "cmd ::= COMMIT trans_opt",
132653:  /*   9 */ "cmd ::= END trans_opt",
132654:  /*  10 */ "cmd ::= ROLLBACK trans_opt",
132655:  /*  11 */ "cmd ::= SAVEPOINT nm",
132656:  /*  12 */ "cmd ::= RELEASE savepoint_opt nm",
132657:  /*  13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
132658:  /*  14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
132659:  /*  15 */ "createkw ::= CREATE",
132660:  /*  16 */ "ifnotexists ::=",
132661:  /*  17 */ "ifnotexists ::= IF NOT EXISTS",
132662:  /*  18 */ "temp ::= TEMP",
132663:  /*  19 */ "temp ::=",
132664:  /*  20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
132665:  /*  21 */ "create_table_args ::= AS select",
132666:  /*  22 */ "table_options ::=",
132667:  /*  23 */ "table_options ::= WITHOUT nm",
132668:  /*  24 */ "columnname ::= nm typetoken",
132669:  /*  25 */ "typetoken ::=",
132670:  /*  26 */ "typetoken ::= typename LP signed RP",
132671:  /*  27 */ "typetoken ::= typename LP signed COMMA signed RP",
132672:  /*  28 */ "typename ::= typename ID|STRING",
132673:  /*  29 */ "ccons ::= CONSTRAINT nm",
132674:  /*  30 */ "ccons ::= DEFAULT term",
132675:  /*  31 */ "ccons ::= DEFAULT LP expr RP",
132676:  /*  32 */ "ccons ::= DEFAULT PLUS term",
132677:  /*  33 */ "ccons ::= DEFAULT MINUS term",
132678:  /*  34 */ "ccons ::= DEFAULT ID|INDEXED",
132679:  /*  35 */ "ccons ::= NOT NULL onconf",
132680:  /*  36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
132681:  /*  37 */ "ccons ::= UNIQUE onconf",
132682:  /*  38 */ "ccons ::= CHECK LP expr RP",
132683:  /*  39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
132684:  /*  40 */ "ccons ::= defer_subclause",
132685:  /*  41 */ "ccons ::= COLLATE ID|STRING",
132686:  /*  42 */ "autoinc ::=",
132687:  /*  43 */ "autoinc ::= AUTOINCR",
132688:  /*  44 */ "refargs ::=",
132689:  /*  45 */ "refargs ::= refargs refarg",
132690:  /*  46 */ "refarg ::= MATCH nm",
132691:  /*  47 */ "refarg ::= ON INSERT refact",
132692:  /*  48 */ "refarg ::= ON DELETE refact",
132693:  /*  49 */ "refarg ::= ON UPDATE refact",
132694:  /*  50 */ "refact ::= SET NULL",
132695:  /*  51 */ "refact ::= SET DEFAULT",
132696:  /*  52 */ "refact ::= CASCADE",
132697:  /*  53 */ "refact ::= RESTRICT",
132698:  /*  54 */ "refact ::= NO ACTION",
132699:  /*  55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
132700:  /*  56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
132701:  /*  57 */ "init_deferred_pred_opt ::=",
132702:  /*  58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
132703:  /*  59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
132704:  /*  60 */ "conslist_opt ::=",
132705:  /*  61 */ "tconscomma ::= COMMA",
132706:  /*  62 */ "tcons ::= CONSTRAINT nm",
132707:  /*  63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
132708:  /*  64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
132709:  /*  65 */ "tcons ::= CHECK LP expr RP onconf",
132710:  /*  66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
132711:  /*  67 */ "defer_subclause_opt ::=",
132712:  /*  68 */ "onconf ::=",
132713:  /*  69 */ "onconf ::= ON CONFLICT resolvetype",
132714:  /*  70 */ "orconf ::=",
132715:  /*  71 */ "orconf ::= OR resolvetype",
132716:  /*  72 */ "resolvetype ::= IGNORE",
132717:  /*  73 */ "resolvetype ::= REPLACE",
132718:  /*  74 */ "cmd ::= DROP TABLE ifexists fullname",
132719:  /*  75 */ "ifexists ::= IF EXISTS",
132720:  /*  76 */ "ifexists ::=",
132721:  /*  77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
132722:  /*  78 */ "cmd ::= DROP VIEW ifexists fullname",
132723:  /*  79 */ "cmd ::= select",
132724:  /*  80 */ "select ::= with selectnowith",
132725:  /*  81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
132726:  /*  82 */ "multiselect_op ::= UNION",
132727:  /*  83 */ "multiselect_op ::= UNION ALL",
132728:  /*  84 */ "multiselect_op ::= EXCEPT|INTERSECT",
132729:  /*  85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
132730:  /*  86 */ "values ::= VALUES LP nexprlist RP",
132731:  /*  87 */ "values ::= values COMMA LP exprlist RP",
132732:  /*  88 */ "distinct ::= DISTINCT",
132733:  /*  89 */ "distinct ::= ALL",
132734:  /*  90 */ "distinct ::=",
132735:  /*  91 */ "sclp ::=",
132736:  /*  92 */ "selcollist ::= sclp expr as",
132737:  /*  93 */ "selcollist ::= sclp STAR",
132738:  /*  94 */ "selcollist ::= sclp nm DOT STAR",
132739:  /*  95 */ "as ::= AS nm",
132740:  /*  96 */ "as ::=",
132741:  /*  97 */ "from ::=",
132742:  /*  98 */ "from ::= FROM seltablist",
132743:  /*  99 */ "stl_prefix ::= seltablist joinop",
132744:  /* 100 */ "stl_prefix ::=",
132745:  /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
132746:  /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
132747:  /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
132748:  /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
132749:  /* 105 */ "dbnm ::=",
132750:  /* 106 */ "dbnm ::= DOT nm",
132751:  /* 107 */ "fullname ::= nm dbnm",
132752:  /* 108 */ "joinop ::= COMMA|JOIN",
132753:  /* 109 */ "joinop ::= JOIN_KW JOIN",
132754:  /* 110 */ "joinop ::= JOIN_KW nm JOIN",
132755:  /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
132756:  /* 112 */ "on_opt ::= ON expr",
132757:  /* 113 */ "on_opt ::=",
132758:  /* 114 */ "indexed_opt ::=",
132759:  /* 115 */ "indexed_opt ::= INDEXED BY nm",
132760:  /* 116 */ "indexed_opt ::= NOT INDEXED",
132761:  /* 117 */ "using_opt ::= USING LP idlist RP",
132762:  /* 118 */ "using_opt ::=",
132763:  /* 119 */ "orderby_opt ::=",
132764:  /* 120 */ "orderby_opt ::= ORDER BY sortlist",
132765:  /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
132766:  /* 122 */ "sortlist ::= expr sortorder",
132767:  /* 123 */ "sortorder ::= ASC",
132768:  /* 124 */ "sortorder ::= DESC",
132769:  /* 125 */ "sortorder ::=",
132770:  /* 126 */ "groupby_opt ::=",
132771:  /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
132772:  /* 128 */ "having_opt ::=",
132773:  /* 129 */ "having_opt ::= HAVING expr",
132774:  /* 130 */ "limit_opt ::=",
132775:  /* 131 */ "limit_opt ::= LIMIT expr",
132776:  /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
132777:  /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
132778:  /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
132779:  /* 135 */ "where_opt ::=",
132780:  /* 136 */ "where_opt ::= WHERE expr",
132781:  /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
132782:  /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
132783:  /* 139 */ "setlist ::= nm EQ expr",
132784:  /* 140 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
132785:  /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
132786:  /* 142 */ "insert_cmd ::= INSERT orconf",
132787:  /* 143 */ "insert_cmd ::= REPLACE",
132788:  /* 144 */ "idlist_opt ::=",
132789:  /* 145 */ "idlist_opt ::= LP idlist RP",
132790:  /* 146 */ "idlist ::= idlist COMMA nm",
132791:  /* 147 */ "idlist ::= nm",
132792:  /* 148 */ "expr ::= LP expr RP",
132793:  /* 149 */ "term ::= NULL",
132794:  /* 150 */ "expr ::= ID|INDEXED",
132795:  /* 151 */ "expr ::= JOIN_KW",
132796:  /* 152 */ "expr ::= nm DOT nm",
132797:  /* 153 */ "expr ::= nm DOT nm DOT nm",
132798:  /* 154 */ "term ::= INTEGER|FLOAT|BLOB",
132799:  /* 155 */ "term ::= STRING",
132800:  /* 156 */ "expr ::= VARIABLE",
132801:  /* 157 */ "expr ::= expr COLLATE ID|STRING",
132802:  /* 158 */ "expr ::= CAST LP expr AS typetoken RP",
132803:  /* 159 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
132804:  /* 160 */ "expr ::= ID|INDEXED LP STAR RP",
132805:  /* 161 */ "term ::= CTIME_KW",
132806:  /* 162 */ "expr ::= expr AND expr",
132807:  /* 163 */ "expr ::= expr OR expr",
132808:  /* 164 */ "expr ::= expr LT|GT|GE|LE expr",
132809:  /* 165 */ "expr ::= expr EQ|NE expr",
132810:  /* 166 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
132811:  /* 167 */ "expr ::= expr PLUS|MINUS expr",
132812:  /* 168 */ "expr ::= expr STAR|SLASH|REM expr",
132813:  /* 169 */ "expr ::= expr CONCAT expr",
132814:  /* 170 */ "likeop ::= LIKE_KW|MATCH",
132815:  /* 171 */ "likeop ::= NOT LIKE_KW|MATCH",
132816:  /* 172 */ "expr ::= expr likeop expr",
132817:  /* 173 */ "expr ::= expr likeop expr ESCAPE expr",
132818:  /* 174 */ "expr ::= expr ISNULL|NOTNULL",
132819:  /* 175 */ "expr ::= expr NOT NULL",
132820:  /* 176 */ "expr ::= expr IS expr",
132821:  /* 177 */ "expr ::= expr IS NOT expr",
132822:  /* 178 */ "expr ::= NOT expr",
132823:  /* 179 */ "expr ::= BITNOT expr",
132824:  /* 180 */ "expr ::= MINUS expr",
132825:  /* 181 */ "expr ::= PLUS expr",
132826:  /* 182 */ "between_op ::= BETWEEN",
132827:  /* 183 */ "between_op ::= NOT BETWEEN",
132828:  /* 184 */ "expr ::= expr between_op expr AND expr",
132829:  /* 185 */ "in_op ::= IN",
132830:  /* 186 */ "in_op ::= NOT IN",
132831:  /* 187 */ "expr ::= expr in_op LP exprlist RP",
132832:  /* 188 */ "expr ::= LP select RP",
132833:  /* 189 */ "expr ::= expr in_op LP select RP",
132834:  /* 190 */ "expr ::= expr in_op nm dbnm paren_exprlist",
132835:  /* 191 */ "expr ::= EXISTS LP select RP",
132836:  /* 192 */ "expr ::= CASE case_operand case_exprlist case_else END",
132837:  /* 193 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
132838:  /* 194 */ "case_exprlist ::= WHEN expr THEN expr",
132839:  /* 195 */ "case_else ::= ELSE expr",
132840:  /* 196 */ "case_else ::=",
132841:  /* 197 */ "case_operand ::= expr",
132842:  /* 198 */ "case_operand ::=",
132843:  /* 199 */ "exprlist ::=",
132844:  /* 200 */ "nexprlist ::= nexprlist COMMA expr",
132845:  /* 201 */ "nexprlist ::= expr",
132846:  /* 202 */ "paren_exprlist ::=",
132847:  /* 203 */ "paren_exprlist ::= LP exprlist RP",
132848:  /* 204 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
132849:  /* 205 */ "uniqueflag ::= UNIQUE",
132850:  /* 206 */ "uniqueflag ::=",
132851:  /* 207 */ "eidlist_opt ::=",
132852:  /* 208 */ "eidlist_opt ::= LP eidlist RP",
132853:  /* 209 */ "eidlist ::= eidlist COMMA nm collate sortorder",
132854:  /* 210 */ "eidlist ::= nm collate sortorder",
132855:  /* 211 */ "collate ::=",
132856:  /* 212 */ "collate ::= COLLATE ID|STRING",
132857:  /* 213 */ "cmd ::= DROP INDEX ifexists fullname",
132858:  /* 214 */ "cmd ::= VACUUM",
132859:  /* 215 */ "cmd ::= VACUUM nm",
132860:  /* 216 */ "cmd ::= PRAGMA nm dbnm",
132861:  /* 217 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
132862:  /* 218 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
132863:  /* 219 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
132864:  /* 220 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
132865:  /* 221 */ "plus_num ::= PLUS INTEGER|FLOAT",
132866:  /* 222 */ "minus_num ::= MINUS INTEGER|FLOAT",
132867:  /* 223 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
132868:  /* 224 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
132869:  /* 225 */ "trigger_time ::= BEFORE",
132870:  /* 226 */ "trigger_time ::= AFTER",
132871:  /* 227 */ "trigger_time ::= INSTEAD OF",
132872:  /* 228 */ "trigger_time ::=",
132873:  /* 229 */ "trigger_event ::= DELETE|INSERT",
132874:  /* 230 */ "trigger_event ::= UPDATE",
132875:  /* 231 */ "trigger_event ::= UPDATE OF idlist",
132876:  /* 232 */ "when_clause ::=",
132877:  /* 233 */ "when_clause ::= WHEN expr",
132878:  /* 234 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
132879:  /* 235 */ "trigger_cmd_list ::= trigger_cmd SEMI",
132880:  /* 236 */ "trnm ::= nm DOT nm",
132881:  /* 237 */ "tridxby ::= INDEXED BY nm",
132882:  /* 238 */ "tridxby ::= NOT INDEXED",
132883:  /* 239 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
132884:  /* 240 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
132885:  /* 241 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
132886:  /* 242 */ "trigger_cmd ::= select",
132887:  /* 243 */ "expr ::= RAISE LP IGNORE RP",
132888:  /* 244 */ "expr ::= RAISE LP raisetype COMMA nm RP",
132889:  /* 245 */ "raisetype ::= ROLLBACK",
132890:  /* 246 */ "raisetype ::= ABORT",
132891:  /* 247 */ "raisetype ::= FAIL",
132892:  /* 248 */ "cmd ::= DROP TRIGGER ifexists fullname",
132893:  /* 249 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
132894:  /* 250 */ "cmd ::= DETACH database_kw_opt expr",
132895:  /* 251 */ "key_opt ::=",
132896:  /* 252 */ "key_opt ::= KEY expr",
132897:  /* 253 */ "cmd ::= REINDEX",
132898:  /* 254 */ "cmd ::= REINDEX nm dbnm",
132899:  /* 255 */ "cmd ::= ANALYZE",
132900:  /* 256 */ "cmd ::= ANALYZE nm dbnm",
132901:  /* 257 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
132902:  /* 258 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
132903:  /* 259 */ "add_column_fullname ::= fullname",
132904:  /* 260 */ "cmd ::= create_vtab",
132905:  /* 261 */ "cmd ::= create_vtab LP vtabarglist RP",
132906:  /* 262 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
132907:  /* 263 */ "vtabarg ::=",
132908:  /* 264 */ "vtabargtoken ::= ANY",
132909:  /* 265 */ "vtabargtoken ::= lp anylist RP",
132910:  /* 266 */ "lp ::= LP",
132911:  /* 267 */ "with ::=",
132912:  /* 268 */ "with ::= WITH wqlist",
132913:  /* 269 */ "with ::= WITH RECURSIVE wqlist",
132914:  /* 270 */ "wqlist ::= nm eidlist_opt AS LP select RP",
132915:  /* 271 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
132916:  /* 272 */ "input ::= cmdlist",
132917:  /* 273 */ "cmdlist ::= cmdlist ecmd",
132918:  /* 274 */ "cmdlist ::= ecmd",
132919:  /* 275 */ "ecmd ::= SEMI",
132920:  /* 276 */ "ecmd ::= explain cmdx SEMI",
132921:  /* 277 */ "explain ::=",
132922:  /* 278 */ "trans_opt ::=",
132923:  /* 279 */ "trans_opt ::= TRANSACTION",
132924:  /* 280 */ "trans_opt ::= TRANSACTION nm",
132925:  /* 281 */ "savepoint_opt ::= SAVEPOINT",
132926:  /* 282 */ "savepoint_opt ::=",
132927:  /* 283 */ "cmd ::= create_table create_table_args",
132928:  /* 284 */ "columnlist ::= columnlist COMMA columnname carglist",
132929:  /* 285 */ "columnlist ::= columnname carglist",
132930:  /* 286 */ "nm ::= ID|INDEXED",
132931:  /* 287 */ "nm ::= STRING",
132932:  /* 288 */ "nm ::= JOIN_KW",
132933:  /* 289 */ "typetoken ::= typename",
132934:  /* 290 */ "typename ::= ID|STRING",
132935:  /* 291 */ "signed ::= plus_num",
132936:  /* 292 */ "signed ::= minus_num",
132937:  /* 293 */ "carglist ::= carglist ccons",
132938:  /* 294 */ "carglist ::=",
132939:  /* 295 */ "ccons ::= NULL onconf",
132940:  /* 296 */ "conslist_opt ::= COMMA conslist",
132941:  /* 297 */ "conslist ::= conslist tconscomma tcons",
132942:  /* 298 */ "conslist ::= tcons",
132943:  /* 299 */ "tconscomma ::=",
132944:  /* 300 */ "defer_subclause_opt ::= defer_subclause",
132945:  /* 301 */ "resolvetype ::= raisetype",
132946:  /* 302 */ "selectnowith ::= oneselect",
132947:  /* 303 */ "oneselect ::= values",
132948:  /* 304 */ "sclp ::= selcollist COMMA",
132949:  /* 305 */ "as ::= ID|STRING",
132950:  /* 306 */ "expr ::= term",
132951:  /* 307 */ "exprlist ::= nexprlist",
132952:  /* 308 */ "nmnum ::= plus_num",
132953:  /* 309 */ "nmnum ::= nm",
132954:  /* 310 */ "nmnum ::= ON",
132955:  /* 311 */ "nmnum ::= DELETE",
132956:  /* 312 */ "nmnum ::= DEFAULT",
132957:  /* 313 */ "plus_num ::= INTEGER|FLOAT",
132958:  /* 314 */ "foreach_clause ::=",
132959:  /* 315 */ "foreach_clause ::= FOR EACH ROW",
132960:  /* 316 */ "trnm ::= nm",
132961:  /* 317 */ "tridxby ::=",
132962:  /* 318 */ "database_kw_opt ::= DATABASE",
132963:  /* 319 */ "database_kw_opt ::=",
132964:  /* 320 */ "kwcolumn_opt ::=",
132965:  /* 321 */ "kwcolumn_opt ::= COLUMNKW",
132966:  /* 322 */ "vtabarglist ::= vtabarg",
132967:  /* 323 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
132968:  /* 324 */ "vtabarg ::= vtabarg vtabargtoken",
132969:  /* 325 */ "anylist ::=",
132970:  /* 326 */ "anylist ::= anylist LP anylist RP",
132971:  /* 327 */ "anylist ::= anylist ANY",
132972: };
132973: #endif /* NDEBUG */
132974: 
132975: 
132976: #if YYSTACKDEPTH<=0
132977: /*
132978: ** Try to increase the size of the parser stack.  Return the number
132979: ** of errors.  Return 0 on success.
132980: */
132981: static int yyGrowStack(yyParser *p){
132982:   int newSize;
132983:   int idx;
132984:   yyStackEntry *pNew;
132985: 
132986:   newSize = p->yystksz*2 + 100;
132987:   idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
132988:   if( p->yystack==&p->yystk0 ){
132989:     pNew = malloc(newSize*sizeof(pNew[0]));
132990:     if( pNew ) pNew[0] = p->yystk0;
132991:   }else{
132992:     pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
132993:   }
132994:   if( pNew ){
132995:     p->yystack = pNew;
132996:     p->yytos = &p->yystack[idx];
132997: #ifndef NDEBUG
132998:     if( yyTraceFILE ){
132999:       fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
133000:               yyTracePrompt, p->yystksz, newSize);
133001:     }
133002: #endif
133003:     p->yystksz = newSize;
133004:   }
133005:   return pNew==0; 
133006: }
133007: #endif
133008: 
133009: /* Datatype of the argument to the memory allocated passed as the
133010: ** second argument to sqlite3ParserAlloc() below.  This can be changed by
133011: ** putting an appropriate #define in the %include section of the input
133012: ** grammar.
133013: */
133014: #ifndef YYMALLOCARGTYPE
133015: # define YYMALLOCARGTYPE size_t
133016: #endif
133017: 
133018: /* 
133019: ** This function allocates a new parser.
133020: ** The only argument is a pointer to a function which works like
133021: ** malloc.
133022: **
133023: ** Inputs:
133024: ** A pointer to the function used to allocate memory.
133025: **
133026: ** Outputs:
133027: ** A pointer to a parser.  This pointer is used in subsequent calls
133028: ** to sqlite3Parser and sqlite3ParserFree.
133029: */
133030: SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
133031:   yyParser *pParser;
133032:   pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
133033:   if( pParser ){
133034: #ifdef YYTRACKMAXSTACKDEPTH
133035:     pParser->yyhwm = 0;
133036: #endif
133037: #if YYSTACKDEPTH<=0
133038:     pParser->yytos = NULL;
133039:     pParser->yystack = NULL;
133040:     pParser->yystksz = 0;
133041:     if( yyGrowStack(pParser) ){
133042:       pParser->yystack = &pParser->yystk0;
133043:       pParser->yystksz = 1;
133044:     }
133045: #endif
133046: #ifndef YYNOERRORRECOVERY
133047:     pParser->yyerrcnt = -1;
133048: #endif
133049:     pParser->yytos = pParser->yystack;
133050:     pParser->yystack[0].stateno = 0;
133051:     pParser->yystack[0].major = 0;
133052:   }
133053:   return pParser;
133054: }
133055: 
133056: /* The following function deletes the "minor type" or semantic value
133057: ** associated with a symbol.  The symbol can be either a terminal
133058: ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
133059: ** a pointer to the value to be deleted.  The code used to do the 
133060: ** deletions is derived from the %destructor and/or %token_destructor
133061: ** directives of the input grammar.
133062: */
133063: static void yy_destructor(
133064:   yyParser *yypParser,    /* The parser */
133065:   YYCODETYPE yymajor,     /* Type code for object to destroy */
133066:   YYMINORTYPE *yypminor   /* The object to be destroyed */
133067: ){
133068:   sqlite3ParserARG_FETCH;
133069:   switch( yymajor ){
133070:     /* Here is inserted the actions which take place when a
133071:     ** terminal or non-terminal is destroyed.  This can happen
133072:     ** when the symbol is popped from the stack during a
133073:     ** reduce or during error processing or when a parser is 
133074:     ** being destroyed before it is finished parsing.
133075:     **
133076:     ** Note: during a reduce, the only symbols destroyed are those
133077:     ** which appear on the RHS of the rule, but which are *not* used
133078:     ** inside the C code.
133079:     */
133080: /********* Begin destructor definitions ***************************************/
133081:     case 163: /* select */
133082:     case 194: /* selectnowith */
133083:     case 195: /* oneselect */
133084:     case 206: /* values */
133085: {
133086: sqlite3SelectDelete(pParse->db, (yypminor->yy243));
133087: }
133088:       break;
133089:     case 172: /* term */
133090:     case 173: /* expr */
133091: {
133092: sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
133093: }
133094:       break;
133095:     case 177: /* eidlist_opt */
133096:     case 186: /* sortlist */
133097:     case 187: /* eidlist */
133098:     case 199: /* selcollist */
133099:     case 202: /* groupby_opt */
133100:     case 204: /* orderby_opt */
133101:     case 207: /* nexprlist */
133102:     case 208: /* exprlist */
133103:     case 209: /* sclp */
133104:     case 218: /* setlist */
133105:     case 224: /* paren_exprlist */
133106:     case 226: /* case_exprlist */
133107: {
133108: sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
133109: }
133110:       break;
133111:     case 193: /* fullname */
133112:     case 200: /* from */
133113:     case 211: /* seltablist */
133114:     case 212: /* stl_prefix */
133115: {
133116: sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
133117: }
133118:       break;
133119:     case 196: /* with */
133120:     case 250: /* wqlist */
133121: {
133122: sqlite3WithDelete(pParse->db, (yypminor->yy285));
133123: }
133124:       break;
133125:     case 201: /* where_opt */
133126:     case 203: /* having_opt */
133127:     case 215: /* on_opt */
133128:     case 225: /* case_operand */
133129:     case 227: /* case_else */
133130:     case 236: /* when_clause */
133131:     case 241: /* key_opt */
133132: {
133133: sqlite3ExprDelete(pParse->db, (yypminor->yy72));
133134: }
133135:       break;
133136:     case 216: /* using_opt */
133137:     case 217: /* idlist */
133138:     case 220: /* idlist_opt */
133139: {
133140: sqlite3IdListDelete(pParse->db, (yypminor->yy254));
133141: }
133142:       break;
133143:     case 232: /* trigger_cmd_list */
133144:     case 237: /* trigger_cmd */
133145: {
133146: sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
133147: }
133148:       break;
133149:     case 234: /* trigger_event */
133150: {
133151: sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
133152: }
133153:       break;
133154: /********* End destructor definitions *****************************************/
133155:     default:  break;   /* If no destructor action specified: do nothing */
133156:   }
133157: }
133158: 
133159: /*
133160: ** Pop the parser's stack once.
133161: **
133162: ** If there is a destructor routine associated with the token which
133163: ** is popped from the stack, then call it.
133164: */
133165: static void yy_pop_parser_stack(yyParser *pParser){
133166:   yyStackEntry *yytos;
133167:   assert( pParser->yytos!=0 );
133168:   assert( pParser->yytos > pParser->yystack );
133169:   yytos = pParser->yytos--;
133170: #ifndef NDEBUG
133171:   if( yyTraceFILE ){
133172:     fprintf(yyTraceFILE,"%sPopping %s\n",
133173:       yyTracePrompt,
133174:       yyTokenName[yytos->major]);
133175:   }
133176: #endif
133177:   yy_destructor(pParser, yytos->major, &yytos->minor);
133178: }
133179: 
133180: /* 
133181: ** Deallocate and destroy a parser.  Destructors are called for
133182: ** all stack elements before shutting the parser down.
133183: **
133184: ** If the YYPARSEFREENEVERNULL macro exists (for example because it
133185: ** is defined in a %include section of the input grammar) then it is
133186: ** assumed that the input pointer is never NULL.
133187: */
133188: SQLITE_PRIVATE void sqlite3ParserFree(
133189:   void *p,                    /* The parser to be deleted */
133190:   void (*freeProc)(void*)     /* Function used to reclaim memory */
133191: ){
133192:   yyParser *pParser = (yyParser*)p;
133193: #ifndef YYPARSEFREENEVERNULL
133194:   if( pParser==0 ) return;
133195: #endif
133196:   while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
133197: #if YYSTACKDEPTH<=0
133198:   if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
133199: #endif
133200:   (*freeProc)((void*)pParser);
133201: }
133202: 
133203: /*
133204: ** Return the peak depth of the stack for a parser.
133205: */
133206: #ifdef YYTRACKMAXSTACKDEPTH
133207: SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
133208:   yyParser *pParser = (yyParser*)p;
133209:   return pParser->yyhwm;
133210: }
133211: #endif
133212: 
133213: /*
133214: ** Find the appropriate action for a parser given the terminal
133215: ** look-ahead token iLookAhead.
133216: */
133217: static unsigned int yy_find_shift_action(
133218:   yyParser *pParser,        /* The parser */
133219:   YYCODETYPE iLookAhead     /* The look-ahead token */
133220: ){
133221:   int i;
133222:   int stateno = pParser->yytos->stateno;
133223:  
133224:   if( stateno>=YY_MIN_REDUCE ) return stateno;
133225:   assert( stateno <= YY_SHIFT_COUNT );
133226:   do{
133227:     i = yy_shift_ofst[stateno];
133228:     if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
133229:     assert( iLookAhead!=YYNOCODE );
133230:     i += iLookAhead;
133231:     if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
133232:       if( iLookAhead>0 ){
133233: #ifdef YYFALLBACK
133234:         YYCODETYPE iFallback;            /* Fallback token */
133235:         if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
133236:                && (iFallback = yyFallback[iLookAhead])!=0 ){
133237: #ifndef NDEBUG
133238:           if( yyTraceFILE ){
133239:             fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
133240:                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
133241:           }
133242: #endif
133243:           assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
133244:           iLookAhead = iFallback;
133245:           continue;
133246:         }
133247: #endif
133248: #ifdef YYWILDCARD
133249:         {
133250:           int j = i - iLookAhead + YYWILDCARD;
133251:           if( 
133252: #if YY_SHIFT_MIN+YYWILDCARD<0
133253:             j>=0 &&
133254: #endif
133255: #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
133256:             j<YY_ACTTAB_COUNT &&
133257: #endif
133258:             yy_lookahead[j]==YYWILDCARD
133259:           ){
133260: #ifndef NDEBUG
133261:             if( yyTraceFILE ){
133262:               fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
133263:                  yyTracePrompt, yyTokenName[iLookAhead],
133264:                  yyTokenName[YYWILDCARD]);
133265:             }
133266: #endif /* NDEBUG */
133267:             return yy_action[j];
133268:           }
133269:         }
133270: #endif /* YYWILDCARD */
133271:       }
133272:       return yy_default[stateno];
133273:     }else{
133274:       return yy_action[i];
133275:     }
133276:   }while(1);
133277: }
133278: 
133279: /*
133280: ** Find the appropriate action for a parser given the non-terminal
133281: ** look-ahead token iLookAhead.
133282: */
133283: static int yy_find_reduce_action(
133284:   int stateno,              /* Current state number */
133285:   YYCODETYPE iLookAhead     /* The look-ahead token */
133286: ){
133287:   int i;
133288: #ifdef YYERRORSYMBOL
133289:   if( stateno>YY_REDUCE_COUNT ){
133290:     return yy_default[stateno];
133291:   }
133292: #else
133293:   assert( stateno<=YY_REDUCE_COUNT );
133294: #endif
133295:   i = yy_reduce_ofst[stateno];
133296:   assert( i!=YY_REDUCE_USE_DFLT );
133297:   assert( iLookAhead!=YYNOCODE );
133298:   i += iLookAhead;
133299: #ifdef YYERRORSYMBOL
133300:   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
133301:     return yy_default[stateno];
133302:   }
133303: #else
133304:   assert( i>=0 && i<YY_ACTTAB_COUNT );
133305:   assert( yy_lookahead[i]==iLookAhead );
133306: #endif
133307:   return yy_action[i];
133308: }
133309: 
133310: /*
133311: ** The following routine is called if the stack overflows.
133312: */
133313: static void yyStackOverflow(yyParser *yypParser){
133314:    sqlite3ParserARG_FETCH;
133315:    yypParser->yytos--;
133316: #ifndef NDEBUG
133317:    if( yyTraceFILE ){
133318:      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
133319:    }
133320: #endif
133321:    while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
133322:    /* Here code is inserted which will execute if the parser
133323:    ** stack every overflows */
133324: /******** Begin %stack_overflow code ******************************************/
133325: 
133326:   sqlite3ErrorMsg(pParse, "parser stack overflow");
133327: /******** End %stack_overflow code ********************************************/
133328:    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
133329: }
133330: 
133331: /*
133332: ** Print tracing information for a SHIFT action
133333: */
133334: #ifndef NDEBUG
133335: static void yyTraceShift(yyParser *yypParser, int yyNewState){
133336:   if( yyTraceFILE ){
133337:     if( yyNewState<YYNSTATE ){
133338:       fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
133339:          yyTracePrompt,yyTokenName[yypParser->yytos->major],
133340:          yyNewState);
133341:     }else{
133342:       fprintf(yyTraceFILE,"%sShift '%s'\n",
133343:          yyTracePrompt,yyTokenName[yypParser->yytos->major]);
133344:     }
133345:   }
133346: }
133347: #else
133348: # define yyTraceShift(X,Y)
133349: #endif
133350: 
133351: /*
133352: ** Perform a shift action.
133353: */
133354: static void yy_shift(
133355:   yyParser *yypParser,          /* The parser to be shifted */
133356:   int yyNewState,               /* The new state to shift in */
133357:   int yyMajor,                  /* The major token to shift in */
133358:   sqlite3ParserTOKENTYPE yyMinor        /* The minor token to shift in */
133359: ){
133360:   yyStackEntry *yytos;
133361:   yypParser->yytos++;
133362: #ifdef YYTRACKMAXSTACKDEPTH
133363:   if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
133364:     yypParser->yyhwm++;
133365:     assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
133366:   }
133367: #endif
133368: #if YYSTACKDEPTH>0 
133369:   if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
133370:     yyStackOverflow(yypParser);
133371:     return;
133372:   }
133373: #else
133374:   if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
133375:     if( yyGrowStack(yypParser) ){
133376:       yyStackOverflow(yypParser);
133377:       return;
133378:     }
133379:   }
133380: #endif
133381:   if( yyNewState > YY_MAX_SHIFT ){
133382:     yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
133383:   }
133384:   yytos = yypParser->yytos;
133385:   yytos->stateno = (YYACTIONTYPE)yyNewState;
133386:   yytos->major = (YYCODETYPE)yyMajor;
133387:   yytos->minor.yy0 = yyMinor;
133388:   yyTraceShift(yypParser, yyNewState);
133389: }
133390: 
133391: /* The following table contains information about every rule that
133392: ** is used during the reduce.
133393: */
133394: static const struct {
133395:   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
133396:   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
133397: } yyRuleInfo[] = {
133398:   { 147, 1 },
133399:   { 147, 3 },
133400:   { 148, 1 },
133401:   { 149, 3 },
133402:   { 150, 0 },
133403:   { 150, 1 },
133404:   { 150, 1 },
133405:   { 150, 1 },
133406:   { 149, 2 },
133407:   { 149, 2 },
133408:   { 149, 2 },
133409:   { 149, 2 },
133410:   { 149, 3 },
133411:   { 149, 5 },
133412:   { 154, 6 },
133413:   { 156, 1 },
133414:   { 158, 0 },
133415:   { 158, 3 },
133416:   { 157, 1 },
133417:   { 157, 0 },
133418:   { 155, 5 },
133419:   { 155, 2 },
133420:   { 162, 0 },
133421:   { 162, 2 },
133422:   { 164, 2 },
133423:   { 166, 0 },
133424:   { 166, 4 },
133425:   { 166, 6 },
133426:   { 167, 2 },
133427:   { 171, 2 },
133428:   { 171, 2 },
133429:   { 171, 4 },
133430:   { 171, 3 },
133431:   { 171, 3 },
133432:   { 171, 2 },
133433:   { 171, 3 },
133434:   { 171, 5 },
133435:   { 171, 2 },
133436:   { 171, 4 },
133437:   { 171, 4 },
133438:   { 171, 1 },
133439:   { 171, 2 },
133440:   { 176, 0 },
133441:   { 176, 1 },
133442:   { 178, 0 },
133443:   { 178, 2 },
133444:   { 180, 2 },
133445:   { 180, 3 },
133446:   { 180, 3 },
133447:   { 180, 3 },
133448:   { 181, 2 },
133449:   { 181, 2 },
133450:   { 181, 1 },
133451:   { 181, 1 },
133452:   { 181, 2 },
133453:   { 179, 3 },
133454:   { 179, 2 },
133455:   { 182, 0 },
133456:   { 182, 2 },
133457:   { 182, 2 },
133458:   { 161, 0 },
133459:   { 184, 1 },
133460:   { 185, 2 },
133461:   { 185, 7 },
133462:   { 185, 5 },
133463:   { 185, 5 },
133464:   { 185, 10 },
133465:   { 188, 0 },
133466:   { 174, 0 },
133467:   { 174, 3 },
133468:   { 189, 0 },
133469:   { 189, 2 },
133470:   { 190, 1 },
133471:   { 190, 1 },
133472:   { 149, 4 },
133473:   { 192, 2 },
133474:   { 192, 0 },
133475:   { 149, 9 },
133476:   { 149, 4 },
133477:   { 149, 1 },
133478:   { 163, 2 },
133479:   { 194, 3 },
133480:   { 197, 1 },
133481:   { 197, 2 },
133482:   { 197, 1 },
133483:   { 195, 9 },
133484:   { 206, 4 },
133485:   { 206, 5 },
133486:   { 198, 1 },
133487:   { 198, 1 },
133488:   { 198, 0 },
133489:   { 209, 0 },
133490:   { 199, 3 },
133491:   { 199, 2 },
133492:   { 199, 4 },
133493:   { 210, 2 },
133494:   { 210, 0 },
133495:   { 200, 0 },
133496:   { 200, 2 },
133497:   { 212, 2 },
133498:   { 212, 0 },
133499:   { 211, 7 },
133500:   { 211, 9 },
133501:   { 211, 7 },
133502:   { 211, 7 },
133503:   { 159, 0 },
133504:   { 159, 2 },
133505:   { 193, 2 },
133506:   { 213, 1 },
133507:   { 213, 2 },
133508:   { 213, 3 },
133509:   { 213, 4 },
133510:   { 215, 2 },
133511:   { 215, 0 },
133512:   { 214, 0 },
133513:   { 214, 3 },
133514:   { 214, 2 },
133515:   { 216, 4 },
133516:   { 216, 0 },
133517:   { 204, 0 },
133518:   { 204, 3 },
133519:   { 186, 4 },
133520:   { 186, 2 },
133521:   { 175, 1 },
133522:   { 175, 1 },
133523:   { 175, 0 },
133524:   { 202, 0 },
133525:   { 202, 3 },
133526:   { 203, 0 },
133527:   { 203, 2 },
133528:   { 205, 0 },
133529:   { 205, 2 },
133530:   { 205, 4 },
133531:   { 205, 4 },
133532:   { 149, 6 },
133533:   { 201, 0 },
133534:   { 201, 2 },
133535:   { 149, 8 },
133536:   { 218, 5 },
133537:   { 218, 3 },
133538:   { 149, 6 },
133539:   { 149, 7 },
133540:   { 219, 2 },
133541:   { 219, 1 },
133542:   { 220, 0 },
133543:   { 220, 3 },
133544:   { 217, 3 },
133545:   { 217, 1 },
133546:   { 173, 3 },
133547:   { 172, 1 },
133548:   { 173, 1 },
133549:   { 173, 1 },
133550:   { 173, 3 },
133551:   { 173, 5 },
133552:   { 172, 1 },
133553:   { 172, 1 },
133554:   { 173, 1 },
133555:   { 173, 3 },
133556:   { 173, 6 },
133557:   { 173, 5 },
133558:   { 173, 4 },
133559:   { 172, 1 },
133560:   { 173, 3 },
133561:   { 173, 3 },
133562:   { 173, 3 },
133563:   { 173, 3 },
133564:   { 173, 3 },
133565:   { 173, 3 },
133566:   { 173, 3 },
133567:   { 173, 3 },
133568:   { 221, 1 },
133569:   { 221, 2 },
133570:   { 173, 3 },
133571:   { 173, 5 },
133572:   { 173, 2 },
133573:   { 173, 3 },
133574:   { 173, 3 },
133575:   { 173, 4 },
133576:   { 173, 2 },
133577:   { 173, 2 },
133578:   { 173, 2 },
133579:   { 173, 2 },
133580:   { 222, 1 },
133581:   { 222, 2 },
133582:   { 173, 5 },
133583:   { 223, 1 },
133584:   { 223, 2 },
133585:   { 173, 5 },
133586:   { 173, 3 },
133587:   { 173, 5 },
133588:   { 173, 5 },
133589:   { 173, 4 },
133590:   { 173, 5 },
133591:   { 226, 5 },
133592:   { 226, 4 },
133593:   { 227, 2 },
133594:   { 227, 0 },
133595:   { 225, 1 },
133596:   { 225, 0 },
133597:   { 208, 0 },
133598:   { 207, 3 },
133599:   { 207, 1 },
133600:   { 224, 0 },
133601:   { 224, 3 },
133602:   { 149, 12 },
133603:   { 228, 1 },
133604:   { 228, 0 },
133605:   { 177, 0 },
133606:   { 177, 3 },
133607:   { 187, 5 },
133608:   { 187, 3 },
133609:   { 229, 0 },
133610:   { 229, 2 },
133611:   { 149, 4 },
133612:   { 149, 1 },
133613:   { 149, 2 },
133614:   { 149, 3 },
133615:   { 149, 5 },
133616:   { 149, 6 },
133617:   { 149, 5 },
133618:   { 149, 6 },
133619:   { 169, 2 },
133620:   { 170, 2 },
133621:   { 149, 5 },
133622:   { 231, 11 },
133623:   { 233, 1 },
133624:   { 233, 1 },
133625:   { 233, 2 },
133626:   { 233, 0 },
133627:   { 234, 1 },
133628:   { 234, 1 },
133629:   { 234, 3 },
133630:   { 236, 0 },
133631:   { 236, 2 },
133632:   { 232, 3 },
133633:   { 232, 2 },
133634:   { 238, 3 },
133635:   { 239, 3 },
133636:   { 239, 2 },
133637:   { 237, 7 },
133638:   { 237, 5 },
133639:   { 237, 5 },
133640:   { 237, 1 },
133641:   { 173, 4 },
133642:   { 173, 6 },
133643:   { 191, 1 },
133644:   { 191, 1 },
133645:   { 191, 1 },
133646:   { 149, 4 },
133647:   { 149, 6 },
133648:   { 149, 3 },
133649:   { 241, 0 },
133650:   { 241, 2 },
133651:   { 149, 1 },
133652:   { 149, 3 },
133653:   { 149, 1 },
133654:   { 149, 3 },
133655:   { 149, 6 },
133656:   { 149, 7 },
133657:   { 242, 1 },
133658:   { 149, 1 },
133659:   { 149, 4 },
133660:   { 244, 8 },
133661:   { 246, 0 },
133662:   { 247, 1 },
133663:   { 247, 3 },
133664:   { 248, 1 },
133665:   { 196, 0 },
133666:   { 196, 2 },
133667:   { 196, 3 },
133668:   { 250, 6 },
133669:   { 250, 8 },
133670:   { 144, 1 },
133671:   { 145, 2 },
133672:   { 145, 1 },
133673:   { 146, 1 },
133674:   { 146, 3 },
133675:   { 147, 0 },
133676:   { 151, 0 },
133677:   { 151, 1 },
133678:   { 151, 2 },
133679:   { 153, 1 },
133680:   { 153, 0 },
133681:   { 149, 2 },
133682:   { 160, 4 },
133683:   { 160, 2 },
133684:   { 152, 1 },
133685:   { 152, 1 },
133686:   { 152, 1 },
133687:   { 166, 1 },
133688:   { 167, 1 },
133689:   { 168, 1 },
133690:   { 168, 1 },
133691:   { 165, 2 },
133692:   { 165, 0 },
133693:   { 171, 2 },
133694:   { 161, 2 },
133695:   { 183, 3 },
133696:   { 183, 1 },
133697:   { 184, 0 },
133698:   { 188, 1 },
133699:   { 190, 1 },
133700:   { 194, 1 },
133701:   { 195, 1 },
133702:   { 209, 2 },
133703:   { 210, 1 },
133704:   { 173, 1 },
133705:   { 208, 1 },
133706:   { 230, 1 },
133707:   { 230, 1 },
133708:   { 230, 1 },
133709:   { 230, 1 },
133710:   { 230, 1 },
133711:   { 169, 1 },
133712:   { 235, 0 },
133713:   { 235, 3 },
133714:   { 238, 1 },
133715:   { 239, 0 },
133716:   { 240, 1 },
133717:   { 240, 0 },
133718:   { 243, 0 },
133719:   { 243, 1 },
133720:   { 245, 1 },
133721:   { 245, 3 },
133722:   { 246, 2 },
133723:   { 249, 0 },
133724:   { 249, 4 },
133725:   { 249, 2 },
133726: };
133727: 
133728: static void yy_accept(yyParser*);  /* Forward Declaration */
133729: 
133730: /*
133731: ** Perform a reduce action and the shift that must immediately
133732: ** follow the reduce.
133733: */
133734: static void yy_reduce(
133735:   yyParser *yypParser,         /* The parser */
133736:   unsigned int yyruleno        /* Number of the rule by which to reduce */
133737: ){
133738:   int yygoto;                     /* The next state */
133739:   int yyact;                      /* The next action */
133740:   yyStackEntry *yymsp;            /* The top of the parser's stack */
133741:   int yysize;                     /* Amount to pop the stack */
133742:   sqlite3ParserARG_FETCH;
133743:   yymsp = yypParser->yytos;
133744: #ifndef NDEBUG
133745:   if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
133746:     yysize = yyRuleInfo[yyruleno].nrhs;
133747:     fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
133748:       yyRuleName[yyruleno], yymsp[-yysize].stateno);
133749:   }
133750: #endif /* NDEBUG */
133751: 
133752:   /* Check that the stack is large enough to grow by a single entry
133753:   ** if the RHS of the rule is empty.  This ensures that there is room
133754:   ** enough on the stack to push the LHS value */
133755:   if( yyRuleInfo[yyruleno].nrhs==0 ){
133756: #ifdef YYTRACKMAXSTACKDEPTH
133757:     if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
133758:       yypParser->yyhwm++;
133759:       assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
133760:     }
133761: #endif
133762: #if YYSTACKDEPTH>0 
133763:     if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
133764:       yyStackOverflow(yypParser);
133765:       return;
133766:     }
133767: #else
133768:     if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
133769:       if( yyGrowStack(yypParser) ){
133770:         yyStackOverflow(yypParser);
133771:         return;
133772:       }
133773:       yymsp = yypParser->yytos;
133774:     }
133775: #endif
133776:   }
133777: 
133778:   switch( yyruleno ){
133779:   /* Beginning here are the reduction cases.  A typical example
133780:   ** follows:
133781:   **   case 0:
133782:   **  #line <lineno> <grammarfile>
133783:   **     { ... }           // User supplied code
133784:   **  #line <lineno> <thisfile>
133785:   **     break;
133786:   */
133787: /********** Begin reduce actions **********************************************/
133788:         YYMINORTYPE yylhsminor;
133789:       case 0: /* explain ::= EXPLAIN */
133790: { pParse->explain = 1; }
133791:         break;
133792:       case 1: /* explain ::= EXPLAIN QUERY PLAN */
133793: { pParse->explain = 2; }
133794:         break;
133795:       case 2: /* cmdx ::= cmd */
133796: { sqlite3FinishCoding(pParse); }
133797:         break;
133798:       case 3: /* cmd ::= BEGIN transtype trans_opt */
133799: {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
133800:         break;
133801:       case 4: /* transtype ::= */
133802: {yymsp[1].minor.yy194 = TK_DEFERRED;}
133803:         break;
133804:       case 5: /* transtype ::= DEFERRED */
133805:       case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
133806:       case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
133807: {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
133808:         break;
133809:       case 8: /* cmd ::= COMMIT trans_opt */
133810:       case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
133811: {sqlite3CommitTransaction(pParse);}
133812:         break;
133813:       case 10: /* cmd ::= ROLLBACK trans_opt */
133814: {sqlite3RollbackTransaction(pParse);}
133815:         break;
133816:       case 11: /* cmd ::= SAVEPOINT nm */
133817: {
133818:   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
133819: }
133820:         break;
133821:       case 12: /* cmd ::= RELEASE savepoint_opt nm */
133822: {
133823:   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
133824: }
133825:         break;
133826:       case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
133827: {
133828:   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
133829: }
133830:         break;
133831:       case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
133832: {
133833:    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
133834: }
133835:         break;
133836:       case 15: /* createkw ::= CREATE */
133837: {disableLookaside(pParse);}
133838:         break;
133839:       case 16: /* ifnotexists ::= */
133840:       case 19: /* temp ::= */ yytestcase(yyruleno==19);
133841:       case 22: /* table_options ::= */ yytestcase(yyruleno==22);
133842:       case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
133843:       case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
133844:       case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
133845:       case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
133846:       case 90: /* distinct ::= */ yytestcase(yyruleno==90);
133847:       case 211: /* collate ::= */ yytestcase(yyruleno==211);
133848: {yymsp[1].minor.yy194 = 0;}
133849:         break;
133850:       case 17: /* ifnotexists ::= IF NOT EXISTS */
133851: {yymsp[-2].minor.yy194 = 1;}
133852:         break;
133853:       case 18: /* temp ::= TEMP */
133854:       case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
133855: {yymsp[0].minor.yy194 = 1;}
133856:         break;
133857:       case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
133858: {
133859:   sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
133860: }
133861:         break;
133862:       case 21: /* create_table_args ::= AS select */
133863: {
133864:   sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
133865:   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
133866: }
133867:         break;
133868:       case 23: /* table_options ::= WITHOUT nm */
133869: {
133870:   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
133871:     yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
133872:   }else{
133873:     yymsp[-1].minor.yy194 = 0;
133874:     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
133875:   }
133876: }
133877:         break;
133878:       case 24: /* columnname ::= nm typetoken */
133879: {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
133880:         break;
133881:       case 25: /* typetoken ::= */
133882:       case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
133883:       case 96: /* as ::= */ yytestcase(yyruleno==96);
133884: {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
133885:         break;
133886:       case 26: /* typetoken ::= typename LP signed RP */
133887: {
133888:   yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
133889: }
133890:         break;
133891:       case 27: /* typetoken ::= typename LP signed COMMA signed RP */
133892: {
133893:   yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
133894: }
133895:         break;
133896:       case 28: /* typename ::= typename ID|STRING */
133897: {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
133898:         break;
133899:       case 29: /* ccons ::= CONSTRAINT nm */
133900:       case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
133901: {pParse->constraintName = yymsp[0].minor.yy0;}
133902:         break;
133903:       case 30: /* ccons ::= DEFAULT term */
133904:       case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
133905: {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
133906:         break;
133907:       case 31: /* ccons ::= DEFAULT LP expr RP */
133908: {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
133909:         break;
133910:       case 33: /* ccons ::= DEFAULT MINUS term */
133911: {
133912:   ExprSpan v;
133913:   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0, 0);
133914:   v.zStart = yymsp[-1].minor.yy0.z;
133915:   v.zEnd = yymsp[0].minor.yy190.zEnd;
133916:   sqlite3AddDefaultValue(pParse,&v);
133917: }
133918:         break;
133919:       case 34: /* ccons ::= DEFAULT ID|INDEXED */
133920: {
133921:   ExprSpan v;
133922:   spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
133923:   sqlite3AddDefaultValue(pParse,&v);
133924: }
133925:         break;
133926:       case 35: /* ccons ::= NOT NULL onconf */
133927: {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
133928:         break;
133929:       case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
133930: {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
133931:         break;
133932:       case 37: /* ccons ::= UNIQUE onconf */
133933: {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
133934:                                    SQLITE_IDXTYPE_UNIQUE);}
133935:         break;
133936:       case 38: /* ccons ::= CHECK LP expr RP */
133937: {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
133938:         break;
133939:       case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
133940: {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
133941:         break;
133942:       case 40: /* ccons ::= defer_subclause */
133943: {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
133944:         break;
133945:       case 41: /* ccons ::= COLLATE ID|STRING */
133946: {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
133947:         break;
133948:       case 44: /* refargs ::= */
133949: { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
133950:         break;
133951:       case 45: /* refargs ::= refargs refarg */
133952: { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
133953:         break;
133954:       case 46: /* refarg ::= MATCH nm */
133955: { yymsp[-1].minor.yy497.value = 0;     yymsp[-1].minor.yy497.mask = 0x000000; }
133956:         break;
133957:       case 47: /* refarg ::= ON INSERT refact */
133958: { yymsp[-2].minor.yy497.value = 0;     yymsp[-2].minor.yy497.mask = 0x000000; }
133959:         break;
133960:       case 48: /* refarg ::= ON DELETE refact */
133961: { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194;     yymsp[-2].minor.yy497.mask = 0x0000ff; }
133962:         break;
133963:       case 49: /* refarg ::= ON UPDATE refact */
133964: { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8;  yymsp[-2].minor.yy497.mask = 0x00ff00; }
133965:         break;
133966:       case 50: /* refact ::= SET NULL */
133967: { yymsp[-1].minor.yy194 = OE_SetNull;  /* EV: R-33326-45252 */}
133968:         break;
133969:       case 51: /* refact ::= SET DEFAULT */
133970: { yymsp[-1].minor.yy194 = OE_SetDflt;  /* EV: R-33326-45252 */}
133971:         break;
133972:       case 52: /* refact ::= CASCADE */
133973: { yymsp[0].minor.yy194 = OE_Cascade;  /* EV: R-33326-45252 */}
133974:         break;
133975:       case 53: /* refact ::= RESTRICT */
133976: { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
133977:         break;
133978:       case 54: /* refact ::= NO ACTION */
133979: { yymsp[-1].minor.yy194 = OE_None;     /* EV: R-33326-45252 */}
133980:         break;
133981:       case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
133982: {yymsp[-2].minor.yy194 = 0;}
133983:         break;
133984:       case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
133985:       case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
133986:       case 142: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==142);
133987: {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
133988:         break;
133989:       case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
133990:       case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
133991:       case 183: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==183);
133992:       case 186: /* in_op ::= NOT IN */ yytestcase(yyruleno==186);
133993:       case 212: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==212);
133994: {yymsp[-1].minor.yy194 = 1;}
133995:         break;
133996:       case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
133997: {yymsp[-1].minor.yy194 = 0;}
133998:         break;
133999:       case 61: /* tconscomma ::= COMMA */
134000: {pParse->constraintName.n = 0;}
134001:         break;
134002:       case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
134003: {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
134004:         break;
134005:       case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
134006: {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
134007:                                        SQLITE_IDXTYPE_UNIQUE);}
134008:         break;
134009:       case 65: /* tcons ::= CHECK LP expr RP onconf */
134010: {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
134011:         break;
134012:       case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
134013: {
134014:     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
134015:     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
134016: }
134017:         break;
134018:       case 68: /* onconf ::= */
134019:       case 70: /* orconf ::= */ yytestcase(yyruleno==70);
134020: {yymsp[1].minor.yy194 = OE_Default;}
134021:         break;
134022:       case 69: /* onconf ::= ON CONFLICT resolvetype */
134023: {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
134024:         break;
134025:       case 72: /* resolvetype ::= IGNORE */
134026: {yymsp[0].minor.yy194 = OE_Ignore;}
134027:         break;
134028:       case 73: /* resolvetype ::= REPLACE */
134029:       case 143: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==143);
134030: {yymsp[0].minor.yy194 = OE_Replace;}
134031:         break;
134032:       case 74: /* cmd ::= DROP TABLE ifexists fullname */
134033: {
134034:   sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
134035: }
134036:         break;
134037:       case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
134038: {
134039:   sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
134040: }
134041:         break;
134042:       case 78: /* cmd ::= DROP VIEW ifexists fullname */
134043: {
134044:   sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
134045: }
134046:         break;
134047:       case 79: /* cmd ::= select */
134048: {
134049:   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
134050:   sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
134051:   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
134052: }
134053:         break;
134054:       case 80: /* select ::= with selectnowith */
134055: {
134056:   Select *p = yymsp[0].minor.yy243;
134057:   if( p ){
134058:     p->pWith = yymsp[-1].minor.yy285;
134059:     parserDoubleLinkSelect(pParse, p);
134060:   }else{
134061:     sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
134062:   }
134063:   yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
134064: }
134065:         break;
134066:       case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
134067: {
134068:   Select *pRhs = yymsp[0].minor.yy243;
134069:   Select *pLhs = yymsp[-2].minor.yy243;
134070:   if( pRhs && pRhs->pPrior ){
134071:     SrcList *pFrom;
134072:     Token x;
134073:     x.n = 0;
134074:     parserDoubleLinkSelect(pParse, pRhs);
134075:     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
134076:     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
134077:   }
134078:   if( pRhs ){
134079:     pRhs->op = (u8)yymsp[-1].minor.yy194;
134080:     pRhs->pPrior = pLhs;
134081:     if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
134082:     pRhs->selFlags &= ~SF_MultiValue;
134083:     if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
134084:   }else{
134085:     sqlite3SelectDelete(pParse->db, pLhs);
134086:   }
134087:   yymsp[-2].minor.yy243 = pRhs;
134088: }
134089:         break;
134090:       case 82: /* multiselect_op ::= UNION */
134091:       case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
134092: {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
134093:         break;
134094:       case 83: /* multiselect_op ::= UNION ALL */
134095: {yymsp[-1].minor.yy194 = TK_ALL;}
134096:         break;
134097:       case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
134098: {
134099: #if SELECTTRACE_ENABLED
134100:   Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
134101: #endif
134102:   yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
134103: #if SELECTTRACE_ENABLED
134104:   /* Populate the Select.zSelName[] string that is used to help with
134105:   ** query planner debugging, to differentiate between multiple Select
134106:   ** objects in a complex query.
134107:   **
134108:   ** If the SELECT keyword is immediately followed by a C-style comment
134109:   ** then extract the first few alphanumeric characters from within that
134110:   ** comment to be the zSelName value.  Otherwise, the label is #N where
134111:   ** is an integer that is incremented with each SELECT statement seen.
134112:   */
134113:   if( yymsp[-8].minor.yy243!=0 ){
134114:     const char *z = s.z+6;
134115:     int i;
134116:     sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
134117:                      ++pParse->nSelect);
134118:     while( z[0]==' ' ) z++;
134119:     if( z[0]=='/' && z[1]=='*' ){
134120:       z += 2;
134121:       while( z[0]==' ' ) z++;
134122:       for(i=0; sqlite3Isalnum(z[i]); i++){}
134123:       sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
134124:     }
134125:   }
134126: #endif /* SELECTRACE_ENABLED */
134127: }
134128:         break;
134129:       case 86: /* values ::= VALUES LP nexprlist RP */
134130: {
134131:   yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
134132: }
134133:         break;
134134:       case 87: /* values ::= values COMMA LP exprlist RP */
134135: {
134136:   Select *pRight, *pLeft = yymsp[-4].minor.yy243;
134137:   pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
134138:   if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
134139:   if( pRight ){
134140:     pRight->op = TK_ALL;
134141:     pRight->pPrior = pLeft;
134142:     yymsp[-4].minor.yy243 = pRight;
134143:   }else{
134144:     yymsp[-4].minor.yy243 = pLeft;
134145:   }
134146: }
134147:         break;
134148:       case 88: /* distinct ::= DISTINCT */
134149: {yymsp[0].minor.yy194 = SF_Distinct;}
134150:         break;
134151:       case 89: /* distinct ::= ALL */
134152: {yymsp[0].minor.yy194 = SF_All;}
134153:         break;
134154:       case 91: /* sclp ::= */
134155:       case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
134156:       case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
134157:       case 199: /* exprlist ::= */ yytestcase(yyruleno==199);
134158:       case 202: /* paren_exprlist ::= */ yytestcase(yyruleno==202);
134159:       case 207: /* eidlist_opt ::= */ yytestcase(yyruleno==207);
134160: {yymsp[1].minor.yy148 = 0;}
134161:         break;
134162:       case 92: /* selcollist ::= sclp expr as */
134163: {
134164:    yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
134165:    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
134166:    sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
134167: }
134168:         break;
134169:       case 93: /* selcollist ::= sclp STAR */
134170: {
134171:   Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
134172:   yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
134173: }
134174:         break;
134175:       case 94: /* selcollist ::= sclp nm DOT STAR */
134176: {
134177:   Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, &yymsp[0].minor.yy0);
134178:   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134179:   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
134180:   yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
134181: }
134182:         break;
134183:       case 95: /* as ::= AS nm */
134184:       case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
134185:       case 221: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==221);
134186:       case 222: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==222);
134187: {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
134188:         break;
134189:       case 97: /* from ::= */
134190: {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
134191:         break;
134192:       case 98: /* from ::= FROM seltablist */
134193: {
134194:   yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
134195:   sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
134196: }
134197:         break;
134198:       case 99: /* stl_prefix ::= seltablist joinop */
134199: {
134200:    if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
134201: }
134202:         break;
134203:       case 100: /* stl_prefix ::= */
134204: {yymsp[1].minor.yy185 = 0;}
134205:         break;
134206:       case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
134207: {
134208:   yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134209:   sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
134210: }
134211:         break;
134212:       case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
134213: {
134214:   yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134215:   sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
134216: }
134217:         break;
134218:       case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
134219: {
134220:     yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134221:   }
134222:         break;
134223:       case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
134224: {
134225:     if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
134226:       yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
134227:     }else if( yymsp[-4].minor.yy185->nSrc==1 ){
134228:       yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134229:       if( yymsp[-6].minor.yy185 ){
134230:         struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
134231:         struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
134232:         pNew->zName = pOld->zName;
134233:         pNew->zDatabase = pOld->zDatabase;
134234:         pNew->pSelect = pOld->pSelect;
134235:         pOld->zName = pOld->zDatabase = 0;
134236:         pOld->pSelect = 0;
134237:       }
134238:       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
134239:     }else{
134240:       Select *pSubquery;
134241:       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
134242:       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
134243:       yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
134244:     }
134245:   }
134246:         break;
134247:       case 105: /* dbnm ::= */
134248:       case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
134249: {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
134250:         break;
134251:       case 107: /* fullname ::= nm dbnm */
134252: {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
134253:         break;
134254:       case 108: /* joinop ::= COMMA|JOIN */
134255: { yymsp[0].minor.yy194 = JT_INNER; }
134256:         break;
134257:       case 109: /* joinop ::= JOIN_KW JOIN */
134258: {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0);  /*X-overwrites-A*/}
134259:         break;
134260:       case 110: /* joinop ::= JOIN_KW nm JOIN */
134261: {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
134262:         break;
134263:       case 111: /* joinop ::= JOIN_KW nm nm JOIN */
134264: {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
134265:         break;
134266:       case 112: /* on_opt ::= ON expr */
134267:       case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
134268:       case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
134269:       case 195: /* case_else ::= ELSE expr */ yytestcase(yyruleno==195);
134270: {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
134271:         break;
134272:       case 113: /* on_opt ::= */
134273:       case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
134274:       case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
134275:       case 196: /* case_else ::= */ yytestcase(yyruleno==196);
134276:       case 198: /* case_operand ::= */ yytestcase(yyruleno==198);
134277: {yymsp[1].minor.yy72 = 0;}
134278:         break;
134279:       case 115: /* indexed_opt ::= INDEXED BY nm */
134280: {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
134281:         break;
134282:       case 116: /* indexed_opt ::= NOT INDEXED */
134283: {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
134284:         break;
134285:       case 117: /* using_opt ::= USING LP idlist RP */
134286: {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
134287:         break;
134288:       case 118: /* using_opt ::= */
134289:       case 144: /* idlist_opt ::= */ yytestcase(yyruleno==144);
134290: {yymsp[1].minor.yy254 = 0;}
134291:         break;
134292:       case 120: /* orderby_opt ::= ORDER BY sortlist */
134293:       case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
134294: {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
134295:         break;
134296:       case 121: /* sortlist ::= sortlist COMMA expr sortorder */
134297: {
134298:   yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
134299:   sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
134300: }
134301:         break;
134302:       case 122: /* sortlist ::= expr sortorder */
134303: {
134304:   yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
134305:   sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
134306: }
134307:         break;
134308:       case 123: /* sortorder ::= ASC */
134309: {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
134310:         break;
134311:       case 124: /* sortorder ::= DESC */
134312: {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
134313:         break;
134314:       case 125: /* sortorder ::= */
134315: {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
134316:         break;
134317:       case 130: /* limit_opt ::= */
134318: {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
134319:         break;
134320:       case 131: /* limit_opt ::= LIMIT expr */
134321: {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
134322:         break;
134323:       case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
134324: {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
134325:         break;
134326:       case 133: /* limit_opt ::= LIMIT expr COMMA expr */
134327: {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
134328:         break;
134329:       case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
134330: {
134331:   sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
134332:   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
134333:   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
134334: }
134335:         break;
134336:       case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
134337: {
134338:   sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
134339:   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
134340:   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list"); 
134341:   sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
134342: }
134343:         break;
134344:       case 138: /* setlist ::= setlist COMMA nm EQ expr */
134345: {
134346:   yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
134347:   sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
134348: }
134349:         break;
134350:       case 139: /* setlist ::= nm EQ expr */
134351: {
134352:   yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
134353:   sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
134354: }
134355:   yymsp[-2].minor.yy148 = yylhsminor.yy148;
134356:         break;
134357:       case 140: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
134358: {
134359:   sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
134360:   sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
134361: }
134362:         break;
134363:       case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
134364: {
134365:   sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
134366:   sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
134367: }
134368:         break;
134369:       case 145: /* idlist_opt ::= LP idlist RP */
134370: {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
134371:         break;
134372:       case 146: /* idlist ::= idlist COMMA nm */
134373: {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
134374:         break;
134375:       case 147: /* idlist ::= nm */
134376: {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
134377:         break;
134378:       case 148: /* expr ::= LP expr RP */
134379: {spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/  yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
134380:         break;
134381:       case 149: /* term ::= NULL */
134382:       case 154: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==154);
134383:       case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
134384: {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
134385:         break;
134386:       case 150: /* expr ::= ID|INDEXED */
134387:       case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
134388: {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
134389:         break;
134390:       case 152: /* expr ::= nm DOT nm */
134391: {
134392:   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134393:   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
134394:   spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134395:   yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
134396: }
134397:         break;
134398:       case 153: /* expr ::= nm DOT nm DOT nm */
134399: {
134400:   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
134401:   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
134402:   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
134403:   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
134404:   spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134405:   yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
134406: }
134407:         break;
134408:       case 156: /* expr ::= VARIABLE */
134409: {
134410:   if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
134411:     spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
134412:     sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr);
134413:   }else{
134414:     /* When doing a nested parse, one can include terms in an expression
134415:     ** that look like this:   #1 #2 ...  These terms refer to registers
134416:     ** in the virtual machine.  #N is the N-th register. */
134417:     Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
134418:     assert( t.n>=2 );
134419:     spanSet(&yymsp[0].minor.yy190, &t, &t);
134420:     if( pParse->nested==0 ){
134421:       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
134422:       yymsp[0].minor.yy190.pExpr = 0;
134423:     }else{
134424:       yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
134425:       if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
134426:     }
134427:   }
134428: }
134429:         break;
134430:       case 157: /* expr ::= expr COLLATE ID|STRING */
134431: {
134432:   yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
134433:   yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134434: }
134435:         break;
134436:       case 158: /* expr ::= CAST LP expr AS typetoken RP */
134437: {
134438:   spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
134439:   yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy190.pExpr, 0, &yymsp[-1].minor.yy0);
134440: }
134441:         break;
134442:       case 159: /* expr ::= ID|INDEXED LP distinct exprlist RP */
134443: {
134444:   if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
134445:     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
134446:   }
134447:   yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
134448:   spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
134449:   if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
134450:     yylhsminor.yy190.pExpr->flags |= EP_Distinct;
134451:   }
134452: }
134453:   yymsp[-4].minor.yy190 = yylhsminor.yy190;
134454:         break;
134455:       case 160: /* expr ::= ID|INDEXED LP STAR RP */
134456: {
134457:   yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
134458:   spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
134459: }
134460:   yymsp[-3].minor.yy190 = yylhsminor.yy190;
134461:         break;
134462:       case 161: /* term ::= CTIME_KW */
134463: {
134464:   yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
134465:   spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
134466: }
134467:   yymsp[0].minor.yy190 = yylhsminor.yy190;
134468:         break;
134469:       case 162: /* expr ::= expr AND expr */
134470:       case 163: /* expr ::= expr OR expr */ yytestcase(yyruleno==163);
134471:       case 164: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==164);
134472:       case 165: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==165);
134473:       case 166: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==166);
134474:       case 167: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==167);
134475:       case 168: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==168);
134476:       case 169: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==169);
134477: {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
134478:         break;
134479:       case 170: /* likeop ::= LIKE_KW|MATCH */
134480: {yymsp[0].minor.yy392.eOperator = yymsp[0].minor.yy0; yymsp[0].minor.yy392.bNot = 0;/*A-overwrites-X*/}
134481:         break;
134482:       case 171: /* likeop ::= NOT LIKE_KW|MATCH */
134483: {yymsp[-1].minor.yy392.eOperator = yymsp[0].minor.yy0; yymsp[-1].minor.yy392.bNot = 1;}
134484:         break;
134485:       case 172: /* expr ::= expr likeop expr */
134486: {
134487:   ExprList *pList;
134488:   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
134489:   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
134490:   yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy392.eOperator);
134491:   exprNot(pParse, yymsp[-1].minor.yy392.bNot, &yymsp[-2].minor.yy190);
134492:   yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134493:   if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
134494: }
134495:         break;
134496:       case 173: /* expr ::= expr likeop expr ESCAPE expr */
134497: {
134498:   ExprList *pList;
134499:   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134500:   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
134501:   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
134502:   yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy392.eOperator);
134503:   exprNot(pParse, yymsp[-3].minor.yy392.bNot, &yymsp[-4].minor.yy190);
134504:   yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134505:   if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
134506: }
134507:         break;
134508:       case 174: /* expr ::= expr ISNULL|NOTNULL */
134509: {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
134510:         break;
134511:       case 175: /* expr ::= expr NOT NULL */
134512: {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
134513:         break;
134514:       case 176: /* expr ::= expr IS expr */
134515: {
134516:   spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
134517:   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
134518: }
134519:         break;
134520:       case 177: /* expr ::= expr IS NOT expr */
134521: {
134522:   spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
134523:   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
134524: }
134525:         break;
134526:       case 178: /* expr ::= NOT expr */
134527:       case 179: /* expr ::= BITNOT expr */ yytestcase(yyruleno==179);
134528: {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134529:         break;
134530:       case 180: /* expr ::= MINUS expr */
134531: {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134532:         break;
134533:       case 181: /* expr ::= PLUS expr */
134534: {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
134535:         break;
134536:       case 182: /* between_op ::= BETWEEN */
134537:       case 185: /* in_op ::= IN */ yytestcase(yyruleno==185);
134538: {yymsp[0].minor.yy194 = 0;}
134539:         break;
134540:       case 184: /* expr ::= expr between_op expr AND expr */
134541: {
134542:   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134543:   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
134544:   yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134545:   if( yymsp[-4].minor.yy190.pExpr ){
134546:     yymsp[-4].minor.yy190.pExpr->x.pList = pList;
134547:   }else{
134548:     sqlite3ExprListDelete(pParse->db, pList);
134549:   } 
134550:   exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134551:   yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
134552: }
134553:         break;
134554:       case 187: /* expr ::= expr in_op LP exprlist RP */
134555: {
134556:     if( yymsp[-1].minor.yy148==0 ){
134557:       /* Expressions of the form
134558:       **
134559:       **      expr1 IN ()
134560:       **      expr1 NOT IN ()
134561:       **
134562:       ** simplify to constants 0 (false) and 1 (true), respectively,
134563:       ** regardless of the value of expr1.
134564:       */
134565:       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
134566:       yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy194]);
134567:     }else if( yymsp[-1].minor.yy148->nExpr==1 ){
134568:       /* Expressions of the form:
134569:       **
134570:       **      expr1 IN (?1)
134571:       **      expr1 NOT IN (?2)
134572:       **
134573:       ** with exactly one value on the RHS can be simplified to something
134574:       ** like this:
134575:       **
134576:       **      expr1 == ?1
134577:       **      expr1 <> ?2
134578:       **
134579:       ** But, the RHS of the == or <> is marked with the EP_Generic flag
134580:       ** so that it may not contribute to the computation of comparison
134581:       ** affinity or the collating sequence to use for comparison.  Otherwise,
134582:       ** the semantics would be subtly different from IN or NOT IN.
134583:       */
134584:       Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
134585:       yymsp[-1].minor.yy148->a[0].pExpr = 0;
134586:       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
134587:       /* pRHS cannot be NULL because a malloc error would have been detected
134588:       ** before now and control would have never reached this point */
134589:       if( ALWAYS(pRHS) ){
134590:         pRHS->flags &= ~EP_Collate;
134591:         pRHS->flags |= EP_Generic;
134592:       }
134593:       yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS, 0);
134594:     }else{
134595:       yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134596:       if( yymsp[-4].minor.yy190.pExpr ){
134597:         yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
134598:         sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
134599:       }else{
134600:         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
134601:       }
134602:       exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134603:     }
134604:     yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134605:   }
134606:         break;
134607:       case 188: /* expr ::= LP select RP */
134608: {
134609:     spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
134610:     yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
134611:     sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
134612:   }
134613:         break;
134614:       case 189: /* expr ::= expr in_op LP select RP */
134615: {
134616:     yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134617:     sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
134618:     exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134619:     yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
134620:   }
134621:         break;
134622:       case 190: /* expr ::= expr in_op nm dbnm paren_exprlist */
134623: {
134624:     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
134625:     Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
134626:     if( yymsp[0].minor.yy148 )  sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
134627:     yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0, 0);
134628:     sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
134629:     exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
134630:     yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
134631:   }
134632:         break;
134633:       case 191: /* expr ::= EXISTS LP select RP */
134634: {
134635:     Expr *p;
134636:     spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
134637:     p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
134638:     sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
134639:   }
134640:         break;
134641:       case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
134642: {
134643:   spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-C*/
134644:   yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0, 0);
134645:   if( yymsp[-4].minor.yy190.pExpr ){
134646:     yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
134647:     sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
134648:   }else{
134649:     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
134650:     sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
134651:   }
134652: }
134653:         break;
134654:       case 193: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
134655: {
134656:   yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
134657:   yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
134658: }
134659:         break;
134660:       case 194: /* case_exprlist ::= WHEN expr THEN expr */
134661: {
134662:   yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
134663:   yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
134664: }
134665:         break;
134666:       case 197: /* case_operand ::= expr */
134667: {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
134668:         break;
134669:       case 200: /* nexprlist ::= nexprlist COMMA expr */
134670: {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
134671:         break;
134672:       case 201: /* nexprlist ::= expr */
134673: {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
134674:         break;
134675:       case 203: /* paren_exprlist ::= LP exprlist RP */
134676:       case 208: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==208);
134677: {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
134678:         break;
134679:       case 204: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
134680: {
134681:   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, 
134682:                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
134683:                       &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
134684: }
134685:         break;
134686:       case 205: /* uniqueflag ::= UNIQUE */
134687:       case 246: /* raisetype ::= ABORT */ yytestcase(yyruleno==246);
134688: {yymsp[0].minor.yy194 = OE_Abort;}
134689:         break;
134690:       case 206: /* uniqueflag ::= */
134691: {yymsp[1].minor.yy194 = OE_None;}
134692:         break;
134693:       case 209: /* eidlist ::= eidlist COMMA nm collate sortorder */
134694: {
134695:   yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
134696: }
134697:         break;
134698:       case 210: /* eidlist ::= nm collate sortorder */
134699: {
134700:   yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
134701: }
134702:         break;
134703:       case 213: /* cmd ::= DROP INDEX ifexists fullname */
134704: {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
134705:         break;
134706:       case 214: /* cmd ::= VACUUM */
134707:       case 215: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==215);
134708: {sqlite3Vacuum(pParse);}
134709:         break;
134710:       case 216: /* cmd ::= PRAGMA nm dbnm */
134711: {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
134712:         break;
134713:       case 217: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
134714: {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
134715:         break;
134716:       case 218: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
134717: {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
134718:         break;
134719:       case 219: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
134720: {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
134721:         break;
134722:       case 220: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
134723: {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
134724:         break;
134725:       case 223: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
134726: {
134727:   Token all;
134728:   all.z = yymsp[-3].minor.yy0.z;
134729:   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
134730:   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
134731: }
134732:         break;
134733:       case 224: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
134734: {
134735:   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
134736:   yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
134737: }
134738:         break;
134739:       case 225: /* trigger_time ::= BEFORE */
134740: { yymsp[0].minor.yy194 = TK_BEFORE; }
134741:         break;
134742:       case 226: /* trigger_time ::= AFTER */
134743: { yymsp[0].minor.yy194 = TK_AFTER;  }
134744:         break;
134745:       case 227: /* trigger_time ::= INSTEAD OF */
134746: { yymsp[-1].minor.yy194 = TK_INSTEAD;}
134747:         break;
134748:       case 228: /* trigger_time ::= */
134749: { yymsp[1].minor.yy194 = TK_BEFORE; }
134750:         break;
134751:       case 229: /* trigger_event ::= DELETE|INSERT */
134752:       case 230: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==230);
134753: {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
134754:         break;
134755:       case 231: /* trigger_event ::= UPDATE OF idlist */
134756: {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
134757:         break;
134758:       case 232: /* when_clause ::= */
134759:       case 251: /* key_opt ::= */ yytestcase(yyruleno==251);
134760: { yymsp[1].minor.yy72 = 0; }
134761:         break;
134762:       case 233: /* when_clause ::= WHEN expr */
134763:       case 252: /* key_opt ::= KEY expr */ yytestcase(yyruleno==252);
134764: { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
134765:         break;
134766:       case 234: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
134767: {
134768:   assert( yymsp[-2].minor.yy145!=0 );
134769:   yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
134770:   yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
134771: }
134772:         break;
134773:       case 235: /* trigger_cmd_list ::= trigger_cmd SEMI */
134774: { 
134775:   assert( yymsp[-1].minor.yy145!=0 );
134776:   yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
134777: }
134778:         break;
134779:       case 236: /* trnm ::= nm DOT nm */
134780: {
134781:   yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
134782:   sqlite3ErrorMsg(pParse, 
134783:         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
134784:         "statements within triggers");
134785: }
134786:         break;
134787:       case 237: /* tridxby ::= INDEXED BY nm */
134788: {
134789:   sqlite3ErrorMsg(pParse,
134790:         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
134791:         "within triggers");
134792: }
134793:         break;
134794:       case 238: /* tridxby ::= NOT INDEXED */
134795: {
134796:   sqlite3ErrorMsg(pParse,
134797:         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
134798:         "within triggers");
134799: }
134800:         break;
134801:       case 239: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
134802: {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
134803:         break;
134804:       case 240: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
134805: {yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
134806:         break;
134807:       case 241: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
134808: {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
134809:         break;
134810:       case 242: /* trigger_cmd ::= select */
134811: {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
134812:         break;
134813:       case 243: /* expr ::= RAISE LP IGNORE RP */
134814: {
134815:   spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
134816:   yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
134817:   if( yymsp[-3].minor.yy190.pExpr ){
134818:     yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
134819:   }
134820: }
134821:         break;
134822:       case 244: /* expr ::= RAISE LP raisetype COMMA nm RP */
134823: {
134824:   spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);  /*A-overwrites-X*/
134825:   yymsp[-5].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
134826:   if( yymsp[-5].minor.yy190.pExpr ) {
134827:     yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
134828:   }
134829: }
134830:         break;
134831:       case 245: /* raisetype ::= ROLLBACK */
134832: {yymsp[0].minor.yy194 = OE_Rollback;}
134833:         break;
134834:       case 247: /* raisetype ::= FAIL */
134835: {yymsp[0].minor.yy194 = OE_Fail;}
134836:         break;
134837:       case 248: /* cmd ::= DROP TRIGGER ifexists fullname */
134838: {
134839:   sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
134840: }
134841:         break;
134842:       case 249: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
134843: {
134844:   sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
134845: }
134846:         break;
134847:       case 250: /* cmd ::= DETACH database_kw_opt expr */
134848: {
134849:   sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
134850: }
134851:         break;
134852:       case 253: /* cmd ::= REINDEX */
134853: {sqlite3Reindex(pParse, 0, 0);}
134854:         break;
134855:       case 254: /* cmd ::= REINDEX nm dbnm */
134856: {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
134857:         break;
134858:       case 255: /* cmd ::= ANALYZE */
134859: {sqlite3Analyze(pParse, 0, 0);}
134860:         break;
134861:       case 256: /* cmd ::= ANALYZE nm dbnm */
134862: {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
134863:         break;
134864:       case 257: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
134865: {
134866:   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
134867: }
134868:         break;
134869:       case 258: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
134870: {
134871:   yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
134872:   sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
134873: }
134874:         break;
134875:       case 259: /* add_column_fullname ::= fullname */
134876: {
134877:   disableLookaside(pParse);
134878:   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
134879: }
134880:         break;
134881:       case 260: /* cmd ::= create_vtab */
134882: {sqlite3VtabFinishParse(pParse,0);}
134883:         break;
134884:       case 261: /* cmd ::= create_vtab LP vtabarglist RP */
134885: {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
134886:         break;
134887:       case 262: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
134888: {
134889:     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
134890: }
134891:         break;
134892:       case 263: /* vtabarg ::= */
134893: {sqlite3VtabArgInit(pParse);}
134894:         break;
134895:       case 264: /* vtabargtoken ::= ANY */
134896:       case 265: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==265);
134897:       case 266: /* lp ::= LP */ yytestcase(yyruleno==266);
134898: {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
134899:         break;
134900:       case 267: /* with ::= */
134901: {yymsp[1].minor.yy285 = 0;}
134902:         break;
134903:       case 268: /* with ::= WITH wqlist */
134904: { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
134905:         break;
134906:       case 269: /* with ::= WITH RECURSIVE wqlist */
134907: { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
134908:         break;
134909:       case 270: /* wqlist ::= nm eidlist_opt AS LP select RP */
134910: {
134911:   yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
134912: }
134913:         break;
134914:       case 271: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
134915: {
134916:   yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
134917: }
134918:         break;
134919:       default:
134920:       /* (272) input ::= cmdlist */ yytestcase(yyruleno==272);
134921:       /* (273) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==273);
134922:       /* (274) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=274);
134923:       /* (275) ecmd ::= SEMI */ yytestcase(yyruleno==275);
134924:       /* (276) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==276);
134925:       /* (277) explain ::= */ yytestcase(yyruleno==277);
134926:       /* (278) trans_opt ::= */ yytestcase(yyruleno==278);
134927:       /* (279) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==279);
134928:       /* (280) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==280);
134929:       /* (281) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==281);
134930:       /* (282) savepoint_opt ::= */ yytestcase(yyruleno==282);
134931:       /* (283) cmd ::= create_table create_table_args */ yytestcase(yyruleno==283);
134932:       /* (284) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==284);
134933:       /* (285) columnlist ::= columnname carglist */ yytestcase(yyruleno==285);
134934:       /* (286) nm ::= ID|INDEXED */ yytestcase(yyruleno==286);
134935:       /* (287) nm ::= STRING */ yytestcase(yyruleno==287);
134936:       /* (288) nm ::= JOIN_KW */ yytestcase(yyruleno==288);
134937:       /* (289) typetoken ::= typename */ yytestcase(yyruleno==289);
134938:       /* (290) typename ::= ID|STRING */ yytestcase(yyruleno==290);
134939:       /* (291) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=291);
134940:       /* (292) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=292);
134941:       /* (293) carglist ::= carglist ccons */ yytestcase(yyruleno==293);
134942:       /* (294) carglist ::= */ yytestcase(yyruleno==294);
134943:       /* (295) ccons ::= NULL onconf */ yytestcase(yyruleno==295);
134944:       /* (296) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==296);
134945:       /* (297) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==297);
134946:       /* (298) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=298);
134947:       /* (299) tconscomma ::= */ yytestcase(yyruleno==299);
134948:       /* (300) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=300);
134949:       /* (301) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=301);
134950:       /* (302) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=302);
134951:       /* (303) oneselect ::= values */ yytestcase(yyruleno==303);
134952:       /* (304) sclp ::= selcollist COMMA */ yytestcase(yyruleno==304);
134953:       /* (305) as ::= ID|STRING */ yytestcase(yyruleno==305);
134954:       /* (306) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=306);
134955:       /* (307) exprlist ::= nexprlist */ yytestcase(yyruleno==307);
134956:       /* (308) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=308);
134957:       /* (309) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=309);
134958:       /* (310) nmnum ::= ON */ yytestcase(yyruleno==310);
134959:       /* (311) nmnum ::= DELETE */ yytestcase(yyruleno==311);
134960:       /* (312) nmnum ::= DEFAULT */ yytestcase(yyruleno==312);
134961:       /* (313) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==313);
134962:       /* (314) foreach_clause ::= */ yytestcase(yyruleno==314);
134963:       /* (315) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==315);
134964:       /* (316) trnm ::= nm */ yytestcase(yyruleno==316);
134965:       /* (317) tridxby ::= */ yytestcase(yyruleno==317);
134966:       /* (318) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==318);
134967:       /* (319) database_kw_opt ::= */ yytestcase(yyruleno==319);
134968:       /* (320) kwcolumn_opt ::= */ yytestcase(yyruleno==320);
134969:       /* (321) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==321);
134970:       /* (322) vtabarglist ::= vtabarg */ yytestcase(yyruleno==322);
134971:       /* (323) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==323);
134972:       /* (324) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==324);
134973:       /* (325) anylist ::= */ yytestcase(yyruleno==325);
134974:       /* (326) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==326);
134975:       /* (327) anylist ::= anylist ANY */ yytestcase(yyruleno==327);
134976:         break;
134977: /********** End reduce actions ************************************************/
134978:   };
134979:   assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
134980:   yygoto = yyRuleInfo[yyruleno].lhs;
134981:   yysize = yyRuleInfo[yyruleno].nrhs;
134982:   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
134983:   if( yyact <= YY_MAX_SHIFTREDUCE ){
134984:     if( yyact>YY_MAX_SHIFT ){
134985:       yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
134986:     }
134987:     yymsp -= yysize-1;
134988:     yypParser->yytos = yymsp;
134989:     yymsp->stateno = (YYACTIONTYPE)yyact;
134990:     yymsp->major = (YYCODETYPE)yygoto;
134991:     yyTraceShift(yypParser, yyact);
134992:   }else{
134993:     assert( yyact == YY_ACCEPT_ACTION );
134994:     yypParser->yytos -= yysize;
134995:     yy_accept(yypParser);
134996:   }
134997: }
134998: 
134999: /*
135000: ** The following code executes when the parse fails
135001: */
135002: #ifndef YYNOERRORRECOVERY
135003: static void yy_parse_failed(
135004:   yyParser *yypParser           /* The parser */
135005: ){
135006:   sqlite3ParserARG_FETCH;
135007: #ifndef NDEBUG
135008:   if( yyTraceFILE ){
135009:     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
135010:   }
135011: #endif
135012:   while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
135013:   /* Here code is inserted which will be executed whenever the
135014:   ** parser fails */
135015: /************ Begin %parse_failure code ***************************************/
135016: /************ End %parse_failure code *****************************************/
135017:   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
135018: }
135019: #endif /* YYNOERRORRECOVERY */
135020: 
135021: /*
135022: ** The following code executes when a syntax error first occurs.
135023: */
135024: static void yy_syntax_error(
135025:   yyParser *yypParser,           /* The parser */
135026:   int yymajor,                   /* The major type of the error token */
135027:   sqlite3ParserTOKENTYPE yyminor         /* The minor type of the error token */
135028: ){
135029:   sqlite3ParserARG_FETCH;
135030: #define TOKEN yyminor
135031: /************ Begin %syntax_error code ****************************************/
135032: 
135033:   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
135034:   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
135035:   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
135036: /************ End %syntax_error code ******************************************/
135037:   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
135038: }
135039: 
135040: /*
135041: ** The following is executed when the parser accepts
135042: */
135043: static void yy_accept(
135044:   yyParser *yypParser           /* The parser */
135045: ){
135046:   sqlite3ParserARG_FETCH;
135047: #ifndef NDEBUG
135048:   if( yyTraceFILE ){
135049:     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
135050:   }
135051: #endif
135052: #ifndef YYNOERRORRECOVERY
135053:   yypParser->yyerrcnt = -1;
135054: #endif
135055:   assert( yypParser->yytos==yypParser->yystack );
135056:   /* Here code is inserted which will be executed whenever the
135057:   ** parser accepts */
135058: /*********** Begin %parse_accept code *****************************************/
135059: /*********** End %parse_accept code *******************************************/
135060:   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
135061: }
135062: 
135063: /* The main parser program.
135064: ** The first argument is a pointer to a structure obtained from
135065: ** "sqlite3ParserAlloc" which describes the current state of the parser.
135066: ** The second argument is the major token number.  The third is
135067: ** the minor token.  The fourth optional argument is whatever the
135068: ** user wants (and specified in the grammar) and is available for
135069: ** use by the action routines.
135070: **
135071: ** Inputs:
135072: ** <ul>
135073: ** <li> A pointer to the parser (an opaque structure.)
135074: ** <li> The major token number.
135075: ** <li> The minor token number.
135076: ** <li> An option argument of a grammar-specified type.
135077: ** </ul>
135078: **
135079: ** Outputs:
135080: ** None.
135081: */
135082: SQLITE_PRIVATE void sqlite3Parser(
135083:   void *yyp,                   /* The parser */
135084:   int yymajor,                 /* The major token code number */
135085:   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
135086:   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
135087: ){
135088:   YYMINORTYPE yyminorunion;
135089:   unsigned int yyact;   /* The parser action. */
135090: #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
135091:   int yyendofinput;     /* True if we are at the end of input */
135092: #endif
135093: #ifdef YYERRORSYMBOL
135094:   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
135095: #endif
135096:   yyParser *yypParser;  /* The parser */
135097: 
135098:   yypParser = (yyParser*)yyp;
135099:   assert( yypParser->yytos!=0 );
135100: #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
135101:   yyendofinput = (yymajor==0);
135102: #endif
135103:   sqlite3ParserARG_STORE;
135104: 
135105: #ifndef NDEBUG
135106:   if( yyTraceFILE ){
135107:     fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
135108:   }
135109: #endif
135110: 
135111:   do{
135112:     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
135113:     if( yyact <= YY_MAX_SHIFTREDUCE ){
135114:       yy_shift(yypParser,yyact,yymajor,yyminor);
135115: #ifndef YYNOERRORRECOVERY
135116:       yypParser->yyerrcnt--;
135117: #endif
135118:       yymajor = YYNOCODE;
135119:     }else if( yyact <= YY_MAX_REDUCE ){
135120:       yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
135121:     }else{
135122:       assert( yyact == YY_ERROR_ACTION );
135123:       yyminorunion.yy0 = yyminor;
135124: #ifdef YYERRORSYMBOL
135125:       int yymx;
135126: #endif
135127: #ifndef NDEBUG
135128:       if( yyTraceFILE ){
135129:         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
135130:       }
135131: #endif
135132: #ifdef YYERRORSYMBOL
135133:       /* A syntax error has occurred.
135134:       ** The response to an error depends upon whether or not the
135135:       ** grammar defines an error token "ERROR".  
135136:       **
135137:       ** This is what we do if the grammar does define ERROR:
135138:       **
135139:       **  * Call the %syntax_error function.
135140:       **
135141:       **  * Begin popping the stack until we enter a state where
135142:       **    it is legal to shift the error symbol, then shift
135143:       **    the error symbol.
135144:       **
135145:       **  * Set the error count to three.
135146:       **
135147:       **  * Begin accepting and shifting new tokens.  No new error
135148:       **    processing will occur until three tokens have been
135149:       **    shifted successfully.
135150:       **
135151:       */
135152:       if( yypParser->yyerrcnt<0 ){
135153:         yy_syntax_error(yypParser,yymajor,yyminor);
135154:       }
135155:       yymx = yypParser->yytos->major;
135156:       if( yymx==YYERRORSYMBOL || yyerrorhit ){
135157: #ifndef NDEBUG
135158:         if( yyTraceFILE ){
135159:           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
135160:              yyTracePrompt,yyTokenName[yymajor]);
135161:         }
135162: #endif
135163:         yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
135164:         yymajor = YYNOCODE;
135165:       }else{
135166:         while( yypParser->yytos >= &yypParser->yystack
135167:             && yymx != YYERRORSYMBOL
135168:             && (yyact = yy_find_reduce_action(
135169:                         yypParser->yytos->stateno,
135170:                         YYERRORSYMBOL)) >= YY_MIN_REDUCE
135171:         ){
135172:           yy_pop_parser_stack(yypParser);
135173:         }
135174:         if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
135175:           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135176:           yy_parse_failed(yypParser);
135177: #ifndef YYNOERRORRECOVERY
135178:           yypParser->yyerrcnt = -1;
135179: #endif
135180:           yymajor = YYNOCODE;
135181:         }else if( yymx!=YYERRORSYMBOL ){
135182:           yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
135183:         }
135184:       }
135185:       yypParser->yyerrcnt = 3;
135186:       yyerrorhit = 1;
135187: #elif defined(YYNOERRORRECOVERY)
135188:       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
135189:       ** do any kind of error recovery.  Instead, simply invoke the syntax
135190:       ** error routine and continue going as if nothing had happened.
135191:       **
135192:       ** Applications can set this macro (for example inside %include) if
135193:       ** they intend to abandon the parse upon the first syntax error seen.
135194:       */
135195:       yy_syntax_error(yypParser,yymajor, yyminor);
135196:       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135197:       yymajor = YYNOCODE;
135198:       
135199: #else  /* YYERRORSYMBOL is not defined */
135200:       /* This is what we do if the grammar does not define ERROR:
135201:       **
135202:       **  * Report an error message, and throw away the input token.
135203:       **
135204:       **  * If the input token is $, then fail the parse.
135205:       **
135206:       ** As before, subsequent error messages are suppressed until
135207:       ** three input tokens have been successfully shifted.
135208:       */
135209:       if( yypParser->yyerrcnt<=0 ){
135210:         yy_syntax_error(yypParser,yymajor, yyminor);
135211:       }
135212:       yypParser->yyerrcnt = 3;
135213:       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
135214:       if( yyendofinput ){
135215:         yy_parse_failed(yypParser);
135216: #ifndef YYNOERRORRECOVERY
135217:         yypParser->yyerrcnt = -1;
135218: #endif
135219:       }
135220:       yymajor = YYNOCODE;
135221: #endif
135222:     }
135223:   }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
135224: #ifndef NDEBUG
135225:   if( yyTraceFILE ){
135226:     yyStackEntry *i;
135227:     char cDiv = '[';
135228:     fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
135229:     for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
135230:       fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
135231:       cDiv = ' ';
135232:     }
135233:     fprintf(yyTraceFILE,"]\n");
135234:   }
135235: #endif
135236:   return;
135237: }
135238: 
135239: /************** End of parse.c ***********************************************/
135240: /************** Begin file tokenize.c ****************************************/
135241: /*
135242: ** 2001 September 15
135243: **
135244: ** The author disclaims copyright to this source code.  In place of
135245: ** a legal notice, here is a blessing:
135246: **
135247: **    May you do good and not evil.
135248: **    May you find forgiveness for yourself and forgive others.
135249: **    May you share freely, never taking more than you give.
135250: **
135251: *************************************************************************
135252: ** An tokenizer for SQL
135253: **
135254: ** This file contains C code that splits an SQL input string up into
135255: ** individual tokens and sends those tokens one-by-one over to the
135256: ** parser for analysis.
135257: */
135258: /* #include "sqliteInt.h" */
135259: /* #include <stdlib.h> */
135260: 
135261: /* Character classes for tokenizing
135262: **
135263: ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
135264: ** using a lookup table, whereas a switch() directly on c uses a binary search.
135265: ** The lookup table is much faster.  To maximize speed, and to ensure that
135266: ** a lookup table is used, all of the classes need to be small integers and
135267: ** all of them need to be used within the switch.
135268: */
135269: #define CC_X          0    /* The letter 'x', or start of BLOB literal */
135270: #define CC_KYWD       1    /* Alphabetics or '_'.  Usable in a keyword */
135271: #define CC_ID         2    /* unicode characters usable in IDs */
135272: #define CC_DIGIT      3    /* Digits */
135273: #define CC_DOLLAR     4    /* '$' */
135274: #define CC_VARALPHA   5    /* '@', '#', ':'.  Alphabetic SQL variables */
135275: #define CC_VARNUM     6    /* '?'.  Numeric SQL variables */
135276: #define CC_SPACE      7    /* Space characters */
135277: #define CC_QUOTE      8    /* '"', '\'', or '`'.  String literals, quoted ids */
135278: #define CC_QUOTE2     9    /* '['.   [...] style quoted ids */
135279: #define CC_PIPE      10    /* '|'.   Bitwise OR or concatenate */
135280: #define CC_MINUS     11    /* '-'.  Minus or SQL-style comment */
135281: #define CC_LT        12    /* '<'.  Part of < or <= or <> */
135282: #define CC_GT        13    /* '>'.  Part of > or >= */
135283: #define CC_EQ        14    /* '='.  Part of = or == */
135284: #define CC_BANG      15    /* '!'.  Part of != */
135285: #define CC_SLASH     16    /* '/'.  / or c-style comment */
135286: #define CC_LP        17    /* '(' */
135287: #define CC_RP        18    /* ')' */
135288: #define CC_SEMI      19    /* ';' */
135289: #define CC_PLUS      20    /* '+' */
135290: #define CC_STAR      21    /* '*' */
135291: #define CC_PERCENT   22    /* '%' */
135292: #define CC_COMMA     23    /* ',' */
135293: #define CC_AND       24    /* '&' */
135294: #define CC_TILDA     25    /* '~' */
135295: #define CC_DOT       26    /* '.' */
135296: #define CC_ILLEGAL   27    /* Illegal character */
135297: 
135298: static const unsigned char aiClass[] = {
135299: #ifdef SQLITE_ASCII
135300: /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
135301: /* 0x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  7,  7, 27,  7,  7, 27, 27,
135302: /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135303: /* 2x */    7, 15,  8,  5,  4, 22, 24,  8, 17, 18, 21, 20, 23, 11, 26, 16,
135304: /* 3x */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3,  5, 19, 12, 14, 13,  6,
135305: /* 4x */    5,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
135306: /* 5x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1,  9, 27, 27, 27,  1,
135307: /* 6x */    8,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
135308: /* 7x */    1,  1,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 10, 27, 25, 27,
135309: /* 8x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135310: /* 9x */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135311: /* Ax */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135312: /* Bx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135313: /* Cx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135314: /* Dx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135315: /* Ex */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,
135316: /* Fx */    2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2,  2
135317: #endif
135318: #ifdef SQLITE_EBCDIC
135319: /*         x0  x1  x2  x3  x4  x5  x6  x7  x8  x9  xa  xb  xc  xd  xe  xf */
135320: /* 0x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27,  7,  7, 27, 27,
135321: /* 1x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135322: /* 2x */   27, 27, 27, 27, 27,  7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135323: /* 3x */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
135324: /* 4x */    7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10,
135325: /* 5x */   24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15,  4, 21, 18, 19, 27,
135326: /* 6x */   11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22,  1, 13,  7,
135327: /* 7x */   27, 27, 27, 27, 27, 27, 27, 27, 27,  8,  5,  5,  5,  8, 14,  8,
135328: /* 8x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135329: /* 9x */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135330: /* 9x */   25,  1,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
135331: /* Bx */   27, 27, 27, 27, 27, 27, 27, 27, 27, 27,  9, 27, 27, 27, 27, 27,
135332: /* Cx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135333: /* Dx */   27,  1,  1,  1,  1,  1,  1,  1,  1,  1, 27, 27, 27, 27, 27, 27,
135334: /* Ex */   27, 27,  1,  1,  1,  1,  1,  0,  1,  1, 27, 27, 27, 27, 27, 27,
135335: /* Fx */    3,  3,  3,  3,  3,  3,  3,  3,  3,  3, 27, 27, 27, 27, 27, 27,
135336: #endif
135337: };
135338: 
135339: /*
135340: ** The charMap() macro maps alphabetic characters (only) into their
135341: ** lower-case ASCII equivalent.  On ASCII machines, this is just
135342: ** an upper-to-lower case map.  On EBCDIC machines we also need
135343: ** to adjust the encoding.  The mapping is only valid for alphabetics
135344: ** which are the only characters for which this feature is used. 
135345: **
135346: ** Used by keywordhash.h
135347: */
135348: #ifdef SQLITE_ASCII
135349: # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
135350: #endif
135351: #ifdef SQLITE_EBCDIC
135352: # define charMap(X) ebcdicToAscii[(unsigned char)X]
135353: const unsigned char ebcdicToAscii[] = {
135354: /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
135355:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
135356:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
135357:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
135358:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
135359:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
135360:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
135361:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
135362:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
135363:    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
135364:    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
135365:    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
135366:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
135367:    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
135368:    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
135369:    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
135370:    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
135371: };
135372: #endif
135373: 
135374: /*
135375: ** The sqlite3KeywordCode function looks up an identifier to determine if
135376: ** it is a keyword.  If it is a keyword, the token code of that keyword is 
135377: ** returned.  If the input is not a keyword, TK_ID is returned.
135378: **
135379: ** The implementation of this routine was generated by a program,
135380: ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
135381: ** The output of the mkkeywordhash.c program is written into a file
135382: ** named keywordhash.h and then included into this source file by
135383: ** the #include below.
135384: */
135385: /************** Include keywordhash.h in the middle of tokenize.c ************/
135386: /************** Begin file keywordhash.h *************************************/
135387: /***** This file contains automatically generated code ******
135388: **
135389: ** The code in this file has been automatically generated by
135390: **
135391: **   sqlite/tool/mkkeywordhash.c
135392: **
135393: ** The code in this file implements a function that determines whether
135394: ** or not a given identifier is really an SQL keyword.  The same thing
135395: ** might be implemented more directly using a hand-written hash table.
135396: ** But by using this automatically generated code, the size of the code
135397: ** is substantially reduced.  This is important for embedded applications
135398: ** on platforms with limited memory.
135399: */
135400: /* Hash score: 182 */
135401: static int keywordCode(const char *z, int n, int *pType){
135402:   /* zText[] encodes 834 bytes of keywords in 554 bytes */
135403:   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
135404:   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
135405:   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
135406:   /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
135407:   /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
135408:   /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
135409:   /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
135410:   /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
135411:   /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
135412:   /*   VACUUMVIEWINITIALLY                                                */
135413:   static const char zText[553] = {
135414:     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
135415:     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
135416:     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
135417:     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
135418:     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
135419:     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
135420:     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
135421:     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
135422:     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
135423:     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
135424:     'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
135425:     'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
135426:     'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
135427:     'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
135428:     'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
135429:     'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
135430:     'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
135431:     'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
135432:     'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
135433:     'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
135434:     'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
135435:     'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
135436:     'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
135437:     'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
135438:     'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
135439:     'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
135440:     'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
135441:     'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
135442:     'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
135443:     'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
135444:     'V','I','E','W','I','N','I','T','I','A','L','L','Y',
135445:   };
135446:   static const unsigned char aHash[127] = {
135447:       76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
135448:       42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
135449:      121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
135450:        0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
135451:        0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
135452:       96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
135453:      100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
135454:       39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
135455:       62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
135456:       29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
135457:   };
135458:   static const unsigned char aNext[124] = {
135459:        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
135460:        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
135461:        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
135462:        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
135463:        0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
135464:        0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
135465:        0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
135466:       10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
135467:        0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
135468:       73,  83,   0,  35,  68,   0,   0,
135469:   };
135470:   static const unsigned char aLen[124] = {
135471:        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
135472:        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
135473:       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
135474:        4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
135475:        6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
135476:        7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
135477:        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
135478:       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
135479:        2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
135480:        3,   5,   5,   6,   4,   9,   3,
135481:   };
135482:   static const unsigned short int aOffset[124] = {
135483:        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
135484:       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
135485:       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
135486:      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
135487:      199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
135488:      250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
135489:      320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
135490:      387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
135491:      460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
135492:      521, 524, 529, 534, 540, 544, 549,
135493:   };
135494:   static const unsigned char aCode[124] = {
135495:     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
135496:     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
135497:     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
135498:     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
135499:     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
135500:     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
135501:     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
135502:     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
135503:     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
135504:     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,       
135505:     TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,      
135506:     TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,    
135507:     TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,    
135508:     TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    
135509:     TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       
135510:     TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     
135511:     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       
135512:     TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,        
135513:     TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       
135514:     TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   
135515:     TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         
135516:     TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,    
135517:     TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,   
135518:     TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,      
135519:     TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,        
135520:   };
135521:   int i, j;
135522:   const char *zKW;
135523:   if( n>=2 ){
135524:     i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
135525:     for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
135526:       if( aLen[i]!=n ) continue;
135527:       j = 0;
135528:       zKW = &zText[aOffset[i]];
135529: #ifdef SQLITE_ASCII
135530:       while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
135531: #endif
135532: #ifdef SQLITE_EBCDIC
135533:       while( j<n && toupper(z[j])==zKW[j] ){ j++; }
135534: #endif
135535:       if( j<n ) continue;
135536:       testcase( i==0 ); /* REINDEX */
135537:       testcase( i==1 ); /* INDEXED */
135538:       testcase( i==2 ); /* INDEX */
135539:       testcase( i==3 ); /* DESC */
135540:       testcase( i==4 ); /* ESCAPE */
135541:       testcase( i==5 ); /* EACH */
135542:       testcase( i==6 ); /* CHECK */
135543:       testcase( i==7 ); /* KEY */
135544:       testcase( i==8 ); /* BEFORE */
135545:       testcase( i==9 ); /* FOREIGN */
135546:       testcase( i==10 ); /* FOR */
135547:       testcase( i==11 ); /* IGNORE */
135548:       testcase( i==12 ); /* REGEXP */
135549:       testcase( i==13 ); /* EXPLAIN */
135550:       testcase( i==14 ); /* INSTEAD */
135551:       testcase( i==15 ); /* ADD */
135552:       testcase( i==16 ); /* DATABASE */
135553:       testcase( i==17 ); /* AS */
135554:       testcase( i==18 ); /* SELECT */
135555:       testcase( i==19 ); /* TABLE */
135556:       testcase( i==20 ); /* LEFT */
135557:       testcase( i==21 ); /* THEN */
135558:       testcase( i==22 ); /* END */
135559:       testcase( i==23 ); /* DEFERRABLE */
135560:       testcase( i==24 ); /* ELSE */
135561:       testcase( i==25 ); /* EXCEPT */
135562:       testcase( i==26 ); /* TRANSACTION */
135563:       testcase( i==27 ); /* ACTION */
135564:       testcase( i==28 ); /* ON */
135565:       testcase( i==29 ); /* NATURAL */
135566:       testcase( i==30 ); /* ALTER */
135567:       testcase( i==31 ); /* RAISE */
135568:       testcase( i==32 ); /* EXCLUSIVE */
135569:       testcase( i==33 ); /* EXISTS */
135570:       testcase( i==34 ); /* SAVEPOINT */
135571:       testcase( i==35 ); /* INTERSECT */
135572:       testcase( i==36 ); /* TRIGGER */
135573:       testcase( i==37 ); /* REFERENCES */
135574:       testcase( i==38 ); /* CONSTRAINT */
135575:       testcase( i==39 ); /* INTO */
135576:       testcase( i==40 ); /* OFFSET */
135577:       testcase( i==41 ); /* OF */
135578:       testcase( i==42 ); /* SET */
135579:       testcase( i==43 ); /* TEMPORARY */
135580:       testcase( i==44 ); /* TEMP */
135581:       testcase( i==45 ); /* OR */
135582:       testcase( i==46 ); /* UNIQUE */
135583:       testcase( i==47 ); /* QUERY */
135584:       testcase( i==48 ); /* WITHOUT */
135585:       testcase( i==49 ); /* WITH */
135586:       testcase( i==50 ); /* OUTER */
135587:       testcase( i==51 ); /* RELEASE */
135588:       testcase( i==52 ); /* ATTACH */
135589:       testcase( i==53 ); /* HAVING */
135590:       testcase( i==54 ); /* GROUP */
135591:       testcase( i==55 ); /* UPDATE */
135592:       testcase( i==56 ); /* BEGIN */
135593:       testcase( i==57 ); /* INNER */
135594:       testcase( i==58 ); /* RECURSIVE */
135595:       testcase( i==59 ); /* BETWEEN */
135596:       testcase( i==60 ); /* NOTNULL */
135597:       testcase( i==61 ); /* NOT */
135598:       testcase( i==62 ); /* NO */
135599:       testcase( i==63 ); /* NULL */
135600:       testcase( i==64 ); /* LIKE */
135601:       testcase( i==65 ); /* CASCADE */
135602:       testcase( i==66 ); /* ASC */
135603:       testcase( i==67 ); /* DELETE */
135604:       testcase( i==68 ); /* CASE */
135605:       testcase( i==69 ); /* COLLATE */
135606:       testcase( i==70 ); /* CREATE */
135607:       testcase( i==71 ); /* CURRENT_DATE */
135608:       testcase( i==72 ); /* DETACH */
135609:       testcase( i==73 ); /* IMMEDIATE */
135610:       testcase( i==74 ); /* JOIN */
135611:       testcase( i==75 ); /* INSERT */
135612:       testcase( i==76 ); /* MATCH */
135613:       testcase( i==77 ); /* PLAN */
135614:       testcase( i==78 ); /* ANALYZE */
135615:       testcase( i==79 ); /* PRAGMA */
135616:       testcase( i==80 ); /* ABORT */
135617:       testcase( i==81 ); /* VALUES */
135618:       testcase( i==82 ); /* VIRTUAL */
135619:       testcase( i==83 ); /* LIMIT */
135620:       testcase( i==84 ); /* WHEN */
135621:       testcase( i==85 ); /* WHERE */
135622:       testcase( i==86 ); /* RENAME */
135623:       testcase( i==87 ); /* AFTER */
135624:       testcase( i==88 ); /* REPLACE */
135625:       testcase( i==89 ); /* AND */
135626:       testcase( i==90 ); /* DEFAULT */
135627:       testcase( i==91 ); /* AUTOINCREMENT */
135628:       testcase( i==92 ); /* TO */
135629:       testcase( i==93 ); /* IN */
135630:       testcase( i==94 ); /* CAST */
135631:       testcase( i==95 ); /* COLUMN */
135632:       testcase( i==96 ); /* COMMIT */
135633:       testcase( i==97 ); /* CONFLICT */
135634:       testcase( i==98 ); /* CROSS */
135635:       testcase( i==99 ); /* CURRENT_TIMESTAMP */
135636:       testcase( i==100 ); /* CURRENT_TIME */
135637:       testcase( i==101 ); /* PRIMARY */
135638:       testcase( i==102 ); /* DEFERRED */
135639:       testcase( i==103 ); /* DISTINCT */
135640:       testcase( i==104 ); /* IS */
135641:       testcase( i==105 ); /* DROP */
135642:       testcase( i==106 ); /* FAIL */
135643:       testcase( i==107 ); /* FROM */
135644:       testcase( i==108 ); /* FULL */
135645:       testcase( i==109 ); /* GLOB */
135646:       testcase( i==110 ); /* BY */
135647:       testcase( i==111 ); /* IF */
135648:       testcase( i==112 ); /* ISNULL */
135649:       testcase( i==113 ); /* ORDER */
135650:       testcase( i==114 ); /* RESTRICT */
135651:       testcase( i==115 ); /* RIGHT */
135652:       testcase( i==116 ); /* ROLLBACK */
135653:       testcase( i==117 ); /* ROW */
135654:       testcase( i==118 ); /* UNION */
135655:       testcase( i==119 ); /* USING */
135656:       testcase( i==120 ); /* VACUUM */
135657:       testcase( i==121 ); /* VIEW */
135658:       testcase( i==122 ); /* INITIALLY */
135659:       testcase( i==123 ); /* ALL */
135660:       *pType = aCode[i];
135661:       break;
135662:     }
135663:   }
135664:   return n;
135665: }
135666: SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
135667:   int id = TK_ID;
135668:   keywordCode((char*)z, n, &id);
135669:   return id;
135670: }
135671: #define SQLITE_N_KEYWORD 124
135672: 
135673: /************** End of keywordhash.h *****************************************/
135674: /************** Continuing where we left off in tokenize.c *******************/
135675: 
135676: 
135677: /*
135678: ** If X is a character that can be used in an identifier then
135679: ** IdChar(X) will be true.  Otherwise it is false.
135680: **
135681: ** For ASCII, any character with the high-order bit set is
135682: ** allowed in an identifier.  For 7-bit characters, 
135683: ** sqlite3IsIdChar[X] must be 1.
135684: **
135685: ** For EBCDIC, the rules are more complex but have the same
135686: ** end result.
135687: **
135688: ** Ticket #1066.  the SQL standard does not allow '$' in the
135689: ** middle of identifiers.  But many SQL implementations do. 
135690: ** SQLite will allow '$' in identifiers for compatibility.
135691: ** But the feature is undocumented.
135692: */
135693: #ifdef SQLITE_ASCII
135694: #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
135695: #endif
135696: #ifdef SQLITE_EBCDIC
135697: SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
135698: /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
135699:     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
135700:     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
135701:     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
135702:     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
135703:     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
135704:     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
135705:     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
135706:     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
135707:     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
135708:     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
135709:     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
135710:     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
135711: };
135712: #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
135713: #endif
135714: 
135715: /* Make the IdChar function accessible from ctime.c */
135716: #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
135717: SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
135718: #endif
135719: 
135720: 
135721: /*
135722: ** Return the length (in bytes) of the token that begins at z[0]. 
135723: ** Store the token type in *tokenType before returning.
135724: */
135725: SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
135726:   int i, c;
135727:   switch( aiClass[*z] ){  /* Switch on the character-class of the first byte
135728:                           ** of the token. See the comment on the CC_ defines
135729:                           ** above. */
135730:     case CC_SPACE: {
135731:       testcase( z[0]==' ' );
135732:       testcase( z[0]=='\t' );
135733:       testcase( z[0]=='\n' );
135734:       testcase( z[0]=='\f' );
135735:       testcase( z[0]=='\r' );
135736:       for(i=1; sqlite3Isspace(z[i]); i++){}
135737:       *tokenType = TK_SPACE;
135738:       return i;
135739:     }
135740:     case CC_MINUS: {
135741:       if( z[1]=='-' ){
135742:         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
135743:         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
135744:         return i;
135745:       }
135746:       *tokenType = TK_MINUS;
135747:       return 1;
135748:     }
135749:     case CC_LP: {
135750:       *tokenType = TK_LP;
135751:       return 1;
135752:     }
135753:     case CC_RP: {
135754:       *tokenType = TK_RP;
135755:       return 1;
135756:     }
135757:     case CC_SEMI: {
135758:       *tokenType = TK_SEMI;
135759:       return 1;
135760:     }
135761:     case CC_PLUS: {
135762:       *tokenType = TK_PLUS;
135763:       return 1;
135764:     }
135765:     case CC_STAR: {
135766:       *tokenType = TK_STAR;
135767:       return 1;
135768:     }
135769:     case CC_SLASH: {
135770:       if( z[1]!='*' || z[2]==0 ){
135771:         *tokenType = TK_SLASH;
135772:         return 1;
135773:       }
135774:       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
135775:       if( c ) i++;
135776:       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
135777:       return i;
135778:     }
135779:     case CC_PERCENT: {
135780:       *tokenType = TK_REM;
135781:       return 1;
135782:     }
135783:     case CC_EQ: {
135784:       *tokenType = TK_EQ;
135785:       return 1 + (z[1]=='=');
135786:     }
135787:     case CC_LT: {
135788:       if( (c=z[1])=='=' ){
135789:         *tokenType = TK_LE;
135790:         return 2;
135791:       }else if( c=='>' ){
135792:         *tokenType = TK_NE;
135793:         return 2;
135794:       }else if( c=='<' ){
135795:         *tokenType = TK_LSHIFT;
135796:         return 2;
135797:       }else{
135798:         *tokenType = TK_LT;
135799:         return 1;
135800:       }
135801:     }
135802:     case CC_GT: {
135803:       if( (c=z[1])=='=' ){
135804:         *tokenType = TK_GE;
135805:         return 2;
135806:       }else if( c=='>' ){
135807:         *tokenType = TK_RSHIFT;
135808:         return 2;
135809:       }else{
135810:         *tokenType = TK_GT;
135811:         return 1;
135812:       }
135813:     }
135814:     case CC_BANG: {
135815:       if( z[1]!='=' ){
135816:         *tokenType = TK_ILLEGAL;
135817:         return 1;
135818:       }else{
135819:         *tokenType = TK_NE;
135820:         return 2;
135821:       }
135822:     }
135823:     case CC_PIPE: {
135824:       if( z[1]!='|' ){
135825:         *tokenType = TK_BITOR;
135826:         return 1;
135827:       }else{
135828:         *tokenType = TK_CONCAT;
135829:         return 2;
135830:       }
135831:     }
135832:     case CC_COMMA: {
135833:       *tokenType = TK_COMMA;
135834:       return 1;
135835:     }
135836:     case CC_AND: {
135837:       *tokenType = TK_BITAND;
135838:       return 1;
135839:     }
135840:     case CC_TILDA: {
135841:       *tokenType = TK_BITNOT;
135842:       return 1;
135843:     }
135844:     case CC_QUOTE: {
135845:       int delim = z[0];
135846:       testcase( delim=='`' );
135847:       testcase( delim=='\'' );
135848:       testcase( delim=='"' );
135849:       for(i=1; (c=z[i])!=0; i++){
135850:         if( c==delim ){
135851:           if( z[i+1]==delim ){
135852:             i++;
135853:           }else{
135854:             break;
135855:           }
135856:         }
135857:       }
135858:       if( c=='\'' ){
135859:         *tokenType = TK_STRING;
135860:         return i+1;
135861:       }else if( c!=0 ){
135862:         *tokenType = TK_ID;
135863:         return i+1;
135864:       }else{
135865:         *tokenType = TK_ILLEGAL;
135866:         return i;
135867:       }
135868:     }
135869:     case CC_DOT: {
135870: #ifndef SQLITE_OMIT_FLOATING_POINT
135871:       if( !sqlite3Isdigit(z[1]) )
135872: #endif
135873:       {
135874:         *tokenType = TK_DOT;
135875:         return 1;
135876:       }
135877:       /* If the next character is a digit, this is a floating point
135878:       ** number that begins with ".".  Fall thru into the next case */
135879:     }
135880:     case CC_DIGIT: {
135881:       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
135882:       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
135883:       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
135884:       testcase( z[0]=='9' );
135885:       *tokenType = TK_INTEGER;
135886: #ifndef SQLITE_OMIT_HEX_INTEGER
135887:       if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
135888:         for(i=3; sqlite3Isxdigit(z[i]); i++){}
135889:         return i;
135890:       }
135891: #endif
135892:       for(i=0; sqlite3Isdigit(z[i]); i++){}
135893: #ifndef SQLITE_OMIT_FLOATING_POINT
135894:       if( z[i]=='.' ){
135895:         i++;
135896:         while( sqlite3Isdigit(z[i]) ){ i++; }
135897:         *tokenType = TK_FLOAT;
135898:       }
135899:       if( (z[i]=='e' || z[i]=='E') &&
135900:            ( sqlite3Isdigit(z[i+1]) 
135901:             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
135902:            )
135903:       ){
135904:         i += 2;
135905:         while( sqlite3Isdigit(z[i]) ){ i++; }
135906:         *tokenType = TK_FLOAT;
135907:       }
135908: #endif
135909:       while( IdChar(z[i]) ){
135910:         *tokenType = TK_ILLEGAL;
135911:         i++;
135912:       }
135913:       return i;
135914:     }
135915:     case CC_QUOTE2: {
135916:       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
135917:       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
135918:       return i;
135919:     }
135920:     case CC_VARNUM: {
135921:       *tokenType = TK_VARIABLE;
135922:       for(i=1; sqlite3Isdigit(z[i]); i++){}
135923:       return i;
135924:     }
135925:     case CC_DOLLAR:
135926:     case CC_VARALPHA: {
135927:       int n = 0;
135928:       testcase( z[0]=='$' );  testcase( z[0]=='@' );
135929:       testcase( z[0]==':' );  testcase( z[0]=='#' );
135930:       *tokenType = TK_VARIABLE;
135931:       for(i=1; (c=z[i])!=0; i++){
135932:         if( IdChar(c) ){
135933:           n++;
135934: #ifndef SQLITE_OMIT_TCL_VARIABLE
135935:         }else if( c=='(' && n>0 ){
135936:           do{
135937:             i++;
135938:           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
135939:           if( c==')' ){
135940:             i++;
135941:           }else{
135942:             *tokenType = TK_ILLEGAL;
135943:           }
135944:           break;
135945:         }else if( c==':' && z[i+1]==':' ){
135946:           i++;
135947: #endif
135948:         }else{
135949:           break;
135950:         }
135951:       }
135952:       if( n==0 ) *tokenType = TK_ILLEGAL;
135953:       return i;
135954:     }
135955:     case CC_KYWD: {
135956:       for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
135957:       if( IdChar(z[i]) ){
135958:         /* This token started out using characters that can appear in keywords,
135959:         ** but z[i] is a character not allowed within keywords, so this must
135960:         ** be an identifier instead */
135961:         i++;
135962:         break;
135963:       }
135964:       *tokenType = TK_ID;
135965:       return keywordCode((char*)z, i, tokenType);
135966:     }
135967:     case CC_X: {
135968: #ifndef SQLITE_OMIT_BLOB_LITERAL
135969:       testcase( z[0]=='x' ); testcase( z[0]=='X' );
135970:       if( z[1]=='\'' ){
135971:         *tokenType = TK_BLOB;
135972:         for(i=2; sqlite3Isxdigit(z[i]); i++){}
135973:         if( z[i]!='\'' || i%2 ){
135974:           *tokenType = TK_ILLEGAL;
135975:           while( z[i] && z[i]!='\'' ){ i++; }
135976:         }
135977:         if( z[i] ) i++;
135978:         return i;
135979:       }
135980: #endif
135981:       /* If it is not a BLOB literal, then it must be an ID, since no
135982:       ** SQL keywords start with the letter 'x'.  Fall through */
135983:     }
135984:     case CC_ID: {
135985:       i = 1;
135986:       break;
135987:     }
135988:     default: {
135989:       *tokenType = TK_ILLEGAL;
135990:       return 1;
135991:     }
135992:   }
135993:   while( IdChar(z[i]) ){ i++; }
135994:   *tokenType = TK_ID;
135995:   return i;
135996: }
135997: 
135998: /*
135999: ** Run the parser on the given SQL string.  The parser structure is
136000: ** passed in.  An SQLITE_ status code is returned.  If an error occurs
136001: ** then an and attempt is made to write an error message into 
136002: ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
136003: ** error message.
136004: */
136005: SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
136006:   int nErr = 0;                   /* Number of errors encountered */
136007:   int i;                          /* Loop counter */
136008:   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
136009:   int tokenType;                  /* type of the next token */
136010:   int lastTokenParsed = -1;       /* type of the previous token */
136011:   sqlite3 *db = pParse->db;       /* The database connection */
136012:   int mxSqlLen;                   /* Max length of an SQL string */
136013: 
136014:   assert( zSql!=0 );
136015:   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
136016:   if( db->nVdbeActive==0 ){
136017:     db->u1.isInterrupted = 0;
136018:   }
136019:   pParse->rc = SQLITE_OK;
136020:   pParse->zTail = zSql;
136021:   i = 0;
136022:   assert( pzErrMsg!=0 );
136023:   /* sqlite3ParserTrace(stdout, "parser: "); */
136024:   pEngine = sqlite3ParserAlloc(sqlite3Malloc);
136025:   if( pEngine==0 ){
136026:     sqlite3OomFault(db);
136027:     return SQLITE_NOMEM_BKPT;
136028:   }
136029:   assert( pParse->pNewTable==0 );
136030:   assert( pParse->pNewTrigger==0 );
136031:   assert( pParse->nVar==0 );
136032:   assert( pParse->nzVar==0 );
136033:   assert( pParse->azVar==0 );
136034:   while( zSql[i]!=0 ){
136035:     assert( i>=0 );
136036:     pParse->sLastToken.z = &zSql[i];
136037:     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
136038:     i += pParse->sLastToken.n;
136039:     if( i>mxSqlLen ){
136040:       pParse->rc = SQLITE_TOOBIG;
136041:       break;
136042:     }
136043:     if( tokenType>=TK_SPACE ){
136044:       assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
136045:       if( db->u1.isInterrupted ){
136046:         pParse->rc = SQLITE_INTERRUPT;
136047:         break;
136048:       }
136049:       if( tokenType==TK_ILLEGAL ){
136050:         sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
136051:                         &pParse->sLastToken);
136052:         break;
136053:       }
136054:     }else{
136055:       sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
136056:       lastTokenParsed = tokenType;
136057:       if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
136058:     }
136059:   }
136060:   assert( nErr==0 );
136061:   pParse->zTail = &zSql[i];
136062:   if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
136063:     assert( zSql[i]==0 );
136064:     if( lastTokenParsed!=TK_SEMI ){
136065:       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
136066:     }
136067:     if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
136068:       sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
136069:     }
136070:   }
136071: #ifdef YYTRACKMAXSTACKDEPTH
136072:   sqlite3_mutex_enter(sqlite3MallocMutex());
136073:   sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
136074:       sqlite3ParserStackPeak(pEngine)
136075:   );
136076:   sqlite3_mutex_leave(sqlite3MallocMutex());
136077: #endif /* YYDEBUG */
136078:   sqlite3ParserFree(pEngine, sqlite3_free);
136079:   if( db->mallocFailed ){
136080:     pParse->rc = SQLITE_NOMEM_BKPT;
136081:   }
136082:   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
136083:     pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
136084:   }
136085:   assert( pzErrMsg!=0 );
136086:   if( pParse->zErrMsg ){
136087:     *pzErrMsg = pParse->zErrMsg;
136088:     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
136089:     pParse->zErrMsg = 0;
136090:     nErr++;
136091:   }
136092:   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
136093:     sqlite3VdbeDelete(pParse->pVdbe);
136094:     pParse->pVdbe = 0;
136095:   }
136096: #ifndef SQLITE_OMIT_SHARED_CACHE
136097:   if( pParse->nested==0 ){
136098:     sqlite3DbFree(db, pParse->aTableLock);
136099:     pParse->aTableLock = 0;
136100:     pParse->nTableLock = 0;
136101:   }
136102: #endif
136103: #ifndef SQLITE_OMIT_VIRTUALTABLE
136104:   sqlite3_free(pParse->apVtabLock);
136105: #endif
136106: 
136107:   if( !IN_DECLARE_VTAB ){
136108:     /* If the pParse->declareVtab flag is set, do not delete any table 
136109:     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
136110:     ** will take responsibility for freeing the Table structure.
136111:     */
136112:     sqlite3DeleteTable(db, pParse->pNewTable);
136113:   }
136114: 
136115:   if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
136116:   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
136117:   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
136118:   sqlite3DbFree(db, pParse->azVar);
136119:   while( pParse->pAinc ){
136120:     AutoincInfo *p = pParse->pAinc;
136121:     pParse->pAinc = p->pNext;
136122:     sqlite3DbFree(db, p);
136123:   }
136124:   while( pParse->pZombieTab ){
136125:     Table *p = pParse->pZombieTab;
136126:     pParse->pZombieTab = p->pNextZombie;
136127:     sqlite3DeleteTable(db, p);
136128:   }
136129:   assert( nErr==0 || pParse->rc!=SQLITE_OK );
136130:   return nErr;
136131: }
136132: 
136133: /************** End of tokenize.c ********************************************/
136134: /************** Begin file complete.c ****************************************/
136135: /*
136136: ** 2001 September 15
136137: **
136138: ** The author disclaims copyright to this source code.  In place of
136139: ** a legal notice, here is a blessing:
136140: **
136141: **    May you do good and not evil.
136142: **    May you find forgiveness for yourself and forgive others.
136143: **    May you share freely, never taking more than you give.
136144: **
136145: *************************************************************************
136146: ** An tokenizer for SQL
136147: **
136148: ** This file contains C code that implements the sqlite3_complete() API.
136149: ** This code used to be part of the tokenizer.c source file.  But by
136150: ** separating it out, the code will be automatically omitted from
136151: ** static links that do not use it.
136152: */
136153: /* #include "sqliteInt.h" */
136154: #ifndef SQLITE_OMIT_COMPLETE
136155: 
136156: /*
136157: ** This is defined in tokenize.c.  We just have to import the definition.
136158: */
136159: #ifndef SQLITE_AMALGAMATION
136160: #ifdef SQLITE_ASCII
136161: #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
136162: #endif
136163: #ifdef SQLITE_EBCDIC
136164: SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
136165: #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
136166: #endif
136167: #endif /* SQLITE_AMALGAMATION */
136168: 
136169: 
136170: /*
136171: ** Token types used by the sqlite3_complete() routine.  See the header
136172: ** comments on that procedure for additional information.
136173: */
136174: #define tkSEMI    0
136175: #define tkWS      1
136176: #define tkOTHER   2
136177: #ifndef SQLITE_OMIT_TRIGGER
136178: #define tkEXPLAIN 3
136179: #define tkCREATE  4
136180: #define tkTEMP    5
136181: #define tkTRIGGER 6
136182: #define tkEND     7
136183: #endif
136184: 
136185: /*
136186: ** Return TRUE if the given SQL string ends in a semicolon.
136187: **
136188: ** Special handling is require for CREATE TRIGGER statements.
136189: ** Whenever the CREATE TRIGGER keywords are seen, the statement
136190: ** must end with ";END;".
136191: **
136192: ** This implementation uses a state machine with 8 states:
136193: **
136194: **   (0) INVALID   We have not yet seen a non-whitespace character.
136195: **
136196: **   (1) START     At the beginning or end of an SQL statement.  This routine
136197: **                 returns 1 if it ends in the START state and 0 if it ends
136198: **                 in any other state.
136199: **
136200: **   (2) NORMAL    We are in the middle of statement which ends with a single
136201: **                 semicolon.
136202: **
136203: **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
136204: **                 a statement.
136205: **
136206: **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
136207: **                 statement, possibly preceded by EXPLAIN and/or followed by
136208: **                 TEMP or TEMPORARY
136209: **
136210: **   (5) TRIGGER   We are in the middle of a trigger definition that must be
136211: **                 ended by a semicolon, the keyword END, and another semicolon.
136212: **
136213: **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
136214: **                 the end of a trigger definition.
136215: **
136216: **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
136217: **                 of a trigger definition.
136218: **
136219: ** Transitions between states above are determined by tokens extracted
136220: ** from the input.  The following tokens are significant:
136221: **
136222: **   (0) tkSEMI      A semicolon.
136223: **   (1) tkWS        Whitespace.
136224: **   (2) tkOTHER     Any other SQL token.
136225: **   (3) tkEXPLAIN   The "explain" keyword.
136226: **   (4) tkCREATE    The "create" keyword.
136227: **   (5) tkTEMP      The "temp" or "temporary" keyword.
136228: **   (6) tkTRIGGER   The "trigger" keyword.
136229: **   (7) tkEND       The "end" keyword.
136230: **
136231: ** Whitespace never causes a state transition and is always ignored.
136232: ** This means that a SQL string of all whitespace is invalid.
136233: **
136234: ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
136235: ** to recognize the end of a trigger can be omitted.  All we have to do
136236: ** is look for a semicolon that is not part of an string or comment.
136237: */
136238: SQLITE_API int sqlite3_complete(const char *zSql){
136239:   u8 state = 0;   /* Current state, using numbers defined in header comment */
136240:   u8 token;       /* Value of the next token */
136241: 
136242: #ifndef SQLITE_OMIT_TRIGGER
136243:   /* A complex statement machine used to detect the end of a CREATE TRIGGER
136244:   ** statement.  This is the normal case.
136245:   */
136246:   static const u8 trans[8][8] = {
136247:                      /* Token:                                                */
136248:      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
136249:      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
136250:      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
136251:      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
136252:      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
136253:      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
136254:      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
136255:      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
136256:      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
136257:   };
136258: #else
136259:   /* If triggers are not supported by this compile then the statement machine
136260:   ** used to detect the end of a statement is much simpler
136261:   */
136262:   static const u8 trans[3][3] = {
136263:                      /* Token:           */
136264:      /* State:       **  SEMI  WS  OTHER */
136265:      /* 0 INVALID: */ {    1,  0,     2, },
136266:      /* 1   START: */ {    1,  1,     2, },
136267:      /* 2  NORMAL: */ {    1,  2,     2, },
136268:   };
136269: #endif /* SQLITE_OMIT_TRIGGER */
136270: 
136271: #ifdef SQLITE_ENABLE_API_ARMOR
136272:   if( zSql==0 ){
136273:     (void)SQLITE_MISUSE_BKPT;
136274:     return 0;
136275:   }
136276: #endif
136277: 
136278:   while( *zSql ){
136279:     switch( *zSql ){
136280:       case ';': {  /* A semicolon */
136281:         token = tkSEMI;
136282:         break;
136283:       }
136284:       case ' ':
136285:       case '\r':
136286:       case '\t':
136287:       case '\n':
136288:       case '\f': {  /* White space is ignored */
136289:         token = tkWS;
136290:         break;
136291:       }
136292:       case '/': {   /* C-style comments */
136293:         if( zSql[1]!='*' ){
136294:           token = tkOTHER;
136295:           break;
136296:         }
136297:         zSql += 2;
136298:         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
136299:         if( zSql[0]==0 ) return 0;
136300:         zSql++;
136301:         token = tkWS;
136302:         break;
136303:       }
136304:       case '-': {   /* SQL-style comments from "--" to end of line */
136305:         if( zSql[1]!='-' ){
136306:           token = tkOTHER;
136307:           break;
136308:         }
136309:         while( *zSql && *zSql!='\n' ){ zSql++; }
136310:         if( *zSql==0 ) return state==1;
136311:         token = tkWS;
136312:         break;
136313:       }
136314:       case '[': {   /* Microsoft-style identifiers in [...] */
136315:         zSql++;
136316:         while( *zSql && *zSql!=']' ){ zSql++; }
136317:         if( *zSql==0 ) return 0;
136318:         token = tkOTHER;
136319:         break;
136320:       }
136321:       case '`':     /* Grave-accent quoted symbols used by MySQL */
136322:       case '"':     /* single- and double-quoted strings */
136323:       case '\'': {
136324:         int c = *zSql;
136325:         zSql++;
136326:         while( *zSql && *zSql!=c ){ zSql++; }
136327:         if( *zSql==0 ) return 0;
136328:         token = tkOTHER;
136329:         break;
136330:       }
136331:       default: {
136332: #ifdef SQLITE_EBCDIC
136333:         unsigned char c;
136334: #endif
136335:         if( IdChar((u8)*zSql) ){
136336:           /* Keywords and unquoted identifiers */
136337:           int nId;
136338:           for(nId=1; IdChar(zSql[nId]); nId++){}
136339: #ifdef SQLITE_OMIT_TRIGGER
136340:           token = tkOTHER;
136341: #else
136342:           switch( *zSql ){
136343:             case 'c': case 'C': {
136344:               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
136345:                 token = tkCREATE;
136346:               }else{
136347:                 token = tkOTHER;
136348:               }
136349:               break;
136350:             }
136351:             case 't': case 'T': {
136352:               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
136353:                 token = tkTRIGGER;
136354:               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
136355:                 token = tkTEMP;
136356:               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
136357:                 token = tkTEMP;
136358:               }else{
136359:                 token = tkOTHER;
136360:               }
136361:               break;
136362:             }
136363:             case 'e':  case 'E': {
136364:               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
136365:                 token = tkEND;
136366:               }else
136367: #ifndef SQLITE_OMIT_EXPLAIN
136368:               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
136369:                 token = tkEXPLAIN;
136370:               }else
136371: #endif
136372:               {
136373:                 token = tkOTHER;
136374:               }
136375:               break;
136376:             }
136377:             default: {
136378:               token = tkOTHER;
136379:               break;
136380:             }
136381:           }
136382: #endif /* SQLITE_OMIT_TRIGGER */
136383:           zSql += nId-1;
136384:         }else{
136385:           /* Operators and special symbols */
136386:           token = tkOTHER;
136387:         }
136388:         break;
136389:       }
136390:     }
136391:     state = trans[state][token];
136392:     zSql++;
136393:   }
136394:   return state==1;
136395: }
136396: 
136397: #ifndef SQLITE_OMIT_UTF16
136398: /*
136399: ** This routine is the same as the sqlite3_complete() routine described
136400: ** above, except that the parameter is required to be UTF-16 encoded, not
136401: ** UTF-8.
136402: */
136403: SQLITE_API int sqlite3_complete16(const void *zSql){
136404:   sqlite3_value *pVal;
136405:   char const *zSql8;
136406:   int rc;
136407: 
136408: #ifndef SQLITE_OMIT_AUTOINIT
136409:   rc = sqlite3_initialize();
136410:   if( rc ) return rc;
136411: #endif
136412:   pVal = sqlite3ValueNew(0);
136413:   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
136414:   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
136415:   if( zSql8 ){
136416:     rc = sqlite3_complete(zSql8);
136417:   }else{
136418:     rc = SQLITE_NOMEM_BKPT;
136419:   }
136420:   sqlite3ValueFree(pVal);
136421:   return rc & 0xff;
136422: }
136423: #endif /* SQLITE_OMIT_UTF16 */
136424: #endif /* SQLITE_OMIT_COMPLETE */
136425: 
136426: /************** End of complete.c ********************************************/
136427: /************** Begin file main.c ********************************************/
136428: /*
136429: ** 2001 September 15
136430: **
136431: ** The author disclaims copyright to this source code.  In place of
136432: ** a legal notice, here is a blessing:
136433: **
136434: **    May you do good and not evil.
136435: **    May you find forgiveness for yourself and forgive others.
136436: **    May you share freely, never taking more than you give.
136437: **
136438: *************************************************************************
136439: ** Main file for the SQLite library.  The routines in this file
136440: ** implement the programmer interface to the library.  Routines in
136441: ** other files are for internal use by SQLite and should not be
136442: ** accessed by users of the library.
136443: */
136444: /* #include "sqliteInt.h" */
136445: 
136446: #ifdef SQLITE_ENABLE_FTS3
136447: /************** Include fts3.h in the middle of main.c ***********************/
136448: /************** Begin file fts3.h ********************************************/
136449: /*
136450: ** 2006 Oct 10
136451: **
136452: ** The author disclaims copyright to this source code.  In place of
136453: ** a legal notice, here is a blessing:
136454: **
136455: **    May you do good and not evil.
136456: **    May you find forgiveness for yourself and forgive others.
136457: **    May you share freely, never taking more than you give.
136458: **
136459: ******************************************************************************
136460: **
136461: ** This header file is used by programs that want to link against the
136462: ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
136463: */
136464: /* #include "sqlite3.h" */
136465: 
136466: #if 0
136467: extern "C" {
136468: #endif  /* __cplusplus */
136469: 
136470: SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
136471: 
136472: #if 0
136473: }  /* extern "C" */
136474: #endif  /* __cplusplus */
136475: 
136476: /************** End of fts3.h ************************************************/
136477: /************** Continuing where we left off in main.c ***********************/
136478: #endif
136479: #ifdef SQLITE_ENABLE_RTREE
136480: /************** Include rtree.h in the middle of main.c **********************/
136481: /************** Begin file rtree.h *******************************************/
136482: /*
136483: ** 2008 May 26
136484: **
136485: ** The author disclaims copyright to this source code.  In place of
136486: ** a legal notice, here is a blessing:
136487: **
136488: **    May you do good and not evil.
136489: **    May you find forgiveness for yourself and forgive others.
136490: **    May you share freely, never taking more than you give.
136491: **
136492: ******************************************************************************
136493: **
136494: ** This header file is used by programs that want to link against the
136495: ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
136496: */
136497: /* #include "sqlite3.h" */
136498: 
136499: #if 0
136500: extern "C" {
136501: #endif  /* __cplusplus */
136502: 
136503: SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
136504: 
136505: #if 0
136506: }  /* extern "C" */
136507: #endif  /* __cplusplus */
136508: 
136509: /************** End of rtree.h ***********************************************/
136510: /************** Continuing where we left off in main.c ***********************/
136511: #endif
136512: #ifdef SQLITE_ENABLE_ICU
136513: /************** Include sqliteicu.h in the middle of main.c ******************/
136514: /************** Begin file sqliteicu.h ***************************************/
136515: /*
136516: ** 2008 May 26
136517: **
136518: ** The author disclaims copyright to this source code.  In place of
136519: ** a legal notice, here is a blessing:
136520: **
136521: **    May you do good and not evil.
136522: **    May you find forgiveness for yourself and forgive others.
136523: **    May you share freely, never taking more than you give.
136524: **
136525: ******************************************************************************
136526: **
136527: ** This header file is used by programs that want to link against the
136528: ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
136529: */
136530: /* #include "sqlite3.h" */
136531: 
136532: #if 0
136533: extern "C" {
136534: #endif  /* __cplusplus */
136535: 
136536: SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
136537: 
136538: #if 0
136539: }  /* extern "C" */
136540: #endif  /* __cplusplus */
136541: 
136542: 
136543: /************** End of sqliteicu.h *******************************************/
136544: /************** Continuing where we left off in main.c ***********************/
136545: #endif
136546: #ifdef SQLITE_ENABLE_JSON1
136547: SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
136548: #endif
136549: #ifdef SQLITE_ENABLE_FTS5
136550: SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
136551: #endif
136552: 
136553: #ifndef SQLITE_AMALGAMATION
136554: /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
136555: ** contains the text of SQLITE_VERSION macro. 
136556: */
136557: SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
136558: #endif
136559: 
136560: /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
136561: ** a pointer to the to the sqlite3_version[] string constant. 
136562: */
136563: SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
136564: 
136565: /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
136566: ** pointer to a string constant whose value is the same as the
136567: ** SQLITE_SOURCE_ID C preprocessor macro. 
136568: */
136569: SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
136570: 
136571: /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
136572: ** returns an integer equal to SQLITE_VERSION_NUMBER.
136573: */
136574: SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
136575: 
136576: /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
136577: ** zero if and only if SQLite was compiled with mutexing code omitted due to
136578: ** the SQLITE_THREADSAFE compile-time option being set to 0.
136579: */
136580: SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
136581: 
136582: /*
136583: ** When compiling the test fixture or with debugging enabled (on Win32),
136584: ** this variable being set to non-zero will cause OSTRACE macros to emit
136585: ** extra diagnostic information.
136586: */
136587: #ifdef SQLITE_HAVE_OS_TRACE
136588: # ifndef SQLITE_DEBUG_OS_TRACE
136589: #   define SQLITE_DEBUG_OS_TRACE 0
136590: # endif
136591:   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
136592: #endif
136593: 
136594: #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
136595: /*
136596: ** If the following function pointer is not NULL and if
136597: ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
136598: ** I/O active are written using this function.  These messages
136599: ** are intended for debugging activity only.
136600: */
136601: SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
136602: #endif
136603: 
136604: /*
136605: ** If the following global variable points to a string which is the
136606: ** name of a directory, then that directory will be used to store
136607: ** temporary files.
136608: **
136609: ** See also the "PRAGMA temp_store_directory" SQL command.
136610: */
136611: SQLITE_API char *sqlite3_temp_directory = 0;
136612: 
136613: /*
136614: ** If the following global variable points to a string which is the
136615: ** name of a directory, then that directory will be used to store
136616: ** all database files specified with a relative pathname.
136617: **
136618: ** See also the "PRAGMA data_store_directory" SQL command.
136619: */
136620: SQLITE_API char *sqlite3_data_directory = 0;
136621: 
136622: /*
136623: ** Initialize SQLite.  
136624: **
136625: ** This routine must be called to initialize the memory allocation,
136626: ** VFS, and mutex subsystems prior to doing any serious work with
136627: ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
136628: ** this routine will be called automatically by key routines such as
136629: ** sqlite3_open().  
136630: **
136631: ** This routine is a no-op except on its very first call for the process,
136632: ** or for the first call after a call to sqlite3_shutdown.
136633: **
136634: ** The first thread to call this routine runs the initialization to
136635: ** completion.  If subsequent threads call this routine before the first
136636: ** thread has finished the initialization process, then the subsequent
136637: ** threads must block until the first thread finishes with the initialization.
136638: **
136639: ** The first thread might call this routine recursively.  Recursive
136640: ** calls to this routine should not block, of course.  Otherwise the
136641: ** initialization process would never complete.
136642: **
136643: ** Let X be the first thread to enter this routine.  Let Y be some other
136644: ** thread.  Then while the initial invocation of this routine by X is
136645: ** incomplete, it is required that:
136646: **
136647: **    *  Calls to this routine from Y must block until the outer-most
136648: **       call by X completes.
136649: **
136650: **    *  Recursive calls to this routine from thread X return immediately
136651: **       without blocking.
136652: */
136653: SQLITE_API int sqlite3_initialize(void){
136654:   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
136655:   int rc;                                      /* Result code */
136656: #ifdef SQLITE_EXTRA_INIT
136657:   int bRunExtraInit = 0;                       /* Extra initialization needed */
136658: #endif
136659: 
136660: #ifdef SQLITE_OMIT_WSD
136661:   rc = sqlite3_wsd_init(4096, 24);
136662:   if( rc!=SQLITE_OK ){
136663:     return rc;
136664:   }
136665: #endif
136666: 
136667:   /* If the following assert() fails on some obscure processor/compiler
136668:   ** combination, the work-around is to set the correct pointer
136669:   ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
136670:   assert( SQLITE_PTRSIZE==sizeof(char*) );
136671: 
136672:   /* If SQLite is already completely initialized, then this call
136673:   ** to sqlite3_initialize() should be a no-op.  But the initialization
136674:   ** must be complete.  So isInit must not be set until the very end
136675:   ** of this routine.
136676:   */
136677:   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
136678: 
136679:   /* Make sure the mutex subsystem is initialized.  If unable to 
136680:   ** initialize the mutex subsystem, return early with the error.
136681:   ** If the system is so sick that we are unable to allocate a mutex,
136682:   ** there is not much SQLite is going to be able to do.
136683:   **
136684:   ** The mutex subsystem must take care of serializing its own
136685:   ** initialization.
136686:   */
136687:   rc = sqlite3MutexInit();
136688:   if( rc ) return rc;
136689: 
136690:   /* Initialize the malloc() system and the recursive pInitMutex mutex.
136691:   ** This operation is protected by the STATIC_MASTER mutex.  Note that
136692:   ** MutexAlloc() is called for a static mutex prior to initializing the
136693:   ** malloc subsystem - this implies that the allocation of a static
136694:   ** mutex must not require support from the malloc subsystem.
136695:   */
136696:   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
136697:   sqlite3_mutex_enter(pMaster);
136698:   sqlite3GlobalConfig.isMutexInit = 1;
136699:   if( !sqlite3GlobalConfig.isMallocInit ){
136700:     rc = sqlite3MallocInit();
136701:   }
136702:   if( rc==SQLITE_OK ){
136703:     sqlite3GlobalConfig.isMallocInit = 1;
136704:     if( !sqlite3GlobalConfig.pInitMutex ){
136705:       sqlite3GlobalConfig.pInitMutex =
136706:            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
136707:       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
136708:         rc = SQLITE_NOMEM_BKPT;
136709:       }
136710:     }
136711:   }
136712:   if( rc==SQLITE_OK ){
136713:     sqlite3GlobalConfig.nRefInitMutex++;
136714:   }
136715:   sqlite3_mutex_leave(pMaster);
136716: 
136717:   /* If rc is not SQLITE_OK at this point, then either the malloc
136718:   ** subsystem could not be initialized or the system failed to allocate
136719:   ** the pInitMutex mutex. Return an error in either case.  */
136720:   if( rc!=SQLITE_OK ){
136721:     return rc;
136722:   }
136723: 
136724:   /* Do the rest of the initialization under the recursive mutex so
136725:   ** that we will be able to handle recursive calls into
136726:   ** sqlite3_initialize().  The recursive calls normally come through
136727:   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
136728:   ** recursive calls might also be possible.
136729:   **
136730:   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
136731:   ** to the xInit method, so the xInit method need not be threadsafe.
136732:   **
136733:   ** The following mutex is what serializes access to the appdef pcache xInit
136734:   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
136735:   ** call to sqlite3PcacheInitialize().
136736:   */
136737:   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
136738:   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
136739:     sqlite3GlobalConfig.inProgress = 1;
136740: #ifdef SQLITE_ENABLE_SQLLOG
136741:     {
136742:       extern void sqlite3_init_sqllog(void);
136743:       sqlite3_init_sqllog();
136744:     }
136745: #endif
136746:     memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
136747:     sqlite3RegisterBuiltinFunctions();
136748:     if( sqlite3GlobalConfig.isPCacheInit==0 ){
136749:       rc = sqlite3PcacheInitialize();
136750:     }
136751:     if( rc==SQLITE_OK ){
136752:       sqlite3GlobalConfig.isPCacheInit = 1;
136753:       rc = sqlite3OsInit();
136754:     }
136755:     if( rc==SQLITE_OK ){
136756:       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
136757:           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
136758:       sqlite3GlobalConfig.isInit = 1;
136759: #ifdef SQLITE_EXTRA_INIT
136760:       bRunExtraInit = 1;
136761: #endif
136762:     }
136763:     sqlite3GlobalConfig.inProgress = 0;
136764:   }
136765:   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
136766: 
136767:   /* Go back under the static mutex and clean up the recursive
136768:   ** mutex to prevent a resource leak.
136769:   */
136770:   sqlite3_mutex_enter(pMaster);
136771:   sqlite3GlobalConfig.nRefInitMutex--;
136772:   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
136773:     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
136774:     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
136775:     sqlite3GlobalConfig.pInitMutex = 0;
136776:   }
136777:   sqlite3_mutex_leave(pMaster);
136778: 
136779:   /* The following is just a sanity check to make sure SQLite has
136780:   ** been compiled correctly.  It is important to run this code, but
136781:   ** we don't want to run it too often and soak up CPU cycles for no
136782:   ** reason.  So we run it once during initialization.
136783:   */
136784: #ifndef NDEBUG
136785: #ifndef SQLITE_OMIT_FLOATING_POINT
136786:   /* This section of code's only "output" is via assert() statements. */
136787:   if ( rc==SQLITE_OK ){
136788:     u64 x = (((u64)1)<<63)-1;
136789:     double y;
136790:     assert(sizeof(x)==8);
136791:     assert(sizeof(x)==sizeof(y));
136792:     memcpy(&y, &x, 8);
136793:     assert( sqlite3IsNaN(y) );
136794:   }
136795: #endif
136796: #endif
136797: 
136798:   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
136799:   ** compile-time option.
136800:   */
136801: #ifdef SQLITE_EXTRA_INIT
136802:   if( bRunExtraInit ){
136803:     int SQLITE_EXTRA_INIT(const char*);
136804:     rc = SQLITE_EXTRA_INIT(0);
136805:   }
136806: #endif
136807: 
136808:   return rc;
136809: }
136810: 
136811: /*
136812: ** Undo the effects of sqlite3_initialize().  Must not be called while
136813: ** there are outstanding database connections or memory allocations or
136814: ** while any part of SQLite is otherwise in use in any thread.  This
136815: ** routine is not threadsafe.  But it is safe to invoke this routine
136816: ** on when SQLite is already shut down.  If SQLite is already shut down
136817: ** when this routine is invoked, then this routine is a harmless no-op.
136818: */
136819: SQLITE_API int sqlite3_shutdown(void){
136820: #ifdef SQLITE_OMIT_WSD
136821:   int rc = sqlite3_wsd_init(4096, 24);
136822:   if( rc!=SQLITE_OK ){
136823:     return rc;
136824:   }
136825: #endif
136826: 
136827:   if( sqlite3GlobalConfig.isInit ){
136828: #ifdef SQLITE_EXTRA_SHUTDOWN
136829:     void SQLITE_EXTRA_SHUTDOWN(void);
136830:     SQLITE_EXTRA_SHUTDOWN();
136831: #endif
136832:     sqlite3_os_end();
136833:     sqlite3_reset_auto_extension();
136834:     sqlite3GlobalConfig.isInit = 0;
136835:   }
136836:   if( sqlite3GlobalConfig.isPCacheInit ){
136837:     sqlite3PcacheShutdown();
136838:     sqlite3GlobalConfig.isPCacheInit = 0;
136839:   }
136840:   if( sqlite3GlobalConfig.isMallocInit ){
136841:     sqlite3MallocEnd();
136842:     sqlite3GlobalConfig.isMallocInit = 0;
136843: 
136844: #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
136845:     /* The heap subsystem has now been shutdown and these values are supposed
136846:     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
136847:     ** which would rely on that heap subsystem; therefore, make sure these
136848:     ** values cannot refer to heap memory that was just invalidated when the
136849:     ** heap subsystem was shutdown.  This is only done if the current call to
136850:     ** this function resulted in the heap subsystem actually being shutdown.
136851:     */
136852:     sqlite3_data_directory = 0;
136853:     sqlite3_temp_directory = 0;
136854: #endif
136855:   }
136856:   if( sqlite3GlobalConfig.isMutexInit ){
136857:     sqlite3MutexEnd();
136858:     sqlite3GlobalConfig.isMutexInit = 0;
136859:   }
136860: 
136861:   return SQLITE_OK;
136862: }
136863: 
136864: /*
136865: ** This API allows applications to modify the global configuration of
136866: ** the SQLite library at run-time.
136867: **
136868: ** This routine should only be called when there are no outstanding
136869: ** database connections or memory allocations.  This routine is not
136870: ** threadsafe.  Failure to heed these warnings can lead to unpredictable
136871: ** behavior.
136872: */
136873: SQLITE_API int sqlite3_config(int op, ...){
136874:   va_list ap;
136875:   int rc = SQLITE_OK;
136876: 
136877:   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
136878:   ** the SQLite library is in use. */
136879:   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
136880: 
136881:   va_start(ap, op);
136882:   switch( op ){
136883: 
136884:     /* Mutex configuration options are only available in a threadsafe
136885:     ** compile.
136886:     */
136887: #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
136888:     case SQLITE_CONFIG_SINGLETHREAD: {
136889:       /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
136890:       ** Single-thread. */
136891:       sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
136892:       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
136893:       break;
136894:     }
136895: #endif
136896: #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
136897:     case SQLITE_CONFIG_MULTITHREAD: {
136898:       /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
136899:       ** Multi-thread. */
136900:       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
136901:       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
136902:       break;
136903:     }
136904: #endif
136905: #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
136906:     case SQLITE_CONFIG_SERIALIZED: {
136907:       /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
136908:       ** Serialized. */
136909:       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
136910:       sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
136911:       break;
136912:     }
136913: #endif
136914: #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
136915:     case SQLITE_CONFIG_MUTEX: {
136916:       /* Specify an alternative mutex implementation */
136917:       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
136918:       break;
136919:     }
136920: #endif
136921: #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
136922:     case SQLITE_CONFIG_GETMUTEX: {
136923:       /* Retrieve the current mutex implementation */
136924:       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
136925:       break;
136926:     }
136927: #endif
136928: 
136929:     case SQLITE_CONFIG_MALLOC: {
136930:       /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
136931:       ** single argument which is a pointer to an instance of the
136932:       ** sqlite3_mem_methods structure. The argument specifies alternative
136933:       ** low-level memory allocation routines to be used in place of the memory
136934:       ** allocation routines built into SQLite. */
136935:       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
136936:       break;
136937:     }
136938:     case SQLITE_CONFIG_GETMALLOC: {
136939:       /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
136940:       ** single argument which is a pointer to an instance of the
136941:       ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
136942:       ** filled with the currently defined memory allocation routines. */
136943:       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
136944:       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
136945:       break;
136946:     }
136947:     case SQLITE_CONFIG_MEMSTATUS: {
136948:       /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
136949:       ** single argument of type int, interpreted as a boolean, which enables
136950:       ** or disables the collection of memory allocation statistics. */
136951:       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
136952:       break;
136953:     }
136954:     case SQLITE_CONFIG_SCRATCH: {
136955:       /* EVIDENCE-OF: R-08404-60887 There are three arguments to
136956:       ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
136957:       ** which the scratch allocations will be drawn, the size of each scratch
136958:       ** allocation (sz), and the maximum number of scratch allocations (N). */
136959:       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
136960:       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
136961:       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
136962:       break;
136963:     }
136964:     case SQLITE_CONFIG_PAGECACHE: {
136965:       /* EVIDENCE-OF: R-18761-36601 There are three arguments to
136966:       ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
136967:       ** the size of each page cache line (sz), and the number of cache lines
136968:       ** (N). */
136969:       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
136970:       sqlite3GlobalConfig.szPage = va_arg(ap, int);
136971:       sqlite3GlobalConfig.nPage = va_arg(ap, int);
136972:       break;
136973:     }
136974:     case SQLITE_CONFIG_PCACHE_HDRSZ: {
136975:       /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
136976:       ** a single parameter which is a pointer to an integer and writes into
136977:       ** that integer the number of extra bytes per page required for each page
136978:       ** in SQLITE_CONFIG_PAGECACHE. */
136979:       *va_arg(ap, int*) = 
136980:           sqlite3HeaderSizeBtree() +
136981:           sqlite3HeaderSizePcache() +
136982:           sqlite3HeaderSizePcache1();
136983:       break;
136984:     }
136985: 
136986:     case SQLITE_CONFIG_PCACHE: {
136987:       /* no-op */
136988:       break;
136989:     }
136990:     case SQLITE_CONFIG_GETPCACHE: {
136991:       /* now an error */
136992:       rc = SQLITE_ERROR;
136993:       break;
136994:     }
136995: 
136996:     case SQLITE_CONFIG_PCACHE2: {
136997:       /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
136998:       ** single argument which is a pointer to an sqlite3_pcache_methods2
136999:       ** object. This object specifies the interface to a custom page cache
137000:       ** implementation. */
137001:       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
137002:       break;
137003:     }
137004:     case SQLITE_CONFIG_GETPCACHE2: {
137005:       /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
137006:       ** single argument which is a pointer to an sqlite3_pcache_methods2
137007:       ** object. SQLite copies of the current page cache implementation into
137008:       ** that object. */
137009:       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
137010:         sqlite3PCacheSetDefault();
137011:       }
137012:       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
137013:       break;
137014:     }
137015: 
137016: /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
137017: ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
137018: ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
137019: #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
137020:     case SQLITE_CONFIG_HEAP: {
137021:       /* EVIDENCE-OF: R-19854-42126 There are three arguments to
137022:       ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
137023:       ** number of bytes in the memory buffer, and the minimum allocation size.
137024:       */
137025:       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
137026:       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
137027:       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
137028: 
137029:       if( sqlite3GlobalConfig.mnReq<1 ){
137030:         sqlite3GlobalConfig.mnReq = 1;
137031:       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
137032:         /* cap min request size at 2^12 */
137033:         sqlite3GlobalConfig.mnReq = (1<<12);
137034:       }
137035: 
137036:       if( sqlite3GlobalConfig.pHeap==0 ){
137037:         /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
137038:         ** is NULL, then SQLite reverts to using its default memory allocator
137039:         ** (the system malloc() implementation), undoing any prior invocation of
137040:         ** SQLITE_CONFIG_MALLOC.
137041:         **
137042:         ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
137043:         ** revert to its default implementation when sqlite3_initialize() is run
137044:         */
137045:         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
137046:       }else{
137047:         /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
137048:         ** alternative memory allocator is engaged to handle all of SQLites
137049:         ** memory allocation needs. */
137050: #ifdef SQLITE_ENABLE_MEMSYS3
137051:         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
137052: #endif
137053: #ifdef SQLITE_ENABLE_MEMSYS5
137054:         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
137055: #endif
137056:       }
137057:       break;
137058:     }
137059: #endif
137060: 
137061:     case SQLITE_CONFIG_LOOKASIDE: {
137062:       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
137063:       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
137064:       break;
137065:     }
137066:     
137067:     /* Record a pointer to the logger function and its first argument.
137068:     ** The default is NULL.  Logging is disabled if the function pointer is
137069:     ** NULL.
137070:     */
137071:     case SQLITE_CONFIG_LOG: {
137072:       /* MSVC is picky about pulling func ptrs from va lists.
137073:       ** http://support.microsoft.com/kb/47961
137074:       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
137075:       */
137076:       typedef void(*LOGFUNC_t)(void*,int,const char*);
137077:       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
137078:       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
137079:       break;
137080:     }
137081: 
137082:     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
137083:     ** can be changed at start-time using the
137084:     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
137085:     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
137086:     */
137087:     case SQLITE_CONFIG_URI: {
137088:       /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
137089:       ** argument of type int. If non-zero, then URI handling is globally
137090:       ** enabled. If the parameter is zero, then URI handling is globally
137091:       ** disabled. */
137092:       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
137093:       break;
137094:     }
137095: 
137096:     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
137097:       /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
137098:       ** option takes a single integer argument which is interpreted as a
137099:       ** boolean in order to enable or disable the use of covering indices for
137100:       ** full table scans in the query optimizer. */
137101:       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
137102:       break;
137103:     }
137104: 
137105: #ifdef SQLITE_ENABLE_SQLLOG
137106:     case SQLITE_CONFIG_SQLLOG: {
137107:       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
137108:       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
137109:       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
137110:       break;
137111:     }
137112: #endif
137113: 
137114:     case SQLITE_CONFIG_MMAP_SIZE: {
137115:       /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
137116:       ** integer (sqlite3_int64) values that are the default mmap size limit
137117:       ** (the default setting for PRAGMA mmap_size) and the maximum allowed
137118:       ** mmap size limit. */
137119:       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
137120:       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
137121:       /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
137122:       ** negative, then that argument is changed to its compile-time default.
137123:       **
137124:       ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
137125:       ** silently truncated if necessary so that it does not exceed the
137126:       ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
137127:       ** compile-time option.
137128:       */
137129:       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
137130:         mxMmap = SQLITE_MAX_MMAP_SIZE;
137131:       }
137132:       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
137133:       if( szMmap>mxMmap) szMmap = mxMmap;
137134:       sqlite3GlobalConfig.mxMmap = mxMmap;
137135:       sqlite3GlobalConfig.szMmap = szMmap;
137136:       break;
137137:     }
137138: 
137139: #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
137140:     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
137141:       /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
137142:       ** unsigned integer value that specifies the maximum size of the created
137143:       ** heap. */
137144:       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
137145:       break;
137146:     }
137147: #endif
137148: 
137149:     case SQLITE_CONFIG_PMASZ: {
137150:       sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
137151:       break;
137152:     }
137153: 
137154:     case SQLITE_CONFIG_STMTJRNL_SPILL: {
137155:       sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
137156:       break;
137157:     }
137158: 
137159:     default: {
137160:       rc = SQLITE_ERROR;
137161:       break;
137162:     }
137163:   }
137164:   va_end(ap);
137165:   return rc;
137166: }
137167: 
137168: /*
137169: ** Set up the lookaside buffers for a database connection.
137170: ** Return SQLITE_OK on success.  
137171: ** If lookaside is already active, return SQLITE_BUSY.
137172: **
137173: ** The sz parameter is the number of bytes in each lookaside slot.
137174: ** The cnt parameter is the number of slots.  If pStart is NULL the
137175: ** space for the lookaside memory is obtained from sqlite3_malloc().
137176: ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
137177: ** the lookaside memory.
137178: */
137179: static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
137180: #ifndef SQLITE_OMIT_LOOKASIDE
137181:   void *pStart;
137182:   if( db->lookaside.nOut ){
137183:     return SQLITE_BUSY;
137184:   }
137185:   /* Free any existing lookaside buffer for this handle before
137186:   ** allocating a new one so we don't have to have space for 
137187:   ** both at the same time.
137188:   */
137189:   if( db->lookaside.bMalloced ){
137190:     sqlite3_free(db->lookaside.pStart);
137191:   }
137192:   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
137193:   ** than a pointer to be useful.
137194:   */
137195:   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
137196:   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
137197:   if( cnt<0 ) cnt = 0;
137198:   if( sz==0 || cnt==0 ){
137199:     sz = 0;
137200:     pStart = 0;
137201:   }else if( pBuf==0 ){
137202:     sqlite3BeginBenignMalloc();
137203:     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
137204:     sqlite3EndBenignMalloc();
137205:     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
137206:   }else{
137207:     pStart = pBuf;
137208:   }
137209:   db->lookaside.pStart = pStart;
137210:   db->lookaside.pFree = 0;
137211:   db->lookaside.sz = (u16)sz;
137212:   if( pStart ){
137213:     int i;
137214:     LookasideSlot *p;
137215:     assert( sz > (int)sizeof(LookasideSlot*) );
137216:     p = (LookasideSlot*)pStart;
137217:     for(i=cnt-1; i>=0; i--){
137218:       p->pNext = db->lookaside.pFree;
137219:       db->lookaside.pFree = p;
137220:       p = (LookasideSlot*)&((u8*)p)[sz];
137221:     }
137222:     db->lookaside.pEnd = p;
137223:     db->lookaside.bDisable = 0;
137224:     db->lookaside.bMalloced = pBuf==0 ?1:0;
137225:   }else{
137226:     db->lookaside.pStart = db;
137227:     db->lookaside.pEnd = db;
137228:     db->lookaside.bDisable = 1;
137229:     db->lookaside.bMalloced = 0;
137230:   }
137231: #endif /* SQLITE_OMIT_LOOKASIDE */
137232:   return SQLITE_OK;
137233: }
137234: 
137235: /*
137236: ** Return the mutex associated with a database connection.
137237: */
137238: SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
137239: #ifdef SQLITE_ENABLE_API_ARMOR
137240:   if( !sqlite3SafetyCheckOk(db) ){
137241:     (void)SQLITE_MISUSE_BKPT;
137242:     return 0;
137243:   }
137244: #endif
137245:   return db->mutex;
137246: }
137247: 
137248: /*
137249: ** Free up as much memory as we can from the given database
137250: ** connection.
137251: */
137252: SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
137253:   int i;
137254: 
137255: #ifdef SQLITE_ENABLE_API_ARMOR
137256:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137257: #endif
137258:   sqlite3_mutex_enter(db->mutex);
137259:   sqlite3BtreeEnterAll(db);
137260:   for(i=0; i<db->nDb; i++){
137261:     Btree *pBt = db->aDb[i].pBt;
137262:     if( pBt ){
137263:       Pager *pPager = sqlite3BtreePager(pBt);
137264:       sqlite3PagerShrink(pPager);
137265:     }
137266:   }
137267:   sqlite3BtreeLeaveAll(db);
137268:   sqlite3_mutex_leave(db->mutex);
137269:   return SQLITE_OK;
137270: }
137271: 
137272: /*
137273: ** Flush any dirty pages in the pager-cache for any attached database
137274: ** to disk.
137275: */
137276: SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
137277:   int i;
137278:   int rc = SQLITE_OK;
137279:   int bSeenBusy = 0;
137280: 
137281: #ifdef SQLITE_ENABLE_API_ARMOR
137282:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137283: #endif
137284:   sqlite3_mutex_enter(db->mutex);
137285:   sqlite3BtreeEnterAll(db);
137286:   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
137287:     Btree *pBt = db->aDb[i].pBt;
137288:     if( pBt && sqlite3BtreeIsInTrans(pBt) ){
137289:       Pager *pPager = sqlite3BtreePager(pBt);
137290:       rc = sqlite3PagerFlush(pPager);
137291:       if( rc==SQLITE_BUSY ){
137292:         bSeenBusy = 1;
137293:         rc = SQLITE_OK;
137294:       }
137295:     }
137296:   }
137297:   sqlite3BtreeLeaveAll(db);
137298:   sqlite3_mutex_leave(db->mutex);
137299:   return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
137300: }
137301: 
137302: /*
137303: ** Configuration settings for an individual database connection
137304: */
137305: SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
137306:   va_list ap;
137307:   int rc;
137308:   va_start(ap, op);
137309:   switch( op ){
137310:     case SQLITE_DBCONFIG_LOOKASIDE: {
137311:       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
137312:       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
137313:       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
137314:       rc = setupLookaside(db, pBuf, sz, cnt);
137315:       break;
137316:     }
137317:     default: {
137318:       static const struct {
137319:         int op;      /* The opcode */
137320:         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
137321:       } aFlagOp[] = {
137322:         { SQLITE_DBCONFIG_ENABLE_FKEY,           SQLITE_ForeignKeys    },
137323:         { SQLITE_DBCONFIG_ENABLE_TRIGGER,        SQLITE_EnableTrigger  },
137324:         { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer  },
137325:         { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension  },
137326:       };
137327:       unsigned int i;
137328:       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
137329:       for(i=0; i<ArraySize(aFlagOp); i++){
137330:         if( aFlagOp[i].op==op ){
137331:           int onoff = va_arg(ap, int);
137332:           int *pRes = va_arg(ap, int*);
137333:           int oldFlags = db->flags;
137334:           if( onoff>0 ){
137335:             db->flags |= aFlagOp[i].mask;
137336:           }else if( onoff==0 ){
137337:             db->flags &= ~aFlagOp[i].mask;
137338:           }
137339:           if( oldFlags!=db->flags ){
137340:             sqlite3ExpirePreparedStatements(db);
137341:           }
137342:           if( pRes ){
137343:             *pRes = (db->flags & aFlagOp[i].mask)!=0;
137344:           }
137345:           rc = SQLITE_OK;
137346:           break;
137347:         }
137348:       }
137349:       break;
137350:     }
137351:   }
137352:   va_end(ap);
137353:   return rc;
137354: }
137355: 
137356: 
137357: /*
137358: ** Return true if the buffer z[0..n-1] contains all spaces.
137359: */
137360: static int allSpaces(const char *z, int n){
137361:   while( n>0 && z[n-1]==' ' ){ n--; }
137362:   return n==0;
137363: }
137364: 
137365: /*
137366: ** This is the default collating function named "BINARY" which is always
137367: ** available.
137368: **
137369: ** If the padFlag argument is not NULL then space padding at the end
137370: ** of strings is ignored.  This implements the RTRIM collation.
137371: */
137372: static int binCollFunc(
137373:   void *padFlag,
137374:   int nKey1, const void *pKey1,
137375:   int nKey2, const void *pKey2
137376: ){
137377:   int rc, n;
137378:   n = nKey1<nKey2 ? nKey1 : nKey2;
137379:   /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
137380:   ** strings byte by byte using the memcmp() function from the standard C
137381:   ** library. */
137382:   rc = memcmp(pKey1, pKey2, n);
137383:   if( rc==0 ){
137384:     if( padFlag
137385:      && allSpaces(((char*)pKey1)+n, nKey1-n)
137386:      && allSpaces(((char*)pKey2)+n, nKey2-n)
137387:     ){
137388:       /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
137389:       ** spaces at the end of either string do not change the result. In other
137390:       ** words, strings will compare equal to one another as long as they
137391:       ** differ only in the number of spaces at the end.
137392:       */
137393:     }else{
137394:       rc = nKey1 - nKey2;
137395:     }
137396:   }
137397:   return rc;
137398: }
137399: 
137400: /*
137401: ** Another built-in collating sequence: NOCASE. 
137402: **
137403: ** This collating sequence is intended to be used for "case independent
137404: ** comparison". SQLite's knowledge of upper and lower case equivalents
137405: ** extends only to the 26 characters used in the English language.
137406: **
137407: ** At the moment there is only a UTF-8 implementation.
137408: */
137409: static int nocaseCollatingFunc(
137410:   void *NotUsed,
137411:   int nKey1, const void *pKey1,
137412:   int nKey2, const void *pKey2
137413: ){
137414:   int r = sqlite3StrNICmp(
137415:       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
137416:   UNUSED_PARAMETER(NotUsed);
137417:   if( 0==r ){
137418:     r = nKey1-nKey2;
137419:   }
137420:   return r;
137421: }
137422: 
137423: /*
137424: ** Return the ROWID of the most recent insert
137425: */
137426: SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
137427: #ifdef SQLITE_ENABLE_API_ARMOR
137428:   if( !sqlite3SafetyCheckOk(db) ){
137429:     (void)SQLITE_MISUSE_BKPT;
137430:     return 0;
137431:   }
137432: #endif
137433:   return db->lastRowid;
137434: }
137435: 
137436: /*
137437: ** Return the number of changes in the most recent call to sqlite3_exec().
137438: */
137439: SQLITE_API int sqlite3_changes(sqlite3 *db){
137440: #ifdef SQLITE_ENABLE_API_ARMOR
137441:   if( !sqlite3SafetyCheckOk(db) ){
137442:     (void)SQLITE_MISUSE_BKPT;
137443:     return 0;
137444:   }
137445: #endif
137446:   return db->nChange;
137447: }
137448: 
137449: /*
137450: ** Return the number of changes since the database handle was opened.
137451: */
137452: SQLITE_API int sqlite3_total_changes(sqlite3 *db){
137453: #ifdef SQLITE_ENABLE_API_ARMOR
137454:   if( !sqlite3SafetyCheckOk(db) ){
137455:     (void)SQLITE_MISUSE_BKPT;
137456:     return 0;
137457:   }
137458: #endif
137459:   return db->nTotalChange;
137460: }
137461: 
137462: /*
137463: ** Close all open savepoints. This function only manipulates fields of the
137464: ** database handle object, it does not close any savepoints that may be open
137465: ** at the b-tree/pager level.
137466: */
137467: SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
137468:   while( db->pSavepoint ){
137469:     Savepoint *pTmp = db->pSavepoint;
137470:     db->pSavepoint = pTmp->pNext;
137471:     sqlite3DbFree(db, pTmp);
137472:   }
137473:   db->nSavepoint = 0;
137474:   db->nStatement = 0;
137475:   db->isTransactionSavepoint = 0;
137476: }
137477: 
137478: /*
137479: ** Invoke the destructor function associated with FuncDef p, if any. Except,
137480: ** if this is not the last copy of the function, do not invoke it. Multiple
137481: ** copies of a single function are created when create_function() is called
137482: ** with SQLITE_ANY as the encoding.
137483: */
137484: static void functionDestroy(sqlite3 *db, FuncDef *p){
137485:   FuncDestructor *pDestructor = p->u.pDestructor;
137486:   if( pDestructor ){
137487:     pDestructor->nRef--;
137488:     if( pDestructor->nRef==0 ){
137489:       pDestructor->xDestroy(pDestructor->pUserData);
137490:       sqlite3DbFree(db, pDestructor);
137491:     }
137492:   }
137493: }
137494: 
137495: /*
137496: ** Disconnect all sqlite3_vtab objects that belong to database connection
137497: ** db. This is called when db is being closed.
137498: */
137499: static void disconnectAllVtab(sqlite3 *db){
137500: #ifndef SQLITE_OMIT_VIRTUALTABLE
137501:   int i;
137502:   HashElem *p;
137503:   sqlite3BtreeEnterAll(db);
137504:   for(i=0; i<db->nDb; i++){
137505:     Schema *pSchema = db->aDb[i].pSchema;
137506:     if( db->aDb[i].pSchema ){
137507:       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
137508:         Table *pTab = (Table *)sqliteHashData(p);
137509:         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
137510:       }
137511:     }
137512:   }
137513:   for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
137514:     Module *pMod = (Module *)sqliteHashData(p);
137515:     if( pMod->pEpoTab ){
137516:       sqlite3VtabDisconnect(db, pMod->pEpoTab);
137517:     }
137518:   }
137519:   sqlite3VtabUnlockList(db);
137520:   sqlite3BtreeLeaveAll(db);
137521: #else
137522:   UNUSED_PARAMETER(db);
137523: #endif
137524: }
137525: 
137526: /*
137527: ** Return TRUE if database connection db has unfinalized prepared
137528: ** statements or unfinished sqlite3_backup objects.  
137529: */
137530: static int connectionIsBusy(sqlite3 *db){
137531:   int j;
137532:   assert( sqlite3_mutex_held(db->mutex) );
137533:   if( db->pVdbe ) return 1;
137534:   for(j=0; j<db->nDb; j++){
137535:     Btree *pBt = db->aDb[j].pBt;
137536:     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
137537:   }
137538:   return 0;
137539: }
137540: 
137541: /*
137542: ** Close an existing SQLite database
137543: */
137544: static int sqlite3Close(sqlite3 *db, int forceZombie){
137545:   if( !db ){
137546:     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
137547:     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
137548:     return SQLITE_OK;
137549:   }
137550:   if( !sqlite3SafetyCheckSickOrOk(db) ){
137551:     return SQLITE_MISUSE_BKPT;
137552:   }
137553:   sqlite3_mutex_enter(db->mutex);
137554:   if( db->mTrace & SQLITE_TRACE_CLOSE ){
137555:     db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
137556:   }
137557: 
137558:   /* Force xDisconnect calls on all virtual tables */
137559:   disconnectAllVtab(db);
137560: 
137561:   /* If a transaction is open, the disconnectAllVtab() call above
137562:   ** will not have called the xDisconnect() method on any virtual
137563:   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
137564:   ** call will do so. We need to do this before the check for active
137565:   ** SQL statements below, as the v-table implementation may be storing
137566:   ** some prepared statements internally.
137567:   */
137568:   sqlite3VtabRollback(db);
137569: 
137570:   /* Legacy behavior (sqlite3_close() behavior) is to return
137571:   ** SQLITE_BUSY if the connection can not be closed immediately.
137572:   */
137573:   if( !forceZombie && connectionIsBusy(db) ){
137574:     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
137575:        "statements or unfinished backups");
137576:     sqlite3_mutex_leave(db->mutex);
137577:     return SQLITE_BUSY;
137578:   }
137579: 
137580: #ifdef SQLITE_ENABLE_SQLLOG
137581:   if( sqlite3GlobalConfig.xSqllog ){
137582:     /* Closing the handle. Fourth parameter is passed the value 2. */
137583:     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
137584:   }
137585: #endif
137586: 
137587:   /* Convert the connection into a zombie and then close it.
137588:   */
137589:   db->magic = SQLITE_MAGIC_ZOMBIE;
137590:   sqlite3LeaveMutexAndCloseZombie(db);
137591:   return SQLITE_OK;
137592: }
137593: 
137594: /*
137595: ** Two variations on the public interface for closing a database
137596: ** connection. The sqlite3_close() version returns SQLITE_BUSY and
137597: ** leaves the connection option if there are unfinalized prepared
137598: ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
137599: ** version forces the connection to become a zombie if there are
137600: ** unclosed resources, and arranges for deallocation when the last
137601: ** prepare statement or sqlite3_backup closes.
137602: */
137603: SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
137604: SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
137605: 
137606: 
137607: /*
137608: ** Close the mutex on database connection db.
137609: **
137610: ** Furthermore, if database connection db is a zombie (meaning that there
137611: ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
137612: ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
137613: ** finished, then free all resources.
137614: */
137615: SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
137616:   HashElem *i;                    /* Hash table iterator */
137617:   int j;
137618: 
137619:   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
137620:   ** or if the connection has not yet been closed by sqlite3_close_v2(),
137621:   ** then just leave the mutex and return.
137622:   */
137623:   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
137624:     sqlite3_mutex_leave(db->mutex);
137625:     return;
137626:   }
137627: 
137628:   /* If we reach this point, it means that the database connection has
137629:   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
137630:   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
137631:   ** go ahead and free all resources.
137632:   */
137633: 
137634:   /* If a transaction is open, roll it back. This also ensures that if
137635:   ** any database schemas have been modified by an uncommitted transaction
137636:   ** they are reset. And that the required b-tree mutex is held to make
137637:   ** the pager rollback and schema reset an atomic operation. */
137638:   sqlite3RollbackAll(db, SQLITE_OK);
137639: 
137640:   /* Free any outstanding Savepoint structures. */
137641:   sqlite3CloseSavepoints(db);
137642: 
137643:   /* Close all database connections */
137644:   for(j=0; j<db->nDb; j++){
137645:     struct Db *pDb = &db->aDb[j];
137646:     if( pDb->pBt ){
137647:       sqlite3BtreeClose(pDb->pBt);
137648:       pDb->pBt = 0;
137649:       if( j!=1 ){
137650:         pDb->pSchema = 0;
137651:       }
137652:     }
137653:   }
137654:   /* Clear the TEMP schema separately and last */
137655:   if( db->aDb[1].pSchema ){
137656:     sqlite3SchemaClear(db->aDb[1].pSchema);
137657:   }
137658:   sqlite3VtabUnlockList(db);
137659: 
137660:   /* Free up the array of auxiliary databases */
137661:   sqlite3CollapseDatabaseArray(db);
137662:   assert( db->nDb<=2 );
137663:   assert( db->aDb==db->aDbStatic );
137664: 
137665:   /* Tell the code in notify.c that the connection no longer holds any
137666:   ** locks and does not require any further unlock-notify callbacks.
137667:   */
137668:   sqlite3ConnectionClosed(db);
137669: 
137670:   for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
137671:     FuncDef *pNext, *p;
137672:     p = sqliteHashData(i);
137673:     do{
137674:       functionDestroy(db, p);
137675:       pNext = p->pNext;
137676:       sqlite3DbFree(db, p);
137677:       p = pNext;
137678:     }while( p );
137679:   }
137680:   sqlite3HashClear(&db->aFunc);
137681:   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
137682:     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
137683:     /* Invoke any destructors registered for collation sequence user data. */
137684:     for(j=0; j<3; j++){
137685:       if( pColl[j].xDel ){
137686:         pColl[j].xDel(pColl[j].pUser);
137687:       }
137688:     }
137689:     sqlite3DbFree(db, pColl);
137690:   }
137691:   sqlite3HashClear(&db->aCollSeq);
137692: #ifndef SQLITE_OMIT_VIRTUALTABLE
137693:   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
137694:     Module *pMod = (Module *)sqliteHashData(i);
137695:     if( pMod->xDestroy ){
137696:       pMod->xDestroy(pMod->pAux);
137697:     }
137698:     sqlite3VtabEponymousTableClear(db, pMod);
137699:     sqlite3DbFree(db, pMod);
137700:   }
137701:   sqlite3HashClear(&db->aModule);
137702: #endif
137703: 
137704:   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
137705:   sqlite3ValueFree(db->pErr);
137706:   sqlite3CloseExtensions(db);
137707: #if SQLITE_USER_AUTHENTICATION
137708:   sqlite3_free(db->auth.zAuthUser);
137709:   sqlite3_free(db->auth.zAuthPW);
137710: #endif
137711: 
137712:   db->magic = SQLITE_MAGIC_ERROR;
137713: 
137714:   /* The temp-database schema is allocated differently from the other schema
137715:   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
137716:   ** So it needs to be freed here. Todo: Why not roll the temp schema into
137717:   ** the same sqliteMalloc() as the one that allocates the database 
137718:   ** structure?
137719:   */
137720:   sqlite3DbFree(db, db->aDb[1].pSchema);
137721:   sqlite3_mutex_leave(db->mutex);
137722:   db->magic = SQLITE_MAGIC_CLOSED;
137723:   sqlite3_mutex_free(db->mutex);
137724:   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
137725:   if( db->lookaside.bMalloced ){
137726:     sqlite3_free(db->lookaside.pStart);
137727:   }
137728:   sqlite3_free(db);
137729: }
137730: 
137731: /*
137732: ** Rollback all database files.  If tripCode is not SQLITE_OK, then
137733: ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
137734: ** breaker") and made to return tripCode if there are any further
137735: ** attempts to use that cursor.  Read cursors remain open and valid
137736: ** but are "saved" in case the table pages are moved around.
137737: */
137738: SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
137739:   int i;
137740:   int inTrans = 0;
137741:   int schemaChange;
137742:   assert( sqlite3_mutex_held(db->mutex) );
137743:   sqlite3BeginBenignMalloc();
137744: 
137745:   /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
137746:   ** This is important in case the transaction being rolled back has
137747:   ** modified the database schema. If the b-tree mutexes are not taken
137748:   ** here, then another shared-cache connection might sneak in between
137749:   ** the database rollback and schema reset, which can cause false
137750:   ** corruption reports in some cases.  */
137751:   sqlite3BtreeEnterAll(db);
137752:   schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
137753: 
137754:   for(i=0; i<db->nDb; i++){
137755:     Btree *p = db->aDb[i].pBt;
137756:     if( p ){
137757:       if( sqlite3BtreeIsInTrans(p) ){
137758:         inTrans = 1;
137759:       }
137760:       sqlite3BtreeRollback(p, tripCode, !schemaChange);
137761:     }
137762:   }
137763:   sqlite3VtabRollback(db);
137764:   sqlite3EndBenignMalloc();
137765: 
137766:   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
137767:     sqlite3ExpirePreparedStatements(db);
137768:     sqlite3ResetAllSchemasOfConnection(db);
137769:   }
137770:   sqlite3BtreeLeaveAll(db);
137771: 
137772:   /* Any deferred constraint violations have now been resolved. */
137773:   db->nDeferredCons = 0;
137774:   db->nDeferredImmCons = 0;
137775:   db->flags &= ~SQLITE_DeferFKs;
137776: 
137777:   /* If one has been configured, invoke the rollback-hook callback */
137778:   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
137779:     db->xRollbackCallback(db->pRollbackArg);
137780:   }
137781: }
137782: 
137783: /*
137784: ** Return a static string containing the name corresponding to the error code
137785: ** specified in the argument.
137786: */
137787: #if defined(SQLITE_NEED_ERR_NAME)
137788: SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
137789:   const char *zName = 0;
137790:   int i, origRc = rc;
137791:   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
137792:     switch( rc ){
137793:       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
137794:       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
137795:       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
137796:       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
137797:       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
137798:       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
137799:       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
137800:       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
137801:       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
137802:       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
137803:       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
137804:       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
137805:       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
137806:       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
137807:       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
137808:       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
137809:       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
137810:       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
137811:       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
137812:       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
137813:       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
137814:       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
137815:       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
137816:       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
137817:       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
137818:       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
137819:       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
137820:       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
137821:       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
137822:       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
137823:       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
137824:       case SQLITE_IOERR_CHECKRESERVEDLOCK:
137825:                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
137826:       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
137827:       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
137828:       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
137829:       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
137830:       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
137831:       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
137832:       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
137833:       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
137834:       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
137835:       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
137836:       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
137837:       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
137838:       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
137839:       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
137840:       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
137841:       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
137842:       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
137843:       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
137844:       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
137845:       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
137846:       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
137847:       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
137848:       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
137849:       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
137850:       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
137851:       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
137852:       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
137853:       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
137854:       case SQLITE_CONSTRAINT_FOREIGNKEY:
137855:                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
137856:       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
137857:       case SQLITE_CONSTRAINT_PRIMARYKEY:
137858:                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
137859:       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
137860:       case SQLITE_CONSTRAINT_COMMITHOOK:
137861:                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
137862:       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
137863:       case SQLITE_CONSTRAINT_FUNCTION:
137864:                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
137865:       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
137866:       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
137867:       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
137868:       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
137869:       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
137870:       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
137871:       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
137872:       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
137873:       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
137874:       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
137875:       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
137876:       case SQLITE_NOTICE_RECOVER_ROLLBACK:
137877:                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
137878:       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
137879:       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
137880:       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
137881:     }
137882:   }
137883:   if( zName==0 ){
137884:     static char zBuf[50];
137885:     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
137886:     zName = zBuf;
137887:   }
137888:   return zName;
137889: }
137890: #endif
137891: 
137892: /*
137893: ** Return a static string that describes the kind of error specified in the
137894: ** argument.
137895: */
137896: SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
137897:   static const char* const aMsg[] = {
137898:     /* SQLITE_OK          */ "not an error",
137899:     /* SQLITE_ERROR       */ "SQL logic error or missing database",
137900:     /* SQLITE_INTERNAL    */ 0,
137901:     /* SQLITE_PERM        */ "access permission denied",
137902:     /* SQLITE_ABORT       */ "callback requested query abort",
137903:     /* SQLITE_BUSY        */ "database is locked",
137904:     /* SQLITE_LOCKED      */ "database table is locked",
137905:     /* SQLITE_NOMEM       */ "out of memory",
137906:     /* SQLITE_READONLY    */ "attempt to write a readonly database",
137907:     /* SQLITE_INTERRUPT   */ "interrupted",
137908:     /* SQLITE_IOERR       */ "disk I/O error",
137909:     /* SQLITE_CORRUPT     */ "database disk image is malformed",
137910:     /* SQLITE_NOTFOUND    */ "unknown operation",
137911:     /* SQLITE_FULL        */ "database or disk is full",
137912:     /* SQLITE_CANTOPEN    */ "unable to open database file",
137913:     /* SQLITE_PROTOCOL    */ "locking protocol",
137914:     /* SQLITE_EMPTY       */ "table contains no data",
137915:     /* SQLITE_SCHEMA      */ "database schema has changed",
137916:     /* SQLITE_TOOBIG      */ "string or blob too big",
137917:     /* SQLITE_CONSTRAINT  */ "constraint failed",
137918:     /* SQLITE_MISMATCH    */ "datatype mismatch",
137919:     /* SQLITE_MISUSE      */ "library routine called out of sequence",
137920:     /* SQLITE_NOLFS       */ "large file support is disabled",
137921:     /* SQLITE_AUTH        */ "authorization denied",
137922:     /* SQLITE_FORMAT      */ "auxiliary database format error",
137923:     /* SQLITE_RANGE       */ "bind or column index out of range",
137924:     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
137925:   };
137926:   const char *zErr = "unknown error";
137927:   switch( rc ){
137928:     case SQLITE_ABORT_ROLLBACK: {
137929:       zErr = "abort due to ROLLBACK";
137930:       break;
137931:     }
137932:     default: {
137933:       rc &= 0xff;
137934:       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
137935:         zErr = aMsg[rc];
137936:       }
137937:       break;
137938:     }
137939:   }
137940:   return zErr;
137941: }
137942: 
137943: /*
137944: ** This routine implements a busy callback that sleeps and tries
137945: ** again until a timeout value is reached.  The timeout value is
137946: ** an integer number of milliseconds passed in as the first
137947: ** argument.
137948: */
137949: static int sqliteDefaultBusyCallback(
137950:  void *ptr,               /* Database connection */
137951:  int count                /* Number of times table has been busy */
137952: ){
137953: #if SQLITE_OS_WIN || HAVE_USLEEP
137954:   static const u8 delays[] =
137955:      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
137956:   static const u8 totals[] =
137957:      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
137958: # define NDELAY ArraySize(delays)
137959:   sqlite3 *db = (sqlite3 *)ptr;
137960:   int timeout = db->busyTimeout;
137961:   int delay, prior;
137962: 
137963:   assert( count>=0 );
137964:   if( count < NDELAY ){
137965:     delay = delays[count];
137966:     prior = totals[count];
137967:   }else{
137968:     delay = delays[NDELAY-1];
137969:     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
137970:   }
137971:   if( prior + delay > timeout ){
137972:     delay = timeout - prior;
137973:     if( delay<=0 ) return 0;
137974:   }
137975:   sqlite3OsSleep(db->pVfs, delay*1000);
137976:   return 1;
137977: #else
137978:   sqlite3 *db = (sqlite3 *)ptr;
137979:   int timeout = ((sqlite3 *)ptr)->busyTimeout;
137980:   if( (count+1)*1000 > timeout ){
137981:     return 0;
137982:   }
137983:   sqlite3OsSleep(db->pVfs, 1000000);
137984:   return 1;
137985: #endif
137986: }
137987: 
137988: /*
137989: ** Invoke the given busy handler.
137990: **
137991: ** This routine is called when an operation failed with a lock.
137992: ** If this routine returns non-zero, the lock is retried.  If it
137993: ** returns 0, the operation aborts with an SQLITE_BUSY error.
137994: */
137995: SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
137996:   int rc;
137997:   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
137998:   rc = p->xFunc(p->pArg, p->nBusy);
137999:   if( rc==0 ){
138000:     p->nBusy = -1;
138001:   }else{
138002:     p->nBusy++;
138003:   }
138004:   return rc; 
138005: }
138006: 
138007: /*
138008: ** This routine sets the busy callback for an Sqlite database to the
138009: ** given callback function with the given argument.
138010: */
138011: SQLITE_API int sqlite3_busy_handler(
138012:   sqlite3 *db,
138013:   int (*xBusy)(void*,int),
138014:   void *pArg
138015: ){
138016: #ifdef SQLITE_ENABLE_API_ARMOR
138017:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138018: #endif
138019:   sqlite3_mutex_enter(db->mutex);
138020:   db->busyHandler.xFunc = xBusy;
138021:   db->busyHandler.pArg = pArg;
138022:   db->busyHandler.nBusy = 0;
138023:   db->busyTimeout = 0;
138024:   sqlite3_mutex_leave(db->mutex);
138025:   return SQLITE_OK;
138026: }
138027: 
138028: #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
138029: /*
138030: ** This routine sets the progress callback for an Sqlite database to the
138031: ** given callback function with the given argument. The progress callback will
138032: ** be invoked every nOps opcodes.
138033: */
138034: SQLITE_API void sqlite3_progress_handler(
138035:   sqlite3 *db, 
138036:   int nOps,
138037:   int (*xProgress)(void*), 
138038:   void *pArg
138039: ){
138040: #ifdef SQLITE_ENABLE_API_ARMOR
138041:   if( !sqlite3SafetyCheckOk(db) ){
138042:     (void)SQLITE_MISUSE_BKPT;
138043:     return;
138044:   }
138045: #endif
138046:   sqlite3_mutex_enter(db->mutex);
138047:   if( nOps>0 ){
138048:     db->xProgress = xProgress;
138049:     db->nProgressOps = (unsigned)nOps;
138050:     db->pProgressArg = pArg;
138051:   }else{
138052:     db->xProgress = 0;
138053:     db->nProgressOps = 0;
138054:     db->pProgressArg = 0;
138055:   }
138056:   sqlite3_mutex_leave(db->mutex);
138057: }
138058: #endif
138059: 
138060: 
138061: /*
138062: ** This routine installs a default busy handler that waits for the
138063: ** specified number of milliseconds before returning 0.
138064: */
138065: SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
138066: #ifdef SQLITE_ENABLE_API_ARMOR
138067:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138068: #endif
138069:   if( ms>0 ){
138070:     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
138071:     db->busyTimeout = ms;
138072:   }else{
138073:     sqlite3_busy_handler(db, 0, 0);
138074:   }
138075:   return SQLITE_OK;
138076: }
138077: 
138078: /*
138079: ** Cause any pending operation to stop at its earliest opportunity.
138080: */
138081: SQLITE_API void sqlite3_interrupt(sqlite3 *db){
138082: #ifdef SQLITE_ENABLE_API_ARMOR
138083:   if( !sqlite3SafetyCheckOk(db) ){
138084:     (void)SQLITE_MISUSE_BKPT;
138085:     return;
138086:   }
138087: #endif
138088:   db->u1.isInterrupted = 1;
138089: }
138090: 
138091: 
138092: /*
138093: ** This function is exactly the same as sqlite3_create_function(), except
138094: ** that it is designed to be called by internal code. The difference is
138095: ** that if a malloc() fails in sqlite3_create_function(), an error code
138096: ** is returned and the mallocFailed flag cleared. 
138097: */
138098: SQLITE_PRIVATE int sqlite3CreateFunc(
138099:   sqlite3 *db,
138100:   const char *zFunctionName,
138101:   int nArg,
138102:   int enc,
138103:   void *pUserData,
138104:   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138105:   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138106:   void (*xFinal)(sqlite3_context*),
138107:   FuncDestructor *pDestructor
138108: ){
138109:   FuncDef *p;
138110:   int nName;
138111:   int extraFlags;
138112: 
138113:   assert( sqlite3_mutex_held(db->mutex) );
138114:   if( zFunctionName==0 ||
138115:       (xSFunc && (xFinal || xStep)) || 
138116:       (!xSFunc && (xFinal && !xStep)) ||
138117:       (!xSFunc && (!xFinal && xStep)) ||
138118:       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
138119:       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
138120:     return SQLITE_MISUSE_BKPT;
138121:   }
138122: 
138123:   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
138124:   extraFlags = enc &  SQLITE_DETERMINISTIC;
138125:   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
138126:   
138127: #ifndef SQLITE_OMIT_UTF16
138128:   /* If SQLITE_UTF16 is specified as the encoding type, transform this
138129:   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
138130:   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
138131:   **
138132:   ** If SQLITE_ANY is specified, add three versions of the function
138133:   ** to the hash table.
138134:   */
138135:   if( enc==SQLITE_UTF16 ){
138136:     enc = SQLITE_UTF16NATIVE;
138137:   }else if( enc==SQLITE_ANY ){
138138:     int rc;
138139:     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
138140:          pUserData, xSFunc, xStep, xFinal, pDestructor);
138141:     if( rc==SQLITE_OK ){
138142:       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
138143:           pUserData, xSFunc, xStep, xFinal, pDestructor);
138144:     }
138145:     if( rc!=SQLITE_OK ){
138146:       return rc;
138147:     }
138148:     enc = SQLITE_UTF16BE;
138149:   }
138150: #else
138151:   enc = SQLITE_UTF8;
138152: #endif
138153:   
138154:   /* Check if an existing function is being overridden or deleted. If so,
138155:   ** and there are active VMs, then return SQLITE_BUSY. If a function
138156:   ** is being overridden/deleted but there are no active VMs, allow the
138157:   ** operation to continue but invalidate all precompiled statements.
138158:   */
138159:   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
138160:   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
138161:     if( db->nVdbeActive ){
138162:       sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
138163:         "unable to delete/modify user-function due to active statements");
138164:       assert( !db->mallocFailed );
138165:       return SQLITE_BUSY;
138166:     }else{
138167:       sqlite3ExpirePreparedStatements(db);
138168:     }
138169:   }
138170: 
138171:   p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
138172:   assert(p || db->mallocFailed);
138173:   if( !p ){
138174:     return SQLITE_NOMEM_BKPT;
138175:   }
138176: 
138177:   /* If an older version of the function with a configured destructor is
138178:   ** being replaced invoke the destructor function here. */
138179:   functionDestroy(db, p);
138180: 
138181:   if( pDestructor ){
138182:     pDestructor->nRef++;
138183:   }
138184:   p->u.pDestructor = pDestructor;
138185:   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
138186:   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
138187:   p->xSFunc = xSFunc ? xSFunc : xStep;
138188:   p->xFinalize = xFinal;
138189:   p->pUserData = pUserData;
138190:   p->nArg = (u16)nArg;
138191:   return SQLITE_OK;
138192: }
138193: 
138194: /*
138195: ** Create new user functions.
138196: */
138197: SQLITE_API int sqlite3_create_function(
138198:   sqlite3 *db,
138199:   const char *zFunc,
138200:   int nArg,
138201:   int enc,
138202:   void *p,
138203:   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138204:   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138205:   void (*xFinal)(sqlite3_context*)
138206: ){
138207:   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
138208:                                     xFinal, 0);
138209: }
138210: 
138211: SQLITE_API int sqlite3_create_function_v2(
138212:   sqlite3 *db,
138213:   const char *zFunc,
138214:   int nArg,
138215:   int enc,
138216:   void *p,
138217:   void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
138218:   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
138219:   void (*xFinal)(sqlite3_context*),
138220:   void (*xDestroy)(void *)
138221: ){
138222:   int rc = SQLITE_ERROR;
138223:   FuncDestructor *pArg = 0;
138224: 
138225: #ifdef SQLITE_ENABLE_API_ARMOR
138226:   if( !sqlite3SafetyCheckOk(db) ){
138227:     return SQLITE_MISUSE_BKPT;
138228:   }
138229: #endif
138230:   sqlite3_mutex_enter(db->mutex);
138231:   if( xDestroy ){
138232:     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
138233:     if( !pArg ){
138234:       xDestroy(p);
138235:       goto out;
138236:     }
138237:     pArg->xDestroy = xDestroy;
138238:     pArg->pUserData = p;
138239:   }
138240:   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
138241:   if( pArg && pArg->nRef==0 ){
138242:     assert( rc!=SQLITE_OK );
138243:     xDestroy(p);
138244:     sqlite3DbFree(db, pArg);
138245:   }
138246: 
138247:  out:
138248:   rc = sqlite3ApiExit(db, rc);
138249:   sqlite3_mutex_leave(db->mutex);
138250:   return rc;
138251: }
138252: 
138253: #ifndef SQLITE_OMIT_UTF16
138254: SQLITE_API int sqlite3_create_function16(
138255:   sqlite3 *db,
138256:   const void *zFunctionName,
138257:   int nArg,
138258:   int eTextRep,
138259:   void *p,
138260:   void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
138261:   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
138262:   void (*xFinal)(sqlite3_context*)
138263: ){
138264:   int rc;
138265:   char *zFunc8;
138266: 
138267: #ifdef SQLITE_ENABLE_API_ARMOR
138268:   if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
138269: #endif
138270:   sqlite3_mutex_enter(db->mutex);
138271:   assert( !db->mallocFailed );
138272:   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
138273:   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
138274:   sqlite3DbFree(db, zFunc8);
138275:   rc = sqlite3ApiExit(db, rc);
138276:   sqlite3_mutex_leave(db->mutex);
138277:   return rc;
138278: }
138279: #endif
138280: 
138281: 
138282: /*
138283: ** Declare that a function has been overloaded by a virtual table.
138284: **
138285: ** If the function already exists as a regular global function, then
138286: ** this routine is a no-op.  If the function does not exist, then create
138287: ** a new one that always throws a run-time error.  
138288: **
138289: ** When virtual tables intend to provide an overloaded function, they
138290: ** should call this routine to make sure the global function exists.
138291: ** A global function must exist in order for name resolution to work
138292: ** properly.
138293: */
138294: SQLITE_API int sqlite3_overload_function(
138295:   sqlite3 *db,
138296:   const char *zName,
138297:   int nArg
138298: ){
138299:   int rc = SQLITE_OK;
138300: 
138301: #ifdef SQLITE_ENABLE_API_ARMOR
138302:   if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
138303:     return SQLITE_MISUSE_BKPT;
138304:   }
138305: #endif
138306:   sqlite3_mutex_enter(db->mutex);
138307:   if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
138308:     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
138309:                            0, sqlite3InvalidFunction, 0, 0, 0);
138310:   }
138311:   rc = sqlite3ApiExit(db, rc);
138312:   sqlite3_mutex_leave(db->mutex);
138313:   return rc;
138314: }
138315: 
138316: #ifndef SQLITE_OMIT_TRACE
138317: /*
138318: ** Register a trace function.  The pArg from the previously registered trace
138319: ** is returned.  
138320: **
138321: ** A NULL trace function means that no tracing is executes.  A non-NULL
138322: ** trace is a pointer to a function that is invoked at the start of each
138323: ** SQL statement.
138324: */
138325: #ifndef SQLITE_OMIT_DEPRECATED
138326: SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
138327:   void *pOld;
138328: 
138329: #ifdef SQLITE_ENABLE_API_ARMOR
138330:   if( !sqlite3SafetyCheckOk(db) ){
138331:     (void)SQLITE_MISUSE_BKPT;
138332:     return 0;
138333:   }
138334: #endif
138335:   sqlite3_mutex_enter(db->mutex);
138336:   pOld = db->pTraceArg;
138337:   db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
138338:   db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
138339:   db->pTraceArg = pArg;
138340:   sqlite3_mutex_leave(db->mutex);
138341:   return pOld;
138342: }
138343: #endif /* SQLITE_OMIT_DEPRECATED */
138344: 
138345: /* Register a trace callback using the version-2 interface.
138346: */
138347: SQLITE_API int sqlite3_trace_v2(
138348:   sqlite3 *db,                               /* Trace this connection */
138349:   unsigned mTrace,                           /* Mask of events to be traced */
138350:   int(*xTrace)(unsigned,void*,void*,void*),  /* Callback to invoke */
138351:   void *pArg                                 /* Context */
138352: ){
138353: #ifdef SQLITE_ENABLE_API_ARMOR
138354:   if( !sqlite3SafetyCheckOk(db) ){
138355:     return SQLITE_MISUSE_BKPT;
138356:   }
138357: #endif
138358:   sqlite3_mutex_enter(db->mutex);
138359:   if( mTrace==0 ) xTrace = 0;
138360:   if( xTrace==0 ) mTrace = 0;
138361:   db->mTrace = mTrace;
138362:   db->xTrace = xTrace;
138363:   db->pTraceArg = pArg;
138364:   sqlite3_mutex_leave(db->mutex);
138365:   return SQLITE_OK;
138366: }
138367: 
138368: #ifndef SQLITE_OMIT_DEPRECATED
138369: /*
138370: ** Register a profile function.  The pArg from the previously registered 
138371: ** profile function is returned.  
138372: **
138373: ** A NULL profile function means that no profiling is executes.  A non-NULL
138374: ** profile is a pointer to a function that is invoked at the conclusion of
138375: ** each SQL statement that is run.
138376: */
138377: SQLITE_API void *sqlite3_profile(
138378:   sqlite3 *db,
138379:   void (*xProfile)(void*,const char*,sqlite_uint64),
138380:   void *pArg
138381: ){
138382:   void *pOld;
138383: 
138384: #ifdef SQLITE_ENABLE_API_ARMOR
138385:   if( !sqlite3SafetyCheckOk(db) ){
138386:     (void)SQLITE_MISUSE_BKPT;
138387:     return 0;
138388:   }
138389: #endif
138390:   sqlite3_mutex_enter(db->mutex);
138391:   pOld = db->pProfileArg;
138392:   db->xProfile = xProfile;
138393:   db->pProfileArg = pArg;
138394:   sqlite3_mutex_leave(db->mutex);
138395:   return pOld;
138396: }
138397: #endif /* SQLITE_OMIT_DEPRECATED */
138398: #endif /* SQLITE_OMIT_TRACE */
138399: 
138400: /*
138401: ** Register a function to be invoked when a transaction commits.
138402: ** If the invoked function returns non-zero, then the commit becomes a
138403: ** rollback.
138404: */
138405: SQLITE_API void *sqlite3_commit_hook(
138406:   sqlite3 *db,              /* Attach the hook to this database */
138407:   int (*xCallback)(void*),  /* Function to invoke on each commit */
138408:   void *pArg                /* Argument to the function */
138409: ){
138410:   void *pOld;
138411: 
138412: #ifdef SQLITE_ENABLE_API_ARMOR
138413:   if( !sqlite3SafetyCheckOk(db) ){
138414:     (void)SQLITE_MISUSE_BKPT;
138415:     return 0;
138416:   }
138417: #endif
138418:   sqlite3_mutex_enter(db->mutex);
138419:   pOld = db->pCommitArg;
138420:   db->xCommitCallback = xCallback;
138421:   db->pCommitArg = pArg;
138422:   sqlite3_mutex_leave(db->mutex);
138423:   return pOld;
138424: }
138425: 
138426: /*
138427: ** Register a callback to be invoked each time a row is updated,
138428: ** inserted or deleted using this database connection.
138429: */
138430: SQLITE_API void *sqlite3_update_hook(
138431:   sqlite3 *db,              /* Attach the hook to this database */
138432:   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
138433:   void *pArg                /* Argument to the function */
138434: ){
138435:   void *pRet;
138436: 
138437: #ifdef SQLITE_ENABLE_API_ARMOR
138438:   if( !sqlite3SafetyCheckOk(db) ){
138439:     (void)SQLITE_MISUSE_BKPT;
138440:     return 0;
138441:   }
138442: #endif
138443:   sqlite3_mutex_enter(db->mutex);
138444:   pRet = db->pUpdateArg;
138445:   db->xUpdateCallback = xCallback;
138446:   db->pUpdateArg = pArg;
138447:   sqlite3_mutex_leave(db->mutex);
138448:   return pRet;
138449: }
138450: 
138451: /*
138452: ** Register a callback to be invoked each time a transaction is rolled
138453: ** back by this database connection.
138454: */
138455: SQLITE_API void *sqlite3_rollback_hook(
138456:   sqlite3 *db,              /* Attach the hook to this database */
138457:   void (*xCallback)(void*), /* Callback function */
138458:   void *pArg                /* Argument to the function */
138459: ){
138460:   void *pRet;
138461: 
138462: #ifdef SQLITE_ENABLE_API_ARMOR
138463:   if( !sqlite3SafetyCheckOk(db) ){
138464:     (void)SQLITE_MISUSE_BKPT;
138465:     return 0;
138466:   }
138467: #endif
138468:   sqlite3_mutex_enter(db->mutex);
138469:   pRet = db->pRollbackArg;
138470:   db->xRollbackCallback = xCallback;
138471:   db->pRollbackArg = pArg;
138472:   sqlite3_mutex_leave(db->mutex);
138473:   return pRet;
138474: }
138475: 
138476: #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
138477: /*
138478: ** Register a callback to be invoked each time a row is updated,
138479: ** inserted or deleted using this database connection.
138480: */
138481: SQLITE_API void *sqlite3_preupdate_hook(
138482:   sqlite3 *db,              /* Attach the hook to this database */
138483:   void(*xCallback)(         /* Callback function */
138484:     void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
138485:   void *pArg                /* First callback argument */
138486: ){
138487:   void *pRet;
138488:   sqlite3_mutex_enter(db->mutex);
138489:   pRet = db->pPreUpdateArg;
138490:   db->xPreUpdateCallback = xCallback;
138491:   db->pPreUpdateArg = pArg;
138492:   sqlite3_mutex_leave(db->mutex);
138493:   return pRet;
138494: }
138495: #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
138496: 
138497: #ifndef SQLITE_OMIT_WAL
138498: /*
138499: ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
138500: ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
138501: ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
138502: ** wal_autocheckpoint()).
138503: */ 
138504: SQLITE_PRIVATE int sqlite3WalDefaultHook(
138505:   void *pClientData,     /* Argument */
138506:   sqlite3 *db,           /* Connection */
138507:   const char *zDb,       /* Database */
138508:   int nFrame             /* Size of WAL */
138509: ){
138510:   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
138511:     sqlite3BeginBenignMalloc();
138512:     sqlite3_wal_checkpoint(db, zDb);
138513:     sqlite3EndBenignMalloc();
138514:   }
138515:   return SQLITE_OK;
138516: }
138517: #endif /* SQLITE_OMIT_WAL */
138518: 
138519: /*
138520: ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
138521: ** a database after committing a transaction if there are nFrame or
138522: ** more frames in the log file. Passing zero or a negative value as the
138523: ** nFrame parameter disables automatic checkpoints entirely.
138524: **
138525: ** The callback registered by this function replaces any existing callback
138526: ** registered using sqlite3_wal_hook(). Likewise, registering a callback
138527: ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
138528: ** configured by this function.
138529: */
138530: SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
138531: #ifdef SQLITE_OMIT_WAL
138532:   UNUSED_PARAMETER(db);
138533:   UNUSED_PARAMETER(nFrame);
138534: #else
138535: #ifdef SQLITE_ENABLE_API_ARMOR
138536:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138537: #endif
138538:   if( nFrame>0 ){
138539:     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
138540:   }else{
138541:     sqlite3_wal_hook(db, 0, 0);
138542:   }
138543: #endif
138544:   return SQLITE_OK;
138545: }
138546: 
138547: /*
138548: ** Register a callback to be invoked each time a transaction is written
138549: ** into the write-ahead-log by this database connection.
138550: */
138551: SQLITE_API void *sqlite3_wal_hook(
138552:   sqlite3 *db,                    /* Attach the hook to this db handle */
138553:   int(*xCallback)(void *, sqlite3*, const char*, int),
138554:   void *pArg                      /* First argument passed to xCallback() */
138555: ){
138556: #ifndef SQLITE_OMIT_WAL
138557:   void *pRet;
138558: #ifdef SQLITE_ENABLE_API_ARMOR
138559:   if( !sqlite3SafetyCheckOk(db) ){
138560:     (void)SQLITE_MISUSE_BKPT;
138561:     return 0;
138562:   }
138563: #endif
138564:   sqlite3_mutex_enter(db->mutex);
138565:   pRet = db->pWalArg;
138566:   db->xWalCallback = xCallback;
138567:   db->pWalArg = pArg;
138568:   sqlite3_mutex_leave(db->mutex);
138569:   return pRet;
138570: #else
138571:   return 0;
138572: #endif
138573: }
138574: 
138575: /*
138576: ** Checkpoint database zDb.
138577: */
138578: SQLITE_API int sqlite3_wal_checkpoint_v2(
138579:   sqlite3 *db,                    /* Database handle */
138580:   const char *zDb,                /* Name of attached database (or NULL) */
138581:   int eMode,                      /* SQLITE_CHECKPOINT_* value */
138582:   int *pnLog,                     /* OUT: Size of WAL log in frames */
138583:   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
138584: ){
138585: #ifdef SQLITE_OMIT_WAL
138586:   return SQLITE_OK;
138587: #else
138588:   int rc;                         /* Return code */
138589:   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
138590: 
138591: #ifdef SQLITE_ENABLE_API_ARMOR
138592:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138593: #endif
138594: 
138595:   /* Initialize the output variables to -1 in case an error occurs. */
138596:   if( pnLog ) *pnLog = -1;
138597:   if( pnCkpt ) *pnCkpt = -1;
138598: 
138599:   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
138600:   assert( SQLITE_CHECKPOINT_FULL==1 );
138601:   assert( SQLITE_CHECKPOINT_RESTART==2 );
138602:   assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
138603:   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
138604:     /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
138605:     ** mode: */
138606:     return SQLITE_MISUSE;
138607:   }
138608: 
138609:   sqlite3_mutex_enter(db->mutex);
138610:   if( zDb && zDb[0] ){
138611:     iDb = sqlite3FindDbName(db, zDb);
138612:   }
138613:   if( iDb<0 ){
138614:     rc = SQLITE_ERROR;
138615:     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
138616:   }else{
138617:     db->busyHandler.nBusy = 0;
138618:     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
138619:     sqlite3Error(db, rc);
138620:   }
138621:   rc = sqlite3ApiExit(db, rc);
138622:   sqlite3_mutex_leave(db->mutex);
138623:   return rc;
138624: #endif
138625: }
138626: 
138627: 
138628: /*
138629: ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
138630: ** to contains a zero-length string, all attached databases are 
138631: ** checkpointed.
138632: */
138633: SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
138634:   /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
138635:   ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
138636:   return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
138637: }
138638: 
138639: #ifndef SQLITE_OMIT_WAL
138640: /*
138641: ** Run a checkpoint on database iDb. This is a no-op if database iDb is
138642: ** not currently open in WAL mode.
138643: **
138644: ** If a transaction is open on the database being checkpointed, this 
138645: ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
138646: ** an error occurs while running the checkpoint, an SQLite error code is 
138647: ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
138648: **
138649: ** The mutex on database handle db should be held by the caller. The mutex
138650: ** associated with the specific b-tree being checkpointed is taken by
138651: ** this function while the checkpoint is running.
138652: **
138653: ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
138654: ** checkpointed. If an error is encountered it is returned immediately -
138655: ** no attempt is made to checkpoint any remaining databases.
138656: **
138657: ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
138658: */
138659: SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
138660:   int rc = SQLITE_OK;             /* Return code */
138661:   int i;                          /* Used to iterate through attached dbs */
138662:   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
138663: 
138664:   assert( sqlite3_mutex_held(db->mutex) );
138665:   assert( !pnLog || *pnLog==-1 );
138666:   assert( !pnCkpt || *pnCkpt==-1 );
138667: 
138668:   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
138669:     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
138670:       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
138671:       pnLog = 0;
138672:       pnCkpt = 0;
138673:       if( rc==SQLITE_BUSY ){
138674:         bBusy = 1;
138675:         rc = SQLITE_OK;
138676:       }
138677:     }
138678:   }
138679: 
138680:   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
138681: }
138682: #endif /* SQLITE_OMIT_WAL */
138683: 
138684: /*
138685: ** This function returns true if main-memory should be used instead of
138686: ** a temporary file for transient pager files and statement journals.
138687: ** The value returned depends on the value of db->temp_store (runtime
138688: ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
138689: ** following table describes the relationship between these two values
138690: ** and this functions return value.
138691: **
138692: **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
138693: **   -----------------     --------------     ------------------------------
138694: **   0                     any                file      (return 0)
138695: **   1                     1                  file      (return 0)
138696: **   1                     2                  memory    (return 1)
138697: **   1                     0                  file      (return 0)
138698: **   2                     1                  file      (return 0)
138699: **   2                     2                  memory    (return 1)
138700: **   2                     0                  memory    (return 1)
138701: **   3                     any                memory    (return 1)
138702: */
138703: SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
138704: #if SQLITE_TEMP_STORE==1
138705:   return ( db->temp_store==2 );
138706: #endif
138707: #if SQLITE_TEMP_STORE==2
138708:   return ( db->temp_store!=1 );
138709: #endif
138710: #if SQLITE_TEMP_STORE==3
138711:   UNUSED_PARAMETER(db);
138712:   return 1;
138713: #endif
138714: #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
138715:   UNUSED_PARAMETER(db);
138716:   return 0;
138717: #endif
138718: }
138719: 
138720: /*
138721: ** Return UTF-8 encoded English language explanation of the most recent
138722: ** error.
138723: */
138724: SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
138725:   const char *z;
138726:   if( !db ){
138727:     return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
138728:   }
138729:   if( !sqlite3SafetyCheckSickOrOk(db) ){
138730:     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
138731:   }
138732:   sqlite3_mutex_enter(db->mutex);
138733:   if( db->mallocFailed ){
138734:     z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
138735:   }else{
138736:     testcase( db->pErr==0 );
138737:     z = (char*)sqlite3_value_text(db->pErr);
138738:     assert( !db->mallocFailed );
138739:     if( z==0 ){
138740:       z = sqlite3ErrStr(db->errCode);
138741:     }
138742:   }
138743:   sqlite3_mutex_leave(db->mutex);
138744:   return z;
138745: }
138746: 
138747: #ifndef SQLITE_OMIT_UTF16
138748: /*
138749: ** Return UTF-16 encoded English language explanation of the most recent
138750: ** error.
138751: */
138752: SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
138753:   static const u16 outOfMem[] = {
138754:     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
138755:   };
138756:   static const u16 misuse[] = {
138757:     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
138758:     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
138759:     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
138760:     'o', 'u', 't', ' ', 
138761:     'o', 'f', ' ', 
138762:     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
138763:   };
138764: 
138765:   const void *z;
138766:   if( !db ){
138767:     return (void *)outOfMem;
138768:   }
138769:   if( !sqlite3SafetyCheckSickOrOk(db) ){
138770:     return (void *)misuse;
138771:   }
138772:   sqlite3_mutex_enter(db->mutex);
138773:   if( db->mallocFailed ){
138774:     z = (void *)outOfMem;
138775:   }else{
138776:     z = sqlite3_value_text16(db->pErr);
138777:     if( z==0 ){
138778:       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
138779:       z = sqlite3_value_text16(db->pErr);
138780:     }
138781:     /* A malloc() may have failed within the call to sqlite3_value_text16()
138782:     ** above. If this is the case, then the db->mallocFailed flag needs to
138783:     ** be cleared before returning. Do this directly, instead of via
138784:     ** sqlite3ApiExit(), to avoid setting the database handle error message.
138785:     */
138786:     sqlite3OomClear(db);
138787:   }
138788:   sqlite3_mutex_leave(db->mutex);
138789:   return z;
138790: }
138791: #endif /* SQLITE_OMIT_UTF16 */
138792: 
138793: /*
138794: ** Return the most recent error code generated by an SQLite routine. If NULL is
138795: ** passed to this function, we assume a malloc() failed during sqlite3_open().
138796: */
138797: SQLITE_API int sqlite3_errcode(sqlite3 *db){
138798:   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
138799:     return SQLITE_MISUSE_BKPT;
138800:   }
138801:   if( !db || db->mallocFailed ){
138802:     return SQLITE_NOMEM_BKPT;
138803:   }
138804:   return db->errCode & db->errMask;
138805: }
138806: SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
138807:   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
138808:     return SQLITE_MISUSE_BKPT;
138809:   }
138810:   if( !db || db->mallocFailed ){
138811:     return SQLITE_NOMEM_BKPT;
138812:   }
138813:   return db->errCode;
138814: }
138815: SQLITE_API int sqlite3_system_errno(sqlite3 *db){
138816:   return db ? db->iSysErrno : 0;
138817: }  
138818: 
138819: /*
138820: ** Return a string that describes the kind of error specified in the
138821: ** argument.  For now, this simply calls the internal sqlite3ErrStr()
138822: ** function.
138823: */
138824: SQLITE_API const char *sqlite3_errstr(int rc){
138825:   return sqlite3ErrStr(rc);
138826: }
138827: 
138828: /*
138829: ** Create a new collating function for database "db".  The name is zName
138830: ** and the encoding is enc.
138831: */
138832: static int createCollation(
138833:   sqlite3* db,
138834:   const char *zName, 
138835:   u8 enc,
138836:   void* pCtx,
138837:   int(*xCompare)(void*,int,const void*,int,const void*),
138838:   void(*xDel)(void*)
138839: ){
138840:   CollSeq *pColl;
138841:   int enc2;
138842:   
138843:   assert( sqlite3_mutex_held(db->mutex) );
138844: 
138845:   /* If SQLITE_UTF16 is specified as the encoding type, transform this
138846:   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
138847:   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
138848:   */
138849:   enc2 = enc;
138850:   testcase( enc2==SQLITE_UTF16 );
138851:   testcase( enc2==SQLITE_UTF16_ALIGNED );
138852:   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
138853:     enc2 = SQLITE_UTF16NATIVE;
138854:   }
138855:   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
138856:     return SQLITE_MISUSE_BKPT;
138857:   }
138858: 
138859:   /* Check if this call is removing or replacing an existing collation 
138860:   ** sequence. If so, and there are active VMs, return busy. If there
138861:   ** are no active VMs, invalidate any pre-compiled statements.
138862:   */
138863:   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
138864:   if( pColl && pColl->xCmp ){
138865:     if( db->nVdbeActive ){
138866:       sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
138867:         "unable to delete/modify collation sequence due to active statements");
138868:       return SQLITE_BUSY;
138869:     }
138870:     sqlite3ExpirePreparedStatements(db);
138871: 
138872:     /* If collation sequence pColl was created directly by a call to
138873:     ** sqlite3_create_collation, and not generated by synthCollSeq(),
138874:     ** then any copies made by synthCollSeq() need to be invalidated.
138875:     ** Also, collation destructor - CollSeq.xDel() - function may need
138876:     ** to be called.
138877:     */ 
138878:     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
138879:       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
138880:       int j;
138881:       for(j=0; j<3; j++){
138882:         CollSeq *p = &aColl[j];
138883:         if( p->enc==pColl->enc ){
138884:           if( p->xDel ){
138885:             p->xDel(p->pUser);
138886:           }
138887:           p->xCmp = 0;
138888:         }
138889:       }
138890:     }
138891:   }
138892: 
138893:   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
138894:   if( pColl==0 ) return SQLITE_NOMEM_BKPT;
138895:   pColl->xCmp = xCompare;
138896:   pColl->pUser = pCtx;
138897:   pColl->xDel = xDel;
138898:   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
138899:   sqlite3Error(db, SQLITE_OK);
138900:   return SQLITE_OK;
138901: }
138902: 
138903: 
138904: /*
138905: ** This array defines hard upper bounds on limit values.  The
138906: ** initializer must be kept in sync with the SQLITE_LIMIT_*
138907: ** #defines in sqlite3.h.
138908: */
138909: static const int aHardLimit[] = {
138910:   SQLITE_MAX_LENGTH,
138911:   SQLITE_MAX_SQL_LENGTH,
138912:   SQLITE_MAX_COLUMN,
138913:   SQLITE_MAX_EXPR_DEPTH,
138914:   SQLITE_MAX_COMPOUND_SELECT,
138915:   SQLITE_MAX_VDBE_OP,
138916:   SQLITE_MAX_FUNCTION_ARG,
138917:   SQLITE_MAX_ATTACHED,
138918:   SQLITE_MAX_LIKE_PATTERN_LENGTH,
138919:   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
138920:   SQLITE_MAX_TRIGGER_DEPTH,
138921:   SQLITE_MAX_WORKER_THREADS,
138922: };
138923: 
138924: /*
138925: ** Make sure the hard limits are set to reasonable values
138926: */
138927: #if SQLITE_MAX_LENGTH<100
138928: # error SQLITE_MAX_LENGTH must be at least 100
138929: #endif
138930: #if SQLITE_MAX_SQL_LENGTH<100
138931: # error SQLITE_MAX_SQL_LENGTH must be at least 100
138932: #endif
138933: #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
138934: # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
138935: #endif
138936: #if SQLITE_MAX_COMPOUND_SELECT<2
138937: # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
138938: #endif
138939: #if SQLITE_MAX_VDBE_OP<40
138940: # error SQLITE_MAX_VDBE_OP must be at least 40
138941: #endif
138942: #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
138943: # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
138944: #endif
138945: #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
138946: # error SQLITE_MAX_ATTACHED must be between 0 and 125
138947: #endif
138948: #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
138949: # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
138950: #endif
138951: #if SQLITE_MAX_COLUMN>32767
138952: # error SQLITE_MAX_COLUMN must not exceed 32767
138953: #endif
138954: #if SQLITE_MAX_TRIGGER_DEPTH<1
138955: # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
138956: #endif
138957: #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
138958: # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
138959: #endif
138960: 
138961: 
138962: /*
138963: ** Change the value of a limit.  Report the old value.
138964: ** If an invalid limit index is supplied, report -1.
138965: ** Make no changes but still report the old value if the
138966: ** new limit is negative.
138967: **
138968: ** A new lower limit does not shrink existing constructs.
138969: ** It merely prevents new constructs that exceed the limit
138970: ** from forming.
138971: */
138972: SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
138973:   int oldLimit;
138974: 
138975: #ifdef SQLITE_ENABLE_API_ARMOR
138976:   if( !sqlite3SafetyCheckOk(db) ){
138977:     (void)SQLITE_MISUSE_BKPT;
138978:     return -1;
138979:   }
138980: #endif
138981: 
138982:   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
138983:   ** there is a hard upper bound set at compile-time by a C preprocessor
138984:   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
138985:   ** "_MAX_".)
138986:   */
138987:   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
138988:   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
138989:   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
138990:   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
138991:   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
138992:   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
138993:   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
138994:   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
138995:   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
138996:                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
138997:   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
138998:   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
138999:   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
139000:   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
139001: 
139002: 
139003:   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
139004:     return -1;
139005:   }
139006:   oldLimit = db->aLimit[limitId];
139007:   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
139008:     if( newLimit>aHardLimit[limitId] ){
139009:       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
139010:     }
139011:     db->aLimit[limitId] = newLimit;
139012:   }
139013:   return oldLimit;                     /* IMP: R-53341-35419 */
139014: }
139015: 
139016: /*
139017: ** This function is used to parse both URIs and non-URI filenames passed by the
139018: ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
139019: ** URIs specified as part of ATTACH statements.
139020: **
139021: ** The first argument to this function is the name of the VFS to use (or
139022: ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
139023: ** query parameter. The second argument contains the URI (or non-URI filename)
139024: ** itself. When this function is called the *pFlags variable should contain
139025: ** the default flags to open the database handle with. The value stored in
139026: ** *pFlags may be updated before returning if the URI filename contains 
139027: ** "cache=xxx" or "mode=xxx" query parameters.
139028: **
139029: ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
139030: ** the VFS that should be used to open the database file. *pzFile is set to
139031: ** point to a buffer containing the name of the file to open. It is the 
139032: ** responsibility of the caller to eventually call sqlite3_free() to release
139033: ** this buffer.
139034: **
139035: ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
139036: ** may be set to point to a buffer containing an English language error 
139037: ** message. It is the responsibility of the caller to eventually release
139038: ** this buffer by calling sqlite3_free().
139039: */
139040: SQLITE_PRIVATE int sqlite3ParseUri(
139041:   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
139042:   const char *zUri,               /* Nul-terminated URI to parse */
139043:   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
139044:   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
139045:   char **pzFile,                  /* OUT: Filename component of URI */
139046:   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
139047: ){
139048:   int rc = SQLITE_OK;
139049:   unsigned int flags = *pFlags;
139050:   const char *zVfs = zDefaultVfs;
139051:   char *zFile;
139052:   char c;
139053:   int nUri = sqlite3Strlen30(zUri);
139054: 
139055:   assert( *pzErrMsg==0 );
139056: 
139057:   if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
139058:             || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
139059:    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
139060:   ){
139061:     char *zOpt;
139062:     int eState;                   /* Parser state when parsing URI */
139063:     int iIn;                      /* Input character index */
139064:     int iOut = 0;                 /* Output character index */
139065:     u64 nByte = nUri+2;           /* Bytes of space to allocate */
139066: 
139067:     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
139068:     ** method that there may be extra parameters following the file-name.  */
139069:     flags |= SQLITE_OPEN_URI;
139070: 
139071:     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
139072:     zFile = sqlite3_malloc64(nByte);
139073:     if( !zFile ) return SQLITE_NOMEM_BKPT;
139074: 
139075:     iIn = 5;
139076: #ifdef SQLITE_ALLOW_URI_AUTHORITY
139077:     if( strncmp(zUri+5, "///", 3)==0 ){
139078:       iIn = 7;
139079:       /* The following condition causes URIs with five leading / characters
139080:       ** like file://///host/path to be converted into UNCs like //host/path.
139081:       ** The correct URI for that UNC has only two or four leading / characters
139082:       ** file://host/path or file:////host/path.  But 5 leading slashes is a 
139083:       ** common error, we are told, so we handle it as a special case. */
139084:       if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
139085:     }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
139086:       iIn = 16;
139087:     }
139088: #else
139089:     /* Discard the scheme and authority segments of the URI. */
139090:     if( zUri[5]=='/' && zUri[6]=='/' ){
139091:       iIn = 7;
139092:       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
139093:       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
139094:         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
139095:             iIn-7, &zUri[7]);
139096:         rc = SQLITE_ERROR;
139097:         goto parse_uri_out;
139098:       }
139099:     }
139100: #endif
139101: 
139102:     /* Copy the filename and any query parameters into the zFile buffer. 
139103:     ** Decode %HH escape codes along the way. 
139104:     **
139105:     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
139106:     ** on the parsing context. As follows:
139107:     **
139108:     **   0: Parsing file-name.
139109:     **   1: Parsing name section of a name=value query parameter.
139110:     **   2: Parsing value section of a name=value query parameter.
139111:     */
139112:     eState = 0;
139113:     while( (c = zUri[iIn])!=0 && c!='#' ){
139114:       iIn++;
139115:       if( c=='%' 
139116:        && sqlite3Isxdigit(zUri[iIn]) 
139117:        && sqlite3Isxdigit(zUri[iIn+1]) 
139118:       ){
139119:         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
139120:         octet += sqlite3HexToInt(zUri[iIn++]);
139121: 
139122:         assert( octet>=0 && octet<256 );
139123:         if( octet==0 ){
139124:           /* This branch is taken when "%00" appears within the URI. In this
139125:           ** case we ignore all text in the remainder of the path, name or
139126:           ** value currently being parsed. So ignore the current character
139127:           ** and skip to the next "?", "=" or "&", as appropriate. */
139128:           while( (c = zUri[iIn])!=0 && c!='#' 
139129:               && (eState!=0 || c!='?')
139130:               && (eState!=1 || (c!='=' && c!='&'))
139131:               && (eState!=2 || c!='&')
139132:           ){
139133:             iIn++;
139134:           }
139135:           continue;
139136:         }
139137:         c = octet;
139138:       }else if( eState==1 && (c=='&' || c=='=') ){
139139:         if( zFile[iOut-1]==0 ){
139140:           /* An empty option name. Ignore this option altogether. */
139141:           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
139142:           continue;
139143:         }
139144:         if( c=='&' ){
139145:           zFile[iOut++] = '\0';
139146:         }else{
139147:           eState = 2;
139148:         }
139149:         c = 0;
139150:       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
139151:         c = 0;
139152:         eState = 1;
139153:       }
139154:       zFile[iOut++] = c;
139155:     }
139156:     if( eState==1 ) zFile[iOut++] = '\0';
139157:     zFile[iOut++] = '\0';
139158:     zFile[iOut++] = '\0';
139159: 
139160:     /* Check if there were any options specified that should be interpreted 
139161:     ** here. Options that are interpreted here include "vfs" and those that
139162:     ** correspond to flags that may be passed to the sqlite3_open_v2()
139163:     ** method. */
139164:     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
139165:     while( zOpt[0] ){
139166:       int nOpt = sqlite3Strlen30(zOpt);
139167:       char *zVal = &zOpt[nOpt+1];
139168:       int nVal = sqlite3Strlen30(zVal);
139169: 
139170:       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
139171:         zVfs = zVal;
139172:       }else{
139173:         struct OpenMode {
139174:           const char *z;
139175:           int mode;
139176:         } *aMode = 0;
139177:         char *zModeType = 0;
139178:         int mask = 0;
139179:         int limit = 0;
139180: 
139181:         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
139182:           static struct OpenMode aCacheMode[] = {
139183:             { "shared",  SQLITE_OPEN_SHAREDCACHE },
139184:             { "private", SQLITE_OPEN_PRIVATECACHE },
139185:             { 0, 0 }
139186:           };
139187: 
139188:           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
139189:           aMode = aCacheMode;
139190:           limit = mask;
139191:           zModeType = "cache";
139192:         }
139193:         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
139194:           static struct OpenMode aOpenMode[] = {
139195:             { "ro",  SQLITE_OPEN_READONLY },
139196:             { "rw",  SQLITE_OPEN_READWRITE }, 
139197:             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
139198:             { "memory", SQLITE_OPEN_MEMORY },
139199:             { 0, 0 }
139200:           };
139201: 
139202:           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
139203:                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
139204:           aMode = aOpenMode;
139205:           limit = mask & flags;
139206:           zModeType = "access";
139207:         }
139208: 
139209:         if( aMode ){
139210:           int i;
139211:           int mode = 0;
139212:           for(i=0; aMode[i].z; i++){
139213:             const char *z = aMode[i].z;
139214:             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
139215:               mode = aMode[i].mode;
139216:               break;
139217:             }
139218:           }
139219:           if( mode==0 ){
139220:             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
139221:             rc = SQLITE_ERROR;
139222:             goto parse_uri_out;
139223:           }
139224:           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
139225:             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
139226:                                         zModeType, zVal);
139227:             rc = SQLITE_PERM;
139228:             goto parse_uri_out;
139229:           }
139230:           flags = (flags & ~mask) | mode;
139231:         }
139232:       }
139233: 
139234:       zOpt = &zVal[nVal+1];
139235:     }
139236: 
139237:   }else{
139238:     zFile = sqlite3_malloc64(nUri+2);
139239:     if( !zFile ) return SQLITE_NOMEM_BKPT;
139240:     memcpy(zFile, zUri, nUri);
139241:     zFile[nUri] = '\0';
139242:     zFile[nUri+1] = '\0';
139243:     flags &= ~SQLITE_OPEN_URI;
139244:   }
139245: 
139246:   *ppVfs = sqlite3_vfs_find(zVfs);
139247:   if( *ppVfs==0 ){
139248:     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
139249:     rc = SQLITE_ERROR;
139250:   }
139251:  parse_uri_out:
139252:   if( rc!=SQLITE_OK ){
139253:     sqlite3_free(zFile);
139254:     zFile = 0;
139255:   }
139256:   *pFlags = flags;
139257:   *pzFile = zFile;
139258:   return rc;
139259: }
139260: 
139261: 
139262: /*
139263: ** This routine does the work of opening a database on behalf of
139264: ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
139265: ** is UTF-8 encoded.
139266: */
139267: static int openDatabase(
139268:   const char *zFilename, /* Database filename UTF-8 encoded */
139269:   sqlite3 **ppDb,        /* OUT: Returned database handle */
139270:   unsigned int flags,    /* Operational flags */
139271:   const char *zVfs       /* Name of the VFS to use */
139272: ){
139273:   sqlite3 *db;                    /* Store allocated handle here */
139274:   int rc;                         /* Return code */
139275:   int isThreadsafe;               /* True for threadsafe connections */
139276:   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
139277:   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
139278: 
139279: #ifdef SQLITE_ENABLE_API_ARMOR
139280:   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
139281: #endif
139282:   *ppDb = 0;
139283: #ifndef SQLITE_OMIT_AUTOINIT
139284:   rc = sqlite3_initialize();
139285:   if( rc ) return rc;
139286: #endif
139287: 
139288:   /* Only allow sensible combinations of bits in the flags argument.  
139289:   ** Throw an error if any non-sense combination is used.  If we
139290:   ** do not block illegal combinations here, it could trigger
139291:   ** assert() statements in deeper layers.  Sensible combinations
139292:   ** are:
139293:   **
139294:   **  1:  SQLITE_OPEN_READONLY
139295:   **  2:  SQLITE_OPEN_READWRITE
139296:   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
139297:   */
139298:   assert( SQLITE_OPEN_READONLY  == 0x01 );
139299:   assert( SQLITE_OPEN_READWRITE == 0x02 );
139300:   assert( SQLITE_OPEN_CREATE    == 0x04 );
139301:   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
139302:   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
139303:   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
139304:   if( ((1<<(flags&7)) & 0x46)==0 ){
139305:     return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
139306:   }
139307: 
139308:   if( sqlite3GlobalConfig.bCoreMutex==0 ){
139309:     isThreadsafe = 0;
139310:   }else if( flags & SQLITE_OPEN_NOMUTEX ){
139311:     isThreadsafe = 0;
139312:   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
139313:     isThreadsafe = 1;
139314:   }else{
139315:     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
139316:   }
139317:   if( flags & SQLITE_OPEN_PRIVATECACHE ){
139318:     flags &= ~SQLITE_OPEN_SHAREDCACHE;
139319:   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
139320:     flags |= SQLITE_OPEN_SHAREDCACHE;
139321:   }
139322: 
139323:   /* Remove harmful bits from the flags parameter
139324:   **
139325:   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
139326:   ** dealt with in the previous code block.  Besides these, the only
139327:   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
139328:   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
139329:   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
139330:   ** off all other flags.
139331:   */
139332:   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
139333:                SQLITE_OPEN_EXCLUSIVE |
139334:                SQLITE_OPEN_MAIN_DB |
139335:                SQLITE_OPEN_TEMP_DB | 
139336:                SQLITE_OPEN_TRANSIENT_DB | 
139337:                SQLITE_OPEN_MAIN_JOURNAL | 
139338:                SQLITE_OPEN_TEMP_JOURNAL | 
139339:                SQLITE_OPEN_SUBJOURNAL | 
139340:                SQLITE_OPEN_MASTER_JOURNAL |
139341:                SQLITE_OPEN_NOMUTEX |
139342:                SQLITE_OPEN_FULLMUTEX |
139343:                SQLITE_OPEN_WAL
139344:              );
139345: 
139346:   /* Allocate the sqlite data structure */
139347:   db = sqlite3MallocZero( sizeof(sqlite3) );
139348:   if( db==0 ) goto opendb_out;
139349:   if( isThreadsafe ){
139350:     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
139351:     if( db->mutex==0 ){
139352:       sqlite3_free(db);
139353:       db = 0;
139354:       goto opendb_out;
139355:     }
139356:   }
139357:   sqlite3_mutex_enter(db->mutex);
139358:   db->errMask = 0xff;
139359:   db->nDb = 2;
139360:   db->magic = SQLITE_MAGIC_BUSY;
139361:   db->aDb = db->aDbStatic;
139362: 
139363:   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
139364:   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
139365:   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
139366:   db->autoCommit = 1;
139367:   db->nextAutovac = -1;
139368:   db->szMmap = sqlite3GlobalConfig.szMmap;
139369:   db->nextPagesize = 0;
139370:   db->nMaxSorterMmap = 0x7FFFFFFF;
139371:   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
139372: #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
139373:                  | SQLITE_AutoIndex
139374: #endif
139375: #if SQLITE_DEFAULT_CKPTFULLFSYNC
139376:                  | SQLITE_CkptFullFSync
139377: #endif
139378: #if SQLITE_DEFAULT_FILE_FORMAT<4
139379:                  | SQLITE_LegacyFileFmt
139380: #endif
139381: #ifdef SQLITE_ENABLE_LOAD_EXTENSION
139382:                  | SQLITE_LoadExtension
139383: #endif
139384: #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
139385:                  | SQLITE_RecTriggers
139386: #endif
139387: #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
139388:                  | SQLITE_ForeignKeys
139389: #endif
139390: #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
139391:                  | SQLITE_ReverseOrder
139392: #endif
139393: #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
139394:                  | SQLITE_CellSizeCk
139395: #endif
139396: #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
139397:                  | SQLITE_Fts3Tokenizer
139398: #endif
139399:       ;
139400:   sqlite3HashInit(&db->aCollSeq);
139401: #ifndef SQLITE_OMIT_VIRTUALTABLE
139402:   sqlite3HashInit(&db->aModule);
139403: #endif
139404: 
139405:   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
139406:   ** and UTF-16, so add a version for each to avoid any unnecessary
139407:   ** conversions. The only error that can occur here is a malloc() failure.
139408:   **
139409:   ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
139410:   ** functions:
139411:   */
139412:   createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
139413:   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
139414:   createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
139415:   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
139416:   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
139417:   if( db->mallocFailed ){
139418:     goto opendb_out;
139419:   }
139420:   /* EVIDENCE-OF: R-08308-17224 The default collating function for all
139421:   ** strings is BINARY. 
139422:   */
139423:   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
139424:   assert( db->pDfltColl!=0 );
139425: 
139426:   /* Parse the filename/URI argument. */
139427:   db->openFlags = flags;
139428:   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
139429:   if( rc!=SQLITE_OK ){
139430:     if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
139431:     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
139432:     sqlite3_free(zErrMsg);
139433:     goto opendb_out;
139434:   }
139435: 
139436:   /* Open the backend database driver */
139437:   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
139438:                         flags | SQLITE_OPEN_MAIN_DB);
139439:   if( rc!=SQLITE_OK ){
139440:     if( rc==SQLITE_IOERR_NOMEM ){
139441:       rc = SQLITE_NOMEM_BKPT;
139442:     }
139443:     sqlite3Error(db, rc);
139444:     goto opendb_out;
139445:   }
139446:   sqlite3BtreeEnter(db->aDb[0].pBt);
139447:   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
139448:   if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
139449:   sqlite3BtreeLeave(db->aDb[0].pBt);
139450:   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
139451: 
139452:   /* The default safety_level for the main database is FULL; for the temp
139453:   ** database it is OFF. This matches the pager layer defaults.  
139454:   */
139455:   db->aDb[0].zName = "main";
139456:   db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
139457:   db->aDb[1].zName = "temp";
139458:   db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
139459: 
139460:   db->magic = SQLITE_MAGIC_OPEN;
139461:   if( db->mallocFailed ){
139462:     goto opendb_out;
139463:   }
139464: 
139465:   /* Register all built-in functions, but do not attempt to read the
139466:   ** database schema yet. This is delayed until the first time the database
139467:   ** is accessed.
139468:   */
139469:   sqlite3Error(db, SQLITE_OK);
139470:   sqlite3RegisterPerConnectionBuiltinFunctions(db);
139471: 
139472:   /* Load automatic extensions - extensions that have been registered
139473:   ** using the sqlite3_automatic_extension() API.
139474:   */
139475:   rc = sqlite3_errcode(db);
139476:   if( rc==SQLITE_OK ){
139477:     sqlite3AutoLoadExtensions(db);
139478:     rc = sqlite3_errcode(db);
139479:     if( rc!=SQLITE_OK ){
139480:       goto opendb_out;
139481:     }
139482:   }
139483: 
139484: #ifdef SQLITE_ENABLE_FTS1
139485:   if( !db->mallocFailed ){
139486:     extern int sqlite3Fts1Init(sqlite3*);
139487:     rc = sqlite3Fts1Init(db);
139488:   }
139489: #endif
139490: 
139491: #ifdef SQLITE_ENABLE_FTS2
139492:   if( !db->mallocFailed && rc==SQLITE_OK ){
139493:     extern int sqlite3Fts2Init(sqlite3*);
139494:     rc = sqlite3Fts2Init(db);
139495:   }
139496: #endif
139497: 
139498: #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
139499:   if( !db->mallocFailed && rc==SQLITE_OK ){
139500:     rc = sqlite3Fts3Init(db);
139501:   }
139502: #endif
139503: 
139504: #ifdef SQLITE_ENABLE_FTS5
139505:   if( !db->mallocFailed && rc==SQLITE_OK ){
139506:     rc = sqlite3Fts5Init(db);
139507:   }
139508: #endif
139509: 
139510: #ifdef SQLITE_ENABLE_ICU
139511:   if( !db->mallocFailed && rc==SQLITE_OK ){
139512:     rc = sqlite3IcuInit(db);
139513:   }
139514: #endif
139515: 
139516: #ifdef SQLITE_ENABLE_RTREE
139517:   if( !db->mallocFailed && rc==SQLITE_OK){
139518:     rc = sqlite3RtreeInit(db);
139519:   }
139520: #endif
139521: 
139522: #ifdef SQLITE_ENABLE_DBSTAT_VTAB
139523:   if( !db->mallocFailed && rc==SQLITE_OK){
139524:     rc = sqlite3DbstatRegister(db);
139525:   }
139526: #endif
139527: 
139528: #ifdef SQLITE_ENABLE_JSON1
139529:   if( !db->mallocFailed && rc==SQLITE_OK){
139530:     rc = sqlite3Json1Init(db);
139531:   }
139532: #endif
139533: 
139534:   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
139535:   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
139536:   ** mode.  Doing nothing at all also makes NORMAL the default.
139537:   */
139538: #ifdef SQLITE_DEFAULT_LOCKING_MODE
139539:   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
139540:   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
139541:                           SQLITE_DEFAULT_LOCKING_MODE);
139542: #endif
139543: 
139544:   if( rc ) sqlite3Error(db, rc);
139545: 
139546:   /* Enable the lookaside-malloc subsystem */
139547:   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
139548:                         sqlite3GlobalConfig.nLookaside);
139549: 
139550:   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
139551: 
139552: opendb_out:
139553:   if( db ){
139554:     assert( db->mutex!=0 || isThreadsafe==0
139555:            || sqlite3GlobalConfig.bFullMutex==0 );
139556:     sqlite3_mutex_leave(db->mutex);
139557:   }
139558:   rc = sqlite3_errcode(db);
139559:   assert( db!=0 || rc==SQLITE_NOMEM );
139560:   if( rc==SQLITE_NOMEM ){
139561:     sqlite3_close(db);
139562:     db = 0;
139563:   }else if( rc!=SQLITE_OK ){
139564:     db->magic = SQLITE_MAGIC_SICK;
139565:   }
139566:   *ppDb = db;
139567: #ifdef SQLITE_ENABLE_SQLLOG
139568:   if( sqlite3GlobalConfig.xSqllog ){
139569:     /* Opening a db handle. Fourth parameter is passed 0. */
139570:     void *pArg = sqlite3GlobalConfig.pSqllogArg;
139571:     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
139572:   }
139573: #endif
139574: #if defined(SQLITE_HAS_CODEC)
139575:   if( rc==SQLITE_OK ){
139576:     const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
139577:     if( zHexKey && zHexKey[0] ){
139578:       u8 iByte;
139579:       int i;
139580:       char zKey[40];
139581:       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
139582:         iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
139583:         if( (i&1)!=0 ) zKey[i/2] = iByte;
139584:       }
139585:       sqlite3_key_v2(db, 0, zKey, i/2);
139586:     }
139587:   }
139588: #endif
139589:   sqlite3_free(zOpen);
139590:   return rc & 0xff;
139591: }
139592: 
139593: /*
139594: ** Open a new database handle.
139595: */
139596: SQLITE_API int sqlite3_open(
139597:   const char *zFilename, 
139598:   sqlite3 **ppDb 
139599: ){
139600:   return openDatabase(zFilename, ppDb,
139601:                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
139602: }
139603: SQLITE_API int sqlite3_open_v2(
139604:   const char *filename,   /* Database filename (UTF-8) */
139605:   sqlite3 **ppDb,         /* OUT: SQLite db handle */
139606:   int flags,              /* Flags */
139607:   const char *zVfs        /* Name of VFS module to use */
139608: ){
139609:   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
139610: }
139611: 
139612: #ifndef SQLITE_OMIT_UTF16
139613: /*
139614: ** Open a new database handle.
139615: */
139616: SQLITE_API int sqlite3_open16(
139617:   const void *zFilename, 
139618:   sqlite3 **ppDb
139619: ){
139620:   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
139621:   sqlite3_value *pVal;
139622:   int rc;
139623: 
139624: #ifdef SQLITE_ENABLE_API_ARMOR
139625:   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
139626: #endif
139627:   *ppDb = 0;
139628: #ifndef SQLITE_OMIT_AUTOINIT
139629:   rc = sqlite3_initialize();
139630:   if( rc ) return rc;
139631: #endif
139632:   if( zFilename==0 ) zFilename = "\000\000";
139633:   pVal = sqlite3ValueNew(0);
139634:   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
139635:   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
139636:   if( zFilename8 ){
139637:     rc = openDatabase(zFilename8, ppDb,
139638:                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
139639:     assert( *ppDb || rc==SQLITE_NOMEM );
139640:     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
139641:       SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
139642:     }
139643:   }else{
139644:     rc = SQLITE_NOMEM_BKPT;
139645:   }
139646:   sqlite3ValueFree(pVal);
139647: 
139648:   return rc & 0xff;
139649: }
139650: #endif /* SQLITE_OMIT_UTF16 */
139651: 
139652: /*
139653: ** Register a new collation sequence with the database handle db.
139654: */
139655: SQLITE_API int sqlite3_create_collation(
139656:   sqlite3* db, 
139657:   const char *zName, 
139658:   int enc, 
139659:   void* pCtx,
139660:   int(*xCompare)(void*,int,const void*,int,const void*)
139661: ){
139662:   return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
139663: }
139664: 
139665: /*
139666: ** Register a new collation sequence with the database handle db.
139667: */
139668: SQLITE_API int sqlite3_create_collation_v2(
139669:   sqlite3* db, 
139670:   const char *zName, 
139671:   int enc, 
139672:   void* pCtx,
139673:   int(*xCompare)(void*,int,const void*,int,const void*),
139674:   void(*xDel)(void*)
139675: ){
139676:   int rc;
139677: 
139678: #ifdef SQLITE_ENABLE_API_ARMOR
139679:   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139680: #endif
139681:   sqlite3_mutex_enter(db->mutex);
139682:   assert( !db->mallocFailed );
139683:   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
139684:   rc = sqlite3ApiExit(db, rc);
139685:   sqlite3_mutex_leave(db->mutex);
139686:   return rc;
139687: }
139688: 
139689: #ifndef SQLITE_OMIT_UTF16
139690: /*
139691: ** Register a new collation sequence with the database handle db.
139692: */
139693: SQLITE_API int sqlite3_create_collation16(
139694:   sqlite3* db, 
139695:   const void *zName,
139696:   int enc, 
139697:   void* pCtx,
139698:   int(*xCompare)(void*,int,const void*,int,const void*)
139699: ){
139700:   int rc = SQLITE_OK;
139701:   char *zName8;
139702: 
139703: #ifdef SQLITE_ENABLE_API_ARMOR
139704:   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
139705: #endif
139706:   sqlite3_mutex_enter(db->mutex);
139707:   assert( !db->mallocFailed );
139708:   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
139709:   if( zName8 ){
139710:     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
139711:     sqlite3DbFree(db, zName8);
139712:   }
139713:   rc = sqlite3ApiExit(db, rc);
139714:   sqlite3_mutex_leave(db->mutex);
139715:   return rc;
139716: }
139717: #endif /* SQLITE_OMIT_UTF16 */
139718: 
139719: /*
139720: ** Register a collation sequence factory callback with the database handle
139721: ** db. Replace any previously installed collation sequence factory.
139722: */
139723: SQLITE_API int sqlite3_collation_needed(
139724:   sqlite3 *db, 
139725:   void *pCollNeededArg, 
139726:   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
139727: ){
139728: #ifdef SQLITE_ENABLE_API_ARMOR
139729:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139730: #endif
139731:   sqlite3_mutex_enter(db->mutex);
139732:   db->xCollNeeded = xCollNeeded;
139733:   db->xCollNeeded16 = 0;
139734:   db->pCollNeededArg = pCollNeededArg;
139735:   sqlite3_mutex_leave(db->mutex);
139736:   return SQLITE_OK;
139737: }
139738: 
139739: #ifndef SQLITE_OMIT_UTF16
139740: /*
139741: ** Register a collation sequence factory callback with the database handle
139742: ** db. Replace any previously installed collation sequence factory.
139743: */
139744: SQLITE_API int sqlite3_collation_needed16(
139745:   sqlite3 *db, 
139746:   void *pCollNeededArg, 
139747:   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
139748: ){
139749: #ifdef SQLITE_ENABLE_API_ARMOR
139750:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139751: #endif
139752:   sqlite3_mutex_enter(db->mutex);
139753:   db->xCollNeeded = 0;
139754:   db->xCollNeeded16 = xCollNeeded16;
139755:   db->pCollNeededArg = pCollNeededArg;
139756:   sqlite3_mutex_leave(db->mutex);
139757:   return SQLITE_OK;
139758: }
139759: #endif /* SQLITE_OMIT_UTF16 */
139760: 
139761: #ifndef SQLITE_OMIT_DEPRECATED
139762: /*
139763: ** This function is now an anachronism. It used to be used to recover from a
139764: ** malloc() failure, but SQLite now does this automatically.
139765: */
139766: SQLITE_API int sqlite3_global_recover(void){
139767:   return SQLITE_OK;
139768: }
139769: #endif
139770: 
139771: /*
139772: ** Test to see whether or not the database connection is in autocommit
139773: ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
139774: ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
139775: ** by the next COMMIT or ROLLBACK.
139776: */
139777: SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
139778: #ifdef SQLITE_ENABLE_API_ARMOR
139779:   if( !sqlite3SafetyCheckOk(db) ){
139780:     (void)SQLITE_MISUSE_BKPT;
139781:     return 0;
139782:   }
139783: #endif
139784:   return db->autoCommit;
139785: }
139786: 
139787: /*
139788: ** The following routines are substitutes for constants SQLITE_CORRUPT,
139789: ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
139790: ** constants.  They serve two purposes:
139791: **
139792: **   1.  Serve as a convenient place to set a breakpoint in a debugger
139793: **       to detect when version error conditions occurs.
139794: **
139795: **   2.  Invoke sqlite3_log() to provide the source code location where
139796: **       a low-level error is first detected.
139797: */
139798: static int reportError(int iErr, int lineno, const char *zType){
139799:   sqlite3_log(iErr, "%s at line %d of [%.10s]",
139800:               zType, lineno, 20+sqlite3_sourceid());
139801:   return iErr;
139802: }
139803: SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
139804:   testcase( sqlite3GlobalConfig.xLog!=0 );
139805:   return reportError(SQLITE_CORRUPT, lineno, "database corruption");
139806: }
139807: SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
139808:   testcase( sqlite3GlobalConfig.xLog!=0 );
139809:   return reportError(SQLITE_MISUSE, lineno, "misuse");
139810: }
139811: SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
139812:   testcase( sqlite3GlobalConfig.xLog!=0 );
139813:   return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
139814: }
139815: #ifdef SQLITE_DEBUG
139816: SQLITE_PRIVATE int sqlite3NomemError(int lineno){
139817:   testcase( sqlite3GlobalConfig.xLog!=0 );
139818:   return reportError(SQLITE_NOMEM, lineno, "OOM");
139819: }
139820: SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
139821:   testcase( sqlite3GlobalConfig.xLog!=0 );
139822:   return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
139823: }
139824: #endif
139825: 
139826: #ifndef SQLITE_OMIT_DEPRECATED
139827: /*
139828: ** This is a convenience routine that makes sure that all thread-specific
139829: ** data for this thread has been deallocated.
139830: **
139831: ** SQLite no longer uses thread-specific data so this routine is now a
139832: ** no-op.  It is retained for historical compatibility.
139833: */
139834: SQLITE_API void sqlite3_thread_cleanup(void){
139835: }
139836: #endif
139837: 
139838: /*
139839: ** Return meta information about a specific column of a database table.
139840: ** See comment in sqlite3.h (sqlite.h.in) for details.
139841: */
139842: SQLITE_API int sqlite3_table_column_metadata(
139843:   sqlite3 *db,                /* Connection handle */
139844:   const char *zDbName,        /* Database name or NULL */
139845:   const char *zTableName,     /* Table name */
139846:   const char *zColumnName,    /* Column name */
139847:   char const **pzDataType,    /* OUTPUT: Declared data type */
139848:   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
139849:   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
139850:   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
139851:   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
139852: ){
139853:   int rc;
139854:   char *zErrMsg = 0;
139855:   Table *pTab = 0;
139856:   Column *pCol = 0;
139857:   int iCol = 0;
139858:   char const *zDataType = 0;
139859:   char const *zCollSeq = 0;
139860:   int notnull = 0;
139861:   int primarykey = 0;
139862:   int autoinc = 0;
139863: 
139864: 
139865: #ifdef SQLITE_ENABLE_API_ARMOR
139866:   if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
139867:     return SQLITE_MISUSE_BKPT;
139868:   }
139869: #endif
139870: 
139871:   /* Ensure the database schema has been loaded */
139872:   sqlite3_mutex_enter(db->mutex);
139873:   sqlite3BtreeEnterAll(db);
139874:   rc = sqlite3Init(db, &zErrMsg);
139875:   if( SQLITE_OK!=rc ){
139876:     goto error_out;
139877:   }
139878: 
139879:   /* Locate the table in question */
139880:   pTab = sqlite3FindTable(db, zTableName, zDbName);
139881:   if( !pTab || pTab->pSelect ){
139882:     pTab = 0;
139883:     goto error_out;
139884:   }
139885: 
139886:   /* Find the column for which info is requested */
139887:   if( zColumnName==0 ){
139888:     /* Query for existance of table only */
139889:   }else{
139890:     for(iCol=0; iCol<pTab->nCol; iCol++){
139891:       pCol = &pTab->aCol[iCol];
139892:       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
139893:         break;
139894:       }
139895:     }
139896:     if( iCol==pTab->nCol ){
139897:       if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
139898:         iCol = pTab->iPKey;
139899:         pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
139900:       }else{
139901:         pTab = 0;
139902:         goto error_out;
139903:       }
139904:     }
139905:   }
139906: 
139907:   /* The following block stores the meta information that will be returned
139908:   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
139909:   ** and autoinc. At this point there are two possibilities:
139910:   ** 
139911:   **     1. The specified column name was rowid", "oid" or "_rowid_" 
139912:   **        and there is no explicitly declared IPK column. 
139913:   **
139914:   **     2. The table is not a view and the column name identified an 
139915:   **        explicitly declared column. Copy meta information from *pCol.
139916:   */ 
139917:   if( pCol ){
139918:     zDataType = sqlite3ColumnType(pCol,0);
139919:     zCollSeq = pCol->zColl;
139920:     notnull = pCol->notNull!=0;
139921:     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
139922:     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
139923:   }else{
139924:     zDataType = "INTEGER";
139925:     primarykey = 1;
139926:   }
139927:   if( !zCollSeq ){
139928:     zCollSeq = sqlite3StrBINARY;
139929:   }
139930: 
139931: error_out:
139932:   sqlite3BtreeLeaveAll(db);
139933: 
139934:   /* Whether the function call succeeded or failed, set the output parameters
139935:   ** to whatever their local counterparts contain. If an error did occur,
139936:   ** this has the effect of zeroing all output parameters.
139937:   */
139938:   if( pzDataType ) *pzDataType = zDataType;
139939:   if( pzCollSeq ) *pzCollSeq = zCollSeq;
139940:   if( pNotNull ) *pNotNull = notnull;
139941:   if( pPrimaryKey ) *pPrimaryKey = primarykey;
139942:   if( pAutoinc ) *pAutoinc = autoinc;
139943: 
139944:   if( SQLITE_OK==rc && !pTab ){
139945:     sqlite3DbFree(db, zErrMsg);
139946:     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
139947:         zColumnName);
139948:     rc = SQLITE_ERROR;
139949:   }
139950:   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
139951:   sqlite3DbFree(db, zErrMsg);
139952:   rc = sqlite3ApiExit(db, rc);
139953:   sqlite3_mutex_leave(db->mutex);
139954:   return rc;
139955: }
139956: 
139957: /*
139958: ** Sleep for a little while.  Return the amount of time slept.
139959: */
139960: SQLITE_API int sqlite3_sleep(int ms){
139961:   sqlite3_vfs *pVfs;
139962:   int rc;
139963:   pVfs = sqlite3_vfs_find(0);
139964:   if( pVfs==0 ) return 0;
139965: 
139966:   /* This function works in milliseconds, but the underlying OsSleep() 
139967:   ** API uses microseconds. Hence the 1000's.
139968:   */
139969:   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
139970:   return rc;
139971: }
139972: 
139973: /*
139974: ** Enable or disable the extended result codes.
139975: */
139976: SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
139977: #ifdef SQLITE_ENABLE_API_ARMOR
139978:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139979: #endif
139980:   sqlite3_mutex_enter(db->mutex);
139981:   db->errMask = onoff ? 0xffffffff : 0xff;
139982:   sqlite3_mutex_leave(db->mutex);
139983:   return SQLITE_OK;
139984: }
139985: 
139986: /*
139987: ** Invoke the xFileControl method on a particular database.
139988: */
139989: SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
139990:   int rc = SQLITE_ERROR;
139991:   Btree *pBtree;
139992: 
139993: #ifdef SQLITE_ENABLE_API_ARMOR
139994:   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139995: #endif
139996:   sqlite3_mutex_enter(db->mutex);
139997:   pBtree = sqlite3DbNameToBtree(db, zDbName);
139998:   if( pBtree ){
139999:     Pager *pPager;
140000:     sqlite3_file *fd;
140001:     sqlite3BtreeEnter(pBtree);
140002:     pPager = sqlite3BtreePager(pBtree);
140003:     assert( pPager!=0 );
140004:     fd = sqlite3PagerFile(pPager);
140005:     assert( fd!=0 );
140006:     if( op==SQLITE_FCNTL_FILE_POINTER ){
140007:       *(sqlite3_file**)pArg = fd;
140008:       rc = SQLITE_OK;
140009:     }else if( op==SQLITE_FCNTL_VFS_POINTER ){
140010:       *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
140011:       rc = SQLITE_OK;
140012:     }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
140013:       *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
140014:       rc = SQLITE_OK;
140015:     }else if( fd->pMethods ){
140016:       rc = sqlite3OsFileControl(fd, op, pArg);
140017:     }else{
140018:       rc = SQLITE_NOTFOUND;
140019:     }
140020:     sqlite3BtreeLeave(pBtree);
140021:   }
140022:   sqlite3_mutex_leave(db->mutex);
140023:   return rc;
140024: }
140025: 
140026: /*
140027: ** Interface to the testing logic.
140028: */
140029: SQLITE_API int sqlite3_test_control(int op, ...){
140030:   int rc = 0;
140031: #ifdef SQLITE_OMIT_BUILTIN_TEST
140032:   UNUSED_PARAMETER(op);
140033: #else
140034:   va_list ap;
140035:   va_start(ap, op);
140036:   switch( op ){
140037: 
140038:     /*
140039:     ** Save the current state of the PRNG.
140040:     */
140041:     case SQLITE_TESTCTRL_PRNG_SAVE: {
140042:       sqlite3PrngSaveState();
140043:       break;
140044:     }
140045: 
140046:     /*
140047:     ** Restore the state of the PRNG to the last state saved using
140048:     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
140049:     ** this verb acts like PRNG_RESET.
140050:     */
140051:     case SQLITE_TESTCTRL_PRNG_RESTORE: {
140052:       sqlite3PrngRestoreState();
140053:       break;
140054:     }
140055: 
140056:     /*
140057:     ** Reset the PRNG back to its uninitialized state.  The next call
140058:     ** to sqlite3_randomness() will reseed the PRNG using a single call
140059:     ** to the xRandomness method of the default VFS.
140060:     */
140061:     case SQLITE_TESTCTRL_PRNG_RESET: {
140062:       sqlite3_randomness(0,0);
140063:       break;
140064:     }
140065: 
140066:     /*
140067:     **  sqlite3_test_control(BITVEC_TEST, size, program)
140068:     **
140069:     ** Run a test against a Bitvec object of size.  The program argument
140070:     ** is an array of integers that defines the test.  Return -1 on a
140071:     ** memory allocation error, 0 on success, or non-zero for an error.
140072:     ** See the sqlite3BitvecBuiltinTest() for additional information.
140073:     */
140074:     case SQLITE_TESTCTRL_BITVEC_TEST: {
140075:       int sz = va_arg(ap, int);
140076:       int *aProg = va_arg(ap, int*);
140077:       rc = sqlite3BitvecBuiltinTest(sz, aProg);
140078:       break;
140079:     }
140080: 
140081:     /*
140082:     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
140083:     **
140084:     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
140085:     ** if xCallback is not NULL.
140086:     **
140087:     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
140088:     ** is called immediately after installing the new callback and the return
140089:     ** value from sqlite3FaultSim(0) becomes the return from
140090:     ** sqlite3_test_control().
140091:     */
140092:     case SQLITE_TESTCTRL_FAULT_INSTALL: {
140093:       /* MSVC is picky about pulling func ptrs from va lists.
140094:       ** http://support.microsoft.com/kb/47961
140095:       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
140096:       */
140097:       typedef int(*TESTCALLBACKFUNC_t)(int);
140098:       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
140099:       rc = sqlite3FaultSim(0);
140100:       break;
140101:     }
140102: 
140103:     /*
140104:     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
140105:     **
140106:     ** Register hooks to call to indicate which malloc() failures 
140107:     ** are benign.
140108:     */
140109:     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
140110:       typedef void (*void_function)(void);
140111:       void_function xBenignBegin;
140112:       void_function xBenignEnd;
140113:       xBenignBegin = va_arg(ap, void_function);
140114:       xBenignEnd = va_arg(ap, void_function);
140115:       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
140116:       break;
140117:     }
140118: 
140119:     /*
140120:     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
140121:     **
140122:     ** Set the PENDING byte to the value in the argument, if X>0.
140123:     ** Make no changes if X==0.  Return the value of the pending byte
140124:     ** as it existing before this routine was called.
140125:     **
140126:     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
140127:     ** an incompatible database file format.  Changing the PENDING byte
140128:     ** while any database connection is open results in undefined and
140129:     ** deleterious behavior.
140130:     */
140131:     case SQLITE_TESTCTRL_PENDING_BYTE: {
140132:       rc = PENDING_BYTE;
140133: #ifndef SQLITE_OMIT_WSD
140134:       {
140135:         unsigned int newVal = va_arg(ap, unsigned int);
140136:         if( newVal ) sqlite3PendingByte = newVal;
140137:       }
140138: #endif
140139:       break;
140140:     }
140141: 
140142:     /*
140143:     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
140144:     **
140145:     ** This action provides a run-time test to see whether or not
140146:     ** assert() was enabled at compile-time.  If X is true and assert()
140147:     ** is enabled, then the return value is true.  If X is true and
140148:     ** assert() is disabled, then the return value is zero.  If X is
140149:     ** false and assert() is enabled, then the assertion fires and the
140150:     ** process aborts.  If X is false and assert() is disabled, then the
140151:     ** return value is zero.
140152:     */
140153:     case SQLITE_TESTCTRL_ASSERT: {
140154:       volatile int x = 0;
140155:       assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
140156:       rc = x;
140157:       break;
140158:     }
140159: 
140160: 
140161:     /*
140162:     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
140163:     **
140164:     ** This action provides a run-time test to see how the ALWAYS and
140165:     ** NEVER macros were defined at compile-time.
140166:     **
140167:     ** The return value is ALWAYS(X).  
140168:     **
140169:     ** The recommended test is X==2.  If the return value is 2, that means
140170:     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
140171:     ** default setting.  If the return value is 1, then ALWAYS() is either
140172:     ** hard-coded to true or else it asserts if its argument is false.
140173:     ** The first behavior (hard-coded to true) is the case if
140174:     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
140175:     ** behavior (assert if the argument to ALWAYS() is false) is the case if
140176:     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
140177:     **
140178:     ** The run-time test procedure might look something like this:
140179:     **
140180:     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
140181:     **      // ALWAYS() and NEVER() are no-op pass-through macros
140182:     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
140183:     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
140184:     **    }else{
140185:     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
140186:     **    }
140187:     */
140188:     case SQLITE_TESTCTRL_ALWAYS: {
140189:       int x = va_arg(ap,int);
140190:       rc = ALWAYS(x);
140191:       break;
140192:     }
140193: 
140194:     /*
140195:     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
140196:     **
140197:     ** The integer returned reveals the byte-order of the computer on which
140198:     ** SQLite is running:
140199:     **
140200:     **       1     big-endian,    determined at run-time
140201:     **      10     little-endian, determined at run-time
140202:     **  432101     big-endian,    determined at compile-time
140203:     **  123410     little-endian, determined at compile-time
140204:     */ 
140205:     case SQLITE_TESTCTRL_BYTEORDER: {
140206:       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
140207:       break;
140208:     }
140209: 
140210:     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
140211:     **
140212:     ** Set the nReserve size to N for the main database on the database
140213:     ** connection db.
140214:     */
140215:     case SQLITE_TESTCTRL_RESERVE: {
140216:       sqlite3 *db = va_arg(ap, sqlite3*);
140217:       int x = va_arg(ap,int);
140218:       sqlite3_mutex_enter(db->mutex);
140219:       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
140220:       sqlite3_mutex_leave(db->mutex);
140221:       break;
140222:     }
140223: 
140224:     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
140225:     **
140226:     ** Enable or disable various optimizations for testing purposes.  The 
140227:     ** argument N is a bitmask of optimizations to be disabled.  For normal
140228:     ** operation N should be 0.  The idea is that a test program (like the
140229:     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
140230:     ** with various optimizations disabled to verify that the same answer
140231:     ** is obtained in every case.
140232:     */
140233:     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
140234:       sqlite3 *db = va_arg(ap, sqlite3*);
140235:       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
140236:       break;
140237:     }
140238: 
140239: #ifdef SQLITE_N_KEYWORD
140240:     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
140241:     **
140242:     ** If zWord is a keyword recognized by the parser, then return the
140243:     ** number of keywords.  Or if zWord is not a keyword, return 0.
140244:     ** 
140245:     ** This test feature is only available in the amalgamation since
140246:     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
140247:     ** is built using separate source files.
140248:     */
140249:     case SQLITE_TESTCTRL_ISKEYWORD: {
140250:       const char *zWord = va_arg(ap, const char*);
140251:       int n = sqlite3Strlen30(zWord);
140252:       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
140253:       break;
140254:     }
140255: #endif 
140256: 
140257:     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
140258:     **
140259:     ** Pass pFree into sqlite3ScratchFree(). 
140260:     ** If sz>0 then allocate a scratch buffer into pNew.  
140261:     */
140262:     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
140263:       void *pFree, **ppNew;
140264:       int sz;
140265:       sz = va_arg(ap, int);
140266:       ppNew = va_arg(ap, void**);
140267:       pFree = va_arg(ap, void*);
140268:       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
140269:       sqlite3ScratchFree(pFree);
140270:       break;
140271:     }
140272: 
140273:     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
140274:     **
140275:     ** If parameter onoff is non-zero, configure the wrappers so that all
140276:     ** subsequent calls to localtime() and variants fail. If onoff is zero,
140277:     ** undo this setting.
140278:     */
140279:     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
140280:       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
140281:       break;
140282:     }
140283: 
140284:     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
140285:     **
140286:     ** Set or clear a flag that indicates that the database file is always well-
140287:     ** formed and never corrupt.  This flag is clear by default, indicating that
140288:     ** database files might have arbitrary corruption.  Setting the flag during
140289:     ** testing causes certain assert() statements in the code to be activated
140290:     ** that demonstrat invariants on well-formed database files.
140291:     */
140292:     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
140293:       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
140294:       break;
140295:     }
140296: 
140297: 
140298:     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
140299:     **
140300:     ** Set the VDBE coverage callback function to xCallback with context 
140301:     ** pointer ptr.
140302:     */
140303:     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
140304: #ifdef SQLITE_VDBE_COVERAGE
140305:       typedef void (*branch_callback)(void*,int,u8,u8);
140306:       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
140307:       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
140308: #endif
140309:       break;
140310:     }
140311: 
140312:     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
140313:     case SQLITE_TESTCTRL_SORTER_MMAP: {
140314:       sqlite3 *db = va_arg(ap, sqlite3*);
140315:       db->nMaxSorterMmap = va_arg(ap, int);
140316:       break;
140317:     }
140318: 
140319:     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
140320:     **
140321:     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
140322:     ** not.
140323:     */
140324:     case SQLITE_TESTCTRL_ISINIT: {
140325:       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
140326:       break;
140327:     }
140328: 
140329:     /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
140330:     **
140331:     ** This test control is used to create imposter tables.  "db" is a pointer
140332:     ** to the database connection.  dbName is the database name (ex: "main" or
140333:     ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
140334:     ** or off.  "tnum" is the root page of the b-tree to which the imposter
140335:     ** table should connect.
140336:     **
140337:     ** Enable imposter mode only when the schema has already been parsed.  Then
140338:     ** run a single CREATE TABLE statement to construct the imposter table in
140339:     ** the parsed schema.  Then turn imposter mode back off again.
140340:     **
140341:     ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
140342:     ** the schema to be reparsed the next time it is needed.  This has the
140343:     ** effect of erasing all imposter tables.
140344:     */
140345:     case SQLITE_TESTCTRL_IMPOSTER: {
140346:       sqlite3 *db = va_arg(ap, sqlite3*);
140347:       sqlite3_mutex_enter(db->mutex);
140348:       db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
140349:       db->init.busy = db->init.imposterTable = va_arg(ap,int);
140350:       db->init.newTnum = va_arg(ap,int);
140351:       if( db->init.busy==0 && db->init.newTnum>0 ){
140352:         sqlite3ResetAllSchemasOfConnection(db);
140353:       }
140354:       sqlite3_mutex_leave(db->mutex);
140355:       break;
140356:     }
140357:   }
140358:   va_end(ap);
140359: #endif /* SQLITE_OMIT_BUILTIN_TEST */
140360:   return rc;
140361: }
140362: 
140363: /*
140364: ** This is a utility routine, useful to VFS implementations, that checks
140365: ** to see if a database file was a URI that contained a specific query 
140366: ** parameter, and if so obtains the value of the query parameter.
140367: **
140368: ** The zFilename argument is the filename pointer passed into the xOpen()
140369: ** method of a VFS implementation.  The zParam argument is the name of the
140370: ** query parameter we seek.  This routine returns the value of the zParam
140371: ** parameter if it exists.  If the parameter does not exist, this routine
140372: ** returns a NULL pointer.
140373: */
140374: SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
140375:   if( zFilename==0 || zParam==0 ) return 0;
140376:   zFilename += sqlite3Strlen30(zFilename) + 1;
140377:   while( zFilename[0] ){
140378:     int x = strcmp(zFilename, zParam);
140379:     zFilename += sqlite3Strlen30(zFilename) + 1;
140380:     if( x==0 ) return zFilename;
140381:     zFilename += sqlite3Strlen30(zFilename) + 1;
140382:   }
140383:   return 0;
140384: }
140385: 
140386: /*
140387: ** Return a boolean value for a query parameter.
140388: */
140389: SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
140390:   const char *z = sqlite3_uri_parameter(zFilename, zParam);
140391:   bDflt = bDflt!=0;
140392:   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
140393: }
140394: 
140395: /*
140396: ** Return a 64-bit integer value for a query parameter.
140397: */
140398: SQLITE_API sqlite3_int64 sqlite3_uri_int64(
140399:   const char *zFilename,    /* Filename as passed to xOpen */
140400:   const char *zParam,       /* URI parameter sought */
140401:   sqlite3_int64 bDflt       /* return if parameter is missing */
140402: ){
140403:   const char *z = sqlite3_uri_parameter(zFilename, zParam);
140404:   sqlite3_int64 v;
140405:   if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
140406:     bDflt = v;
140407:   }
140408:   return bDflt;
140409: }
140410: 
140411: /*
140412: ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
140413: */
140414: SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
140415:   int i;
140416:   for(i=0; i<db->nDb; i++){
140417:     if( db->aDb[i].pBt
140418:      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
140419:     ){
140420:       return db->aDb[i].pBt;
140421:     }
140422:   }
140423:   return 0;
140424: }
140425: 
140426: /*
140427: ** Return the filename of the database associated with a database
140428: ** connection.
140429: */
140430: SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
140431:   Btree *pBt;
140432: #ifdef SQLITE_ENABLE_API_ARMOR
140433:   if( !sqlite3SafetyCheckOk(db) ){
140434:     (void)SQLITE_MISUSE_BKPT;
140435:     return 0;
140436:   }
140437: #endif
140438:   pBt = sqlite3DbNameToBtree(db, zDbName);
140439:   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
140440: }
140441: 
140442: /*
140443: ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
140444: ** no such database exists.
140445: */
140446: SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
140447:   Btree *pBt;
140448: #ifdef SQLITE_ENABLE_API_ARMOR
140449:   if( !sqlite3SafetyCheckOk(db) ){
140450:     (void)SQLITE_MISUSE_BKPT;
140451:     return -1;
140452:   }
140453: #endif
140454:   pBt = sqlite3DbNameToBtree(db, zDbName);
140455:   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
140456: }
140457: 
140458: #ifdef SQLITE_ENABLE_SNAPSHOT
140459: /*
140460: ** Obtain a snapshot handle for the snapshot of database zDb currently 
140461: ** being read by handle db.
140462: */
140463: SQLITE_API int sqlite3_snapshot_get(
140464:   sqlite3 *db, 
140465:   const char *zDb,
140466:   sqlite3_snapshot **ppSnapshot
140467: ){
140468:   int rc = SQLITE_ERROR;
140469: #ifndef SQLITE_OMIT_WAL
140470:   int iDb;
140471: 
140472: #ifdef SQLITE_ENABLE_API_ARMOR
140473:   if( !sqlite3SafetyCheckOk(db) ){
140474:     return SQLITE_MISUSE_BKPT;
140475:   }
140476: #endif
140477:   sqlite3_mutex_enter(db->mutex);
140478: 
140479:   iDb = sqlite3FindDbName(db, zDb);
140480:   if( iDb==0 || iDb>1 ){
140481:     Btree *pBt = db->aDb[iDb].pBt;
140482:     if( 0==sqlite3BtreeIsInTrans(pBt) ){
140483:       rc = sqlite3BtreeBeginTrans(pBt, 0);
140484:       if( rc==SQLITE_OK ){
140485:         rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
140486:       }
140487:     }
140488:   }
140489: 
140490:   sqlite3_mutex_leave(db->mutex);
140491: #endif   /* SQLITE_OMIT_WAL */
140492:   return rc;
140493: }
140494: 
140495: /*
140496: ** Open a read-transaction on the snapshot idendified by pSnapshot.
140497: */
140498: SQLITE_API int sqlite3_snapshot_open(
140499:   sqlite3 *db, 
140500:   const char *zDb, 
140501:   sqlite3_snapshot *pSnapshot
140502: ){
140503:   int rc = SQLITE_ERROR;
140504: #ifndef SQLITE_OMIT_WAL
140505: 
140506: #ifdef SQLITE_ENABLE_API_ARMOR
140507:   if( !sqlite3SafetyCheckOk(db) ){
140508:     return SQLITE_MISUSE_BKPT;
140509:   }
140510: #endif
140511:   sqlite3_mutex_enter(db->mutex);
140512:   if( db->autoCommit==0 ){
140513:     int iDb;
140514:     iDb = sqlite3FindDbName(db, zDb);
140515:     if( iDb==0 || iDb>1 ){
140516:       Btree *pBt = db->aDb[iDb].pBt;
140517:       if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
140518:         rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
140519:         if( rc==SQLITE_OK ){
140520:           rc = sqlite3BtreeBeginTrans(pBt, 0);
140521:           sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
140522:         }
140523:       }
140524:     }
140525:   }
140526: 
140527:   sqlite3_mutex_leave(db->mutex);
140528: #endif   /* SQLITE_OMIT_WAL */
140529:   return rc;
140530: }
140531: 
140532: /*
140533: ** Free a snapshot handle obtained from sqlite3_snapshot_get().
140534: */
140535: SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
140536:   sqlite3_free(pSnapshot);
140537: }
140538: #endif /* SQLITE_ENABLE_SNAPSHOT */
140539: 
140540: /************** End of main.c ************************************************/
140541: /************** Begin file notify.c ******************************************/
140542: /*
140543: ** 2009 March 3
140544: **
140545: ** The author disclaims copyright to this source code.  In place of
140546: ** a legal notice, here is a blessing:
140547: **
140548: **    May you do good and not evil.
140549: **    May you find forgiveness for yourself and forgive others.
140550: **    May you share freely, never taking more than you give.
140551: **
140552: *************************************************************************
140553: **
140554: ** This file contains the implementation of the sqlite3_unlock_notify()
140555: ** API method and its associated functionality.
140556: */
140557: /* #include "sqliteInt.h" */
140558: /* #include "btreeInt.h" */
140559: 
140560: /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
140561: #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
140562: 
140563: /*
140564: ** Public interfaces:
140565: **
140566: **   sqlite3ConnectionBlocked()
140567: **   sqlite3ConnectionUnlocked()
140568: **   sqlite3ConnectionClosed()
140569: **   sqlite3_unlock_notify()
140570: */
140571: 
140572: #define assertMutexHeld() \
140573:   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
140574: 
140575: /*
140576: ** Head of a linked list of all sqlite3 objects created by this process
140577: ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
140578: ** is not NULL. This variable may only accessed while the STATIC_MASTER
140579: ** mutex is held.
140580: */
140581: static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
140582: 
140583: #ifndef NDEBUG
140584: /*
140585: ** This function is a complex assert() that verifies the following 
140586: ** properties of the blocked connections list:
140587: **
140588: **   1) Each entry in the list has a non-NULL value for either 
140589: **      pUnlockConnection or pBlockingConnection, or both.
140590: **
140591: **   2) All entries in the list that share a common value for 
140592: **      xUnlockNotify are grouped together.
140593: **
140594: **   3) If the argument db is not NULL, then none of the entries in the
140595: **      blocked connections list have pUnlockConnection or pBlockingConnection
140596: **      set to db. This is used when closing connection db.
140597: */
140598: static void checkListProperties(sqlite3 *db){
140599:   sqlite3 *p;
140600:   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
140601:     int seen = 0;
140602:     sqlite3 *p2;
140603: 
140604:     /* Verify property (1) */
140605:     assert( p->pUnlockConnection || p->pBlockingConnection );
140606: 
140607:     /* Verify property (2) */
140608:     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
140609:       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
140610:       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
140611:       assert( db==0 || p->pUnlockConnection!=db );
140612:       assert( db==0 || p->pBlockingConnection!=db );
140613:     }
140614:   }
140615: }
140616: #else
140617: # define checkListProperties(x)
140618: #endif
140619: 
140620: /*
140621: ** Remove connection db from the blocked connections list. If connection
140622: ** db is not currently a part of the list, this function is a no-op.
140623: */
140624: static void removeFromBlockedList(sqlite3 *db){
140625:   sqlite3 **pp;
140626:   assertMutexHeld();
140627:   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
140628:     if( *pp==db ){
140629:       *pp = (*pp)->pNextBlocked;
140630:       break;
140631:     }
140632:   }
140633: }
140634: 
140635: /*
140636: ** Add connection db to the blocked connections list. It is assumed
140637: ** that it is not already a part of the list.
140638: */
140639: static void addToBlockedList(sqlite3 *db){
140640:   sqlite3 **pp;
140641:   assertMutexHeld();
140642:   for(
140643:     pp=&sqlite3BlockedList; 
140644:     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
140645:     pp=&(*pp)->pNextBlocked
140646:   );
140647:   db->pNextBlocked = *pp;
140648:   *pp = db;
140649: }
140650: 
140651: /*
140652: ** Obtain the STATIC_MASTER mutex.
140653: */
140654: static void enterMutex(void){
140655:   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
140656:   checkListProperties(0);
140657: }
140658: 
140659: /*
140660: ** Release the STATIC_MASTER mutex.
140661: */
140662: static void leaveMutex(void){
140663:   assertMutexHeld();
140664:   checkListProperties(0);
140665:   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
140666: }
140667: 
140668: /*
140669: ** Register an unlock-notify callback.
140670: **
140671: ** This is called after connection "db" has attempted some operation
140672: ** but has received an SQLITE_LOCKED error because another connection
140673: ** (call it pOther) in the same process was busy using the same shared
140674: ** cache.  pOther is found by looking at db->pBlockingConnection.
140675: **
140676: ** If there is no blocking connection, the callback is invoked immediately,
140677: ** before this routine returns.
140678: **
140679: ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
140680: ** a deadlock.
140681: **
140682: ** Otherwise, make arrangements to invoke xNotify when pOther drops
140683: ** its locks.
140684: **
140685: ** Each call to this routine overrides any prior callbacks registered
140686: ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
140687: ** cancelled.
140688: */
140689: SQLITE_API int sqlite3_unlock_notify(
140690:   sqlite3 *db,
140691:   void (*xNotify)(void **, int),
140692:   void *pArg
140693: ){
140694:   int rc = SQLITE_OK;
140695: 
140696:   sqlite3_mutex_enter(db->mutex);
140697:   enterMutex();
140698: 
140699:   if( xNotify==0 ){
140700:     removeFromBlockedList(db);
140701:     db->pBlockingConnection = 0;
140702:     db->pUnlockConnection = 0;
140703:     db->xUnlockNotify = 0;
140704:     db->pUnlockArg = 0;
140705:   }else if( 0==db->pBlockingConnection ){
140706:     /* The blocking transaction has been concluded. Or there never was a 
140707:     ** blocking transaction. In either case, invoke the notify callback
140708:     ** immediately. 
140709:     */
140710:     xNotify(&pArg, 1);
140711:   }else{
140712:     sqlite3 *p;
140713: 
140714:     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
140715:     if( p ){
140716:       rc = SQLITE_LOCKED;              /* Deadlock detected. */
140717:     }else{
140718:       db->pUnlockConnection = db->pBlockingConnection;
140719:       db->xUnlockNotify = xNotify;
140720:       db->pUnlockArg = pArg;
140721:       removeFromBlockedList(db);
140722:       addToBlockedList(db);
140723:     }
140724:   }
140725: 
140726:   leaveMutex();
140727:   assert( !db->mallocFailed );
140728:   sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
140729:   sqlite3_mutex_leave(db->mutex);
140730:   return rc;
140731: }
140732: 
140733: /*
140734: ** This function is called while stepping or preparing a statement 
140735: ** associated with connection db. The operation will return SQLITE_LOCKED
140736: ** to the user because it requires a lock that will not be available
140737: ** until connection pBlocker concludes its current transaction.
140738: */
140739: SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
140740:   enterMutex();
140741:   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
140742:     addToBlockedList(db);
140743:   }
140744:   db->pBlockingConnection = pBlocker;
140745:   leaveMutex();
140746: }
140747: 
140748: /*
140749: ** This function is called when
140750: ** the transaction opened by database db has just finished. Locks held 
140751: ** by database connection db have been released.
140752: **
140753: ** This function loops through each entry in the blocked connections
140754: ** list and does the following:
140755: **
140756: **   1) If the sqlite3.pBlockingConnection member of a list entry is
140757: **      set to db, then set pBlockingConnection=0.
140758: **
140759: **   2) If the sqlite3.pUnlockConnection member of a list entry is
140760: **      set to db, then invoke the configured unlock-notify callback and
140761: **      set pUnlockConnection=0.
140762: **
140763: **   3) If the two steps above mean that pBlockingConnection==0 and
140764: **      pUnlockConnection==0, remove the entry from the blocked connections
140765: **      list.
140766: */
140767: SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
140768:   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
140769:   int nArg = 0;                            /* Number of entries in aArg[] */
140770:   sqlite3 **pp;                            /* Iterator variable */
140771:   void **aArg;               /* Arguments to the unlock callback */
140772:   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
140773:   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
140774: 
140775:   aArg = aStatic;
140776:   enterMutex();         /* Enter STATIC_MASTER mutex */
140777: 
140778:   /* This loop runs once for each entry in the blocked-connections list. */
140779:   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
140780:     sqlite3 *p = *pp;
140781: 
140782:     /* Step 1. */
140783:     if( p->pBlockingConnection==db ){
140784:       p->pBlockingConnection = 0;
140785:     }
140786: 
140787:     /* Step 2. */
140788:     if( p->pUnlockConnection==db ){
140789:       assert( p->xUnlockNotify );
140790:       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
140791:         xUnlockNotify(aArg, nArg);
140792:         nArg = 0;
140793:       }
140794: 
140795:       sqlite3BeginBenignMalloc();
140796:       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
140797:       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
140798:       if( (!aDyn && nArg==(int)ArraySize(aStatic))
140799:        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
140800:       ){
140801:         /* The aArg[] array needs to grow. */
140802:         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
140803:         if( pNew ){
140804:           memcpy(pNew, aArg, nArg*sizeof(void *));
140805:           sqlite3_free(aDyn);
140806:           aDyn = aArg = pNew;
140807:         }else{
140808:           /* This occurs when the array of context pointers that need to
140809:           ** be passed to the unlock-notify callback is larger than the
140810:           ** aStatic[] array allocated on the stack and the attempt to 
140811:           ** allocate a larger array from the heap has failed.
140812:           **
140813:           ** This is a difficult situation to handle. Returning an error
140814:           ** code to the caller is insufficient, as even if an error code
140815:           ** is returned the transaction on connection db will still be
140816:           ** closed and the unlock-notify callbacks on blocked connections
140817:           ** will go unissued. This might cause the application to wait
140818:           ** indefinitely for an unlock-notify callback that will never 
140819:           ** arrive.
140820:           **
140821:           ** Instead, invoke the unlock-notify callback with the context
140822:           ** array already accumulated. We can then clear the array and
140823:           ** begin accumulating any further context pointers without 
140824:           ** requiring any dynamic allocation. This is sub-optimal because
140825:           ** it means that instead of one callback with a large array of
140826:           ** context pointers the application will receive two or more
140827:           ** callbacks with smaller arrays of context pointers, which will
140828:           ** reduce the applications ability to prioritize multiple 
140829:           ** connections. But it is the best that can be done under the
140830:           ** circumstances.
140831:           */
140832:           xUnlockNotify(aArg, nArg);
140833:           nArg = 0;
140834:         }
140835:       }
140836:       sqlite3EndBenignMalloc();
140837: 
140838:       aArg[nArg++] = p->pUnlockArg;
140839:       xUnlockNotify = p->xUnlockNotify;
140840:       p->pUnlockConnection = 0;
140841:       p->xUnlockNotify = 0;
140842:       p->pUnlockArg = 0;
140843:     }
140844: 
140845:     /* Step 3. */
140846:     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
140847:       /* Remove connection p from the blocked connections list. */
140848:       *pp = p->pNextBlocked;
140849:       p->pNextBlocked = 0;
140850:     }else{
140851:       pp = &p->pNextBlocked;
140852:     }
140853:   }
140854: 
140855:   if( nArg!=0 ){
140856:     xUnlockNotify(aArg, nArg);
140857:   }
140858:   sqlite3_free(aDyn);
140859:   leaveMutex();         /* Leave STATIC_MASTER mutex */
140860: }
140861: 
140862: /*
140863: ** This is called when the database connection passed as an argument is 
140864: ** being closed. The connection is removed from the blocked list.
140865: */
140866: SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
140867:   sqlite3ConnectionUnlocked(db);
140868:   enterMutex();
140869:   removeFromBlockedList(db);
140870:   checkListProperties(db);
140871:   leaveMutex();
140872: }
140873: #endif
140874: 
140875: /************** End of notify.c **********************************************/
140876: /************** Begin file fts3.c ********************************************/
140877: /*
140878: ** 2006 Oct 10
140879: **
140880: ** The author disclaims copyright to this source code.  In place of
140881: ** a legal notice, here is a blessing:
140882: **
140883: **    May you do good and not evil.
140884: **    May you find forgiveness for yourself and forgive others.
140885: **    May you share freely, never taking more than you give.
140886: **
140887: ******************************************************************************
140888: **
140889: ** This is an SQLite module implementing full-text search.
140890: */
140891: 
140892: /*
140893: ** The code in this file is only compiled if:
140894: **
140895: **     * The FTS3 module is being built as an extension
140896: **       (in which case SQLITE_CORE is not defined), or
140897: **
140898: **     * The FTS3 module is being built into the core of
140899: **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140900: */
140901: 
140902: /* The full-text index is stored in a series of b+tree (-like)
140903: ** structures called segments which map terms to doclists.  The
140904: ** structures are like b+trees in layout, but are constructed from the
140905: ** bottom up in optimal fashion and are not updatable.  Since trees
140906: ** are built from the bottom up, things will be described from the
140907: ** bottom up.
140908: **
140909: **
140910: **** Varints ****
140911: ** The basic unit of encoding is a variable-length integer called a
140912: ** varint.  We encode variable-length integers in little-endian order
140913: ** using seven bits * per byte as follows:
140914: **
140915: ** KEY:
140916: **         A = 0xxxxxxx    7 bits of data and one flag bit
140917: **         B = 1xxxxxxx    7 bits of data and one flag bit
140918: **
140919: **  7 bits - A
140920: ** 14 bits - BA
140921: ** 21 bits - BBA
140922: ** and so on.
140923: **
140924: ** This is similar in concept to how sqlite encodes "varints" but
140925: ** the encoding is not the same.  SQLite varints are big-endian
140926: ** are are limited to 9 bytes in length whereas FTS3 varints are
140927: ** little-endian and can be up to 10 bytes in length (in theory).
140928: **
140929: ** Example encodings:
140930: **
140931: **     1:    0x01
140932: **   127:    0x7f
140933: **   128:    0x81 0x00
140934: **
140935: **
140936: **** Document lists ****
140937: ** A doclist (document list) holds a docid-sorted list of hits for a
140938: ** given term.  Doclists hold docids and associated token positions.
140939: ** A docid is the unique integer identifier for a single document.
140940: ** A position is the index of a word within the document.  The first 
140941: ** word of the document has a position of 0.
140942: **
140943: ** FTS3 used to optionally store character offsets using a compile-time
140944: ** option.  But that functionality is no longer supported.
140945: **
140946: ** A doclist is stored like this:
140947: **
140948: ** array {
140949: **   varint docid;          (delta from previous doclist)
140950: **   array {                (position list for column 0)
140951: **     varint position;     (2 more than the delta from previous position)
140952: **   }
140953: **   array {
140954: **     varint POS_COLUMN;   (marks start of position list for new column)
140955: **     varint column;       (index of new column)
140956: **     array {
140957: **       varint position;   (2 more than the delta from previous position)
140958: **     }
140959: **   }
140960: **   varint POS_END;        (marks end of positions for this document.
140961: ** }
140962: **
140963: ** Here, array { X } means zero or more occurrences of X, adjacent in
140964: ** memory.  A "position" is an index of a token in the token stream
140965: ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
140966: ** in the same logical place as the position element, and act as sentinals
140967: ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
140968: ** The positions numbers are not stored literally but rather as two more
140969: ** than the difference from the prior position, or the just the position plus
140970: ** 2 for the first position.  Example:
140971: **
140972: **   label:       A B C D E  F  G H   I  J K
140973: **   value:     123 5 9 1 1 14 35 0 234 72 0
140974: **
140975: ** The 123 value is the first docid.  For column zero in this document
140976: ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
140977: ** at D signals the start of a new column; the 1 at E indicates that the
140978: ** new column is column number 1.  There are two positions at 12 and 45
140979: ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
140980: ** 234 at I is the delta to next docid (357).  It has one position 70
140981: ** (72-2) and then terminates with the 0 at K.
140982: **
140983: ** A "position-list" is the list of positions for multiple columns for
140984: ** a single docid.  A "column-list" is the set of positions for a single
140985: ** column.  Hence, a position-list consists of one or more column-lists,
140986: ** a document record consists of a docid followed by a position-list and
140987: ** a doclist consists of one or more document records.
140988: **
140989: ** A bare doclist omits the position information, becoming an 
140990: ** array of varint-encoded docids.
140991: **
140992: **** Segment leaf nodes ****
140993: ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
140994: ** nodes are written using LeafWriter, and read using LeafReader (to
140995: ** iterate through a single leaf node's data) and LeavesReader (to
140996: ** iterate through a segment's entire leaf layer).  Leaf nodes have
140997: ** the format:
140998: **
140999: ** varint iHeight;             (height from leaf level, always 0)
141000: ** varint nTerm;               (length of first term)
141001: ** char pTerm[nTerm];          (content of first term)
141002: ** varint nDoclist;            (length of term's associated doclist)
141003: ** char pDoclist[nDoclist];    (content of doclist)
141004: ** array {
141005: **                             (further terms are delta-encoded)
141006: **   varint nPrefix;           (length of prefix shared with previous term)
141007: **   varint nSuffix;           (length of unshared suffix)
141008: **   char pTermSuffix[nSuffix];(unshared suffix of next term)
141009: **   varint nDoclist;          (length of term's associated doclist)
141010: **   char pDoclist[nDoclist];  (content of doclist)
141011: ** }
141012: **
141013: ** Here, array { X } means zero or more occurrences of X, adjacent in
141014: ** memory.
141015: **
141016: ** Leaf nodes are broken into blocks which are stored contiguously in
141017: ** the %_segments table in sorted order.  This means that when the end
141018: ** of a node is reached, the next term is in the node with the next
141019: ** greater node id.
141020: **
141021: ** New data is spilled to a new leaf node when the current node
141022: ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
141023: ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
141024: ** node (a leaf node with a single term and doclist).  The goal of
141025: ** these settings is to pack together groups of small doclists while
141026: ** making it efficient to directly access large doclists.  The
141027: ** assumption is that large doclists represent terms which are more
141028: ** likely to be query targets.
141029: **
141030: ** TODO(shess) It may be useful for blocking decisions to be more
141031: ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
141032: ** node rather than splitting into 2k and .5k nodes.  My intuition is
141033: ** that this might extend through 2x or 4x the pagesize.
141034: **
141035: **
141036: **** Segment interior nodes ****
141037: ** Segment interior nodes store blockids for subtree nodes and terms
141038: ** to describe what data is stored by the each subtree.  Interior
141039: ** nodes are written using InteriorWriter, and read using
141040: ** InteriorReader.  InteriorWriters are created as needed when
141041: ** SegmentWriter creates new leaf nodes, or when an interior node
141042: ** itself grows too big and must be split.  The format of interior
141043: ** nodes:
141044: **
141045: ** varint iHeight;           (height from leaf level, always >0)
141046: ** varint iBlockid;          (block id of node's leftmost subtree)
141047: ** optional {
141048: **   varint nTerm;           (length of first term)
141049: **   char pTerm[nTerm];      (content of first term)
141050: **   array {
141051: **                                (further terms are delta-encoded)
141052: **     varint nPrefix;            (length of shared prefix with previous term)
141053: **     varint nSuffix;            (length of unshared suffix)
141054: **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
141055: **   }
141056: ** }
141057: **
141058: ** Here, optional { X } means an optional element, while array { X }
141059: ** means zero or more occurrences of X, adjacent in memory.
141060: **
141061: ** An interior node encodes n terms separating n+1 subtrees.  The
141062: ** subtree blocks are contiguous, so only the first subtree's blockid
141063: ** is encoded.  The subtree at iBlockid will contain all terms less
141064: ** than the first term encoded (or all terms if no term is encoded).
141065: ** Otherwise, for terms greater than or equal to pTerm[i] but less
141066: ** than pTerm[i+1], the subtree for that term will be rooted at
141067: ** iBlockid+i.  Interior nodes only store enough term data to
141068: ** distinguish adjacent children (if the rightmost term of the left
141069: ** child is "something", and the leftmost term of the right child is
141070: ** "wicked", only "w" is stored).
141071: **
141072: ** New data is spilled to a new interior node at the same height when
141073: ** the current node exceeds INTERIOR_MAX bytes (default 2048).
141074: ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
141075: ** interior nodes and making the tree too skinny.  The interior nodes
141076: ** at a given height are naturally tracked by interior nodes at
141077: ** height+1, and so on.
141078: **
141079: **
141080: **** Segment directory ****
141081: ** The segment directory in table %_segdir stores meta-information for
141082: ** merging and deleting segments, and also the root node of the
141083: ** segment's tree.
141084: **
141085: ** The root node is the top node of the segment's tree after encoding
141086: ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
141087: ** This could be either a leaf node or an interior node.  If the top
141088: ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
141089: ** and a new root interior node is generated (which should always fit
141090: ** within ROOT_MAX because it only needs space for 2 varints, the
141091: ** height and the blockid of the previous root).
141092: **
141093: ** The meta-information in the segment directory is:
141094: **   level               - segment level (see below)
141095: **   idx                 - index within level
141096: **                       - (level,idx uniquely identify a segment)
141097: **   start_block         - first leaf node
141098: **   leaves_end_block    - last leaf node
141099: **   end_block           - last block (including interior nodes)
141100: **   root                - contents of root node
141101: **
141102: ** If the root node is a leaf node, then start_block,
141103: ** leaves_end_block, and end_block are all 0.
141104: **
141105: **
141106: **** Segment merging ****
141107: ** To amortize update costs, segments are grouped into levels and
141108: ** merged in batches.  Each increase in level represents exponentially
141109: ** more documents.
141110: **
141111: ** New documents (actually, document updates) are tokenized and
141112: ** written individually (using LeafWriter) to a level 0 segment, with
141113: ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
141114: ** level 0 segments are merged into a single level 1 segment.  Level 1
141115: ** is populated like level 0, and eventually MERGE_COUNT level 1
141116: ** segments are merged to a single level 2 segment (representing
141117: ** MERGE_COUNT^2 updates), and so on.
141118: **
141119: ** A segment merge traverses all segments at a given level in
141120: ** parallel, performing a straightforward sorted merge.  Since segment
141121: ** leaf nodes are written in to the %_segments table in order, this
141122: ** merge traverses the underlying sqlite disk structures efficiently.
141123: ** After the merge, all segment blocks from the merged level are
141124: ** deleted.
141125: **
141126: ** MERGE_COUNT controls how often we merge segments.  16 seems to be
141127: ** somewhat of a sweet spot for insertion performance.  32 and 64 show
141128: ** very similar performance numbers to 16 on insertion, though they're
141129: ** a tiny bit slower (perhaps due to more overhead in merge-time
141130: ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
141131: ** 16, 2 about 66% slower than 16.
141132: **
141133: ** At query time, high MERGE_COUNT increases the number of segments
141134: ** which need to be scanned and merged.  For instance, with 100k docs
141135: ** inserted:
141136: **
141137: **    MERGE_COUNT   segments
141138: **       16           25
141139: **        8           12
141140: **        4           10
141141: **        2            6
141142: **
141143: ** This appears to have only a moderate impact on queries for very
141144: ** frequent terms (which are somewhat dominated by segment merge
141145: ** costs), and infrequent and non-existent terms still seem to be fast
141146: ** even with many segments.
141147: **
141148: ** TODO(shess) That said, it would be nice to have a better query-side
141149: ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
141150: ** optimizations to things like doclist merging will swing the sweet
141151: ** spot around.
141152: **
141153: **
141154: **
141155: **** Handling of deletions and updates ****
141156: ** Since we're using a segmented structure, with no docid-oriented
141157: ** index into the term index, we clearly cannot simply update the term
141158: ** index when a document is deleted or updated.  For deletions, we
141159: ** write an empty doclist (varint(docid) varint(POS_END)), for updates
141160: ** we simply write the new doclist.  Segment merges overwrite older
141161: ** data for a particular docid with newer data, so deletes or updates
141162: ** will eventually overtake the earlier data and knock it out.  The
141163: ** query logic likewise merges doclists so that newer data knocks out
141164: ** older data.
141165: */
141166: 
141167: /************** Include fts3Int.h in the middle of fts3.c ********************/
141168: /************** Begin file fts3Int.h *****************************************/
141169: /*
141170: ** 2009 Nov 12
141171: **
141172: ** The author disclaims copyright to this source code.  In place of
141173: ** a legal notice, here is a blessing:
141174: **
141175: **    May you do good and not evil.
141176: **    May you find forgiveness for yourself and forgive others.
141177: **    May you share freely, never taking more than you give.
141178: **
141179: ******************************************************************************
141180: **
141181: */
141182: #ifndef _FTSINT_H
141183: #define _FTSINT_H
141184: 
141185: #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
141186: # define NDEBUG 1
141187: #endif
141188: 
141189: /* FTS3/FTS4 require virtual tables */
141190: #ifdef SQLITE_OMIT_VIRTUALTABLE
141191: # undef SQLITE_ENABLE_FTS3
141192: # undef SQLITE_ENABLE_FTS4
141193: #endif
141194: 
141195: /*
141196: ** FTS4 is really an extension for FTS3.  It is enabled using the
141197: ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
141198: ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
141199: */
141200: #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
141201: # define SQLITE_ENABLE_FTS3
141202: #endif
141203: 
141204: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141205: 
141206: /* If not building as part of the core, include sqlite3ext.h. */
141207: #ifndef SQLITE_CORE
141208: /* # include "sqlite3ext.h"  */
141209: SQLITE_EXTENSION_INIT3
141210: #endif
141211: 
141212: /* #include "sqlite3.h" */
141213: /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
141214: /************** Begin file fts3_tokenizer.h **********************************/
141215: /*
141216: ** 2006 July 10
141217: **
141218: ** The author disclaims copyright to this source code.
141219: **
141220: *************************************************************************
141221: ** Defines the interface to tokenizers used by fulltext-search.  There
141222: ** are three basic components:
141223: **
141224: ** sqlite3_tokenizer_module is a singleton defining the tokenizer
141225: ** interface functions.  This is essentially the class structure for
141226: ** tokenizers.
141227: **
141228: ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
141229: ** including customization information defined at creation time.
141230: **
141231: ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
141232: ** tokens from a particular input.
141233: */
141234: #ifndef _FTS3_TOKENIZER_H_
141235: #define _FTS3_TOKENIZER_H_
141236: 
141237: /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
141238: ** If tokenizers are to be allowed to call sqlite3_*() functions, then
141239: ** we will need a way to register the API consistently.
141240: */
141241: /* #include "sqlite3.h" */
141242: 
141243: /*
141244: ** Structures used by the tokenizer interface. When a new tokenizer
141245: ** implementation is registered, the caller provides a pointer to
141246: ** an sqlite3_tokenizer_module containing pointers to the callback
141247: ** functions that make up an implementation.
141248: **
141249: ** When an fts3 table is created, it passes any arguments passed to
141250: ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
141251: ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
141252: ** implementation. The xCreate() function in turn returns an 
141253: ** sqlite3_tokenizer structure representing the specific tokenizer to
141254: ** be used for the fts3 table (customized by the tokenizer clause arguments).
141255: **
141256: ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
141257: ** method is called. It returns an sqlite3_tokenizer_cursor object
141258: ** that may be used to tokenize a specific input buffer based on
141259: ** the tokenization rules supplied by a specific sqlite3_tokenizer
141260: ** object.
141261: */
141262: typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
141263: typedef struct sqlite3_tokenizer sqlite3_tokenizer;
141264: typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
141265: 
141266: struct sqlite3_tokenizer_module {
141267: 
141268:   /*
141269:   ** Structure version. Should always be set to 0 or 1.
141270:   */
141271:   int iVersion;
141272: 
141273:   /*
141274:   ** Create a new tokenizer. The values in the argv[] array are the
141275:   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
141276:   ** TABLE statement that created the fts3 table. For example, if
141277:   ** the following SQL is executed:
141278:   **
141279:   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
141280:   **
141281:   ** then argc is set to 2, and the argv[] array contains pointers
141282:   ** to the strings "arg1" and "arg2".
141283:   **
141284:   ** This method should return either SQLITE_OK (0), or an SQLite error 
141285:   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
141286:   ** to point at the newly created tokenizer structure. The generic
141287:   ** sqlite3_tokenizer.pModule variable should not be initialized by
141288:   ** this callback. The caller will do so.
141289:   */
141290:   int (*xCreate)(
141291:     int argc,                           /* Size of argv array */
141292:     const char *const*argv,             /* Tokenizer argument strings */
141293:     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
141294:   );
141295: 
141296:   /*
141297:   ** Destroy an existing tokenizer. The fts3 module calls this method
141298:   ** exactly once for each successful call to xCreate().
141299:   */
141300:   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
141301: 
141302:   /*
141303:   ** Create a tokenizer cursor to tokenize an input buffer. The caller
141304:   ** is responsible for ensuring that the input buffer remains valid
141305:   ** until the cursor is closed (using the xClose() method). 
141306:   */
141307:   int (*xOpen)(
141308:     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
141309:     const char *pInput, int nBytes,      /* Input buffer */
141310:     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
141311:   );
141312: 
141313:   /*
141314:   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
141315:   ** method exactly once for each successful call to xOpen().
141316:   */
141317:   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
141318: 
141319:   /*
141320:   ** Retrieve the next token from the tokenizer cursor pCursor. This
141321:   ** method should either return SQLITE_OK and set the values of the
141322:   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
141323:   ** the end of the buffer has been reached, or an SQLite error code.
141324:   **
141325:   ** *ppToken should be set to point at a buffer containing the 
141326:   ** normalized version of the token (i.e. after any case-folding and/or
141327:   ** stemming has been performed). *pnBytes should be set to the length
141328:   ** of this buffer in bytes. The input text that generated the token is
141329:   ** identified by the byte offsets returned in *piStartOffset and
141330:   ** *piEndOffset. *piStartOffset should be set to the index of the first
141331:   ** byte of the token in the input buffer. *piEndOffset should be set
141332:   ** to the index of the first byte just past the end of the token in
141333:   ** the input buffer.
141334:   **
141335:   ** The buffer *ppToken is set to point at is managed by the tokenizer
141336:   ** implementation. It is only required to be valid until the next call
141337:   ** to xNext() or xClose(). 
141338:   */
141339:   /* TODO(shess) current implementation requires pInput to be
141340:   ** nul-terminated.  This should either be fixed, or pInput/nBytes
141341:   ** should be converted to zInput.
141342:   */
141343:   int (*xNext)(
141344:     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
141345:     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
141346:     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
141347:     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
141348:     int *piPosition      /* OUT: Number of tokens returned before this one */
141349:   );
141350: 
141351:   /***********************************************************************
141352:   ** Methods below this point are only available if iVersion>=1.
141353:   */
141354: 
141355:   /* 
141356:   ** Configure the language id of a tokenizer cursor.
141357:   */
141358:   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
141359: };
141360: 
141361: struct sqlite3_tokenizer {
141362:   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
141363:   /* Tokenizer implementations will typically add additional fields */
141364: };
141365: 
141366: struct sqlite3_tokenizer_cursor {
141367:   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
141368:   /* Tokenizer implementations will typically add additional fields */
141369: };
141370: 
141371: int fts3_global_term_cnt(int iTerm, int iCol);
141372: int fts3_term_cnt(int iTerm, int iCol);
141373: 
141374: 
141375: #endif /* _FTS3_TOKENIZER_H_ */
141376: 
141377: /************** End of fts3_tokenizer.h **************************************/
141378: /************** Continuing where we left off in fts3Int.h ********************/
141379: /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
141380: /************** Begin file fts3_hash.h ***************************************/
141381: /*
141382: ** 2001 September 22
141383: **
141384: ** The author disclaims copyright to this source code.  In place of
141385: ** a legal notice, here is a blessing:
141386: **
141387: **    May you do good and not evil.
141388: **    May you find forgiveness for yourself and forgive others.
141389: **    May you share freely, never taking more than you give.
141390: **
141391: *************************************************************************
141392: ** This is the header file for the generic hash-table implementation
141393: ** used in SQLite.  We've modified it slightly to serve as a standalone
141394: ** hash table implementation for the full-text indexing module.
141395: **
141396: */
141397: #ifndef _FTS3_HASH_H_
141398: #define _FTS3_HASH_H_
141399: 
141400: /* Forward declarations of structures. */
141401: typedef struct Fts3Hash Fts3Hash;
141402: typedef struct Fts3HashElem Fts3HashElem;
141403: 
141404: /* A complete hash table is an instance of the following structure.
141405: ** The internals of this structure are intended to be opaque -- client
141406: ** code should not attempt to access or modify the fields of this structure
141407: ** directly.  Change this structure only by using the routines below.
141408: ** However, many of the "procedures" and "functions" for modifying and
141409: ** accessing this structure are really macros, so we can't really make
141410: ** this structure opaque.
141411: */
141412: struct Fts3Hash {
141413:   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
141414:   char copyKey;           /* True if copy of key made on insert */
141415:   int count;              /* Number of entries in this table */
141416:   Fts3HashElem *first;    /* The first element of the array */
141417:   int htsize;             /* Number of buckets in the hash table */
141418:   struct _fts3ht {        /* the hash table */
141419:     int count;               /* Number of entries with this hash */
141420:     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
141421:   } *ht;
141422: };
141423: 
141424: /* Each element in the hash table is an instance of the following 
141425: ** structure.  All elements are stored on a single doubly-linked list.
141426: **
141427: ** Again, this structure is intended to be opaque, but it can't really
141428: ** be opaque because it is used by macros.
141429: */
141430: struct Fts3HashElem {
141431:   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
141432:   void *data;                /* Data associated with this element */
141433:   void *pKey; int nKey;      /* Key associated with this element */
141434: };
141435: 
141436: /*
141437: ** There are 2 different modes of operation for a hash table:
141438: **
141439: **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
141440: **                           (including the null-terminator, if any).  Case
141441: **                           is respected in comparisons.
141442: **
141443: **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
141444: **                           memcmp() is used to compare keys.
141445: **
141446: ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
141447: */
141448: #define FTS3_HASH_STRING    1
141449: #define FTS3_HASH_BINARY    2
141450: 
141451: /*
141452: ** Access routines.  To delete, insert a NULL pointer.
141453: */
141454: SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
141455: SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
141456: SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
141457: SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
141458: SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
141459: 
141460: /*
141461: ** Shorthand for the functions above
141462: */
141463: #define fts3HashInit     sqlite3Fts3HashInit
141464: #define fts3HashInsert   sqlite3Fts3HashInsert
141465: #define fts3HashFind     sqlite3Fts3HashFind
141466: #define fts3HashClear    sqlite3Fts3HashClear
141467: #define fts3HashFindElem sqlite3Fts3HashFindElem
141468: 
141469: /*
141470: ** Macros for looping over all elements of a hash table.  The idiom is
141471: ** like this:
141472: **
141473: **   Fts3Hash h;
141474: **   Fts3HashElem *p;
141475: **   ...
141476: **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
141477: **     SomeStructure *pData = fts3HashData(p);
141478: **     // do something with pData
141479: **   }
141480: */
141481: #define fts3HashFirst(H)  ((H)->first)
141482: #define fts3HashNext(E)   ((E)->next)
141483: #define fts3HashData(E)   ((E)->data)
141484: #define fts3HashKey(E)    ((E)->pKey)
141485: #define fts3HashKeysize(E) ((E)->nKey)
141486: 
141487: /*
141488: ** Number of entries in a hash table
141489: */
141490: #define fts3HashCount(H)  ((H)->count)
141491: 
141492: #endif /* _FTS3_HASH_H_ */
141493: 
141494: /************** End of fts3_hash.h *******************************************/
141495: /************** Continuing where we left off in fts3Int.h ********************/
141496: 
141497: /*
141498: ** This constant determines the maximum depth of an FTS expression tree
141499: ** that the library will create and use. FTS uses recursion to perform 
141500: ** various operations on the query tree, so the disadvantage of a large
141501: ** limit is that it may allow very large queries to use large amounts
141502: ** of stack space (perhaps causing a stack overflow).
141503: */
141504: #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
141505: # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
141506: #endif
141507: 
141508: 
141509: /*
141510: ** This constant controls how often segments are merged. Once there are
141511: ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
141512: ** segment of level N+1.
141513: */
141514: #define FTS3_MERGE_COUNT 16
141515: 
141516: /*
141517: ** This is the maximum amount of data (in bytes) to store in the 
141518: ** Fts3Table.pendingTerms hash table. Normally, the hash table is
141519: ** populated as documents are inserted/updated/deleted in a transaction
141520: ** and used to create a new segment when the transaction is committed.
141521: ** However if this limit is reached midway through a transaction, a new 
141522: ** segment is created and the hash table cleared immediately.
141523: */
141524: #define FTS3_MAX_PENDING_DATA (1*1024*1024)
141525: 
141526: /*
141527: ** Macro to return the number of elements in an array. SQLite has a
141528: ** similar macro called ArraySize(). Use a different name to avoid
141529: ** a collision when building an amalgamation with built-in FTS3.
141530: */
141531: #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
141532: 
141533: 
141534: #ifndef MIN
141535: # define MIN(x,y) ((x)<(y)?(x):(y))
141536: #endif
141537: #ifndef MAX
141538: # define MAX(x,y) ((x)>(y)?(x):(y))
141539: #endif
141540: 
141541: /*
141542: ** Maximum length of a varint encoded integer. The varint format is different
141543: ** from that used by SQLite, so the maximum length is 10, not 9.
141544: */
141545: #define FTS3_VARINT_MAX 10
141546: 
141547: /*
141548: ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
141549: ** in the document set and zero or more prefix indexes. All indexes are stored
141550: ** as one or more b+-trees in the %_segments and %_segdir tables. 
141551: **
141552: ** It is possible to determine which index a b+-tree belongs to based on the
141553: ** value stored in the "%_segdir.level" column. Given this value L, the index
141554: ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
141555: ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
141556: ** between 1024 and 2047 to index 1, and so on.
141557: **
141558: ** It is considered impossible for an index to use more than 1024 levels. In 
141559: ** theory though this may happen, but only after at least 
141560: ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
141561: */
141562: #define FTS3_SEGDIR_MAXLEVEL      1024
141563: #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
141564: 
141565: /*
141566: ** The testcase() macro is only used by the amalgamation.  If undefined,
141567: ** make it a no-op.
141568: */
141569: #ifndef testcase
141570: # define testcase(X)
141571: #endif
141572: 
141573: /*
141574: ** Terminator values for position-lists and column-lists.
141575: */
141576: #define POS_COLUMN  (1)     /* Column-list terminator */
141577: #define POS_END     (0)     /* Position-list terminator */ 
141578: 
141579: /*
141580: ** This section provides definitions to allow the
141581: ** FTS3 extension to be compiled outside of the 
141582: ** amalgamation.
141583: */
141584: #ifndef SQLITE_AMALGAMATION
141585: /*
141586: ** Macros indicating that conditional expressions are always true or
141587: ** false.
141588: */
141589: #ifdef SQLITE_COVERAGE_TEST
141590: # define ALWAYS(x) (1)
141591: # define NEVER(X)  (0)
141592: #elif defined(SQLITE_DEBUG)
141593: # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
141594: # define NEVER(x) sqlite3Fts3Never((x)!=0)
141595: SQLITE_PRIVATE int sqlite3Fts3Always(int b);
141596: SQLITE_PRIVATE int sqlite3Fts3Never(int b);
141597: #else
141598: # define ALWAYS(x) (x)
141599: # define NEVER(x)  (x)
141600: #endif
141601: 
141602: /*
141603: ** Internal types used by SQLite.
141604: */
141605: typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
141606: typedef short int i16;            /* 2-byte (or larger) signed integer */
141607: typedef unsigned int u32;         /* 4-byte unsigned integer */
141608: typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
141609: typedef sqlite3_int64 i64;        /* 8-byte signed integer */
141610: 
141611: /*
141612: ** Macro used to suppress compiler warnings for unused parameters.
141613: */
141614: #define UNUSED_PARAMETER(x) (void)(x)
141615: 
141616: /*
141617: ** Activate assert() only if SQLITE_TEST is enabled.
141618: */
141619: #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
141620: # define NDEBUG 1
141621: #endif
141622: 
141623: /*
141624: ** The TESTONLY macro is used to enclose variable declarations or
141625: ** other bits of code that are needed to support the arguments
141626: ** within testcase() and assert() macros.
141627: */
141628: #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
141629: # define TESTONLY(X)  X
141630: #else
141631: # define TESTONLY(X)
141632: #endif
141633: 
141634: #endif /* SQLITE_AMALGAMATION */
141635: 
141636: #ifdef SQLITE_DEBUG
141637: SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
141638: # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
141639: #else
141640: # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
141641: #endif
141642: 
141643: typedef struct Fts3Table Fts3Table;
141644: typedef struct Fts3Cursor Fts3Cursor;
141645: typedef struct Fts3Expr Fts3Expr;
141646: typedef struct Fts3Phrase Fts3Phrase;
141647: typedef struct Fts3PhraseToken Fts3PhraseToken;
141648: 
141649: typedef struct Fts3Doclist Fts3Doclist;
141650: typedef struct Fts3SegFilter Fts3SegFilter;
141651: typedef struct Fts3DeferredToken Fts3DeferredToken;
141652: typedef struct Fts3SegReader Fts3SegReader;
141653: typedef struct Fts3MultiSegReader Fts3MultiSegReader;
141654: 
141655: typedef struct MatchinfoBuffer MatchinfoBuffer;
141656: 
141657: /*
141658: ** A connection to a fulltext index is an instance of the following
141659: ** structure. The xCreate and xConnect methods create an instance
141660: ** of this structure and xDestroy and xDisconnect free that instance.
141661: ** All other methods receive a pointer to the structure as one of their
141662: ** arguments.
141663: */
141664: struct Fts3Table {
141665:   sqlite3_vtab base;              /* Base class used by SQLite core */
141666:   sqlite3 *db;                    /* The database connection */
141667:   const char *zDb;                /* logical database name */
141668:   const char *zName;              /* virtual table name */
141669:   int nColumn;                    /* number of named columns in virtual table */
141670:   char **azColumn;                /* column names.  malloced */
141671:   u8 *abNotindexed;               /* True for 'notindexed' columns */
141672:   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
141673:   char *zContentTbl;              /* content=xxx option, or NULL */
141674:   char *zLanguageid;              /* languageid=xxx option, or NULL */
141675:   int nAutoincrmerge;             /* Value configured by 'automerge' */
141676:   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
141677: 
141678:   /* Precompiled statements used by the implementation. Each of these 
141679:   ** statements is run and reset within a single virtual table API call. 
141680:   */
141681:   sqlite3_stmt *aStmt[40];
141682: 
141683:   char *zReadExprlist;
141684:   char *zWriteExprlist;
141685: 
141686:   int nNodeSize;                  /* Soft limit for node size */
141687:   u8 bFts4;                       /* True for FTS4, false for FTS3 */
141688:   u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
141689:   u8 bHasDocsize;                 /* True if %_docsize table exists */
141690:   u8 bDescIdx;                    /* True if doclists are in reverse order */
141691:   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
141692:   int nPgsz;                      /* Page size for host database */
141693:   char *zSegmentsTbl;             /* Name of %_segments table */
141694:   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
141695: 
141696:   /* 
141697:   ** The following array of hash tables is used to buffer pending index 
141698:   ** updates during transactions. All pending updates buffered at any one
141699:   ** time must share a common language-id (see the FTS4 langid= feature).
141700:   ** The current language id is stored in variable iPrevLangid.
141701:   **
141702:   ** A single FTS4 table may have multiple full-text indexes. For each index
141703:   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
141704:   ** terms that appear in the document set. Each subsequent index in aIndex[]
141705:   ** is an index of prefixes of a specific length.
141706:   **
141707:   ** Variable nPendingData contains an estimate the memory consumed by the 
141708:   ** pending data structures, including hash table overhead, but not including
141709:   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
141710:   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
141711:   ** recently inserted record.
141712:   */
141713:   int nIndex;                     /* Size of aIndex[] */
141714:   struct Fts3Index {
141715:     int nPrefix;                  /* Prefix length (0 for main terms index) */
141716:     Fts3Hash hPending;            /* Pending terms table for this index */
141717:   } *aIndex;
141718:   int nMaxPendingData;            /* Max pending data before flush to disk */
141719:   int nPendingData;               /* Current bytes of pending data */
141720:   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
141721:   int iPrevLangid;                /* Langid of recently inserted document */
141722:   int bPrevDelete;                /* True if last operation was a delete */
141723: 
141724: #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
141725:   /* State variables used for validating that the transaction control
141726:   ** methods of the virtual table are called at appropriate times.  These
141727:   ** values do not contribute to FTS functionality; they are used for
141728:   ** verifying the operation of the SQLite core.
141729:   */
141730:   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
141731:   int mxSavepoint;       /* Largest valid xSavepoint integer */
141732: #endif
141733: 
141734: #ifdef SQLITE_TEST
141735:   /* True to disable the incremental doclist optimization. This is controled
141736:   ** by special insert command 'test-no-incr-doclist'.  */
141737:   int bNoIncrDoclist;
141738: #endif
141739: };
141740: 
141741: /*
141742: ** When the core wants to read from the virtual table, it creates a
141743: ** virtual table cursor (an instance of the following structure) using
141744: ** the xOpen method. Cursors are destroyed using the xClose method.
141745: */
141746: struct Fts3Cursor {
141747:   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
141748:   i16 eSearch;                    /* Search strategy (see below) */
141749:   u8 isEof;                       /* True if at End Of Results */
141750:   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
141751:   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
141752:   Fts3Expr *pExpr;                /* Parsed MATCH query string */
141753:   int iLangid;                    /* Language being queried for */
141754:   int nPhrase;                    /* Number of matchable phrases in query */
141755:   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
141756:   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
141757:   char *pNextId;                  /* Pointer into the body of aDoclist */
141758:   char *aDoclist;                 /* List of docids for full-text queries */
141759:   int nDoclist;                   /* Size of buffer at aDoclist */
141760:   u8 bDesc;                       /* True to sort in descending order */
141761:   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
141762:   int nRowAvg;                    /* Average size of database rows, in pages */
141763:   sqlite3_int64 nDoc;             /* Documents in table */
141764:   i64 iMinDocid;                  /* Minimum docid to return */
141765:   i64 iMaxDocid;                  /* Maximum docid to return */
141766:   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
141767:   MatchinfoBuffer *pMIBuffer;     /* Buffer for matchinfo data */
141768: };
141769: 
141770: #define FTS3_EVAL_FILTER    0
141771: #define FTS3_EVAL_NEXT      1
141772: #define FTS3_EVAL_MATCHINFO 2
141773: 
141774: /*
141775: ** The Fts3Cursor.eSearch member is always set to one of the following.
141776: ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
141777: ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
141778: ** of the column to be searched.  For example, in
141779: **
141780: **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
141781: **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
141782: ** 
141783: ** Because the LHS of the MATCH operator is 2nd column "b",
141784: ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
141785: ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
141786: ** indicating that all columns should be searched,
141787: ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
141788: */
141789: #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
141790: #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
141791: #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
141792: 
141793: /*
141794: ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
141795: ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
141796: ** above. The upper 16-bits contain a combination of the following
141797: ** bits, used to describe extra constraints on full-text searches.
141798: */
141799: #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
141800: #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
141801: #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
141802: 
141803: struct Fts3Doclist {
141804:   char *aAll;                    /* Array containing doclist (or NULL) */
141805:   int nAll;                      /* Size of a[] in bytes */
141806:   char *pNextDocid;              /* Pointer to next docid */
141807: 
141808:   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
141809:   int bFreeList;                 /* True if pList should be sqlite3_free()d */
141810:   char *pList;                   /* Pointer to position list following iDocid */
141811:   int nList;                     /* Length of position list */
141812: };
141813: 
141814: /*
141815: ** A "phrase" is a sequence of one or more tokens that must match in
141816: ** sequence.  A single token is the base case and the most common case.
141817: ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
141818: ** nToken will be the number of tokens in the string.
141819: */
141820: struct Fts3PhraseToken {
141821:   char *z;                        /* Text of the token */
141822:   int n;                          /* Number of bytes in buffer z */
141823:   int isPrefix;                   /* True if token ends with a "*" character */
141824:   int bFirst;                     /* True if token must appear at position 0 */
141825: 
141826:   /* Variables above this point are populated when the expression is
141827:   ** parsed (by code in fts3_expr.c). Below this point the variables are
141828:   ** used when evaluating the expression. */
141829:   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
141830:   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
141831: };
141832: 
141833: struct Fts3Phrase {
141834:   /* Cache of doclist for this phrase. */
141835:   Fts3Doclist doclist;
141836:   int bIncr;                 /* True if doclist is loaded incrementally */
141837:   int iDoclistToken;
141838: 
141839:   /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
141840:   ** OR condition.  */
141841:   char *pOrPoslist;
141842:   i64 iOrDocid;
141843: 
141844:   /* Variables below this point are populated by fts3_expr.c when parsing 
141845:   ** a MATCH expression. Everything above is part of the evaluation phase. 
141846:   */
141847:   int nToken;                /* Number of tokens in the phrase */
141848:   int iColumn;               /* Index of column this phrase must match */
141849:   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
141850: };
141851: 
141852: /*
141853: ** A tree of these objects forms the RHS of a MATCH operator.
141854: **
141855: ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
141856: ** points to a malloced buffer, size nDoclist bytes, containing the results 
141857: ** of this phrase query in FTS3 doclist format. As usual, the initial 
141858: ** "Length" field found in doclists stored on disk is omitted from this 
141859: ** buffer.
141860: **
141861: ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
141862: ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
141863: ** where nCol is the number of columns in the queried FTS table. The array
141864: ** is populated as follows:
141865: **
141866: **   aMI[iCol*3 + 0] = Undefined
141867: **   aMI[iCol*3 + 1] = Number of occurrences
141868: **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
141869: **
141870: ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
141871: ** when the expression node is.
141872: */
141873: struct Fts3Expr {
141874:   int eType;                 /* One of the FTSQUERY_XXX values defined below */
141875:   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
141876:   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
141877:   Fts3Expr *pLeft;           /* Left operand */
141878:   Fts3Expr *pRight;          /* Right operand */
141879:   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
141880: 
141881:   /* The following are used by the fts3_eval.c module. */
141882:   sqlite3_int64 iDocid;      /* Current docid */
141883:   u8 bEof;                   /* True this expression is at EOF already */
141884:   u8 bStart;                 /* True if iDocid is valid */
141885:   u8 bDeferred;              /* True if this expression is entirely deferred */
141886: 
141887:   /* The following are used by the fts3_snippet.c module. */
141888:   int iPhrase;               /* Index of this phrase in matchinfo() results */
141889:   u32 *aMI;                  /* See above */
141890: };
141891: 
141892: /*
141893: ** Candidate values for Fts3Query.eType. Note that the order of the first
141894: ** four values is in order of precedence when parsing expressions. For 
141895: ** example, the following:
141896: **
141897: **   "a OR b AND c NOT d NEAR e"
141898: **
141899: ** is equivalent to:
141900: **
141901: **   "a OR (b AND (c NOT (d NEAR e)))"
141902: */
141903: #define FTSQUERY_NEAR   1
141904: #define FTSQUERY_NOT    2
141905: #define FTSQUERY_AND    3
141906: #define FTSQUERY_OR     4
141907: #define FTSQUERY_PHRASE 5
141908: 
141909: 
141910: /* fts3_write.c */
141911: SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
141912: SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
141913: SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
141914: SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
141915: SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
141916:   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
141917: SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
141918:   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
141919: SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
141920: SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
141921: SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
141922: 
141923: SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
141924: SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
141925: 
141926: #ifndef SQLITE_DISABLE_FTS4_DEFERRED
141927: SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
141928: SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
141929: SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
141930: SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
141931: SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
141932: #else
141933: # define sqlite3Fts3FreeDeferredTokens(x)
141934: # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
141935: # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
141936: # define sqlite3Fts3FreeDeferredDoclists(x)
141937: # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
141938: #endif
141939: 
141940: SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
141941: SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
141942: 
141943: /* Special values interpreted by sqlite3SegReaderCursor() */
141944: #define FTS3_SEGCURSOR_PENDING        -1
141945: #define FTS3_SEGCURSOR_ALL            -2
141946: 
141947: SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
141948: SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
141949: SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
141950: 
141951: SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
141952:     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
141953: 
141954: /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
141955: #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
141956: #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
141957: #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
141958: #define FTS3_SEGMENT_PREFIX        0x00000008
141959: #define FTS3_SEGMENT_SCAN          0x00000010
141960: #define FTS3_SEGMENT_FIRST         0x00000020
141961: 
141962: /* Type passed as 4th argument to SegmentReaderIterate() */
141963: struct Fts3SegFilter {
141964:   const char *zTerm;
141965:   int nTerm;
141966:   int iCol;
141967:   int flags;
141968: };
141969: 
141970: struct Fts3MultiSegReader {
141971:   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
141972:   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
141973:   int nSegment;                   /* Size of apSegment array */
141974:   int nAdvance;                   /* How many seg-readers to advance */
141975:   Fts3SegFilter *pFilter;         /* Pointer to filter object */
141976:   char *aBuffer;                  /* Buffer to merge doclists in */
141977:   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
141978: 
141979:   int iColFilter;                 /* If >=0, filter for this column */
141980:   int bRestart;
141981: 
141982:   /* Used by fts3.c only. */
141983:   int nCost;                      /* Cost of running iterator */
141984:   int bLookup;                    /* True if a lookup of a single entry. */
141985: 
141986:   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
141987:   char *zTerm;                    /* Pointer to term buffer */
141988:   int nTerm;                      /* Size of zTerm in bytes */
141989:   char *aDoclist;                 /* Pointer to doclist buffer */
141990:   int nDoclist;                   /* Size of aDoclist[] in bytes */
141991: };
141992: 
141993: SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
141994: 
141995: #define fts3GetVarint32(p, piVal) (                                           \
141996:   (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
141997: )
141998: 
141999: /* fts3.c */
142000: SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
142001: SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
142002: SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
142003: SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
142004: SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
142005: SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
142006: SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
142007: SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
142008: SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
142009: SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
142010: SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
142011: 
142012: /* fts3_tokenizer.c */
142013: SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
142014: SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
142015: SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
142016:     sqlite3_tokenizer **, char **
142017: );
142018: SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
142019: 
142020: /* fts3_snippet.c */
142021: SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
142022: SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
142023:   const char *, const char *, int, int
142024: );
142025: SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
142026: SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
142027: 
142028: /* fts3_expr.c */
142029: SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
142030:   char **, int, int, int, const char *, int, Fts3Expr **, char **
142031: );
142032: SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
142033: #ifdef SQLITE_TEST
142034: SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
142035: SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
142036: #endif
142037: 
142038: SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
142039:   sqlite3_tokenizer_cursor **
142040: );
142041: 
142042: /* fts3_aux.c */
142043: SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
142044: 
142045: SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
142046: 
142047: SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
142048:     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
142049: SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
142050:     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
142051: SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
142052: SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
142053: SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
142054: 
142055: /* fts3_tokenize_vtab.c */
142056: SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
142057: 
142058: /* fts3_unicode2.c (functions generated by parsing unicode text files) */
142059: #ifndef SQLITE_DISABLE_FTS3_UNICODE
142060: SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
142061: SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
142062: SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
142063: #endif
142064: 
142065: #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
142066: #endif /* _FTSINT_H */
142067: 
142068: /************** End of fts3Int.h *********************************************/
142069: /************** Continuing where we left off in fts3.c ***********************/
142070: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142071: 
142072: #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
142073: # define SQLITE_CORE 1
142074: #endif
142075: 
142076: /* #include <assert.h> */
142077: /* #include <stdlib.h> */
142078: /* #include <stddef.h> */
142079: /* #include <stdio.h> */
142080: /* #include <string.h> */
142081: /* #include <stdarg.h> */
142082: 
142083: /* #include "fts3.h" */
142084: #ifndef SQLITE_CORE 
142085: /* # include "sqlite3ext.h" */
142086:   SQLITE_EXTENSION_INIT1
142087: #endif
142088: 
142089: static int fts3EvalNext(Fts3Cursor *pCsr);
142090: static int fts3EvalStart(Fts3Cursor *pCsr);
142091: static int fts3TermSegReaderCursor(
142092:     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
142093: 
142094: #ifndef SQLITE_AMALGAMATION
142095: # if defined(SQLITE_DEBUG)
142096: SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
142097: SQLITE_PRIVATE int sqlite3Fts3Never(int b)  { assert( !b ); return b; }
142098: # endif
142099: #endif
142100: 
142101: /* 
142102: ** Write a 64-bit variable-length integer to memory starting at p[0].
142103: ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
142104: ** The number of bytes written is returned.
142105: */
142106: SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
142107:   unsigned char *q = (unsigned char *) p;
142108:   sqlite_uint64 vu = v;
142109:   do{
142110:     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
142111:     vu >>= 7;
142112:   }while( vu!=0 );
142113:   q[-1] &= 0x7f;  /* turn off high bit in final byte */
142114:   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
142115:   return (int) (q - (unsigned char *)p);
142116: }
142117: 
142118: #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
142119:   v = (v & mask1) | ( (*ptr++) << shift );                    \
142120:   if( (v & mask2)==0 ){ var = v; return ret; }
142121: #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
142122:   v = (*ptr++);                                               \
142123:   if( (v & mask2)==0 ){ var = v; return ret; }
142124: 
142125: /* 
142126: ** Read a 64-bit variable-length integer from memory starting at p[0].
142127: ** Return the number of bytes read, or 0 on error.
142128: ** The value is stored in *v.
142129: */
142130: SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
142131:   const char *pStart = p;
142132:   u32 a;
142133:   u64 b;
142134:   int shift;
142135: 
142136:   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
142137:   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
142138:   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
142139:   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
142140:   b = (a & 0x0FFFFFFF );
142141: 
142142:   for(shift=28; shift<=63; shift+=7){
142143:     u64 c = *p++;
142144:     b += (c&0x7F) << shift;
142145:     if( (c & 0x80)==0 ) break;
142146:   }
142147:   *v = b;
142148:   return (int)(p - pStart);
142149: }
142150: 
142151: /*
142152: ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
142153: ** 32-bit integer before it is returned.
142154: */
142155: SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
142156:   u32 a;
142157: 
142158: #ifndef fts3GetVarint32
142159:   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
142160: #else
142161:   a = (*p++);
142162:   assert( a & 0x80 );
142163: #endif
142164: 
142165:   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
142166:   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
142167:   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
142168:   a = (a & 0x0FFFFFFF );
142169:   *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
142170:   return 5;
142171: }
142172: 
142173: /*
142174: ** Return the number of bytes required to encode v as a varint
142175: */
142176: SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
142177:   int i = 0;
142178:   do{
142179:     i++;
142180:     v >>= 7;
142181:   }while( v!=0 );
142182:   return i;
142183: }
142184: 
142185: /*
142186: ** Convert an SQL-style quoted string into a normal string by removing
142187: ** the quote characters.  The conversion is done in-place.  If the
142188: ** input does not begin with a quote character, then this routine
142189: ** is a no-op.
142190: **
142191: ** Examples:
142192: **
142193: **     "abc"   becomes   abc
142194: **     'xyz'   becomes   xyz
142195: **     [pqr]   becomes   pqr
142196: **     `mno`   becomes   mno
142197: **
142198: */
142199: SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
142200:   char quote;                     /* Quote character (if any ) */
142201: 
142202:   quote = z[0];
142203:   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
142204:     int iIn = 1;                  /* Index of next byte to read from input */
142205:     int iOut = 0;                 /* Index of next byte to write to output */
142206: 
142207:     /* If the first byte was a '[', then the close-quote character is a ']' */
142208:     if( quote=='[' ) quote = ']';  
142209: 
142210:     while( z[iIn] ){
142211:       if( z[iIn]==quote ){
142212:         if( z[iIn+1]!=quote ) break;
142213:         z[iOut++] = quote;
142214:         iIn += 2;
142215:       }else{
142216:         z[iOut++] = z[iIn++];
142217:       }
142218:     }
142219:     z[iOut] = '\0';
142220:   }
142221: }
142222: 
142223: /*
142224: ** Read a single varint from the doclist at *pp and advance *pp to point
142225: ** to the first byte past the end of the varint.  Add the value of the varint
142226: ** to *pVal.
142227: */
142228: static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
142229:   sqlite3_int64 iVal;
142230:   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
142231:   *pVal += iVal;
142232: }
142233: 
142234: /*
142235: ** When this function is called, *pp points to the first byte following a
142236: ** varint that is part of a doclist (or position-list, or any other list
142237: ** of varints). This function moves *pp to point to the start of that varint,
142238: ** and sets *pVal by the varint value.
142239: **
142240: ** Argument pStart points to the first byte of the doclist that the
142241: ** varint is part of.
142242: */
142243: static void fts3GetReverseVarint(
142244:   char **pp, 
142245:   char *pStart, 
142246:   sqlite3_int64 *pVal
142247: ){
142248:   sqlite3_int64 iVal;
142249:   char *p;
142250: 
142251:   /* Pointer p now points at the first byte past the varint we are 
142252:   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
142253:   ** clear on character p[-1]. */
142254:   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
142255:   p++;
142256:   *pp = p;
142257: 
142258:   sqlite3Fts3GetVarint(p, &iVal);
142259:   *pVal = iVal;
142260: }
142261: 
142262: /*
142263: ** The xDisconnect() virtual table method.
142264: */
142265: static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
142266:   Fts3Table *p = (Fts3Table *)pVtab;
142267:   int i;
142268: 
142269:   assert( p->nPendingData==0 );
142270:   assert( p->pSegments==0 );
142271: 
142272:   /* Free any prepared statements held */
142273:   for(i=0; i<SizeofArray(p->aStmt); i++){
142274:     sqlite3_finalize(p->aStmt[i]);
142275:   }
142276:   sqlite3_free(p->zSegmentsTbl);
142277:   sqlite3_free(p->zReadExprlist);
142278:   sqlite3_free(p->zWriteExprlist);
142279:   sqlite3_free(p->zContentTbl);
142280:   sqlite3_free(p->zLanguageid);
142281: 
142282:   /* Invoke the tokenizer destructor to free the tokenizer. */
142283:   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
142284: 
142285:   sqlite3_free(p);
142286:   return SQLITE_OK;
142287: }
142288: 
142289: /*
142290: ** Write an error message into *pzErr
142291: */
142292: SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
142293:   va_list ap;
142294:   sqlite3_free(*pzErr);
142295:   va_start(ap, zFormat);
142296:   *pzErr = sqlite3_vmprintf(zFormat, ap);
142297:   va_end(ap);
142298: }
142299: 
142300: /*
142301: ** Construct one or more SQL statements from the format string given
142302: ** and then evaluate those statements. The success code is written
142303: ** into *pRc.
142304: **
142305: ** If *pRc is initially non-zero then this routine is a no-op.
142306: */
142307: static void fts3DbExec(
142308:   int *pRc,              /* Success code */
142309:   sqlite3 *db,           /* Database in which to run SQL */
142310:   const char *zFormat,   /* Format string for SQL */
142311:   ...                    /* Arguments to the format string */
142312: ){
142313:   va_list ap;
142314:   char *zSql;
142315:   if( *pRc ) return;
142316:   va_start(ap, zFormat);
142317:   zSql = sqlite3_vmprintf(zFormat, ap);
142318:   va_end(ap);
142319:   if( zSql==0 ){
142320:     *pRc = SQLITE_NOMEM;
142321:   }else{
142322:     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
142323:     sqlite3_free(zSql);
142324:   }
142325: }
142326: 
142327: /*
142328: ** The xDestroy() virtual table method.
142329: */
142330: static int fts3DestroyMethod(sqlite3_vtab *pVtab){
142331:   Fts3Table *p = (Fts3Table *)pVtab;
142332:   int rc = SQLITE_OK;              /* Return code */
142333:   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
142334:   sqlite3 *db = p->db;             /* Database handle */
142335: 
142336:   /* Drop the shadow tables */
142337:   if( p->zContentTbl==0 ){
142338:     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
142339:   }
142340:   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
142341:   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
142342:   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
142343:   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
142344: 
142345:   /* If everything has worked, invoke fts3DisconnectMethod() to free the
142346:   ** memory associated with the Fts3Table structure and return SQLITE_OK.
142347:   ** Otherwise, return an SQLite error code.
142348:   */
142349:   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
142350: }
142351: 
142352: 
142353: /*
142354: ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
142355: ** passed as the first argument. This is done as part of the xConnect()
142356: ** and xCreate() methods.
142357: **
142358: ** If *pRc is non-zero when this function is called, it is a no-op. 
142359: ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
142360: ** before returning.
142361: */
142362: static void fts3DeclareVtab(int *pRc, Fts3Table *p){
142363:   if( *pRc==SQLITE_OK ){
142364:     int i;                        /* Iterator variable */
142365:     int rc;                       /* Return code */
142366:     char *zSql;                   /* SQL statement passed to declare_vtab() */
142367:     char *zCols;                  /* List of user defined columns */
142368:     const char *zLanguageid;
142369: 
142370:     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
142371:     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
142372: 
142373:     /* Create a list of user columns for the virtual table */
142374:     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
142375:     for(i=1; zCols && i<p->nColumn; i++){
142376:       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
142377:     }
142378: 
142379:     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
142380:     zSql = sqlite3_mprintf(
142381:         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
142382:         zCols, p->zName, zLanguageid
142383:     );
142384:     if( !zCols || !zSql ){
142385:       rc = SQLITE_NOMEM;
142386:     }else{
142387:       rc = sqlite3_declare_vtab(p->db, zSql);
142388:     }
142389: 
142390:     sqlite3_free(zSql);
142391:     sqlite3_free(zCols);
142392:     *pRc = rc;
142393:   }
142394: }
142395: 
142396: /*
142397: ** Create the %_stat table if it does not already exist.
142398: */
142399: SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
142400:   fts3DbExec(pRc, p->db, 
142401:       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
142402:           "(id INTEGER PRIMARY KEY, value BLOB);",
142403:       p->zDb, p->zName
142404:   );
142405:   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
142406: }
142407: 
142408: /*
142409: ** Create the backing store tables (%_content, %_segments and %_segdir)
142410: ** required by the FTS3 table passed as the only argument. This is done
142411: ** as part of the vtab xCreate() method.
142412: **
142413: ** If the p->bHasDocsize boolean is true (indicating that this is an
142414: ** FTS4 table, not an FTS3 table) then also create the %_docsize and
142415: ** %_stat tables required by FTS4.
142416: */
142417: static int fts3CreateTables(Fts3Table *p){
142418:   int rc = SQLITE_OK;             /* Return code */
142419:   int i;                          /* Iterator variable */
142420:   sqlite3 *db = p->db;            /* The database connection */
142421: 
142422:   if( p->zContentTbl==0 ){
142423:     const char *zLanguageid = p->zLanguageid;
142424:     char *zContentCols;           /* Columns of %_content table */
142425: 
142426:     /* Create a list of user columns for the content table */
142427:     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
142428:     for(i=0; zContentCols && i<p->nColumn; i++){
142429:       char *z = p->azColumn[i];
142430:       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
142431:     }
142432:     if( zLanguageid && zContentCols ){
142433:       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
142434:     }
142435:     if( zContentCols==0 ) rc = SQLITE_NOMEM;
142436:   
142437:     /* Create the content table */
142438:     fts3DbExec(&rc, db, 
142439:        "CREATE TABLE %Q.'%q_content'(%s)",
142440:        p->zDb, p->zName, zContentCols
142441:     );
142442:     sqlite3_free(zContentCols);
142443:   }
142444: 
142445:   /* Create other tables */
142446:   fts3DbExec(&rc, db, 
142447:       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
142448:       p->zDb, p->zName
142449:   );
142450:   fts3DbExec(&rc, db, 
142451:       "CREATE TABLE %Q.'%q_segdir'("
142452:         "level INTEGER,"
142453:         "idx INTEGER,"
142454:         "start_block INTEGER,"
142455:         "leaves_end_block INTEGER,"
142456:         "end_block INTEGER,"
142457:         "root BLOB,"
142458:         "PRIMARY KEY(level, idx)"
142459:       ");",
142460:       p->zDb, p->zName
142461:   );
142462:   if( p->bHasDocsize ){
142463:     fts3DbExec(&rc, db, 
142464:         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
142465:         p->zDb, p->zName
142466:     );
142467:   }
142468:   assert( p->bHasStat==p->bFts4 );
142469:   if( p->bHasStat ){
142470:     sqlite3Fts3CreateStatTable(&rc, p);
142471:   }
142472:   return rc;
142473: }
142474: 
142475: /*
142476: ** Store the current database page-size in bytes in p->nPgsz.
142477: **
142478: ** If *pRc is non-zero when this function is called, it is a no-op. 
142479: ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
142480: ** before returning.
142481: */
142482: static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
142483:   if( *pRc==SQLITE_OK ){
142484:     int rc;                       /* Return code */
142485:     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
142486:     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
142487:   
142488:     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
142489:     if( !zSql ){
142490:       rc = SQLITE_NOMEM;
142491:     }else{
142492:       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
142493:       if( rc==SQLITE_OK ){
142494:         sqlite3_step(pStmt);
142495:         p->nPgsz = sqlite3_column_int(pStmt, 0);
142496:         rc = sqlite3_finalize(pStmt);
142497:       }else if( rc==SQLITE_AUTH ){
142498:         p->nPgsz = 1024;
142499:         rc = SQLITE_OK;
142500:       }
142501:     }
142502:     assert( p->nPgsz>0 || rc!=SQLITE_OK );
142503:     sqlite3_free(zSql);
142504:     *pRc = rc;
142505:   }
142506: }
142507: 
142508: /*
142509: ** "Special" FTS4 arguments are column specifications of the following form:
142510: **
142511: **   <key> = <value>
142512: **
142513: ** There may not be whitespace surrounding the "=" character. The <value> 
142514: ** term may be quoted, but the <key> may not.
142515: */
142516: static int fts3IsSpecialColumn(
142517:   const char *z, 
142518:   int *pnKey,
142519:   char **pzValue
142520: ){
142521:   char *zValue;
142522:   const char *zCsr = z;
142523: 
142524:   while( *zCsr!='=' ){
142525:     if( *zCsr=='\0' ) return 0;
142526:     zCsr++;
142527:   }
142528: 
142529:   *pnKey = (int)(zCsr-z);
142530:   zValue = sqlite3_mprintf("%s", &zCsr[1]);
142531:   if( zValue ){
142532:     sqlite3Fts3Dequote(zValue);
142533:   }
142534:   *pzValue = zValue;
142535:   return 1;
142536: }
142537: 
142538: /*
142539: ** Append the output of a printf() style formatting to an existing string.
142540: */
142541: static void fts3Appendf(
142542:   int *pRc,                       /* IN/OUT: Error code */
142543:   char **pz,                      /* IN/OUT: Pointer to string buffer */
142544:   const char *zFormat,            /* Printf format string to append */
142545:   ...                             /* Arguments for printf format string */
142546: ){
142547:   if( *pRc==SQLITE_OK ){
142548:     va_list ap;
142549:     char *z;
142550:     va_start(ap, zFormat);
142551:     z = sqlite3_vmprintf(zFormat, ap);
142552:     va_end(ap);
142553:     if( z && *pz ){
142554:       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
142555:       sqlite3_free(z);
142556:       z = z2;
142557:     }
142558:     if( z==0 ) *pRc = SQLITE_NOMEM;
142559:     sqlite3_free(*pz);
142560:     *pz = z;
142561:   }
142562: }
142563: 
142564: /*
142565: ** Return a copy of input string zInput enclosed in double-quotes (") and
142566: ** with all double quote characters escaped. For example:
142567: **
142568: **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
142569: **
142570: ** The pointer returned points to memory obtained from sqlite3_malloc(). It
142571: ** is the callers responsibility to call sqlite3_free() to release this
142572: ** memory.
142573: */
142574: static char *fts3QuoteId(char const *zInput){
142575:   int nRet;
142576:   char *zRet;
142577:   nRet = 2 + (int)strlen(zInput)*2 + 1;
142578:   zRet = sqlite3_malloc(nRet);
142579:   if( zRet ){
142580:     int i;
142581:     char *z = zRet;
142582:     *(z++) = '"';
142583:     for(i=0; zInput[i]; i++){
142584:       if( zInput[i]=='"' ) *(z++) = '"';
142585:       *(z++) = zInput[i];
142586:     }
142587:     *(z++) = '"';
142588:     *(z++) = '\0';
142589:   }
142590:   return zRet;
142591: }
142592: 
142593: /*
142594: ** Return a list of comma separated SQL expressions and a FROM clause that 
142595: ** could be used in a SELECT statement such as the following:
142596: **
142597: **     SELECT <list of expressions> FROM %_content AS x ...
142598: **
142599: ** to return the docid, followed by each column of text data in order
142600: ** from left to write. If parameter zFunc is not NULL, then instead of
142601: ** being returned directly each column of text data is passed to an SQL
142602: ** function named zFunc first. For example, if zFunc is "unzip" and the
142603: ** table has the three user-defined columns "a", "b", and "c", the following
142604: ** string is returned:
142605: **
142606: **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
142607: **
142608: ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
142609: ** is the responsibility of the caller to eventually free it.
142610: **
142611: ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
142612: ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
142613: ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
142614: ** no error occurs, *pRc is left unmodified.
142615: */
142616: static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
142617:   char *zRet = 0;
142618:   char *zFree = 0;
142619:   char *zFunction;
142620:   int i;
142621: 
142622:   if( p->zContentTbl==0 ){
142623:     if( !zFunc ){
142624:       zFunction = "";
142625:     }else{
142626:       zFree = zFunction = fts3QuoteId(zFunc);
142627:     }
142628:     fts3Appendf(pRc, &zRet, "docid");
142629:     for(i=0; i<p->nColumn; i++){
142630:       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
142631:     }
142632:     if( p->zLanguageid ){
142633:       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
142634:     }
142635:     sqlite3_free(zFree);
142636:   }else{
142637:     fts3Appendf(pRc, &zRet, "rowid");
142638:     for(i=0; i<p->nColumn; i++){
142639:       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
142640:     }
142641:     if( p->zLanguageid ){
142642:       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
142643:     }
142644:   }
142645:   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
142646:       p->zDb,
142647:       (p->zContentTbl ? p->zContentTbl : p->zName),
142648:       (p->zContentTbl ? "" : "_content")
142649:   );
142650:   return zRet;
142651: }
142652: 
142653: /*
142654: ** Return a list of N comma separated question marks, where N is the number
142655: ** of columns in the %_content table (one for the docid plus one for each
142656: ** user-defined text column).
142657: **
142658: ** If argument zFunc is not NULL, then all but the first question mark
142659: ** is preceded by zFunc and an open bracket, and followed by a closed
142660: ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
142661: ** user-defined text columns, the following string is returned:
142662: **
142663: **     "?, zip(?), zip(?), zip(?)"
142664: **
142665: ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
142666: ** is the responsibility of the caller to eventually free it.
142667: **
142668: ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
142669: ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
142670: ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
142671: ** no error occurs, *pRc is left unmodified.
142672: */
142673: static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
142674:   char *zRet = 0;
142675:   char *zFree = 0;
142676:   char *zFunction;
142677:   int i;
142678: 
142679:   if( !zFunc ){
142680:     zFunction = "";
142681:   }else{
142682:     zFree = zFunction = fts3QuoteId(zFunc);
142683:   }
142684:   fts3Appendf(pRc, &zRet, "?");
142685:   for(i=0; i<p->nColumn; i++){
142686:     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
142687:   }
142688:   if( p->zLanguageid ){
142689:     fts3Appendf(pRc, &zRet, ", ?");
142690:   }
142691:   sqlite3_free(zFree);
142692:   return zRet;
142693: }
142694: 
142695: /*
142696: ** This function interprets the string at (*pp) as a non-negative integer
142697: ** value. It reads the integer and sets *pnOut to the value read, then 
142698: ** sets *pp to point to the byte immediately following the last byte of
142699: ** the integer value.
142700: **
142701: ** Only decimal digits ('0'..'9') may be part of an integer value. 
142702: **
142703: ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
142704: ** the output value undefined. Otherwise SQLITE_OK is returned.
142705: **
142706: ** This function is used when parsing the "prefix=" FTS4 parameter.
142707: */
142708: static int fts3GobbleInt(const char **pp, int *pnOut){
142709:   const int MAX_NPREFIX = 10000000;
142710:   const char *p;                  /* Iterator pointer */
142711:   int nInt = 0;                   /* Output value */
142712: 
142713:   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
142714:     nInt = nInt * 10 + (p[0] - '0');
142715:     if( nInt>MAX_NPREFIX ){
142716:       nInt = 0;
142717:       break;
142718:     }
142719:   }
142720:   if( p==*pp ) return SQLITE_ERROR;
142721:   *pnOut = nInt;
142722:   *pp = p;
142723:   return SQLITE_OK;
142724: }
142725: 
142726: /*
142727: ** This function is called to allocate an array of Fts3Index structures
142728: ** representing the indexes maintained by the current FTS table. FTS tables
142729: ** always maintain the main "terms" index, but may also maintain one or
142730: ** more "prefix" indexes, depending on the value of the "prefix=" parameter
142731: ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
142732: **
142733: ** Argument zParam is passed the value of the "prefix=" option if one was
142734: ** specified, or NULL otherwise.
142735: **
142736: ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
142737: ** the allocated array. *pnIndex is set to the number of elements in the
142738: ** array. If an error does occur, an SQLite error code is returned.
142739: **
142740: ** Regardless of whether or not an error is returned, it is the responsibility
142741: ** of the caller to call sqlite3_free() on the output array to free it.
142742: */
142743: static int fts3PrefixParameter(
142744:   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
142745:   int *pnIndex,                   /* OUT: size of *apIndex[] array */
142746:   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
142747: ){
142748:   struct Fts3Index *aIndex;       /* Allocated array */
142749:   int nIndex = 1;                 /* Number of entries in array */
142750: 
142751:   if( zParam && zParam[0] ){
142752:     const char *p;
142753:     nIndex++;
142754:     for(p=zParam; *p; p++){
142755:       if( *p==',' ) nIndex++;
142756:     }
142757:   }
142758: 
142759:   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
142760:   *apIndex = aIndex;
142761:   if( !aIndex ){
142762:     return SQLITE_NOMEM;
142763:   }
142764: 
142765:   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
142766:   if( zParam ){
142767:     const char *p = zParam;
142768:     int i;
142769:     for(i=1; i<nIndex; i++){
142770:       int nPrefix = 0;
142771:       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
142772:       assert( nPrefix>=0 );
142773:       if( nPrefix==0 ){
142774:         nIndex--;
142775:         i--;
142776:       }else{
142777:         aIndex[i].nPrefix = nPrefix;
142778:       }
142779:       p++;
142780:     }
142781:   }
142782: 
142783:   *pnIndex = nIndex;
142784:   return SQLITE_OK;
142785: }
142786: 
142787: /*
142788: ** This function is called when initializing an FTS4 table that uses the
142789: ** content=xxx option. It determines the number of and names of the columns
142790: ** of the new FTS4 table.
142791: **
142792: ** The third argument passed to this function is the value passed to the
142793: ** config=xxx option (i.e. "xxx"). This function queries the database for
142794: ** a table of that name. If found, the output variables are populated
142795: ** as follows:
142796: **
142797: **   *pnCol:   Set to the number of columns table xxx has,
142798: **
142799: **   *pnStr:   Set to the total amount of space required to store a copy
142800: **             of each columns name, including the nul-terminator.
142801: **
142802: **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
142803: **             the name of the corresponding column in table xxx. The array
142804: **             and its contents are allocated using a single allocation. It
142805: **             is the responsibility of the caller to free this allocation
142806: **             by eventually passing the *pazCol value to sqlite3_free().
142807: **
142808: ** If the table cannot be found, an error code is returned and the output
142809: ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
142810: ** returned (and the output variables are undefined).
142811: */
142812: static int fts3ContentColumns(
142813:   sqlite3 *db,                    /* Database handle */
142814:   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
142815:   const char *zTbl,               /* Name of content table */
142816:   const char ***pazCol,           /* OUT: Malloc'd array of column names */
142817:   int *pnCol,                     /* OUT: Size of array *pazCol */
142818:   int *pnStr,                     /* OUT: Bytes of string content */
142819:   char **pzErr                    /* OUT: error message */
142820: ){
142821:   int rc = SQLITE_OK;             /* Return code */
142822:   char *zSql;                     /* "SELECT *" statement on zTbl */  
142823:   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
142824: 
142825:   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
142826:   if( !zSql ){
142827:     rc = SQLITE_NOMEM;
142828:   }else{
142829:     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
142830:     if( rc!=SQLITE_OK ){
142831:       sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
142832:     }
142833:   }
142834:   sqlite3_free(zSql);
142835: 
142836:   if( rc==SQLITE_OK ){
142837:     const char **azCol;           /* Output array */
142838:     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
142839:     int nCol;                     /* Number of table columns */
142840:     int i;                        /* Used to iterate through columns */
142841: 
142842:     /* Loop through the returned columns. Set nStr to the number of bytes of
142843:     ** space required to store a copy of each column name, including the
142844:     ** nul-terminator byte.  */
142845:     nCol = sqlite3_column_count(pStmt);
142846:     for(i=0; i<nCol; i++){
142847:       const char *zCol = sqlite3_column_name(pStmt, i);
142848:       nStr += (int)strlen(zCol) + 1;
142849:     }
142850: 
142851:     /* Allocate and populate the array to return. */
142852:     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
142853:     if( azCol==0 ){
142854:       rc = SQLITE_NOMEM;
142855:     }else{
142856:       char *p = (char *)&azCol[nCol];
142857:       for(i=0; i<nCol; i++){
142858:         const char *zCol = sqlite3_column_name(pStmt, i);
142859:         int n = (int)strlen(zCol)+1;
142860:         memcpy(p, zCol, n);
142861:         azCol[i] = p;
142862:         p += n;
142863:       }
142864:     }
142865:     sqlite3_finalize(pStmt);
142866: 
142867:     /* Set the output variables. */
142868:     *pnCol = nCol;
142869:     *pnStr = nStr;
142870:     *pazCol = azCol;
142871:   }
142872: 
142873:   return rc;
142874: }
142875: 
142876: /*
142877: ** This function is the implementation of both the xConnect and xCreate
142878: ** methods of the FTS3 virtual table.
142879: **
142880: ** The argv[] array contains the following:
142881: **
142882: **   argv[0]   -> module name  ("fts3" or "fts4")
142883: **   argv[1]   -> database name
142884: **   argv[2]   -> table name
142885: **   argv[...] -> "column name" and other module argument fields.
142886: */
142887: static int fts3InitVtab(
142888:   int isCreate,                   /* True for xCreate, false for xConnect */
142889:   sqlite3 *db,                    /* The SQLite database connection */
142890:   void *pAux,                     /* Hash table containing tokenizers */
142891:   int argc,                       /* Number of elements in argv array */
142892:   const char * const *argv,       /* xCreate/xConnect argument array */
142893:   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
142894:   char **pzErr                    /* Write any error message here */
142895: ){
142896:   Fts3Hash *pHash = (Fts3Hash *)pAux;
142897:   Fts3Table *p = 0;               /* Pointer to allocated vtab */
142898:   int rc = SQLITE_OK;             /* Return code */
142899:   int i;                          /* Iterator variable */
142900:   int nByte;                      /* Size of allocation used for *p */
142901:   int iCol;                       /* Column index */
142902:   int nString = 0;                /* Bytes required to hold all column names */
142903:   int nCol = 0;                   /* Number of columns in the FTS table */
142904:   char *zCsr;                     /* Space for holding column names */
142905:   int nDb;                        /* Bytes required to hold database name */
142906:   int nName;                      /* Bytes required to hold table name */
142907:   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
142908:   const char **aCol;              /* Array of column names */
142909:   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
142910: 
142911:   int nIndex = 0;                 /* Size of aIndex[] array */
142912:   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
142913: 
142914:   /* The results of parsing supported FTS4 key=value options: */
142915:   int bNoDocsize = 0;             /* True to omit %_docsize table */
142916:   int bDescIdx = 0;               /* True to store descending indexes */
142917:   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
142918:   char *zCompress = 0;            /* compress=? parameter (or NULL) */
142919:   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
142920:   char *zContent = 0;             /* content=? parameter (or NULL) */
142921:   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
142922:   char **azNotindexed = 0;        /* The set of notindexed= columns */
142923:   int nNotindexed = 0;            /* Size of azNotindexed[] array */
142924: 
142925:   assert( strlen(argv[0])==4 );
142926:   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
142927:        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
142928:   );
142929: 
142930:   nDb = (int)strlen(argv[1]) + 1;
142931:   nName = (int)strlen(argv[2]) + 1;
142932: 
142933:   nByte = sizeof(const char *) * (argc-2);
142934:   aCol = (const char **)sqlite3_malloc(nByte);
142935:   if( aCol ){
142936:     memset((void*)aCol, 0, nByte);
142937:     azNotindexed = (char **)sqlite3_malloc(nByte);
142938:   }
142939:   if( azNotindexed ){
142940:     memset(azNotindexed, 0, nByte);
142941:   }
142942:   if( !aCol || !azNotindexed ){
142943:     rc = SQLITE_NOMEM;
142944:     goto fts3_init_out;
142945:   }
142946: 
142947:   /* Loop through all of the arguments passed by the user to the FTS3/4
142948:   ** module (i.e. all the column names and special arguments). This loop
142949:   ** does the following:
142950:   **
142951:   **   + Figures out the number of columns the FTSX table will have, and
142952:   **     the number of bytes of space that must be allocated to store copies
142953:   **     of the column names.
142954:   **
142955:   **   + If there is a tokenizer specification included in the arguments,
142956:   **     initializes the tokenizer pTokenizer.
142957:   */
142958:   for(i=3; rc==SQLITE_OK && i<argc; i++){
142959:     char const *z = argv[i];
142960:     int nKey;
142961:     char *zVal;
142962: 
142963:     /* Check if this is a tokenizer specification */
142964:     if( !pTokenizer 
142965:      && strlen(z)>8
142966:      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
142967:      && 0==sqlite3Fts3IsIdChar(z[8])
142968:     ){
142969:       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
142970:     }
142971: 
142972:     /* Check if it is an FTS4 special argument. */
142973:     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
142974:       struct Fts4Option {
142975:         const char *zOpt;
142976:         int nOpt;
142977:       } aFts4Opt[] = {
142978:         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
142979:         { "prefix",      6 },     /* 1 -> PREFIX */
142980:         { "compress",    8 },     /* 2 -> COMPRESS */
142981:         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
142982:         { "order",       5 },     /* 4 -> ORDER */
142983:         { "content",     7 },     /* 5 -> CONTENT */
142984:         { "languageid", 10 },     /* 6 -> LANGUAGEID */
142985:         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
142986:       };
142987: 
142988:       int iOpt;
142989:       if( !zVal ){
142990:         rc = SQLITE_NOMEM;
142991:       }else{
142992:         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
142993:           struct Fts4Option *pOp = &aFts4Opt[iOpt];
142994:           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
142995:             break;
142996:           }
142997:         }
142998:         if( iOpt==SizeofArray(aFts4Opt) ){
142999:           sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
143000:           rc = SQLITE_ERROR;
143001:         }else{
143002:           switch( iOpt ){
143003:             case 0:               /* MATCHINFO */
143004:               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
143005:                 sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
143006:                 rc = SQLITE_ERROR;
143007:               }
143008:               bNoDocsize = 1;
143009:               break;
143010: 
143011:             case 1:               /* PREFIX */
143012:               sqlite3_free(zPrefix);
143013:               zPrefix = zVal;
143014:               zVal = 0;
143015:               break;
143016: 
143017:             case 2:               /* COMPRESS */
143018:               sqlite3_free(zCompress);
143019:               zCompress = zVal;
143020:               zVal = 0;
143021:               break;
143022: 
143023:             case 3:               /* UNCOMPRESS */
143024:               sqlite3_free(zUncompress);
143025:               zUncompress = zVal;
143026:               zVal = 0;
143027:               break;
143028: 
143029:             case 4:               /* ORDER */
143030:               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
143031:                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
143032:               ){
143033:                 sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
143034:                 rc = SQLITE_ERROR;
143035:               }
143036:               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
143037:               break;
143038: 
143039:             case 5:              /* CONTENT */
143040:               sqlite3_free(zContent);
143041:               zContent = zVal;
143042:               zVal = 0;
143043:               break;
143044: 
143045:             case 6:              /* LANGUAGEID */
143046:               assert( iOpt==6 );
143047:               sqlite3_free(zLanguageid);
143048:               zLanguageid = zVal;
143049:               zVal = 0;
143050:               break;
143051: 
143052:             case 7:              /* NOTINDEXED */
143053:               azNotindexed[nNotindexed++] = zVal;
143054:               zVal = 0;
143055:               break;
143056:           }
143057:         }
143058:         sqlite3_free(zVal);
143059:       }
143060:     }
143061: 
143062:     /* Otherwise, the argument is a column name. */
143063:     else {
143064:       nString += (int)(strlen(z) + 1);
143065:       aCol[nCol++] = z;
143066:     }
143067:   }
143068: 
143069:   /* If a content=xxx option was specified, the following:
143070:   **
143071:   **   1. Ignore any compress= and uncompress= options.
143072:   **
143073:   **   2. If no column names were specified as part of the CREATE VIRTUAL
143074:   **      TABLE statement, use all columns from the content table.
143075:   */
143076:   if( rc==SQLITE_OK && zContent ){
143077:     sqlite3_free(zCompress); 
143078:     sqlite3_free(zUncompress); 
143079:     zCompress = 0;
143080:     zUncompress = 0;
143081:     if( nCol==0 ){
143082:       sqlite3_free((void*)aCol); 
143083:       aCol = 0;
143084:       rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
143085: 
143086:       /* If a languageid= option was specified, remove the language id
143087:       ** column from the aCol[] array. */ 
143088:       if( rc==SQLITE_OK && zLanguageid ){
143089:         int j;
143090:         for(j=0; j<nCol; j++){
143091:           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
143092:             int k;
143093:             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
143094:             nCol--;
143095:             break;
143096:           }
143097:         }
143098:       }
143099:     }
143100:   }
143101:   if( rc!=SQLITE_OK ) goto fts3_init_out;
143102: 
143103:   if( nCol==0 ){
143104:     assert( nString==0 );
143105:     aCol[0] = "content";
143106:     nString = 8;
143107:     nCol = 1;
143108:   }
143109: 
143110:   if( pTokenizer==0 ){
143111:     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
143112:     if( rc!=SQLITE_OK ) goto fts3_init_out;
143113:   }
143114:   assert( pTokenizer );
143115: 
143116:   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
143117:   if( rc==SQLITE_ERROR ){
143118:     assert( zPrefix );
143119:     sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
143120:   }
143121:   if( rc!=SQLITE_OK ) goto fts3_init_out;
143122: 
143123:   /* Allocate and populate the Fts3Table structure. */
143124:   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
143125:           nCol * sizeof(char *) +              /* azColumn */
143126:           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
143127:           nCol * sizeof(u8) +                  /* abNotindexed */
143128:           nName +                              /* zName */
143129:           nDb +                                /* zDb */
143130:           nString;                             /* Space for azColumn strings */
143131:   p = (Fts3Table*)sqlite3_malloc(nByte);
143132:   if( p==0 ){
143133:     rc = SQLITE_NOMEM;
143134:     goto fts3_init_out;
143135:   }
143136:   memset(p, 0, nByte);
143137:   p->db = db;
143138:   p->nColumn = nCol;
143139:   p->nPendingData = 0;
143140:   p->azColumn = (char **)&p[1];
143141:   p->pTokenizer = pTokenizer;
143142:   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
143143:   p->bHasDocsize = (isFts4 && bNoDocsize==0);
143144:   p->bHasStat = isFts4;
143145:   p->bFts4 = isFts4;
143146:   p->bDescIdx = bDescIdx;
143147:   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
143148:   p->zContentTbl = zContent;
143149:   p->zLanguageid = zLanguageid;
143150:   zContent = 0;
143151:   zLanguageid = 0;
143152:   TESTONLY( p->inTransaction = -1 );
143153:   TESTONLY( p->mxSavepoint = -1 );
143154: 
143155:   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
143156:   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
143157:   p->nIndex = nIndex;
143158:   for(i=0; i<nIndex; i++){
143159:     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
143160:   }
143161:   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
143162: 
143163:   /* Fill in the zName and zDb fields of the vtab structure. */
143164:   zCsr = (char *)&p->abNotindexed[nCol];
143165:   p->zName = zCsr;
143166:   memcpy(zCsr, argv[2], nName);
143167:   zCsr += nName;
143168:   p->zDb = zCsr;
143169:   memcpy(zCsr, argv[1], nDb);
143170:   zCsr += nDb;
143171: 
143172:   /* Fill in the azColumn array */
143173:   for(iCol=0; iCol<nCol; iCol++){
143174:     char *z; 
143175:     int n = 0;
143176:     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
143177:     memcpy(zCsr, z, n);
143178:     zCsr[n] = '\0';
143179:     sqlite3Fts3Dequote(zCsr);
143180:     p->azColumn[iCol] = zCsr;
143181:     zCsr += n+1;
143182:     assert( zCsr <= &((char *)p)[nByte] );
143183:   }
143184: 
143185:   /* Fill in the abNotindexed array */
143186:   for(iCol=0; iCol<nCol; iCol++){
143187:     int n = (int)strlen(p->azColumn[iCol]);
143188:     for(i=0; i<nNotindexed; i++){
143189:       char *zNot = azNotindexed[i];
143190:       if( zNot && n==(int)strlen(zNot)
143191:        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) 
143192:       ){
143193:         p->abNotindexed[iCol] = 1;
143194:         sqlite3_free(zNot);
143195:         azNotindexed[i] = 0;
143196:       }
143197:     }
143198:   }
143199:   for(i=0; i<nNotindexed; i++){
143200:     if( azNotindexed[i] ){
143201:       sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
143202:       rc = SQLITE_ERROR;
143203:     }
143204:   }
143205: 
143206:   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
143207:     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
143208:     rc = SQLITE_ERROR;
143209:     sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
143210:   }
143211:   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
143212:   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
143213:   if( rc!=SQLITE_OK ) goto fts3_init_out;
143214: 
143215:   /* If this is an xCreate call, create the underlying tables in the 
143216:   ** database. TODO: For xConnect(), it could verify that said tables exist.
143217:   */
143218:   if( isCreate ){
143219:     rc = fts3CreateTables(p);
143220:   }
143221: 
143222:   /* Check to see if a legacy fts3 table has been "upgraded" by the
143223:   ** addition of a %_stat table so that it can use incremental merge.
143224:   */
143225:   if( !isFts4 && !isCreate ){
143226:     p->bHasStat = 2;
143227:   }
143228: 
143229:   /* Figure out the page-size for the database. This is required in order to
143230:   ** estimate the cost of loading large doclists from the database.  */
143231:   fts3DatabasePageSize(&rc, p);
143232:   p->nNodeSize = p->nPgsz-35;
143233: 
143234:   /* Declare the table schema to SQLite. */
143235:   fts3DeclareVtab(&rc, p);
143236: 
143237: fts3_init_out:
143238:   sqlite3_free(zPrefix);
143239:   sqlite3_free(aIndex);
143240:   sqlite3_free(zCompress);
143241:   sqlite3_free(zUncompress);
143242:   sqlite3_free(zContent);
143243:   sqlite3_free(zLanguageid);
143244:   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
143245:   sqlite3_free((void *)aCol);
143246:   sqlite3_free((void *)azNotindexed);
143247:   if( rc!=SQLITE_OK ){
143248:     if( p ){
143249:       fts3DisconnectMethod((sqlite3_vtab *)p);
143250:     }else if( pTokenizer ){
143251:       pTokenizer->pModule->xDestroy(pTokenizer);
143252:     }
143253:   }else{
143254:     assert( p->pSegments==0 );
143255:     *ppVTab = &p->base;
143256:   }
143257:   return rc;
143258: }
143259: 
143260: /*
143261: ** The xConnect() and xCreate() methods for the virtual table. All the
143262: ** work is done in function fts3InitVtab().
143263: */
143264: static int fts3ConnectMethod(
143265:   sqlite3 *db,                    /* Database connection */
143266:   void *pAux,                     /* Pointer to tokenizer hash table */
143267:   int argc,                       /* Number of elements in argv array */
143268:   const char * const *argv,       /* xCreate/xConnect argument array */
143269:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
143270:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
143271: ){
143272:   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
143273: }
143274: static int fts3CreateMethod(
143275:   sqlite3 *db,                    /* Database connection */
143276:   void *pAux,                     /* Pointer to tokenizer hash table */
143277:   int argc,                       /* Number of elements in argv array */
143278:   const char * const *argv,       /* xCreate/xConnect argument array */
143279:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
143280:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
143281: ){
143282:   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
143283: }
143284: 
143285: /*
143286: ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
143287: ** extension is currently being used by a version of SQLite too old to
143288: ** support estimatedRows. In that case this function is a no-op.
143289: */
143290: static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
143291: #if SQLITE_VERSION_NUMBER>=3008002
143292:   if( sqlite3_libversion_number()>=3008002 ){
143293:     pIdxInfo->estimatedRows = nRow;
143294:   }
143295: #endif
143296: }
143297: 
143298: /*
143299: ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
143300: ** extension is currently being used by a version of SQLite too old to
143301: ** support index-info flags. In that case this function is a no-op.
143302: */
143303: static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
143304: #if SQLITE_VERSION_NUMBER>=3008012
143305:   if( sqlite3_libversion_number()>=3008012 ){
143306:     pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
143307:   }
143308: #endif
143309: }
143310: 
143311: /* 
143312: ** Implementation of the xBestIndex method for FTS3 tables. There
143313: ** are three possible strategies, in order of preference:
143314: **
143315: **   1. Direct lookup by rowid or docid. 
143316: **   2. Full-text search using a MATCH operator on a non-docid column.
143317: **   3. Linear scan of %_content table.
143318: */
143319: static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
143320:   Fts3Table *p = (Fts3Table *)pVTab;
143321:   int i;                          /* Iterator variable */
143322:   int iCons = -1;                 /* Index of constraint to use */
143323: 
143324:   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
143325:   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
143326:   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
143327:   int iIdx;
143328: 
143329:   /* By default use a full table scan. This is an expensive option,
143330:   ** so search through the constraints to see if a more efficient 
143331:   ** strategy is possible.
143332:   */
143333:   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
143334:   pInfo->estimatedCost = 5000000;
143335:   for(i=0; i<pInfo->nConstraint; i++){
143336:     int bDocid;                 /* True if this constraint is on docid */
143337:     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
143338:     if( pCons->usable==0 ){
143339:       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
143340:         /* There exists an unusable MATCH constraint. This means that if
143341:         ** the planner does elect to use the results of this call as part
143342:         ** of the overall query plan the user will see an "unable to use
143343:         ** function MATCH in the requested context" error. To discourage
143344:         ** this, return a very high cost here.  */
143345:         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
143346:         pInfo->estimatedCost = 1e50;
143347:         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
143348:         return SQLITE_OK;
143349:       }
143350:       continue;
143351:     }
143352: 
143353:     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
143354: 
143355:     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
143356:     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
143357:       pInfo->idxNum = FTS3_DOCID_SEARCH;
143358:       pInfo->estimatedCost = 1.0;
143359:       iCons = i;
143360:     }
143361: 
143362:     /* A MATCH constraint. Use a full-text search.
143363:     **
143364:     ** If there is more than one MATCH constraint available, use the first
143365:     ** one encountered. If there is both a MATCH constraint and a direct
143366:     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
143367:     ** though the rowid/docid lookup is faster than a MATCH query, selecting
143368:     ** it would lead to an "unable to use function MATCH in the requested 
143369:     ** context" error.
143370:     */
143371:     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
143372:      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
143373:     ){
143374:       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
143375:       pInfo->estimatedCost = 2.0;
143376:       iCons = i;
143377:     }
143378: 
143379:     /* Equality constraint on the langid column */
143380:     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
143381:      && pCons->iColumn==p->nColumn + 2
143382:     ){
143383:       iLangidCons = i;
143384:     }
143385: 
143386:     if( bDocid ){
143387:       switch( pCons->op ){
143388:         case SQLITE_INDEX_CONSTRAINT_GE:
143389:         case SQLITE_INDEX_CONSTRAINT_GT:
143390:           iDocidGe = i;
143391:           break;
143392: 
143393:         case SQLITE_INDEX_CONSTRAINT_LE:
143394:         case SQLITE_INDEX_CONSTRAINT_LT:
143395:           iDocidLe = i;
143396:           break;
143397:       }
143398:     }
143399:   }
143400: 
143401:   /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
143402:   if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
143403: 
143404:   iIdx = 1;
143405:   if( iCons>=0 ){
143406:     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
143407:     pInfo->aConstraintUsage[iCons].omit = 1;
143408:   } 
143409:   if( iLangidCons>=0 ){
143410:     pInfo->idxNum |= FTS3_HAVE_LANGID;
143411:     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
143412:   } 
143413:   if( iDocidGe>=0 ){
143414:     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
143415:     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
143416:   } 
143417:   if( iDocidLe>=0 ){
143418:     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
143419:     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
143420:   } 
143421: 
143422:   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
143423:   ** docid) order. Both ascending and descending are possible. 
143424:   */
143425:   if( pInfo->nOrderBy==1 ){
143426:     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
143427:     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
143428:       if( pOrder->desc ){
143429:         pInfo->idxStr = "DESC";
143430:       }else{
143431:         pInfo->idxStr = "ASC";
143432:       }
143433:       pInfo->orderByConsumed = 1;
143434:     }
143435:   }
143436: 
143437:   assert( p->pSegments==0 );
143438:   return SQLITE_OK;
143439: }
143440: 
143441: /*
143442: ** Implementation of xOpen method.
143443: */
143444: static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
143445:   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
143446: 
143447:   UNUSED_PARAMETER(pVTab);
143448: 
143449:   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
143450:   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
143451:   ** if the allocation fails, return SQLITE_NOMEM.
143452:   */
143453:   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
143454:   if( !pCsr ){
143455:     return SQLITE_NOMEM;
143456:   }
143457:   memset(pCsr, 0, sizeof(Fts3Cursor));
143458:   return SQLITE_OK;
143459: }
143460: 
143461: /*
143462: ** Close the cursor.  For additional information see the documentation
143463: ** on the xClose method of the virtual table interface.
143464: */
143465: static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
143466:   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
143467:   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
143468:   sqlite3_finalize(pCsr->pStmt);
143469:   sqlite3Fts3ExprFree(pCsr->pExpr);
143470:   sqlite3Fts3FreeDeferredTokens(pCsr);
143471:   sqlite3_free(pCsr->aDoclist);
143472:   sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
143473:   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
143474:   sqlite3_free(pCsr);
143475:   return SQLITE_OK;
143476: }
143477: 
143478: /*
143479: ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
143480: ** compose and prepare an SQL statement of the form:
143481: **
143482: **    "SELECT <columns> FROM %_content WHERE rowid = ?"
143483: **
143484: ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
143485: ** it. If an error occurs, return an SQLite error code.
143486: **
143487: ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
143488: */
143489: static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
143490:   int rc = SQLITE_OK;
143491:   if( pCsr->pStmt==0 ){
143492:     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
143493:     char *zSql;
143494:     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
143495:     if( !zSql ) return SQLITE_NOMEM;
143496:     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
143497:     sqlite3_free(zSql);
143498:   }
143499:   *ppStmt = pCsr->pStmt;
143500:   return rc;
143501: }
143502: 
143503: /*
143504: ** Position the pCsr->pStmt statement so that it is on the row
143505: ** of the %_content table that contains the last match.  Return
143506: ** SQLITE_OK on success.  
143507: */
143508: static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
143509:   int rc = SQLITE_OK;
143510:   if( pCsr->isRequireSeek ){
143511:     sqlite3_stmt *pStmt = 0;
143512: 
143513:     rc = fts3CursorSeekStmt(pCsr, &pStmt);
143514:     if( rc==SQLITE_OK ){
143515:       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
143516:       pCsr->isRequireSeek = 0;
143517:       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
143518:         return SQLITE_OK;
143519:       }else{
143520:         rc = sqlite3_reset(pCsr->pStmt);
143521:         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
143522:           /* If no row was found and no error has occurred, then the %_content
143523:           ** table is missing a row that is present in the full-text index.
143524:           ** The data structures are corrupt.  */
143525:           rc = FTS_CORRUPT_VTAB;
143526:           pCsr->isEof = 1;
143527:         }
143528:       }
143529:     }
143530:   }
143531: 
143532:   if( rc!=SQLITE_OK && pContext ){
143533:     sqlite3_result_error_code(pContext, rc);
143534:   }
143535:   return rc;
143536: }
143537: 
143538: /*
143539: ** This function is used to process a single interior node when searching
143540: ** a b-tree for a term or term prefix. The node data is passed to this 
143541: ** function via the zNode/nNode parameters. The term to search for is
143542: ** passed in zTerm/nTerm.
143543: **
143544: ** If piFirst is not NULL, then this function sets *piFirst to the blockid
143545: ** of the child node that heads the sub-tree that may contain the term.
143546: **
143547: ** If piLast is not NULL, then *piLast is set to the right-most child node
143548: ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
143549: ** a prefix.
143550: **
143551: ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
143552: */
143553: static int fts3ScanInteriorNode(
143554:   const char *zTerm,              /* Term to select leaves for */
143555:   int nTerm,                      /* Size of term zTerm in bytes */
143556:   const char *zNode,              /* Buffer containing segment interior node */
143557:   int nNode,                      /* Size of buffer at zNode */
143558:   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
143559:   sqlite3_int64 *piLast           /* OUT: Selected child node */
143560: ){
143561:   int rc = SQLITE_OK;             /* Return code */
143562:   const char *zCsr = zNode;       /* Cursor to iterate through node */
143563:   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
143564:   char *zBuffer = 0;              /* Buffer to load terms into */
143565:   int nAlloc = 0;                 /* Size of allocated buffer */
143566:   int isFirstTerm = 1;            /* True when processing first term on page */
143567:   sqlite3_int64 iChild;           /* Block id of child node to descend to */
143568: 
143569:   /* Skip over the 'height' varint that occurs at the start of every 
143570:   ** interior node. Then load the blockid of the left-child of the b-tree
143571:   ** node into variable iChild.  
143572:   **
143573:   ** Even if the data structure on disk is corrupted, this (reading two
143574:   ** varints from the buffer) does not risk an overread. If zNode is a
143575:   ** root node, then the buffer comes from a SELECT statement. SQLite does
143576:   ** not make this guarantee explicitly, but in practice there are always
143577:   ** either more than 20 bytes of allocated space following the nNode bytes of
143578:   ** contents, or two zero bytes. Or, if the node is read from the %_segments
143579:   ** table, then there are always 20 bytes of zeroed padding following the
143580:   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
143581:   */
143582:   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
143583:   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
143584:   if( zCsr>zEnd ){
143585:     return FTS_CORRUPT_VTAB;
143586:   }
143587:   
143588:   while( zCsr<zEnd && (piFirst || piLast) ){
143589:     int cmp;                      /* memcmp() result */
143590:     int nSuffix;                  /* Size of term suffix */
143591:     int nPrefix = 0;              /* Size of term prefix */
143592:     int nBuffer;                  /* Total term size */
143593:   
143594:     /* Load the next term on the node into zBuffer. Use realloc() to expand
143595:     ** the size of zBuffer if required.  */
143596:     if( !isFirstTerm ){
143597:       zCsr += fts3GetVarint32(zCsr, &nPrefix);
143598:     }
143599:     isFirstTerm = 0;
143600:     zCsr += fts3GetVarint32(zCsr, &nSuffix);
143601:     
143602:     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
143603:       rc = FTS_CORRUPT_VTAB;
143604:       goto finish_scan;
143605:     }
143606:     if( nPrefix+nSuffix>nAlloc ){
143607:       char *zNew;
143608:       nAlloc = (nPrefix+nSuffix) * 2;
143609:       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
143610:       if( !zNew ){
143611:         rc = SQLITE_NOMEM;
143612:         goto finish_scan;
143613:       }
143614:       zBuffer = zNew;
143615:     }
143616:     assert( zBuffer );
143617:     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
143618:     nBuffer = nPrefix + nSuffix;
143619:     zCsr += nSuffix;
143620: 
143621:     /* Compare the term we are searching for with the term just loaded from
143622:     ** the interior node. If the specified term is greater than or equal
143623:     ** to the term from the interior node, then all terms on the sub-tree 
143624:     ** headed by node iChild are smaller than zTerm. No need to search 
143625:     ** iChild.
143626:     **
143627:     ** If the interior node term is larger than the specified term, then
143628:     ** the tree headed by iChild may contain the specified term.
143629:     */
143630:     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
143631:     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
143632:       *piFirst = iChild;
143633:       piFirst = 0;
143634:     }
143635: 
143636:     if( piLast && cmp<0 ){
143637:       *piLast = iChild;
143638:       piLast = 0;
143639:     }
143640: 
143641:     iChild++;
143642:   };
143643: 
143644:   if( piFirst ) *piFirst = iChild;
143645:   if( piLast ) *piLast = iChild;
143646: 
143647:  finish_scan:
143648:   sqlite3_free(zBuffer);
143649:   return rc;
143650: }
143651: 
143652: 
143653: /*
143654: ** The buffer pointed to by argument zNode (size nNode bytes) contains an
143655: ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
143656: ** contains a term. This function searches the sub-tree headed by the zNode
143657: ** node for the range of leaf nodes that may contain the specified term
143658: ** or terms for which the specified term is a prefix.
143659: **
143660: ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
143661: ** left-most leaf node in the tree that may contain the specified term.
143662: ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
143663: ** right-most leaf node that may contain a term for which the specified
143664: ** term is a prefix.
143665: **
143666: ** It is possible that the range of returned leaf nodes does not contain 
143667: ** the specified term or any terms for which it is a prefix. However, if the 
143668: ** segment does contain any such terms, they are stored within the identified
143669: ** range. Because this function only inspects interior segment nodes (and
143670: ** never loads leaf nodes into memory), it is not possible to be sure.
143671: **
143672: ** If an error occurs, an error code other than SQLITE_OK is returned.
143673: */ 
143674: static int fts3SelectLeaf(
143675:   Fts3Table *p,                   /* Virtual table handle */
143676:   const char *zTerm,              /* Term to select leaves for */
143677:   int nTerm,                      /* Size of term zTerm in bytes */
143678:   const char *zNode,              /* Buffer containing segment interior node */
143679:   int nNode,                      /* Size of buffer at zNode */
143680:   sqlite3_int64 *piLeaf,          /* Selected leaf node */
143681:   sqlite3_int64 *piLeaf2          /* Selected leaf node */
143682: ){
143683:   int rc = SQLITE_OK;             /* Return code */
143684:   int iHeight;                    /* Height of this node in tree */
143685: 
143686:   assert( piLeaf || piLeaf2 );
143687: 
143688:   fts3GetVarint32(zNode, &iHeight);
143689:   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
143690:   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
143691: 
143692:   if( rc==SQLITE_OK && iHeight>1 ){
143693:     char *zBlob = 0;              /* Blob read from %_segments table */
143694:     int nBlob = 0;                /* Size of zBlob in bytes */
143695: 
143696:     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
143697:       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
143698:       if( rc==SQLITE_OK ){
143699:         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
143700:       }
143701:       sqlite3_free(zBlob);
143702:       piLeaf = 0;
143703:       zBlob = 0;
143704:     }
143705: 
143706:     if( rc==SQLITE_OK ){
143707:       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
143708:     }
143709:     if( rc==SQLITE_OK ){
143710:       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
143711:     }
143712:     sqlite3_free(zBlob);
143713:   }
143714: 
143715:   return rc;
143716: }
143717: 
143718: /*
143719: ** This function is used to create delta-encoded serialized lists of FTS3 
143720: ** varints. Each call to this function appends a single varint to a list.
143721: */
143722: static void fts3PutDeltaVarint(
143723:   char **pp,                      /* IN/OUT: Output pointer */
143724:   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
143725:   sqlite3_int64 iVal              /* Write this value to the list */
143726: ){
143727:   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
143728:   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
143729:   *piPrev = iVal;
143730: }
143731: 
143732: /*
143733: ** When this function is called, *ppPoslist is assumed to point to the 
143734: ** start of a position-list. After it returns, *ppPoslist points to the
143735: ** first byte after the position-list.
143736: **
143737: ** A position list is list of positions (delta encoded) and columns for 
143738: ** a single document record of a doclist.  So, in other words, this
143739: ** routine advances *ppPoslist so that it points to the next docid in
143740: ** the doclist, or to the first byte past the end of the doclist.
143741: **
143742: ** If pp is not NULL, then the contents of the position list are copied
143743: ** to *pp. *pp is set to point to the first byte past the last byte copied
143744: ** before this function returns.
143745: */
143746: static void fts3PoslistCopy(char **pp, char **ppPoslist){
143747:   char *pEnd = *ppPoslist;
143748:   char c = 0;
143749: 
143750:   /* The end of a position list is marked by a zero encoded as an FTS3 
143751:   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
143752:   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
143753:   ** of some other, multi-byte, value.
143754:   **
143755:   ** The following while-loop moves pEnd to point to the first byte that is not 
143756:   ** immediately preceded by a byte with the 0x80 bit set. Then increments
143757:   ** pEnd once more so that it points to the byte immediately following the
143758:   ** last byte in the position-list.
143759:   */
143760:   while( *pEnd | c ){
143761:     c = *pEnd++ & 0x80;
143762:     testcase( c!=0 && (*pEnd)==0 );
143763:   }
143764:   pEnd++;  /* Advance past the POS_END terminator byte */
143765: 
143766:   if( pp ){
143767:     int n = (int)(pEnd - *ppPoslist);
143768:     char *p = *pp;
143769:     memcpy(p, *ppPoslist, n);
143770:     p += n;
143771:     *pp = p;
143772:   }
143773:   *ppPoslist = pEnd;
143774: }
143775: 
143776: /*
143777: ** When this function is called, *ppPoslist is assumed to point to the 
143778: ** start of a column-list. After it returns, *ppPoslist points to the
143779: ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
143780: **
143781: ** A column-list is list of delta-encoded positions for a single column
143782: ** within a single document within a doclist.
143783: **
143784: ** The column-list is terminated either by a POS_COLUMN varint (1) or
143785: ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
143786: ** the POS_COLUMN or POS_END that terminates the column-list.
143787: **
143788: ** If pp is not NULL, then the contents of the column-list are copied
143789: ** to *pp. *pp is set to point to the first byte past the last byte copied
143790: ** before this function returns.  The POS_COLUMN or POS_END terminator
143791: ** is not copied into *pp.
143792: */
143793: static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
143794:   char *pEnd = *ppPoslist;
143795:   char c = 0;
143796: 
143797:   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
143798:   ** not part of a multi-byte varint.
143799:   */
143800:   while( 0xFE & (*pEnd | c) ){
143801:     c = *pEnd++ & 0x80;
143802:     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
143803:   }
143804:   if( pp ){
143805:     int n = (int)(pEnd - *ppPoslist);
143806:     char *p = *pp;
143807:     memcpy(p, *ppPoslist, n);
143808:     p += n;
143809:     *pp = p;
143810:   }
143811:   *ppPoslist = pEnd;
143812: }
143813: 
143814: /*
143815: ** Value used to signify the end of an position-list. This is safe because
143816: ** it is not possible to have a document with 2^31 terms.
143817: */
143818: #define POSITION_LIST_END 0x7fffffff
143819: 
143820: /*
143821: ** This function is used to help parse position-lists. When this function is
143822: ** called, *pp may point to the start of the next varint in the position-list
143823: ** being parsed, or it may point to 1 byte past the end of the position-list
143824: ** (in which case **pp will be a terminator bytes POS_END (0) or
143825: ** (1)).
143826: **
143827: ** If *pp points past the end of the current position-list, set *pi to 
143828: ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
143829: ** increment the current value of *pi by the value read, and set *pp to
143830: ** point to the next value before returning.
143831: **
143832: ** Before calling this routine *pi must be initialized to the value of
143833: ** the previous position, or zero if we are reading the first position
143834: ** in the position-list.  Because positions are delta-encoded, the value
143835: ** of the previous position is needed in order to compute the value of
143836: ** the next position.
143837: */
143838: static void fts3ReadNextPos(
143839:   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
143840:   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
143841: ){
143842:   if( (**pp)&0xFE ){
143843:     fts3GetDeltaVarint(pp, pi);
143844:     *pi -= 2;
143845:   }else{
143846:     *pi = POSITION_LIST_END;
143847:   }
143848: }
143849: 
143850: /*
143851: ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
143852: ** the value of iCol encoded as a varint to *pp.   This will start a new
143853: ** column list.
143854: **
143855: ** Set *pp to point to the byte just after the last byte written before 
143856: ** returning (do not modify it if iCol==0). Return the total number of bytes
143857: ** written (0 if iCol==0).
143858: */
143859: static int fts3PutColNumber(char **pp, int iCol){
143860:   int n = 0;                      /* Number of bytes written */
143861:   if( iCol ){
143862:     char *p = *pp;                /* Output pointer */
143863:     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
143864:     *p = 0x01;
143865:     *pp = &p[n];
143866:   }
143867:   return n;
143868: }
143869: 
143870: /*
143871: ** Compute the union of two position lists.  The output written
143872: ** into *pp contains all positions of both *pp1 and *pp2 in sorted
143873: ** order and with any duplicates removed.  All pointers are
143874: ** updated appropriately.   The caller is responsible for insuring
143875: ** that there is enough space in *pp to hold the complete output.
143876: */
143877: static void fts3PoslistMerge(
143878:   char **pp,                      /* Output buffer */
143879:   char **pp1,                     /* Left input list */
143880:   char **pp2                      /* Right input list */
143881: ){
143882:   char *p = *pp;
143883:   char *p1 = *pp1;
143884:   char *p2 = *pp2;
143885: 
143886:   while( *p1 || *p2 ){
143887:     int iCol1;         /* The current column index in pp1 */
143888:     int iCol2;         /* The current column index in pp2 */
143889: 
143890:     if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
143891:     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
143892:     else iCol1 = 0;
143893: 
143894:     if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
143895:     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
143896:     else iCol2 = 0;
143897: 
143898:     if( iCol1==iCol2 ){
143899:       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
143900:       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
143901:       sqlite3_int64 iPrev = 0;
143902:       int n = fts3PutColNumber(&p, iCol1);
143903:       p1 += n;
143904:       p2 += n;
143905: 
143906:       /* At this point, both p1 and p2 point to the start of column-lists
143907:       ** for the same column (the column with index iCol1 and iCol2).
143908:       ** A column-list is a list of non-negative delta-encoded varints, each 
143909:       ** incremented by 2 before being stored. Each list is terminated by a
143910:       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
143911:       ** and writes the results to buffer p. p is left pointing to the byte
143912:       ** after the list written. No terminator (POS_END or POS_COLUMN) is
143913:       ** written to the output.
143914:       */
143915:       fts3GetDeltaVarint(&p1, &i1);
143916:       fts3GetDeltaVarint(&p2, &i2);
143917:       do {
143918:         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
143919:         iPrev -= 2;
143920:         if( i1==i2 ){
143921:           fts3ReadNextPos(&p1, &i1);
143922:           fts3ReadNextPos(&p2, &i2);
143923:         }else if( i1<i2 ){
143924:           fts3ReadNextPos(&p1, &i1);
143925:         }else{
143926:           fts3ReadNextPos(&p2, &i2);
143927:         }
143928:       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
143929:     }else if( iCol1<iCol2 ){
143930:       p1 += fts3PutColNumber(&p, iCol1);
143931:       fts3ColumnlistCopy(&p, &p1);
143932:     }else{
143933:       p2 += fts3PutColNumber(&p, iCol2);
143934:       fts3ColumnlistCopy(&p, &p2);
143935:     }
143936:   }
143937: 
143938:   *p++ = POS_END;
143939:   *pp = p;
143940:   *pp1 = p1 + 1;
143941:   *pp2 = p2 + 1;
143942: }
143943: 
143944: /*
143945: ** This function is used to merge two position lists into one. When it is
143946: ** called, *pp1 and *pp2 must both point to position lists. A position-list is
143947: ** the part of a doclist that follows each document id. For example, if a row
143948: ** contains:
143949: **
143950: **     'a b c'|'x y z'|'a b b a'
143951: **
143952: ** Then the position list for this row for token 'b' would consist of:
143953: **
143954: **     0x02 0x01 0x02 0x03 0x03 0x00
143955: **
143956: ** When this function returns, both *pp1 and *pp2 are left pointing to the
143957: ** byte following the 0x00 terminator of their respective position lists.
143958: **
143959: ** If isSaveLeft is 0, an entry is added to the output position list for 
143960: ** each position in *pp2 for which there exists one or more positions in
143961: ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
143962: ** when the *pp1 token appears before the *pp2 token, but not more than nToken
143963: ** slots before it.
143964: **
143965: ** e.g. nToken==1 searches for adjacent positions.
143966: */
143967: static int fts3PoslistPhraseMerge(
143968:   char **pp,                      /* IN/OUT: Preallocated output buffer */
143969:   int nToken,                     /* Maximum difference in token positions */
143970:   int isSaveLeft,                 /* Save the left position */
143971:   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
143972:   char **pp1,                     /* IN/OUT: Left input list */
143973:   char **pp2                      /* IN/OUT: Right input list */
143974: ){
143975:   char *p = *pp;
143976:   char *p1 = *pp1;
143977:   char *p2 = *pp2;
143978:   int iCol1 = 0;
143979:   int iCol2 = 0;
143980: 
143981:   /* Never set both isSaveLeft and isExact for the same invocation. */
143982:   assert( isSaveLeft==0 || isExact==0 );
143983: 
143984:   assert( p!=0 && *p1!=0 && *p2!=0 );
143985:   if( *p1==POS_COLUMN ){ 
143986:     p1++;
143987:     p1 += fts3GetVarint32(p1, &iCol1);
143988:   }
143989:   if( *p2==POS_COLUMN ){ 
143990:     p2++;
143991:     p2 += fts3GetVarint32(p2, &iCol2);
143992:   }
143993: 
143994:   while( 1 ){
143995:     if( iCol1==iCol2 ){
143996:       char *pSave = p;
143997:       sqlite3_int64 iPrev = 0;
143998:       sqlite3_int64 iPos1 = 0;
143999:       sqlite3_int64 iPos2 = 0;
144000: 
144001:       if( iCol1 ){
144002:         *p++ = POS_COLUMN;
144003:         p += sqlite3Fts3PutVarint(p, iCol1);
144004:       }
144005: 
144006:       assert( *p1!=POS_END && *p1!=POS_COLUMN );
144007:       assert( *p2!=POS_END && *p2!=POS_COLUMN );
144008:       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
144009:       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
144010: 
144011:       while( 1 ){
144012:         if( iPos2==iPos1+nToken 
144013:          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
144014:         ){
144015:           sqlite3_int64 iSave;
144016:           iSave = isSaveLeft ? iPos1 : iPos2;
144017:           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
144018:           pSave = 0;
144019:           assert( p );
144020:         }
144021:         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
144022:           if( (*p2&0xFE)==0 ) break;
144023:           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
144024:         }else{
144025:           if( (*p1&0xFE)==0 ) break;
144026:           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
144027:         }
144028:       }
144029: 
144030:       if( pSave ){
144031:         assert( pp && p );
144032:         p = pSave;
144033:       }
144034: 
144035:       fts3ColumnlistCopy(0, &p1);
144036:       fts3ColumnlistCopy(0, &p2);
144037:       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
144038:       if( 0==*p1 || 0==*p2 ) break;
144039: 
144040:       p1++;
144041:       p1 += fts3GetVarint32(p1, &iCol1);
144042:       p2++;
144043:       p2 += fts3GetVarint32(p2, &iCol2);
144044:     }
144045: 
144046:     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
144047:     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
144048:     ** end of the position list, or the 0x01 that precedes the next 
144049:     ** column-number in the position list. 
144050:     */
144051:     else if( iCol1<iCol2 ){
144052:       fts3ColumnlistCopy(0, &p1);
144053:       if( 0==*p1 ) break;
144054:       p1++;
144055:       p1 += fts3GetVarint32(p1, &iCol1);
144056:     }else{
144057:       fts3ColumnlistCopy(0, &p2);
144058:       if( 0==*p2 ) break;
144059:       p2++;
144060:       p2 += fts3GetVarint32(p2, &iCol2);
144061:     }
144062:   }
144063: 
144064:   fts3PoslistCopy(0, &p2);
144065:   fts3PoslistCopy(0, &p1);
144066:   *pp1 = p1;
144067:   *pp2 = p2;
144068:   if( *pp==p ){
144069:     return 0;
144070:   }
144071:   *p++ = 0x00;
144072:   *pp = p;
144073:   return 1;
144074: }
144075: 
144076: /*
144077: ** Merge two position-lists as required by the NEAR operator. The argument
144078: ** position lists correspond to the left and right phrases of an expression 
144079: ** like:
144080: **
144081: **     "phrase 1" NEAR "phrase number 2"
144082: **
144083: ** Position list *pp1 corresponds to the left-hand side of the NEAR 
144084: ** expression and *pp2 to the right. As usual, the indexes in the position 
144085: ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
144086: ** in the example above).
144087: **
144088: ** The output position list - written to *pp - is a copy of *pp2 with those
144089: ** entries that are not sufficiently NEAR entries in *pp1 removed.
144090: */
144091: static int fts3PoslistNearMerge(
144092:   char **pp,                      /* Output buffer */
144093:   char *aTmp,                     /* Temporary buffer space */
144094:   int nRight,                     /* Maximum difference in token positions */
144095:   int nLeft,                      /* Maximum difference in token positions */
144096:   char **pp1,                     /* IN/OUT: Left input list */
144097:   char **pp2                      /* IN/OUT: Right input list */
144098: ){
144099:   char *p1 = *pp1;
144100:   char *p2 = *pp2;
144101: 
144102:   char *pTmp1 = aTmp;
144103:   char *pTmp2;
144104:   char *aTmp2;
144105:   int res = 1;
144106: 
144107:   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
144108:   aTmp2 = pTmp2 = pTmp1;
144109:   *pp1 = p1;
144110:   *pp2 = p2;
144111:   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
144112:   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
144113:     fts3PoslistMerge(pp, &aTmp, &aTmp2);
144114:   }else if( pTmp1!=aTmp ){
144115:     fts3PoslistCopy(pp, &aTmp);
144116:   }else if( pTmp2!=aTmp2 ){
144117:     fts3PoslistCopy(pp, &aTmp2);
144118:   }else{
144119:     res = 0;
144120:   }
144121: 
144122:   return res;
144123: }
144124: 
144125: /* 
144126: ** An instance of this function is used to merge together the (potentially
144127: ** large number of) doclists for each term that matches a prefix query.
144128: ** See function fts3TermSelectMerge() for details.
144129: */
144130: typedef struct TermSelect TermSelect;
144131: struct TermSelect {
144132:   char *aaOutput[16];             /* Malloc'd output buffers */
144133:   int anOutput[16];               /* Size each output buffer in bytes */
144134: };
144135: 
144136: /*
144137: ** This function is used to read a single varint from a buffer. Parameter
144138: ** pEnd points 1 byte past the end of the buffer. When this function is
144139: ** called, if *pp points to pEnd or greater, then the end of the buffer
144140: ** has been reached. In this case *pp is set to 0 and the function returns.
144141: **
144142: ** If *pp does not point to or past pEnd, then a single varint is read
144143: ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
144144: **
144145: ** If bDescIdx is false, the value read is added to *pVal before returning.
144146: ** If it is true, the value read is subtracted from *pVal before this 
144147: ** function returns.
144148: */
144149: static void fts3GetDeltaVarint3(
144150:   char **pp,                      /* IN/OUT: Point to read varint from */
144151:   char *pEnd,                     /* End of buffer */
144152:   int bDescIdx,                   /* True if docids are descending */
144153:   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
144154: ){
144155:   if( *pp>=pEnd ){
144156:     *pp = 0;
144157:   }else{
144158:     sqlite3_int64 iVal;
144159:     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
144160:     if( bDescIdx ){
144161:       *pVal -= iVal;
144162:     }else{
144163:       *pVal += iVal;
144164:     }
144165:   }
144166: }
144167: 
144168: /*
144169: ** This function is used to write a single varint to a buffer. The varint
144170: ** is written to *pp. Before returning, *pp is set to point 1 byte past the
144171: ** end of the value written.
144172: **
144173: ** If *pbFirst is zero when this function is called, the value written to
144174: ** the buffer is that of parameter iVal. 
144175: **
144176: ** If *pbFirst is non-zero when this function is called, then the value 
144177: ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
144178: ** (if bDescIdx is non-zero).
144179: **
144180: ** Before returning, this function always sets *pbFirst to 1 and *piPrev
144181: ** to the value of parameter iVal.
144182: */
144183: static void fts3PutDeltaVarint3(
144184:   char **pp,                      /* IN/OUT: Output pointer */
144185:   int bDescIdx,                   /* True for descending docids */
144186:   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
144187:   int *pbFirst,                   /* IN/OUT: True after first int written */
144188:   sqlite3_int64 iVal              /* Write this value to the list */
144189: ){
144190:   sqlite3_int64 iWrite;
144191:   if( bDescIdx==0 || *pbFirst==0 ){
144192:     iWrite = iVal - *piPrev;
144193:   }else{
144194:     iWrite = *piPrev - iVal;
144195:   }
144196:   assert( *pbFirst || *piPrev==0 );
144197:   assert( *pbFirst==0 || iWrite>0 );
144198:   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
144199:   *piPrev = iVal;
144200:   *pbFirst = 1;
144201: }
144202: 
144203: 
144204: /*
144205: ** This macro is used by various functions that merge doclists. The two
144206: ** arguments are 64-bit docid values. If the value of the stack variable
144207: ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
144208: ** Otherwise, (i2-i1).
144209: **
144210: ** Using this makes it easier to write code that can merge doclists that are
144211: ** sorted in either ascending or descending order.
144212: */
144213: #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
144214: 
144215: /*
144216: ** This function does an "OR" merge of two doclists (output contains all
144217: ** positions contained in either argument doclist). If the docids in the 
144218: ** input doclists are sorted in ascending order, parameter bDescDoclist
144219: ** should be false. If they are sorted in ascending order, it should be
144220: ** passed a non-zero value.
144221: **
144222: ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
144223: ** containing the output doclist and SQLITE_OK is returned. In this case
144224: ** *pnOut is set to the number of bytes in the output doclist.
144225: **
144226: ** If an error occurs, an SQLite error code is returned. The output values
144227: ** are undefined in this case.
144228: */
144229: static int fts3DoclistOrMerge(
144230:   int bDescDoclist,               /* True if arguments are desc */
144231:   char *a1, int n1,               /* First doclist */
144232:   char *a2, int n2,               /* Second doclist */
144233:   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
144234: ){
144235:   sqlite3_int64 i1 = 0;
144236:   sqlite3_int64 i2 = 0;
144237:   sqlite3_int64 iPrev = 0;
144238:   char *pEnd1 = &a1[n1];
144239:   char *pEnd2 = &a2[n2];
144240:   char *p1 = a1;
144241:   char *p2 = a2;
144242:   char *p;
144243:   char *aOut;
144244:   int bFirstOut = 0;
144245: 
144246:   *paOut = 0;
144247:   *pnOut = 0;
144248: 
144249:   /* Allocate space for the output. Both the input and output doclists
144250:   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
144251:   ** then the first docid in each list is simply encoded as a varint. For
144252:   ** each subsequent docid, the varint stored is the difference between the
144253:   ** current and previous docid (a positive number - since the list is in
144254:   ** ascending order).
144255:   **
144256:   ** The first docid written to the output is therefore encoded using the 
144257:   ** same number of bytes as it is in whichever of the input lists it is
144258:   ** read from. And each subsequent docid read from the same input list 
144259:   ** consumes either the same or less bytes as it did in the input (since
144260:   ** the difference between it and the previous value in the output must
144261:   ** be a positive value less than or equal to the delta value read from 
144262:   ** the input list). The same argument applies to all but the first docid
144263:   ** read from the 'other' list. And to the contents of all position lists
144264:   ** that will be copied and merged from the input to the output.
144265:   **
144266:   ** However, if the first docid copied to the output is a negative number,
144267:   ** then the encoding of the first docid from the 'other' input list may
144268:   ** be larger in the output than it was in the input (since the delta value
144269:   ** may be a larger positive integer than the actual docid).
144270:   **
144271:   ** The space required to store the output is therefore the sum of the
144272:   ** sizes of the two inputs, plus enough space for exactly one of the input
144273:   ** docids to grow. 
144274:   **
144275:   ** A symetric argument may be made if the doclists are in descending 
144276:   ** order.
144277:   */
144278:   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
144279:   if( !aOut ) return SQLITE_NOMEM;
144280: 
144281:   p = aOut;
144282:   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
144283:   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
144284:   while( p1 || p2 ){
144285:     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
144286: 
144287:     if( p2 && p1 && iDiff==0 ){
144288:       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144289:       fts3PoslistMerge(&p, &p1, &p2);
144290:       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144291:       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144292:     }else if( !p2 || (p1 && iDiff<0) ){
144293:       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144294:       fts3PoslistCopy(&p, &p1);
144295:       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144296:     }else{
144297:       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
144298:       fts3PoslistCopy(&p, &p2);
144299:       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144300:     }
144301:   }
144302: 
144303:   *paOut = aOut;
144304:   *pnOut = (int)(p-aOut);
144305:   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
144306:   return SQLITE_OK;
144307: }
144308: 
144309: /*
144310: ** This function does a "phrase" merge of two doclists. In a phrase merge,
144311: ** the output contains a copy of each position from the right-hand input
144312: ** doclist for which there is a position in the left-hand input doclist
144313: ** exactly nDist tokens before it.
144314: **
144315: ** If the docids in the input doclists are sorted in ascending order,
144316: ** parameter bDescDoclist should be false. If they are sorted in ascending 
144317: ** order, it should be passed a non-zero value.
144318: **
144319: ** The right-hand input doclist is overwritten by this function.
144320: */
144321: static int fts3DoclistPhraseMerge(
144322:   int bDescDoclist,               /* True if arguments are desc */
144323:   int nDist,                      /* Distance from left to right (1=adjacent) */
144324:   char *aLeft, int nLeft,         /* Left doclist */
144325:   char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
144326: ){
144327:   sqlite3_int64 i1 = 0;
144328:   sqlite3_int64 i2 = 0;
144329:   sqlite3_int64 iPrev = 0;
144330:   char *aRight = *paRight;
144331:   char *pEnd1 = &aLeft[nLeft];
144332:   char *pEnd2 = &aRight[*pnRight];
144333:   char *p1 = aLeft;
144334:   char *p2 = aRight;
144335:   char *p;
144336:   int bFirstOut = 0;
144337:   char *aOut;
144338: 
144339:   assert( nDist>0 );
144340:   if( bDescDoclist ){
144341:     aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
144342:     if( aOut==0 ) return SQLITE_NOMEM;
144343:   }else{
144344:     aOut = aRight;
144345:   }
144346:   p = aOut;
144347: 
144348:   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
144349:   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
144350: 
144351:   while( p1 && p2 ){
144352:     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
144353:     if( iDiff==0 ){
144354:       char *pSave = p;
144355:       sqlite3_int64 iPrevSave = iPrev;
144356:       int bFirstOutSave = bFirstOut;
144357: 
144358:       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
144359:       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
144360:         p = pSave;
144361:         iPrev = iPrevSave;
144362:         bFirstOut = bFirstOutSave;
144363:       }
144364:       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144365:       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144366:     }else if( iDiff<0 ){
144367:       fts3PoslistCopy(0, &p1);
144368:       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
144369:     }else{
144370:       fts3PoslistCopy(0, &p2);
144371:       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
144372:     }
144373:   }
144374: 
144375:   *pnRight = (int)(p - aOut);
144376:   if( bDescDoclist ){
144377:     sqlite3_free(aRight);
144378:     *paRight = aOut;
144379:   }
144380: 
144381:   return SQLITE_OK;
144382: }
144383: 
144384: /*
144385: ** Argument pList points to a position list nList bytes in size. This
144386: ** function checks to see if the position list contains any entries for
144387: ** a token in position 0 (of any column). If so, it writes argument iDelta
144388: ** to the output buffer pOut, followed by a position list consisting only
144389: ** of the entries from pList at position 0, and terminated by an 0x00 byte.
144390: ** The value returned is the number of bytes written to pOut (if any).
144391: */
144392: SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
144393:   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
144394:   char *pList,                    /* Position list (no 0x00 term) */
144395:   int nList,                      /* Size of pList in bytes */
144396:   char *pOut                      /* Write output here */
144397: ){
144398:   int nOut = 0;
144399:   int bWritten = 0;               /* True once iDelta has been written */
144400:   char *p = pList;
144401:   char *pEnd = &pList[nList];
144402: 
144403:   if( *p!=0x01 ){
144404:     if( *p==0x02 ){
144405:       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
144406:       pOut[nOut++] = 0x02;
144407:       bWritten = 1;
144408:     }
144409:     fts3ColumnlistCopy(0, &p);
144410:   }
144411: 
144412:   while( p<pEnd && *p==0x01 ){
144413:     sqlite3_int64 iCol;
144414:     p++;
144415:     p += sqlite3Fts3GetVarint(p, &iCol);
144416:     if( *p==0x02 ){
144417:       if( bWritten==0 ){
144418:         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
144419:         bWritten = 1;
144420:       }
144421:       pOut[nOut++] = 0x01;
144422:       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
144423:       pOut[nOut++] = 0x02;
144424:     }
144425:     fts3ColumnlistCopy(0, &p);
144426:   }
144427:   if( bWritten ){
144428:     pOut[nOut++] = 0x00;
144429:   }
144430: 
144431:   return nOut;
144432: }
144433: 
144434: 
144435: /*
144436: ** Merge all doclists in the TermSelect.aaOutput[] array into a single
144437: ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
144438: ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
144439: **
144440: ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
144441: ** the responsibility of the caller to free any doclists left in the
144442: ** TermSelect.aaOutput[] array.
144443: */
144444: static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
144445:   char *aOut = 0;
144446:   int nOut = 0;
144447:   int i;
144448: 
144449:   /* Loop through the doclists in the aaOutput[] array. Merge them all
144450:   ** into a single doclist.
144451:   */
144452:   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
144453:     if( pTS->aaOutput[i] ){
144454:       if( !aOut ){
144455:         aOut = pTS->aaOutput[i];
144456:         nOut = pTS->anOutput[i];
144457:         pTS->aaOutput[i] = 0;
144458:       }else{
144459:         int nNew;
144460:         char *aNew;
144461: 
144462:         int rc = fts3DoclistOrMerge(p->bDescIdx, 
144463:             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
144464:         );
144465:         if( rc!=SQLITE_OK ){
144466:           sqlite3_free(aOut);
144467:           return rc;
144468:         }
144469: 
144470:         sqlite3_free(pTS->aaOutput[i]);
144471:         sqlite3_free(aOut);
144472:         pTS->aaOutput[i] = 0;
144473:         aOut = aNew;
144474:         nOut = nNew;
144475:       }
144476:     }
144477:   }
144478: 
144479:   pTS->aaOutput[0] = aOut;
144480:   pTS->anOutput[0] = nOut;
144481:   return SQLITE_OK;
144482: }
144483: 
144484: /*
144485: ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
144486: ** as the first argument. The merge is an "OR" merge (see function
144487: ** fts3DoclistOrMerge() for details).
144488: **
144489: ** This function is called with the doclist for each term that matches
144490: ** a queried prefix. It merges all these doclists into one, the doclist
144491: ** for the specified prefix. Since there can be a very large number of
144492: ** doclists to merge, the merging is done pair-wise using the TermSelect
144493: ** object.
144494: **
144495: ** This function returns SQLITE_OK if the merge is successful, or an
144496: ** SQLite error code (SQLITE_NOMEM) if an error occurs.
144497: */
144498: static int fts3TermSelectMerge(
144499:   Fts3Table *p,                   /* FTS table handle */
144500:   TermSelect *pTS,                /* TermSelect object to merge into */
144501:   char *aDoclist,                 /* Pointer to doclist */
144502:   int nDoclist                    /* Size of aDoclist in bytes */
144503: ){
144504:   if( pTS->aaOutput[0]==0 ){
144505:     /* If this is the first term selected, copy the doclist to the output
144506:     ** buffer using memcpy(). 
144507:     **
144508:     ** Add FTS3_VARINT_MAX bytes of unused space to the end of the 
144509:     ** allocation. This is so as to ensure that the buffer is big enough
144510:     ** to hold the current doclist AND'd with any other doclist. If the
144511:     ** doclists are stored in order=ASC order, this padding would not be
144512:     ** required (since the size of [doclistA AND doclistB] is always less
144513:     ** than or equal to the size of [doclistA] in that case). But this is
144514:     ** not true for order=DESC. For example, a doclist containing (1, -1) 
144515:     ** may be smaller than (-1), as in the first example the -1 may be stored
144516:     ** as a single-byte delta, whereas in the second it must be stored as a
144517:     ** FTS3_VARINT_MAX byte varint.
144518:     **
144519:     ** Similar padding is added in the fts3DoclistOrMerge() function.
144520:     */
144521:     pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
144522:     pTS->anOutput[0] = nDoclist;
144523:     if( pTS->aaOutput[0] ){
144524:       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
144525:     }else{
144526:       return SQLITE_NOMEM;
144527:     }
144528:   }else{
144529:     char *aMerge = aDoclist;
144530:     int nMerge = nDoclist;
144531:     int iOut;
144532: 
144533:     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
144534:       if( pTS->aaOutput[iOut]==0 ){
144535:         assert( iOut>0 );
144536:         pTS->aaOutput[iOut] = aMerge;
144537:         pTS->anOutput[iOut] = nMerge;
144538:         break;
144539:       }else{
144540:         char *aNew;
144541:         int nNew;
144542: 
144543:         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
144544:             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
144545:         );
144546:         if( rc!=SQLITE_OK ){
144547:           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
144548:           return rc;
144549:         }
144550: 
144551:         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
144552:         sqlite3_free(pTS->aaOutput[iOut]);
144553:         pTS->aaOutput[iOut] = 0;
144554:   
144555:         aMerge = aNew;
144556:         nMerge = nNew;
144557:         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
144558:           pTS->aaOutput[iOut] = aMerge;
144559:           pTS->anOutput[iOut] = nMerge;
144560:         }
144561:       }
144562:     }
144563:   }
144564:   return SQLITE_OK;
144565: }
144566: 
144567: /*
144568: ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
144569: */
144570: static int fts3SegReaderCursorAppend(
144571:   Fts3MultiSegReader *pCsr, 
144572:   Fts3SegReader *pNew
144573: ){
144574:   if( (pCsr->nSegment%16)==0 ){
144575:     Fts3SegReader **apNew;
144576:     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
144577:     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
144578:     if( !apNew ){
144579:       sqlite3Fts3SegReaderFree(pNew);
144580:       return SQLITE_NOMEM;
144581:     }
144582:     pCsr->apSegment = apNew;
144583:   }
144584:   pCsr->apSegment[pCsr->nSegment++] = pNew;
144585:   return SQLITE_OK;
144586: }
144587: 
144588: /*
144589: ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
144590: ** 8th argument.
144591: **
144592: ** This function returns SQLITE_OK if successful, or an SQLite error code
144593: ** otherwise.
144594: */
144595: static int fts3SegReaderCursor(
144596:   Fts3Table *p,                   /* FTS3 table handle */
144597:   int iLangid,                    /* Language id */
144598:   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
144599:   int iLevel,                     /* Level of segments to scan */
144600:   const char *zTerm,              /* Term to query for */
144601:   int nTerm,                      /* Size of zTerm in bytes */
144602:   int isPrefix,                   /* True for a prefix search */
144603:   int isScan,                     /* True to scan from zTerm to EOF */
144604:   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
144605: ){
144606:   int rc = SQLITE_OK;             /* Error code */
144607:   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
144608:   int rc2;                        /* Result of sqlite3_reset() */
144609: 
144610:   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
144611:   ** for the pending-terms. If this is a scan, then this call must be being
144612:   ** made by an fts4aux module, not an FTS table. In this case calling
144613:   ** Fts3SegReaderPending might segfault, as the data structures used by 
144614:   ** fts4aux are not completely populated. So it's easiest to filter these
144615:   ** calls out here.  */
144616:   if( iLevel<0 && p->aIndex ){
144617:     Fts3SegReader *pSeg = 0;
144618:     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
144619:     if( rc==SQLITE_OK && pSeg ){
144620:       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
144621:     }
144622:   }
144623: 
144624:   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
144625:     if( rc==SQLITE_OK ){
144626:       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
144627:     }
144628: 
144629:     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
144630:       Fts3SegReader *pSeg = 0;
144631: 
144632:       /* Read the values returned by the SELECT into local variables. */
144633:       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
144634:       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
144635:       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
144636:       int nRoot = sqlite3_column_bytes(pStmt, 4);
144637:       char const *zRoot = sqlite3_column_blob(pStmt, 4);
144638: 
144639:       /* If zTerm is not NULL, and this segment is not stored entirely on its
144640:       ** root node, the range of leaves scanned can be reduced. Do this. */
144641:       if( iStartBlock && zTerm ){
144642:         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
144643:         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
144644:         if( rc!=SQLITE_OK ) goto finished;
144645:         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
144646:       }
144647:  
144648:       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
144649:           (isPrefix==0 && isScan==0),
144650:           iStartBlock, iLeavesEndBlock, 
144651:           iEndBlock, zRoot, nRoot, &pSeg
144652:       );
144653:       if( rc!=SQLITE_OK ) goto finished;
144654:       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
144655:     }
144656:   }
144657: 
144658:  finished:
144659:   rc2 = sqlite3_reset(pStmt);
144660:   if( rc==SQLITE_DONE ) rc = rc2;
144661: 
144662:   return rc;
144663: }
144664: 
144665: /*
144666: ** Set up a cursor object for iterating through a full-text index or a 
144667: ** single level therein.
144668: */
144669: SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
144670:   Fts3Table *p,                   /* FTS3 table handle */
144671:   int iLangid,                    /* Language-id to search */
144672:   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
144673:   int iLevel,                     /* Level of segments to scan */
144674:   const char *zTerm,              /* Term to query for */
144675:   int nTerm,                      /* Size of zTerm in bytes */
144676:   int isPrefix,                   /* True for a prefix search */
144677:   int isScan,                     /* True to scan from zTerm to EOF */
144678:   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
144679: ){
144680:   assert( iIndex>=0 && iIndex<p->nIndex );
144681:   assert( iLevel==FTS3_SEGCURSOR_ALL
144682:       ||  iLevel==FTS3_SEGCURSOR_PENDING 
144683:       ||  iLevel>=0
144684:   );
144685:   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
144686:   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
144687:   assert( isPrefix==0 || isScan==0 );
144688: 
144689:   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
144690:   return fts3SegReaderCursor(
144691:       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
144692:   );
144693: }
144694: 
144695: /*
144696: ** In addition to its current configuration, have the Fts3MultiSegReader
144697: ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
144698: **
144699: ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144700: */
144701: static int fts3SegReaderCursorAddZero(
144702:   Fts3Table *p,                   /* FTS virtual table handle */
144703:   int iLangid,
144704:   const char *zTerm,              /* Term to scan doclist of */
144705:   int nTerm,                      /* Number of bytes in zTerm */
144706:   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
144707: ){
144708:   return fts3SegReaderCursor(p, 
144709:       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
144710:   );
144711: }
144712: 
144713: /*
144714: ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
144715: ** if isPrefix is true, to scan the doclist for all terms for which 
144716: ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
144717: ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
144718: ** an SQLite error code.
144719: **
144720: ** It is the responsibility of the caller to free this object by eventually
144721: ** passing it to fts3SegReaderCursorFree() 
144722: **
144723: ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144724: ** Output parameter *ppSegcsr is set to 0 if an error occurs.
144725: */
144726: static int fts3TermSegReaderCursor(
144727:   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
144728:   const char *zTerm,              /* Term to query for */
144729:   int nTerm,                      /* Size of zTerm in bytes */
144730:   int isPrefix,                   /* True for a prefix search */
144731:   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
144732: ){
144733:   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
144734:   int rc = SQLITE_NOMEM;          /* Return code */
144735: 
144736:   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
144737:   if( pSegcsr ){
144738:     int i;
144739:     int bFound = 0;               /* True once an index has been found */
144740:     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
144741: 
144742:     if( isPrefix ){
144743:       for(i=1; bFound==0 && i<p->nIndex; i++){
144744:         if( p->aIndex[i].nPrefix==nTerm ){
144745:           bFound = 1;
144746:           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
144747:               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
144748:           );
144749:           pSegcsr->bLookup = 1;
144750:         }
144751:       }
144752: 
144753:       for(i=1; bFound==0 && i<p->nIndex; i++){
144754:         if( p->aIndex[i].nPrefix==nTerm+1 ){
144755:           bFound = 1;
144756:           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
144757:               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
144758:           );
144759:           if( rc==SQLITE_OK ){
144760:             rc = fts3SegReaderCursorAddZero(
144761:                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
144762:             );
144763:           }
144764:         }
144765:       }
144766:     }
144767: 
144768:     if( bFound==0 ){
144769:       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
144770:           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
144771:       );
144772:       pSegcsr->bLookup = !isPrefix;
144773:     }
144774:   }
144775: 
144776:   *ppSegcsr = pSegcsr;
144777:   return rc;
144778: }
144779: 
144780: /*
144781: ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
144782: */
144783: static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
144784:   sqlite3Fts3SegReaderFinish(pSegcsr);
144785:   sqlite3_free(pSegcsr);
144786: }
144787: 
144788: /*
144789: ** This function retrieves the doclist for the specified term (or term
144790: ** prefix) from the database.
144791: */
144792: static int fts3TermSelect(
144793:   Fts3Table *p,                   /* Virtual table handle */
144794:   Fts3PhraseToken *pTok,          /* Token to query for */
144795:   int iColumn,                    /* Column to query (or -ve for all columns) */
144796:   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
144797:   char **ppOut                    /* OUT: Malloced result buffer */
144798: ){
144799:   int rc;                         /* Return code */
144800:   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
144801:   TermSelect tsc;                 /* Object for pair-wise doclist merging */
144802:   Fts3SegFilter filter;           /* Segment term filter configuration */
144803: 
144804:   pSegcsr = pTok->pSegcsr;
144805:   memset(&tsc, 0, sizeof(TermSelect));
144806: 
144807:   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
144808:         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
144809:         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
144810:         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
144811:   filter.iCol = iColumn;
144812:   filter.zTerm = pTok->z;
144813:   filter.nTerm = pTok->n;
144814: 
144815:   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
144816:   while( SQLITE_OK==rc
144817:       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
144818:   ){
144819:     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
144820:   }
144821: 
144822:   if( rc==SQLITE_OK ){
144823:     rc = fts3TermSelectFinishMerge(p, &tsc);
144824:   }
144825:   if( rc==SQLITE_OK ){
144826:     *ppOut = tsc.aaOutput[0];
144827:     *pnOut = tsc.anOutput[0];
144828:   }else{
144829:     int i;
144830:     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
144831:       sqlite3_free(tsc.aaOutput[i]);
144832:     }
144833:   }
144834: 
144835:   fts3SegReaderCursorFree(pSegcsr);
144836:   pTok->pSegcsr = 0;
144837:   return rc;
144838: }
144839: 
144840: /*
144841: ** This function counts the total number of docids in the doclist stored
144842: ** in buffer aList[], size nList bytes.
144843: **
144844: ** If the isPoslist argument is true, then it is assumed that the doclist
144845: ** contains a position-list following each docid. Otherwise, it is assumed
144846: ** that the doclist is simply a list of docids stored as delta encoded 
144847: ** varints.
144848: */
144849: static int fts3DoclistCountDocids(char *aList, int nList){
144850:   int nDoc = 0;                   /* Return value */
144851:   if( aList ){
144852:     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
144853:     char *p = aList;              /* Cursor */
144854:     while( p<aEnd ){
144855:       nDoc++;
144856:       while( (*p++)&0x80 );     /* Skip docid varint */
144857:       fts3PoslistCopy(0, &p);   /* Skip over position list */
144858:     }
144859:   }
144860: 
144861:   return nDoc;
144862: }
144863: 
144864: /*
144865: ** Advance the cursor to the next row in the %_content table that
144866: ** matches the search criteria.  For a MATCH search, this will be
144867: ** the next row that matches. For a full-table scan, this will be
144868: ** simply the next row in the %_content table.  For a docid lookup,
144869: ** this routine simply sets the EOF flag.
144870: **
144871: ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
144872: ** even if we reach end-of-file.  The fts3EofMethod() will be called
144873: ** subsequently to determine whether or not an EOF was hit.
144874: */
144875: static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
144876:   int rc;
144877:   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144878:   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
144879:     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
144880:       pCsr->isEof = 1;
144881:       rc = sqlite3_reset(pCsr->pStmt);
144882:     }else{
144883:       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
144884:       rc = SQLITE_OK;
144885:     }
144886:   }else{
144887:     rc = fts3EvalNext((Fts3Cursor *)pCursor);
144888:   }
144889:   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144890:   return rc;
144891: }
144892: 
144893: /*
144894: ** The following are copied from sqliteInt.h.
144895: **
144896: ** Constants for the largest and smallest possible 64-bit signed integers.
144897: ** These macros are designed to work correctly on both 32-bit and 64-bit
144898: ** compilers.
144899: */
144900: #ifndef SQLITE_AMALGAMATION
144901: # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
144902: # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
144903: #endif
144904: 
144905: /*
144906: ** If the numeric type of argument pVal is "integer", then return it
144907: ** converted to a 64-bit signed integer. Otherwise, return a copy of
144908: ** the second parameter, iDefault.
144909: */
144910: static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
144911:   if( pVal ){
144912:     int eType = sqlite3_value_numeric_type(pVal);
144913:     if( eType==SQLITE_INTEGER ){
144914:       return sqlite3_value_int64(pVal);
144915:     }
144916:   }
144917:   return iDefault;
144918: }
144919: 
144920: /*
144921: ** This is the xFilter interface for the virtual table.  See
144922: ** the virtual table xFilter method documentation for additional
144923: ** information.
144924: **
144925: ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
144926: ** the %_content table.
144927: **
144928: ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
144929: ** in the %_content table.
144930: **
144931: ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
144932: ** column on the left-hand side of the MATCH operator is column
144933: ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
144934: ** side of the MATCH operator.
144935: */
144936: static int fts3FilterMethod(
144937:   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
144938:   int idxNum,                     /* Strategy index */
144939:   const char *idxStr,             /* Unused */
144940:   int nVal,                       /* Number of elements in apVal */
144941:   sqlite3_value **apVal           /* Arguments for the indexing scheme */
144942: ){
144943:   int rc = SQLITE_OK;
144944:   char *zSql;                     /* SQL statement used to access %_content */
144945:   int eSearch;
144946:   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
144947:   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
144948: 
144949:   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
144950:   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
144951:   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
144952:   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
144953:   int iIdx;
144954: 
144955:   UNUSED_PARAMETER(idxStr);
144956:   UNUSED_PARAMETER(nVal);
144957: 
144958:   eSearch = (idxNum & 0x0000FFFF);
144959:   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
144960:   assert( p->pSegments==0 );
144961: 
144962:   /* Collect arguments into local variables */
144963:   iIdx = 0;
144964:   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
144965:   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
144966:   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
144967:   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
144968:   assert( iIdx==nVal );
144969: 
144970:   /* In case the cursor has been used before, clear it now. */
144971:   sqlite3_finalize(pCsr->pStmt);
144972:   sqlite3_free(pCsr->aDoclist);
144973:   sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
144974:   sqlite3Fts3ExprFree(pCsr->pExpr);
144975:   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
144976: 
144977:   /* Set the lower and upper bounds on docids to return */
144978:   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
144979:   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
144980: 
144981:   if( idxStr ){
144982:     pCsr->bDesc = (idxStr[0]=='D');
144983:   }else{
144984:     pCsr->bDesc = p->bDescIdx;
144985:   }
144986:   pCsr->eSearch = (i16)eSearch;
144987: 
144988:   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
144989:     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
144990:     const char *zQuery = (const char *)sqlite3_value_text(pCons);
144991: 
144992:     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
144993:       return SQLITE_NOMEM;
144994:     }
144995: 
144996:     pCsr->iLangid = 0;
144997:     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
144998: 
144999:     assert( p->base.zErrMsg==0 );
145000:     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
145001:         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
145002:         &p->base.zErrMsg
145003:     );
145004:     if( rc!=SQLITE_OK ){
145005:       return rc;
145006:     }
145007: 
145008:     rc = fts3EvalStart(pCsr);
145009:     sqlite3Fts3SegmentsClose(p);
145010:     if( rc!=SQLITE_OK ) return rc;
145011:     pCsr->pNextId = pCsr->aDoclist;
145012:     pCsr->iPrevId = 0;
145013:   }
145014: 
145015:   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
145016:   ** statement loops through all rows of the %_content table. For a
145017:   ** full-text query or docid lookup, the statement retrieves a single
145018:   ** row by docid.
145019:   */
145020:   if( eSearch==FTS3_FULLSCAN_SEARCH ){
145021:     if( pDocidGe || pDocidLe ){
145022:       zSql = sqlite3_mprintf(
145023:           "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
145024:           p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
145025:           (pCsr->bDesc ? "DESC" : "ASC")
145026:       );
145027:     }else{
145028:       zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", 
145029:           p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
145030:       );
145031:     }
145032:     if( zSql ){
145033:       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
145034:       sqlite3_free(zSql);
145035:     }else{
145036:       rc = SQLITE_NOMEM;
145037:     }
145038:   }else if( eSearch==FTS3_DOCID_SEARCH ){
145039:     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
145040:     if( rc==SQLITE_OK ){
145041:       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
145042:     }
145043:   }
145044:   if( rc!=SQLITE_OK ) return rc;
145045: 
145046:   return fts3NextMethod(pCursor);
145047: }
145048: 
145049: /* 
145050: ** This is the xEof method of the virtual table. SQLite calls this 
145051: ** routine to find out if it has reached the end of a result set.
145052: */
145053: static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
145054:   return ((Fts3Cursor *)pCursor)->isEof;
145055: }
145056: 
145057: /* 
145058: ** This is the xRowid method. The SQLite core calls this routine to
145059: ** retrieve the rowid for the current row of the result set. fts3
145060: ** exposes %_content.docid as the rowid for the virtual table. The
145061: ** rowid should be written to *pRowid.
145062: */
145063: static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
145064:   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
145065:   *pRowid = pCsr->iPrevId;
145066:   return SQLITE_OK;
145067: }
145068: 
145069: /* 
145070: ** This is the xColumn method, called by SQLite to request a value from
145071: ** the row that the supplied cursor currently points to.
145072: **
145073: ** If:
145074: **
145075: **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
145076: **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
145077: **   (iCol == p->nColumn+1) -> Docid column
145078: **   (iCol == p->nColumn+2) -> Langid column
145079: */
145080: static int fts3ColumnMethod(
145081:   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
145082:   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
145083:   int iCol                        /* Index of column to read value from */
145084: ){
145085:   int rc = SQLITE_OK;             /* Return Code */
145086:   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
145087:   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
145088: 
145089:   /* The column value supplied by SQLite must be in range. */
145090:   assert( iCol>=0 && iCol<=p->nColumn+2 );
145091: 
145092:   if( iCol==p->nColumn+1 ){
145093:     /* This call is a request for the "docid" column. Since "docid" is an 
145094:     ** alias for "rowid", use the xRowid() method to obtain the value.
145095:     */
145096:     sqlite3_result_int64(pCtx, pCsr->iPrevId);
145097:   }else if( iCol==p->nColumn ){
145098:     /* The extra column whose name is the same as the table.
145099:     ** Return a blob which is a pointer to the cursor.  */
145100:     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
145101:   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
145102:     sqlite3_result_int64(pCtx, pCsr->iLangid);
145103:   }else{
145104:     /* The requested column is either a user column (one that contains 
145105:     ** indexed data), or the language-id column.  */
145106:     rc = fts3CursorSeek(0, pCsr);
145107: 
145108:     if( rc==SQLITE_OK ){
145109:       if( iCol==p->nColumn+2 ){
145110:         int iLangid = 0;
145111:         if( p->zLanguageid ){
145112:           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
145113:         }
145114:         sqlite3_result_int(pCtx, iLangid);
145115:       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
145116:         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
145117:       }
145118:     }
145119:   }
145120: 
145121:   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
145122:   return rc;
145123: }
145124: 
145125: /* 
145126: ** This function is the implementation of the xUpdate callback used by 
145127: ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
145128: ** inserted, updated or deleted.
145129: */
145130: static int fts3UpdateMethod(
145131:   sqlite3_vtab *pVtab,            /* Virtual table handle */
145132:   int nArg,                       /* Size of argument array */
145133:   sqlite3_value **apVal,          /* Array of arguments */
145134:   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
145135: ){
145136:   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
145137: }
145138: 
145139: /*
145140: ** Implementation of xSync() method. Flush the contents of the pending-terms
145141: ** hash-table to the database.
145142: */
145143: static int fts3SyncMethod(sqlite3_vtab *pVtab){
145144: 
145145:   /* Following an incremental-merge operation, assuming that the input
145146:   ** segments are not completely consumed (the usual case), they are updated
145147:   ** in place to remove the entries that have already been merged. This
145148:   ** involves updating the leaf block that contains the smallest unmerged
145149:   ** entry and each block (if any) between the leaf and the root node. So
145150:   ** if the height of the input segment b-trees is N, and input segments
145151:   ** are merged eight at a time, updating the input segments at the end
145152:   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
145153:   ** small - often between 0 and 2. So the overhead of the incremental
145154:   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
145155:   ** dwarfing the actual productive work accomplished, the incremental merge
145156:   ** is only attempted if it will write at least 64 leaf blocks. Hence
145157:   ** nMinMerge.
145158:   **
145159:   ** Of course, updating the input segments also involves deleting a bunch
145160:   ** of blocks from the segments table. But this is not considered overhead
145161:   ** as it would also be required by a crisis-merge that used the same input 
145162:   ** segments.
145163:   */
145164:   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
145165: 
145166:   Fts3Table *p = (Fts3Table*)pVtab;
145167:   int rc = sqlite3Fts3PendingTermsFlush(p);
145168: 
145169:   if( rc==SQLITE_OK 
145170:    && p->nLeafAdd>(nMinMerge/16) 
145171:    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
145172:   ){
145173:     int mxLevel = 0;              /* Maximum relative level value in db */
145174:     int A;                        /* Incr-merge parameter A */
145175: 
145176:     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
145177:     assert( rc==SQLITE_OK || mxLevel==0 );
145178:     A = p->nLeafAdd * mxLevel;
145179:     A += (A/2);
145180:     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
145181:   }
145182:   sqlite3Fts3SegmentsClose(p);
145183:   return rc;
145184: }
145185: 
145186: /*
145187: ** If it is currently unknown whether or not the FTS table has an %_stat
145188: ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
145189: ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
145190: ** if an error occurs.
145191: */
145192: static int fts3SetHasStat(Fts3Table *p){
145193:   int rc = SQLITE_OK;
145194:   if( p->bHasStat==2 ){
145195:     const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
145196:     char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
145197:     if( zSql ){
145198:       sqlite3_stmt *pStmt = 0;
145199:       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
145200:       if( rc==SQLITE_OK ){
145201:         int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
145202:         rc = sqlite3_finalize(pStmt);
145203:         if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
145204:       }
145205:       sqlite3_free(zSql);
145206:     }else{
145207:       rc = SQLITE_NOMEM;
145208:     }
145209:   }
145210:   return rc;
145211: }
145212: 
145213: /*
145214: ** Implementation of xBegin() method. 
145215: */
145216: static int fts3BeginMethod(sqlite3_vtab *pVtab){
145217:   Fts3Table *p = (Fts3Table*)pVtab;
145218:   UNUSED_PARAMETER(pVtab);
145219:   assert( p->pSegments==0 );
145220:   assert( p->nPendingData==0 );
145221:   assert( p->inTransaction!=1 );
145222:   TESTONLY( p->inTransaction = 1 );
145223:   TESTONLY( p->mxSavepoint = -1; );
145224:   p->nLeafAdd = 0;
145225:   return fts3SetHasStat(p);
145226: }
145227: 
145228: /*
145229: ** Implementation of xCommit() method. This is a no-op. The contents of
145230: ** the pending-terms hash-table have already been flushed into the database
145231: ** by fts3SyncMethod().
145232: */
145233: static int fts3CommitMethod(sqlite3_vtab *pVtab){
145234:   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
145235:   UNUSED_PARAMETER(pVtab);
145236:   assert( p->nPendingData==0 );
145237:   assert( p->inTransaction!=0 );
145238:   assert( p->pSegments==0 );
145239:   TESTONLY( p->inTransaction = 0 );
145240:   TESTONLY( p->mxSavepoint = -1; );
145241:   return SQLITE_OK;
145242: }
145243: 
145244: /*
145245: ** Implementation of xRollback(). Discard the contents of the pending-terms
145246: ** hash-table. Any changes made to the database are reverted by SQLite.
145247: */
145248: static int fts3RollbackMethod(sqlite3_vtab *pVtab){
145249:   Fts3Table *p = (Fts3Table*)pVtab;
145250:   sqlite3Fts3PendingTermsClear(p);
145251:   assert( p->inTransaction!=0 );
145252:   TESTONLY( p->inTransaction = 0 );
145253:   TESTONLY( p->mxSavepoint = -1; );
145254:   return SQLITE_OK;
145255: }
145256: 
145257: /*
145258: ** When called, *ppPoslist must point to the byte immediately following the
145259: ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
145260: ** moves *ppPoslist so that it instead points to the first byte of the
145261: ** same position list.
145262: */
145263: static void fts3ReversePoslist(char *pStart, char **ppPoslist){
145264:   char *p = &(*ppPoslist)[-2];
145265:   char c = 0;
145266: 
145267:   /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
145268:   while( p>pStart && (c=*p--)==0 );
145269: 
145270:   /* Search backwards for a varint with value zero (the end of the previous 
145271:   ** poslist). This is an 0x00 byte preceded by some byte that does not
145272:   ** have the 0x80 bit set.  */
145273:   while( p>pStart && (*p & 0x80) | c ){ 
145274:     c = *p--; 
145275:   }
145276:   assert( p==pStart || c==0 );
145277: 
145278:   /* At this point p points to that preceding byte without the 0x80 bit
145279:   ** set. So to find the start of the poslist, skip forward 2 bytes then
145280:   ** over a varint. 
145281:   **
145282:   ** Normally. The other case is that p==pStart and the poslist to return
145283:   ** is the first in the doclist. In this case do not skip forward 2 bytes.
145284:   ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
145285:   ** is required for cases where the first byte of a doclist and the
145286:   ** doclist is empty. For example, if the first docid is 10, a doclist
145287:   ** that begins with:
145288:   **
145289:   **   0x0A 0x00 <next docid delta varint>
145290:   */
145291:   if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
145292:   while( *p++&0x80 );
145293:   *ppPoslist = p;
145294: }
145295: 
145296: /*
145297: ** Helper function used by the implementation of the overloaded snippet(),
145298: ** offsets() and optimize() SQL functions.
145299: **
145300: ** If the value passed as the third argument is a blob of size
145301: ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
145302: ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
145303: ** message is written to context pContext and SQLITE_ERROR returned. The
145304: ** string passed via zFunc is used as part of the error message.
145305: */
145306: static int fts3FunctionArg(
145307:   sqlite3_context *pContext,      /* SQL function call context */
145308:   const char *zFunc,              /* Function name */
145309:   sqlite3_value *pVal,            /* argv[0] passed to function */
145310:   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
145311: ){
145312:   Fts3Cursor *pRet;
145313:   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
145314:    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
145315:   ){
145316:     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
145317:     sqlite3_result_error(pContext, zErr, -1);
145318:     sqlite3_free(zErr);
145319:     return SQLITE_ERROR;
145320:   }
145321:   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
145322:   *ppCsr = pRet;
145323:   return SQLITE_OK;
145324: }
145325: 
145326: /*
145327: ** Implementation of the snippet() function for FTS3
145328: */
145329: static void fts3SnippetFunc(
145330:   sqlite3_context *pContext,      /* SQLite function call context */
145331:   int nVal,                       /* Size of apVal[] array */
145332:   sqlite3_value **apVal           /* Array of arguments */
145333: ){
145334:   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145335:   const char *zStart = "<b>";
145336:   const char *zEnd = "</b>";
145337:   const char *zEllipsis = "<b>...</b>";
145338:   int iCol = -1;
145339:   int nToken = 15;                /* Default number of tokens in snippet */
145340: 
145341:   /* There must be at least one argument passed to this function (otherwise
145342:   ** the non-overloaded version would have been called instead of this one).
145343:   */
145344:   assert( nVal>=1 );
145345: 
145346:   if( nVal>6 ){
145347:     sqlite3_result_error(pContext, 
145348:         "wrong number of arguments to function snippet()", -1);
145349:     return;
145350:   }
145351:   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
145352: 
145353:   switch( nVal ){
145354:     case 6: nToken = sqlite3_value_int(apVal[5]);
145355:     case 5: iCol = sqlite3_value_int(apVal[4]);
145356:     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
145357:     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
145358:     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
145359:   }
145360:   if( !zEllipsis || !zEnd || !zStart ){
145361:     sqlite3_result_error_nomem(pContext);
145362:   }else if( nToken==0 ){
145363:     sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
145364:   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
145365:     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
145366:   }
145367: }
145368: 
145369: /*
145370: ** Implementation of the offsets() function for FTS3
145371: */
145372: static void fts3OffsetsFunc(
145373:   sqlite3_context *pContext,      /* SQLite function call context */
145374:   int nVal,                       /* Size of argument array */
145375:   sqlite3_value **apVal           /* Array of arguments */
145376: ){
145377:   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145378: 
145379:   UNUSED_PARAMETER(nVal);
145380: 
145381:   assert( nVal==1 );
145382:   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
145383:   assert( pCsr );
145384:   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
145385:     sqlite3Fts3Offsets(pContext, pCsr);
145386:   }
145387: }
145388: 
145389: /* 
145390: ** Implementation of the special optimize() function for FTS3. This 
145391: ** function merges all segments in the database to a single segment.
145392: ** Example usage is:
145393: **
145394: **   SELECT optimize(t) FROM t LIMIT 1;
145395: **
145396: ** where 't' is the name of an FTS3 table.
145397: */
145398: static void fts3OptimizeFunc(
145399:   sqlite3_context *pContext,      /* SQLite function call context */
145400:   int nVal,                       /* Size of argument array */
145401:   sqlite3_value **apVal           /* Array of arguments */
145402: ){
145403:   int rc;                         /* Return code */
145404:   Fts3Table *p;                   /* Virtual table handle */
145405:   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
145406: 
145407:   UNUSED_PARAMETER(nVal);
145408: 
145409:   assert( nVal==1 );
145410:   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
145411:   p = (Fts3Table *)pCursor->base.pVtab;
145412:   assert( p );
145413: 
145414:   rc = sqlite3Fts3Optimize(p);
145415: 
145416:   switch( rc ){
145417:     case SQLITE_OK:
145418:       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
145419:       break;
145420:     case SQLITE_DONE:
145421:       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
145422:       break;
145423:     default:
145424:       sqlite3_result_error_code(pContext, rc);
145425:       break;
145426:   }
145427: }
145428: 
145429: /*
145430: ** Implementation of the matchinfo() function for FTS3
145431: */
145432: static void fts3MatchinfoFunc(
145433:   sqlite3_context *pContext,      /* SQLite function call context */
145434:   int nVal,                       /* Size of argument array */
145435:   sqlite3_value **apVal           /* Array of arguments */
145436: ){
145437:   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
145438:   assert( nVal==1 || nVal==2 );
145439:   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
145440:     const char *zArg = 0;
145441:     if( nVal>1 ){
145442:       zArg = (const char *)sqlite3_value_text(apVal[1]);
145443:     }
145444:     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
145445:   }
145446: }
145447: 
145448: /*
145449: ** This routine implements the xFindFunction method for the FTS3
145450: ** virtual table.
145451: */
145452: static int fts3FindFunctionMethod(
145453:   sqlite3_vtab *pVtab,            /* Virtual table handle */
145454:   int nArg,                       /* Number of SQL function arguments */
145455:   const char *zName,              /* Name of SQL function */
145456:   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
145457:   void **ppArg                    /* Unused */
145458: ){
145459:   struct Overloaded {
145460:     const char *zName;
145461:     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
145462:   } aOverload[] = {
145463:     { "snippet", fts3SnippetFunc },
145464:     { "offsets", fts3OffsetsFunc },
145465:     { "optimize", fts3OptimizeFunc },
145466:     { "matchinfo", fts3MatchinfoFunc },
145467:   };
145468:   int i;                          /* Iterator variable */
145469: 
145470:   UNUSED_PARAMETER(pVtab);
145471:   UNUSED_PARAMETER(nArg);
145472:   UNUSED_PARAMETER(ppArg);
145473: 
145474:   for(i=0; i<SizeofArray(aOverload); i++){
145475:     if( strcmp(zName, aOverload[i].zName)==0 ){
145476:       *pxFunc = aOverload[i].xFunc;
145477:       return 1;
145478:     }
145479:   }
145480: 
145481:   /* No function of the specified name was found. Return 0. */
145482:   return 0;
145483: }
145484: 
145485: /*
145486: ** Implementation of FTS3 xRename method. Rename an fts3 table.
145487: */
145488: static int fts3RenameMethod(
145489:   sqlite3_vtab *pVtab,            /* Virtual table handle */
145490:   const char *zName               /* New name of table */
145491: ){
145492:   Fts3Table *p = (Fts3Table *)pVtab;
145493:   sqlite3 *db = p->db;            /* Database connection */
145494:   int rc;                         /* Return Code */
145495: 
145496:   /* At this point it must be known if the %_stat table exists or not.
145497:   ** So bHasStat may not be 2.  */
145498:   rc = fts3SetHasStat(p);
145499:   
145500:   /* As it happens, the pending terms table is always empty here. This is
145501:   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
145502:   ** always opens a savepoint transaction. And the xSavepoint() method 
145503:   ** flushes the pending terms table. But leave the (no-op) call to
145504:   ** PendingTermsFlush() in in case that changes.
145505:   */
145506:   assert( p->nPendingData==0 );
145507:   if( rc==SQLITE_OK ){
145508:     rc = sqlite3Fts3PendingTermsFlush(p);
145509:   }
145510: 
145511:   if( p->zContentTbl==0 ){
145512:     fts3DbExec(&rc, db,
145513:       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
145514:       p->zDb, p->zName, zName
145515:     );
145516:   }
145517: 
145518:   if( p->bHasDocsize ){
145519:     fts3DbExec(&rc, db,
145520:       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
145521:       p->zDb, p->zName, zName
145522:     );
145523:   }
145524:   if( p->bHasStat ){
145525:     fts3DbExec(&rc, db,
145526:       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
145527:       p->zDb, p->zName, zName
145528:     );
145529:   }
145530:   fts3DbExec(&rc, db,
145531:     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
145532:     p->zDb, p->zName, zName
145533:   );
145534:   fts3DbExec(&rc, db,
145535:     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
145536:     p->zDb, p->zName, zName
145537:   );
145538:   return rc;
145539: }
145540: 
145541: /*
145542: ** The xSavepoint() method.
145543: **
145544: ** Flush the contents of the pending-terms table to disk.
145545: */
145546: static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
145547:   int rc = SQLITE_OK;
145548:   UNUSED_PARAMETER(iSavepoint);
145549:   assert( ((Fts3Table *)pVtab)->inTransaction );
145550:   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
145551:   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
145552:   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
145553:     rc = fts3SyncMethod(pVtab);
145554:   }
145555:   return rc;
145556: }
145557: 
145558: /*
145559: ** The xRelease() method.
145560: **
145561: ** This is a no-op.
145562: */
145563: static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
145564:   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
145565:   UNUSED_PARAMETER(iSavepoint);
145566:   UNUSED_PARAMETER(pVtab);
145567:   assert( p->inTransaction );
145568:   assert( p->mxSavepoint >= iSavepoint );
145569:   TESTONLY( p->mxSavepoint = iSavepoint-1 );
145570:   return SQLITE_OK;
145571: }
145572: 
145573: /*
145574: ** The xRollbackTo() method.
145575: **
145576: ** Discard the contents of the pending terms table.
145577: */
145578: static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
145579:   Fts3Table *p = (Fts3Table*)pVtab;
145580:   UNUSED_PARAMETER(iSavepoint);
145581:   assert( p->inTransaction );
145582:   assert( p->mxSavepoint >= iSavepoint );
145583:   TESTONLY( p->mxSavepoint = iSavepoint );
145584:   sqlite3Fts3PendingTermsClear(p);
145585:   return SQLITE_OK;
145586: }
145587: 
145588: static const sqlite3_module fts3Module = {
145589:   /* iVersion      */ 2,
145590:   /* xCreate       */ fts3CreateMethod,
145591:   /* xConnect      */ fts3ConnectMethod,
145592:   /* xBestIndex    */ fts3BestIndexMethod,
145593:   /* xDisconnect   */ fts3DisconnectMethod,
145594:   /* xDestroy      */ fts3DestroyMethod,
145595:   /* xOpen         */ fts3OpenMethod,
145596:   /* xClose        */ fts3CloseMethod,
145597:   /* xFilter       */ fts3FilterMethod,
145598:   /* xNext         */ fts3NextMethod,
145599:   /* xEof          */ fts3EofMethod,
145600:   /* xColumn       */ fts3ColumnMethod,
145601:   /* xRowid        */ fts3RowidMethod,
145602:   /* xUpdate       */ fts3UpdateMethod,
145603:   /* xBegin        */ fts3BeginMethod,
145604:   /* xSync         */ fts3SyncMethod,
145605:   /* xCommit       */ fts3CommitMethod,
145606:   /* xRollback     */ fts3RollbackMethod,
145607:   /* xFindFunction */ fts3FindFunctionMethod,
145608:   /* xRename */       fts3RenameMethod,
145609:   /* xSavepoint    */ fts3SavepointMethod,
145610:   /* xRelease      */ fts3ReleaseMethod,
145611:   /* xRollbackTo   */ fts3RollbackToMethod,
145612: };
145613: 
145614: /*
145615: ** This function is registered as the module destructor (called when an
145616: ** FTS3 enabled database connection is closed). It frees the memory
145617: ** allocated for the tokenizer hash table.
145618: */
145619: static void hashDestroy(void *p){
145620:   Fts3Hash *pHash = (Fts3Hash *)p;
145621:   sqlite3Fts3HashClear(pHash);
145622:   sqlite3_free(pHash);
145623: }
145624: 
145625: /*
145626: ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
145627: ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
145628: ** respectively. The following three forward declarations are for functions
145629: ** declared in these files used to retrieve the respective implementations.
145630: **
145631: ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
145632: ** to by the argument to point to the "simple" tokenizer implementation.
145633: ** And so on.
145634: */
145635: SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145636: SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145637: #ifndef SQLITE_DISABLE_FTS3_UNICODE
145638: SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
145639: #endif
145640: #ifdef SQLITE_ENABLE_ICU
145641: SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
145642: #endif
145643: 
145644: /*
145645: ** Initialize the fts3 extension. If this extension is built as part
145646: ** of the sqlite library, then this function is called directly by
145647: ** SQLite. If fts3 is built as a dynamically loadable extension, this
145648: ** function is called by the sqlite3_extension_init() entry point.
145649: */
145650: SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
145651:   int rc = SQLITE_OK;
145652:   Fts3Hash *pHash = 0;
145653:   const sqlite3_tokenizer_module *pSimple = 0;
145654:   const sqlite3_tokenizer_module *pPorter = 0;
145655: #ifndef SQLITE_DISABLE_FTS3_UNICODE
145656:   const sqlite3_tokenizer_module *pUnicode = 0;
145657: #endif
145658: 
145659: #ifdef SQLITE_ENABLE_ICU
145660:   const sqlite3_tokenizer_module *pIcu = 0;
145661:   sqlite3Fts3IcuTokenizerModule(&pIcu);
145662: #endif
145663: 
145664: #ifndef SQLITE_DISABLE_FTS3_UNICODE
145665:   sqlite3Fts3UnicodeTokenizer(&pUnicode);
145666: #endif
145667: 
145668: #ifdef SQLITE_TEST
145669:   rc = sqlite3Fts3InitTerm(db);
145670:   if( rc!=SQLITE_OK ) return rc;
145671: #endif
145672: 
145673:   rc = sqlite3Fts3InitAux(db);
145674:   if( rc!=SQLITE_OK ) return rc;
145675: 
145676:   sqlite3Fts3SimpleTokenizerModule(&pSimple);
145677:   sqlite3Fts3PorterTokenizerModule(&pPorter);
145678: 
145679:   /* Allocate and initialize the hash-table used to store tokenizers. */
145680:   pHash = sqlite3_malloc(sizeof(Fts3Hash));
145681:   if( !pHash ){
145682:     rc = SQLITE_NOMEM;
145683:   }else{
145684:     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
145685:   }
145686: 
145687:   /* Load the built-in tokenizers into the hash table */
145688:   if( rc==SQLITE_OK ){
145689:     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
145690:      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
145691: 
145692: #ifndef SQLITE_DISABLE_FTS3_UNICODE
145693:      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
145694: #endif
145695: #ifdef SQLITE_ENABLE_ICU
145696:      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
145697: #endif
145698:     ){
145699:       rc = SQLITE_NOMEM;
145700:     }
145701:   }
145702: 
145703: #ifdef SQLITE_TEST
145704:   if( rc==SQLITE_OK ){
145705:     rc = sqlite3Fts3ExprInitTestInterface(db);
145706:   }
145707: #endif
145708: 
145709:   /* Create the virtual table wrapper around the hash-table and overload 
145710:   ** the two scalar functions. If this is successful, register the
145711:   ** module with sqlite.
145712:   */
145713:   if( SQLITE_OK==rc 
145714:    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
145715:    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
145716:    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
145717:    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
145718:    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
145719:    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
145720:   ){
145721:     rc = sqlite3_create_module_v2(
145722:         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
145723:     );
145724:     if( rc==SQLITE_OK ){
145725:       rc = sqlite3_create_module_v2(
145726:           db, "fts4", &fts3Module, (void *)pHash, 0
145727:       );
145728:     }
145729:     if( rc==SQLITE_OK ){
145730:       rc = sqlite3Fts3InitTok(db, (void *)pHash);
145731:     }
145732:     return rc;
145733:   }
145734: 
145735: 
145736:   /* An error has occurred. Delete the hash table and return the error code. */
145737:   assert( rc!=SQLITE_OK );
145738:   if( pHash ){
145739:     sqlite3Fts3HashClear(pHash);
145740:     sqlite3_free(pHash);
145741:   }
145742:   return rc;
145743: }
145744: 
145745: /*
145746: ** Allocate an Fts3MultiSegReader for each token in the expression headed
145747: ** by pExpr. 
145748: **
145749: ** An Fts3SegReader object is a cursor that can seek or scan a range of
145750: ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
145751: ** Fts3SegReader objects internally to provide an interface to seek or scan
145752: ** within the union of all segments of a b-tree. Hence the name.
145753: **
145754: ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
145755: ** segment b-tree (if the term is not a prefix or it is a prefix for which
145756: ** there exists prefix b-tree of the right length) then it may be traversed
145757: ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
145758: ** doclist and then traversed.
145759: */
145760: static void fts3EvalAllocateReaders(
145761:   Fts3Cursor *pCsr,               /* FTS cursor handle */
145762:   Fts3Expr *pExpr,                /* Allocate readers for this expression */
145763:   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
145764:   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
145765:   int *pRc                        /* IN/OUT: Error code */
145766: ){
145767:   if( pExpr && SQLITE_OK==*pRc ){
145768:     if( pExpr->eType==FTSQUERY_PHRASE ){
145769:       int i;
145770:       int nToken = pExpr->pPhrase->nToken;
145771:       *pnToken += nToken;
145772:       for(i=0; i<nToken; i++){
145773:         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
145774:         int rc = fts3TermSegReaderCursor(pCsr, 
145775:             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
145776:         );
145777:         if( rc!=SQLITE_OK ){
145778:           *pRc = rc;
145779:           return;
145780:         }
145781:       }
145782:       assert( pExpr->pPhrase->iDoclistToken==0 );
145783:       pExpr->pPhrase->iDoclistToken = -1;
145784:     }else{
145785:       *pnOr += (pExpr->eType==FTSQUERY_OR);
145786:       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
145787:       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
145788:     }
145789:   }
145790: }
145791: 
145792: /*
145793: ** Arguments pList/nList contain the doclist for token iToken of phrase p.
145794: ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
145795: **
145796: ** This function assumes that pList points to a buffer allocated using
145797: ** sqlite3_malloc(). This function takes responsibility for eventually
145798: ** freeing the buffer.
145799: **
145800: ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
145801: */
145802: static int fts3EvalPhraseMergeToken(
145803:   Fts3Table *pTab,                /* FTS Table pointer */
145804:   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
145805:   int iToken,                     /* Token pList/nList corresponds to */
145806:   char *pList,                    /* Pointer to doclist */
145807:   int nList                       /* Number of bytes in pList */
145808: ){
145809:   int rc = SQLITE_OK;
145810:   assert( iToken!=p->iDoclistToken );
145811: 
145812:   if( pList==0 ){
145813:     sqlite3_free(p->doclist.aAll);
145814:     p->doclist.aAll = 0;
145815:     p->doclist.nAll = 0;
145816:   }
145817: 
145818:   else if( p->iDoclistToken<0 ){
145819:     p->doclist.aAll = pList;
145820:     p->doclist.nAll = nList;
145821:   }
145822: 
145823:   else if( p->doclist.aAll==0 ){
145824:     sqlite3_free(pList);
145825:   }
145826: 
145827:   else {
145828:     char *pLeft;
145829:     char *pRight;
145830:     int nLeft;
145831:     int nRight;
145832:     int nDiff;
145833: 
145834:     if( p->iDoclistToken<iToken ){
145835:       pLeft = p->doclist.aAll;
145836:       nLeft = p->doclist.nAll;
145837:       pRight = pList;
145838:       nRight = nList;
145839:       nDiff = iToken - p->iDoclistToken;
145840:     }else{
145841:       pRight = p->doclist.aAll;
145842:       nRight = p->doclist.nAll;
145843:       pLeft = pList;
145844:       nLeft = nList;
145845:       nDiff = p->iDoclistToken - iToken;
145846:     }
145847: 
145848:     rc = fts3DoclistPhraseMerge(
145849:         pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
145850:     );
145851:     sqlite3_free(pLeft);
145852:     p->doclist.aAll = pRight;
145853:     p->doclist.nAll = nRight;
145854:   }
145855: 
145856:   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
145857:   return rc;
145858: }
145859: 
145860: /*
145861: ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
145862: ** does not take deferred tokens into account.
145863: **
145864: ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145865: */
145866: static int fts3EvalPhraseLoad(
145867:   Fts3Cursor *pCsr,               /* FTS Cursor handle */
145868:   Fts3Phrase *p                   /* Phrase object */
145869: ){
145870:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145871:   int iToken;
145872:   int rc = SQLITE_OK;
145873: 
145874:   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
145875:     Fts3PhraseToken *pToken = &p->aToken[iToken];
145876:     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
145877: 
145878:     if( pToken->pSegcsr ){
145879:       int nThis = 0;
145880:       char *pThis = 0;
145881:       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
145882:       if( rc==SQLITE_OK ){
145883:         rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
145884:       }
145885:     }
145886:     assert( pToken->pSegcsr==0 );
145887:   }
145888: 
145889:   return rc;
145890: }
145891: 
145892: /*
145893: ** This function is called on each phrase after the position lists for
145894: ** any deferred tokens have been loaded into memory. It updates the phrases
145895: ** current position list to include only those positions that are really
145896: ** instances of the phrase (after considering deferred tokens). If this
145897: ** means that the phrase does not appear in the current row, doclist.pList
145898: ** and doclist.nList are both zeroed.
145899: **
145900: ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145901: */
145902: static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
145903:   int iToken;                     /* Used to iterate through phrase tokens */
145904:   char *aPoslist = 0;             /* Position list for deferred tokens */
145905:   int nPoslist = 0;               /* Number of bytes in aPoslist */
145906:   int iPrev = -1;                 /* Token number of previous deferred token */
145907: 
145908:   assert( pPhrase->doclist.bFreeList==0 );
145909: 
145910:   for(iToken=0; iToken<pPhrase->nToken; iToken++){
145911:     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
145912:     Fts3DeferredToken *pDeferred = pToken->pDeferred;
145913: 
145914:     if( pDeferred ){
145915:       char *pList;
145916:       int nList;
145917:       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
145918:       if( rc!=SQLITE_OK ) return rc;
145919: 
145920:       if( pList==0 ){
145921:         sqlite3_free(aPoslist);
145922:         pPhrase->doclist.pList = 0;
145923:         pPhrase->doclist.nList = 0;
145924:         return SQLITE_OK;
145925: 
145926:       }else if( aPoslist==0 ){
145927:         aPoslist = pList;
145928:         nPoslist = nList;
145929: 
145930:       }else{
145931:         char *aOut = pList;
145932:         char *p1 = aPoslist;
145933:         char *p2 = aOut;
145934: 
145935:         assert( iPrev>=0 );
145936:         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
145937:         sqlite3_free(aPoslist);
145938:         aPoslist = pList;
145939:         nPoslist = (int)(aOut - aPoslist);
145940:         if( nPoslist==0 ){
145941:           sqlite3_free(aPoslist);
145942:           pPhrase->doclist.pList = 0;
145943:           pPhrase->doclist.nList = 0;
145944:           return SQLITE_OK;
145945:         }
145946:       }
145947:       iPrev = iToken;
145948:     }
145949:   }
145950: 
145951:   if( iPrev>=0 ){
145952:     int nMaxUndeferred = pPhrase->iDoclistToken;
145953:     if( nMaxUndeferred<0 ){
145954:       pPhrase->doclist.pList = aPoslist;
145955:       pPhrase->doclist.nList = nPoslist;
145956:       pPhrase->doclist.iDocid = pCsr->iPrevId;
145957:       pPhrase->doclist.bFreeList = 1;
145958:     }else{
145959:       int nDistance;
145960:       char *p1;
145961:       char *p2;
145962:       char *aOut;
145963: 
145964:       if( nMaxUndeferred>iPrev ){
145965:         p1 = aPoslist;
145966:         p2 = pPhrase->doclist.pList;
145967:         nDistance = nMaxUndeferred - iPrev;
145968:       }else{
145969:         p1 = pPhrase->doclist.pList;
145970:         p2 = aPoslist;
145971:         nDistance = iPrev - nMaxUndeferred;
145972:       }
145973: 
145974:       aOut = (char *)sqlite3_malloc(nPoslist+8);
145975:       if( !aOut ){
145976:         sqlite3_free(aPoslist);
145977:         return SQLITE_NOMEM;
145978:       }
145979:       
145980:       pPhrase->doclist.pList = aOut;
145981:       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
145982:         pPhrase->doclist.bFreeList = 1;
145983:         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
145984:       }else{
145985:         sqlite3_free(aOut);
145986:         pPhrase->doclist.pList = 0;
145987:         pPhrase->doclist.nList = 0;
145988:       }
145989:       sqlite3_free(aPoslist);
145990:     }
145991:   }
145992: 
145993:   return SQLITE_OK;
145994: }
145995: 
145996: /*
145997: ** Maximum number of tokens a phrase may have to be considered for the
145998: ** incremental doclists strategy.
145999: */
146000: #define MAX_INCR_PHRASE_TOKENS 4
146001: 
146002: /*
146003: ** This function is called for each Fts3Phrase in a full-text query 
146004: ** expression to initialize the mechanism for returning rows. Once this
146005: ** function has been called successfully on an Fts3Phrase, it may be
146006: ** used with fts3EvalPhraseNext() to iterate through the matching docids.
146007: **
146008: ** If parameter bOptOk is true, then the phrase may (or may not) use the
146009: ** incremental loading strategy. Otherwise, the entire doclist is loaded into
146010: ** memory within this call.
146011: **
146012: ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
146013: */
146014: static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
146015:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146016:   int rc = SQLITE_OK;             /* Error code */
146017:   int i;
146018: 
146019:   /* Determine if doclists may be loaded from disk incrementally. This is
146020:   ** possible if the bOptOk argument is true, the FTS doclists will be
146021:   ** scanned in forward order, and the phrase consists of 
146022:   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
146023:   ** tokens or prefix tokens that cannot use a prefix-index.  */
146024:   int bHaveIncr = 0;
146025:   int bIncrOk = (bOptOk 
146026:    && pCsr->bDesc==pTab->bDescIdx 
146027:    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
146028: #ifdef SQLITE_TEST
146029:    && pTab->bNoIncrDoclist==0
146030: #endif
146031:   );
146032:   for(i=0; bIncrOk==1 && i<p->nToken; i++){
146033:     Fts3PhraseToken *pToken = &p->aToken[i];
146034:     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
146035:       bIncrOk = 0;
146036:     }
146037:     if( pToken->pSegcsr ) bHaveIncr = 1;
146038:   }
146039: 
146040:   if( bIncrOk && bHaveIncr ){
146041:     /* Use the incremental approach. */
146042:     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
146043:     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
146044:       Fts3PhraseToken *pToken = &p->aToken[i];
146045:       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
146046:       if( pSegcsr ){
146047:         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
146048:       }
146049:     }
146050:     p->bIncr = 1;
146051:   }else{
146052:     /* Load the full doclist for the phrase into memory. */
146053:     rc = fts3EvalPhraseLoad(pCsr, p);
146054:     p->bIncr = 0;
146055:   }
146056: 
146057:   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
146058:   return rc;
146059: }
146060: 
146061: /*
146062: ** This function is used to iterate backwards (from the end to start) 
146063: ** through doclists. It is used by this module to iterate through phrase
146064: ** doclists in reverse and by the fts3_write.c module to iterate through
146065: ** pending-terms lists when writing to databases with "order=desc".
146066: **
146067: ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
146068: ** descending (parameter bDescIdx==1) order of docid. Regardless, this
146069: ** function iterates from the end of the doclist to the beginning.
146070: */
146071: SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
146072:   int bDescIdx,                   /* True if the doclist is desc */
146073:   char *aDoclist,                 /* Pointer to entire doclist */
146074:   int nDoclist,                   /* Length of aDoclist in bytes */
146075:   char **ppIter,                  /* IN/OUT: Iterator pointer */
146076:   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
146077:   int *pnList,                    /* OUT: List length pointer */
146078:   u8 *pbEof                       /* OUT: End-of-file flag */
146079: ){
146080:   char *p = *ppIter;
146081: 
146082:   assert( nDoclist>0 );
146083:   assert( *pbEof==0 );
146084:   assert( p || *piDocid==0 );
146085:   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
146086: 
146087:   if( p==0 ){
146088:     sqlite3_int64 iDocid = 0;
146089:     char *pNext = 0;
146090:     char *pDocid = aDoclist;
146091:     char *pEnd = &aDoclist[nDoclist];
146092:     int iMul = 1;
146093: 
146094:     while( pDocid<pEnd ){
146095:       sqlite3_int64 iDelta;
146096:       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
146097:       iDocid += (iMul * iDelta);
146098:       pNext = pDocid;
146099:       fts3PoslistCopy(0, &pDocid);
146100:       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
146101:       iMul = (bDescIdx ? -1 : 1);
146102:     }
146103: 
146104:     *pnList = (int)(pEnd - pNext);
146105:     *ppIter = pNext;
146106:     *piDocid = iDocid;
146107:   }else{
146108:     int iMul = (bDescIdx ? -1 : 1);
146109:     sqlite3_int64 iDelta;
146110:     fts3GetReverseVarint(&p, aDoclist, &iDelta);
146111:     *piDocid -= (iMul * iDelta);
146112: 
146113:     if( p==aDoclist ){
146114:       *pbEof = 1;
146115:     }else{
146116:       char *pSave = p;
146117:       fts3ReversePoslist(aDoclist, &p);
146118:       *pnList = (int)(pSave - p);
146119:     }
146120:     *ppIter = p;
146121:   }
146122: }
146123: 
146124: /*
146125: ** Iterate forwards through a doclist.
146126: */
146127: SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
146128:   int bDescIdx,                   /* True if the doclist is desc */
146129:   char *aDoclist,                 /* Pointer to entire doclist */
146130:   int nDoclist,                   /* Length of aDoclist in bytes */
146131:   char **ppIter,                  /* IN/OUT: Iterator pointer */
146132:   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
146133:   u8 *pbEof                       /* OUT: End-of-file flag */
146134: ){
146135:   char *p = *ppIter;
146136: 
146137:   assert( nDoclist>0 );
146138:   assert( *pbEof==0 );
146139:   assert( p || *piDocid==0 );
146140:   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
146141: 
146142:   if( p==0 ){
146143:     p = aDoclist;
146144:     p += sqlite3Fts3GetVarint(p, piDocid);
146145:   }else{
146146:     fts3PoslistCopy(0, &p);
146147:     while( p<&aDoclist[nDoclist] && *p==0 ) p++; 
146148:     if( p>=&aDoclist[nDoclist] ){
146149:       *pbEof = 1;
146150:     }else{
146151:       sqlite3_int64 iVar;
146152:       p += sqlite3Fts3GetVarint(p, &iVar);
146153:       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
146154:     }
146155:   }
146156: 
146157:   *ppIter = p;
146158: }
146159: 
146160: /*
146161: ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
146162: ** to true if EOF is reached.
146163: */
146164: static void fts3EvalDlPhraseNext(
146165:   Fts3Table *pTab,
146166:   Fts3Doclist *pDL,
146167:   u8 *pbEof
146168: ){
146169:   char *pIter;                            /* Used to iterate through aAll */
146170:   char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
146171:  
146172:   if( pDL->pNextDocid ){
146173:     pIter = pDL->pNextDocid;
146174:   }else{
146175:     pIter = pDL->aAll;
146176:   }
146177: 
146178:   if( pIter>=pEnd ){
146179:     /* We have already reached the end of this doclist. EOF. */
146180:     *pbEof = 1;
146181:   }else{
146182:     sqlite3_int64 iDelta;
146183:     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
146184:     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
146185:       pDL->iDocid += iDelta;
146186:     }else{
146187:       pDL->iDocid -= iDelta;
146188:     }
146189:     pDL->pList = pIter;
146190:     fts3PoslistCopy(0, &pIter);
146191:     pDL->nList = (int)(pIter - pDL->pList);
146192: 
146193:     /* pIter now points just past the 0x00 that terminates the position-
146194:     ** list for document pDL->iDocid. However, if this position-list was
146195:     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
146196:     ** point to the start of the next docid value. The following line deals
146197:     ** with this case by advancing pIter past the zero-padding added by
146198:     ** fts3EvalNearTrim().  */
146199:     while( pIter<pEnd && *pIter==0 ) pIter++;
146200: 
146201:     pDL->pNextDocid = pIter;
146202:     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
146203:     *pbEof = 0;
146204:   }
146205: }
146206: 
146207: /*
146208: ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
146209: */
146210: typedef struct TokenDoclist TokenDoclist;
146211: struct TokenDoclist {
146212:   int bIgnore;
146213:   sqlite3_int64 iDocid;
146214:   char *pList;
146215:   int nList;
146216: };
146217: 
146218: /*
146219: ** Token pToken is an incrementally loaded token that is part of a 
146220: ** multi-token phrase. Advance it to the next matching document in the
146221: ** database and populate output variable *p with the details of the new
146222: ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
146223: **
146224: ** If an error occurs, return an SQLite error code. Otherwise, return 
146225: ** SQLITE_OK.
146226: */
146227: static int incrPhraseTokenNext(
146228:   Fts3Table *pTab,                /* Virtual table handle */
146229:   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
146230:   int iToken,                     /* Specific token to advance */
146231:   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
146232:   u8 *pbEof                       /* OUT: True if iterator is at EOF */
146233: ){
146234:   int rc = SQLITE_OK;
146235: 
146236:   if( pPhrase->iDoclistToken==iToken ){
146237:     assert( p->bIgnore==0 );
146238:     assert( pPhrase->aToken[iToken].pSegcsr==0 );
146239:     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
146240:     p->pList = pPhrase->doclist.pList;
146241:     p->nList = pPhrase->doclist.nList;
146242:     p->iDocid = pPhrase->doclist.iDocid;
146243:   }else{
146244:     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
146245:     assert( pToken->pDeferred==0 );
146246:     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
146247:     if( pToken->pSegcsr ){
146248:       assert( p->bIgnore==0 );
146249:       rc = sqlite3Fts3MsrIncrNext(
146250:           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
146251:       );
146252:       if( p->pList==0 ) *pbEof = 1;
146253:     }else{
146254:       p->bIgnore = 1;
146255:     }
146256:   }
146257: 
146258:   return rc;
146259: }
146260: 
146261: 
146262: /*
146263: ** The phrase iterator passed as the second argument:
146264: **
146265: **   * features at least one token that uses an incremental doclist, and 
146266: **
146267: **   * does not contain any deferred tokens.
146268: **
146269: ** Advance it to the next matching documnent in the database and populate
146270: ** the Fts3Doclist.pList and nList fields. 
146271: **
146272: ** If there is no "next" entry and no error occurs, then *pbEof is set to
146273: ** 1 before returning. Otherwise, if no error occurs and the iterator is
146274: ** successfully advanced, *pbEof is set to 0.
146275: **
146276: ** If an error occurs, return an SQLite error code. Otherwise, return 
146277: ** SQLITE_OK.
146278: */
146279: static int fts3EvalIncrPhraseNext(
146280:   Fts3Cursor *pCsr,               /* FTS Cursor handle */
146281:   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
146282:   u8 *pbEof                       /* OUT: Set to 1 if EOF */
146283: ){
146284:   int rc = SQLITE_OK;
146285:   Fts3Doclist *pDL = &p->doclist;
146286:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146287:   u8 bEof = 0;
146288: 
146289:   /* This is only called if it is guaranteed that the phrase has at least
146290:   ** one incremental token. In which case the bIncr flag is set. */
146291:   assert( p->bIncr==1 );
146292: 
146293:   if( p->nToken==1 && p->bIncr ){
146294:     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
146295:         &pDL->iDocid, &pDL->pList, &pDL->nList
146296:     );
146297:     if( pDL->pList==0 ) bEof = 1;
146298:   }else{
146299:     int bDescDoclist = pCsr->bDesc;
146300:     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
146301: 
146302:     memset(a, 0, sizeof(a));
146303:     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
146304:     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
146305: 
146306:     while( bEof==0 ){
146307:       int bMaxSet = 0;
146308:       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
146309:       int i;                      /* Used to iterate through tokens */
146310: 
146311:       /* Advance the iterator for each token in the phrase once. */
146312:       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
146313:         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
146314:         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
146315:           iMax = a[i].iDocid;
146316:           bMaxSet = 1;
146317:         }
146318:       }
146319:       assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
146320:       assert( rc!=SQLITE_OK || bMaxSet );
146321: 
146322:       /* Keep advancing iterators until they all point to the same document */
146323:       for(i=0; i<p->nToken; i++){
146324:         while( rc==SQLITE_OK && bEof==0 
146325:             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 
146326:         ){
146327:           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
146328:           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
146329:             iMax = a[i].iDocid;
146330:             i = 0;
146331:           }
146332:         }
146333:       }
146334: 
146335:       /* Check if the current entries really are a phrase match */
146336:       if( bEof==0 ){
146337:         int nList = 0;
146338:         int nByte = a[p->nToken-1].nList;
146339:         char *aDoclist = sqlite3_malloc(nByte+1);
146340:         if( !aDoclist ) return SQLITE_NOMEM;
146341:         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
146342: 
146343:         for(i=0; i<(p->nToken-1); i++){
146344:           if( a[i].bIgnore==0 ){
146345:             char *pL = a[i].pList;
146346:             char *pR = aDoclist;
146347:             char *pOut = aDoclist;
146348:             int nDist = p->nToken-1-i;
146349:             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
146350:             if( res==0 ) break;
146351:             nList = (int)(pOut - aDoclist);
146352:           }
146353:         }
146354:         if( i==(p->nToken-1) ){
146355:           pDL->iDocid = iMax;
146356:           pDL->pList = aDoclist;
146357:           pDL->nList = nList;
146358:           pDL->bFreeList = 1;
146359:           break;
146360:         }
146361:         sqlite3_free(aDoclist);
146362:       }
146363:     }
146364:   }
146365: 
146366:   *pbEof = bEof;
146367:   return rc;
146368: }
146369: 
146370: /*
146371: ** Attempt to move the phrase iterator to point to the next matching docid. 
146372: ** If an error occurs, return an SQLite error code. Otherwise, return 
146373: ** SQLITE_OK.
146374: **
146375: ** If there is no "next" entry and no error occurs, then *pbEof is set to
146376: ** 1 before returning. Otherwise, if no error occurs and the iterator is
146377: ** successfully advanced, *pbEof is set to 0.
146378: */
146379: static int fts3EvalPhraseNext(
146380:   Fts3Cursor *pCsr,               /* FTS Cursor handle */
146381:   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
146382:   u8 *pbEof                       /* OUT: Set to 1 if EOF */
146383: ){
146384:   int rc = SQLITE_OK;
146385:   Fts3Doclist *pDL = &p->doclist;
146386:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146387: 
146388:   if( p->bIncr ){
146389:     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
146390:   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
146391:     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
146392:         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
146393:     );
146394:     pDL->pList = pDL->pNextDocid;
146395:   }else{
146396:     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
146397:   }
146398: 
146399:   return rc;
146400: }
146401: 
146402: /*
146403: **
146404: ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146405: ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
146406: ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
146407: ** expressions for which all descendent tokens are deferred.
146408: **
146409: ** If parameter bOptOk is zero, then it is guaranteed that the
146410: ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
146411: ** each phrase in the expression (subject to deferred token processing).
146412: ** Or, if bOptOk is non-zero, then one or more tokens within the expression
146413: ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
146414: **
146415: ** If an error occurs within this function, *pRc is set to an SQLite error
146416: ** code before returning.
146417: */
146418: static void fts3EvalStartReaders(
146419:   Fts3Cursor *pCsr,               /* FTS Cursor handle */
146420:   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
146421:   int *pRc                        /* IN/OUT: Error code */
146422: ){
146423:   if( pExpr && SQLITE_OK==*pRc ){
146424:     if( pExpr->eType==FTSQUERY_PHRASE ){
146425:       int nToken = pExpr->pPhrase->nToken;
146426:       if( nToken ){
146427:         int i;
146428:         for(i=0; i<nToken; i++){
146429:           if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
146430:         }
146431:         pExpr->bDeferred = (i==nToken);
146432:       }
146433:       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
146434:     }else{
146435:       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
146436:       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
146437:       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
146438:     }
146439:   }
146440: }
146441: 
146442: /*
146443: ** An array of the following structures is assembled as part of the process
146444: ** of selecting tokens to defer before the query starts executing (as part
146445: ** of the xFilter() method). There is one element in the array for each
146446: ** token in the FTS expression.
146447: **
146448: ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
146449: ** to phrases that are connected only by AND and NEAR operators (not OR or
146450: ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
146451: ** separately. The root of a tokens AND/NEAR cluster is stored in 
146452: ** Fts3TokenAndCost.pRoot.
146453: */
146454: typedef struct Fts3TokenAndCost Fts3TokenAndCost;
146455: struct Fts3TokenAndCost {
146456:   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
146457:   int iToken;                     /* Position of token in phrase */
146458:   Fts3PhraseToken *pToken;        /* The token itself */
146459:   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
146460:   int nOvfl;                      /* Number of overflow pages to load doclist */
146461:   int iCol;                       /* The column the token must match */
146462: };
146463: 
146464: /*
146465: ** This function is used to populate an allocated Fts3TokenAndCost array.
146466: **
146467: ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146468: ** Otherwise, if an error occurs during execution, *pRc is set to an
146469: ** SQLite error code.
146470: */
146471: static void fts3EvalTokenCosts(
146472:   Fts3Cursor *pCsr,               /* FTS Cursor handle */
146473:   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
146474:   Fts3Expr *pExpr,                /* Expression to consider */
146475:   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
146476:   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
146477:   int *pRc                        /* IN/OUT: Error code */
146478: ){
146479:   if( *pRc==SQLITE_OK ){
146480:     if( pExpr->eType==FTSQUERY_PHRASE ){
146481:       Fts3Phrase *pPhrase = pExpr->pPhrase;
146482:       int i;
146483:       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
146484:         Fts3TokenAndCost *pTC = (*ppTC)++;
146485:         pTC->pPhrase = pPhrase;
146486:         pTC->iToken = i;
146487:         pTC->pRoot = pRoot;
146488:         pTC->pToken = &pPhrase->aToken[i];
146489:         pTC->iCol = pPhrase->iColumn;
146490:         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
146491:       }
146492:     }else if( pExpr->eType!=FTSQUERY_NOT ){
146493:       assert( pExpr->eType==FTSQUERY_OR
146494:            || pExpr->eType==FTSQUERY_AND
146495:            || pExpr->eType==FTSQUERY_NEAR
146496:       );
146497:       assert( pExpr->pLeft && pExpr->pRight );
146498:       if( pExpr->eType==FTSQUERY_OR ){
146499:         pRoot = pExpr->pLeft;
146500:         **ppOr = pRoot;
146501:         (*ppOr)++;
146502:       }
146503:       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
146504:       if( pExpr->eType==FTSQUERY_OR ){
146505:         pRoot = pExpr->pRight;
146506:         **ppOr = pRoot;
146507:         (*ppOr)++;
146508:       }
146509:       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
146510:     }
146511:   }
146512: }
146513: 
146514: /*
146515: ** Determine the average document (row) size in pages. If successful,
146516: ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
146517: ** an SQLite error code.
146518: **
146519: ** The average document size in pages is calculated by first calculating 
146520: ** determining the average size in bytes, B. If B is less than the amount
146521: ** of data that will fit on a single leaf page of an intkey table in
146522: ** this database, then the average docsize is 1. Otherwise, it is 1 plus
146523: ** the number of overflow pages consumed by a record B bytes in size.
146524: */
146525: static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
146526:   if( pCsr->nRowAvg==0 ){
146527:     /* The average document size, which is required to calculate the cost
146528:     ** of each doclist, has not yet been determined. Read the required 
146529:     ** data from the %_stat table to calculate it.
146530:     **
146531:     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
146532:     ** varints, where nCol is the number of columns in the FTS3 table.
146533:     ** The first varint is the number of documents currently stored in
146534:     ** the table. The following nCol varints contain the total amount of
146535:     ** data stored in all rows of each column of the table, from left
146536:     ** to right.
146537:     */
146538:     int rc;
146539:     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
146540:     sqlite3_stmt *pStmt;
146541:     sqlite3_int64 nDoc = 0;
146542:     sqlite3_int64 nByte = 0;
146543:     const char *pEnd;
146544:     const char *a;
146545: 
146546:     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
146547:     if( rc!=SQLITE_OK ) return rc;
146548:     a = sqlite3_column_blob(pStmt, 0);
146549:     assert( a );
146550: 
146551:     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
146552:     a += sqlite3Fts3GetVarint(a, &nDoc);
146553:     while( a<pEnd ){
146554:       a += sqlite3Fts3GetVarint(a, &nByte);
146555:     }
146556:     if( nDoc==0 || nByte==0 ){
146557:       sqlite3_reset(pStmt);
146558:       return FTS_CORRUPT_VTAB;
146559:     }
146560: 
146561:     pCsr->nDoc = nDoc;
146562:     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
146563:     assert( pCsr->nRowAvg>0 ); 
146564:     rc = sqlite3_reset(pStmt);
146565:     if( rc!=SQLITE_OK ) return rc;
146566:   }
146567: 
146568:   *pnPage = pCsr->nRowAvg;
146569:   return SQLITE_OK;
146570: }
146571: 
146572: /*
146573: ** This function is called to select the tokens (if any) that will be 
146574: ** deferred. The array aTC[] has already been populated when this is
146575: ** called.
146576: **
146577: ** This function is called once for each AND/NEAR cluster in the 
146578: ** expression. Each invocation determines which tokens to defer within
146579: ** the cluster with root node pRoot. See comments above the definition
146580: ** of struct Fts3TokenAndCost for more details.
146581: **
146582: ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
146583: ** called on each token to defer. Otherwise, an SQLite error code is
146584: ** returned.
146585: */
146586: static int fts3EvalSelectDeferred(
146587:   Fts3Cursor *pCsr,               /* FTS Cursor handle */
146588:   Fts3Expr *pRoot,                /* Consider tokens with this root node */
146589:   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
146590:   int nTC                         /* Number of entries in aTC[] */
146591: ){
146592:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146593:   int nDocSize = 0;               /* Number of pages per doc loaded */
146594:   int rc = SQLITE_OK;             /* Return code */
146595:   int ii;                         /* Iterator variable for various purposes */
146596:   int nOvfl = 0;                  /* Total overflow pages used by doclists */
146597:   int nToken = 0;                 /* Total number of tokens in cluster */
146598: 
146599:   int nMinEst = 0;                /* The minimum count for any phrase so far. */
146600:   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
146601: 
146602:   /* Tokens are never deferred for FTS tables created using the content=xxx
146603:   ** option. The reason being that it is not guaranteed that the content
146604:   ** table actually contains the same data as the index. To prevent this from
146605:   ** causing any problems, the deferred token optimization is completely
146606:   ** disabled for content=xxx tables. */
146607:   if( pTab->zContentTbl ){
146608:     return SQLITE_OK;
146609:   }
146610: 
146611:   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
146612:   ** associated with the tokens spill onto overflow pages, or if there is
146613:   ** only 1 token, exit early. No tokens to defer in this case. */
146614:   for(ii=0; ii<nTC; ii++){
146615:     if( aTC[ii].pRoot==pRoot ){
146616:       nOvfl += aTC[ii].nOvfl;
146617:       nToken++;
146618:     }
146619:   }
146620:   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
146621: 
146622:   /* Obtain the average docsize (in pages). */
146623:   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
146624:   assert( rc!=SQLITE_OK || nDocSize>0 );
146625: 
146626: 
146627:   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
146628:   ** of the number of overflow pages that will be loaded by the pager layer 
146629:   ** to retrieve the entire doclist for the token from the full-text index.
146630:   ** Load the doclists for tokens that are either:
146631:   **
146632:   **   a. The cheapest token in the entire query (i.e. the one visited by the
146633:   **      first iteration of this loop), or
146634:   **
146635:   **   b. Part of a multi-token phrase.
146636:   **
146637:   ** After each token doclist is loaded, merge it with the others from the
146638:   ** same phrase and count the number of documents that the merged doclist
146639:   ** contains. Set variable "nMinEst" to the smallest number of documents in 
146640:   ** any phrase doclist for which 1 or more token doclists have been loaded.
146641:   ** Let nOther be the number of other phrases for which it is certain that
146642:   ** one or more tokens will not be deferred.
146643:   **
146644:   ** Then, for each token, defer it if loading the doclist would result in
146645:   ** loading N or more overflow pages into memory, where N is computed as:
146646:   **
146647:   **    (nMinEst + 4^nOther - 1) / (4^nOther)
146648:   */
146649:   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
146650:     int iTC;                      /* Used to iterate through aTC[] array. */
146651:     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
146652: 
146653:     /* Set pTC to point to the cheapest remaining token. */
146654:     for(iTC=0; iTC<nTC; iTC++){
146655:       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
146656:        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
146657:       ){
146658:         pTC = &aTC[iTC];
146659:       }
146660:     }
146661:     assert( pTC );
146662: 
146663:     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
146664:       /* The number of overflow pages to load for this (and therefore all
146665:       ** subsequent) tokens is greater than the estimated number of pages 
146666:       ** that will be loaded if all subsequent tokens are deferred.
146667:       */
146668:       Fts3PhraseToken *pToken = pTC->pToken;
146669:       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
146670:       fts3SegReaderCursorFree(pToken->pSegcsr);
146671:       pToken->pSegcsr = 0;
146672:     }else{
146673:       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
146674:       ** for-loop. Except, limit the value to 2^24 to prevent it from 
146675:       ** overflowing the 32-bit integer it is stored in. */
146676:       if( ii<12 ) nLoad4 = nLoad4*4;
146677: 
146678:       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
146679:         /* Either this is the cheapest token in the entire query, or it is
146680:         ** part of a multi-token phrase. Either way, the entire doclist will
146681:         ** (eventually) be loaded into memory. It may as well be now. */
146682:         Fts3PhraseToken *pToken = pTC->pToken;
146683:         int nList = 0;
146684:         char *pList = 0;
146685:         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
146686:         assert( rc==SQLITE_OK || pList==0 );
146687:         if( rc==SQLITE_OK ){
146688:           rc = fts3EvalPhraseMergeToken(
146689:               pTab, pTC->pPhrase, pTC->iToken,pList,nList
146690:           );
146691:         }
146692:         if( rc==SQLITE_OK ){
146693:           int nCount;
146694:           nCount = fts3DoclistCountDocids(
146695:               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
146696:           );
146697:           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
146698:         }
146699:       }
146700:     }
146701:     pTC->pToken = 0;
146702:   }
146703: 
146704:   return rc;
146705: }
146706: 
146707: /*
146708: ** This function is called from within the xFilter method. It initializes
146709: ** the full-text query currently stored in pCsr->pExpr. To iterate through
146710: ** the results of a query, the caller does:
146711: **
146712: **    fts3EvalStart(pCsr);
146713: **    while( 1 ){
146714: **      fts3EvalNext(pCsr);
146715: **      if( pCsr->bEof ) break;
146716: **      ... return row pCsr->iPrevId to the caller ...
146717: **    }
146718: */
146719: static int fts3EvalStart(Fts3Cursor *pCsr){
146720:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146721:   int rc = SQLITE_OK;
146722:   int nToken = 0;
146723:   int nOr = 0;
146724: 
146725:   /* Allocate a MultiSegReader for each token in the expression. */
146726:   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
146727: 
146728:   /* Determine which, if any, tokens in the expression should be deferred. */
146729: #ifndef SQLITE_DISABLE_FTS4_DEFERRED
146730:   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
146731:     Fts3TokenAndCost *aTC;
146732:     Fts3Expr **apOr;
146733:     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
146734:         sizeof(Fts3TokenAndCost) * nToken
146735:       + sizeof(Fts3Expr *) * nOr * 2
146736:     );
146737:     apOr = (Fts3Expr **)&aTC[nToken];
146738: 
146739:     if( !aTC ){
146740:       rc = SQLITE_NOMEM;
146741:     }else{
146742:       int ii;
146743:       Fts3TokenAndCost *pTC = aTC;
146744:       Fts3Expr **ppOr = apOr;
146745: 
146746:       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
146747:       nToken = (int)(pTC-aTC);
146748:       nOr = (int)(ppOr-apOr);
146749: 
146750:       if( rc==SQLITE_OK ){
146751:         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
146752:         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
146753:           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
146754:         }
146755:       }
146756: 
146757:       sqlite3_free(aTC);
146758:     }
146759:   }
146760: #endif
146761: 
146762:   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
146763:   return rc;
146764: }
146765: 
146766: /*
146767: ** Invalidate the current position list for phrase pPhrase.
146768: */
146769: static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
146770:   if( pPhrase->doclist.bFreeList ){
146771:     sqlite3_free(pPhrase->doclist.pList);
146772:   }
146773:   pPhrase->doclist.pList = 0;
146774:   pPhrase->doclist.nList = 0;
146775:   pPhrase->doclist.bFreeList = 0;
146776: }
146777: 
146778: /*
146779: ** This function is called to edit the position list associated with
146780: ** the phrase object passed as the fifth argument according to a NEAR
146781: ** condition. For example:
146782: **
146783: **     abc NEAR/5 "def ghi"
146784: **
146785: ** Parameter nNear is passed the NEAR distance of the expression (5 in
146786: ** the example above). When this function is called, *paPoslist points to
146787: ** the position list, and *pnToken is the number of phrase tokens in, the
146788: ** phrase on the other side of the NEAR operator to pPhrase. For example,
146789: ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
146790: ** the position list associated with phrase "abc".
146791: **
146792: ** All positions in the pPhrase position list that are not sufficiently
146793: ** close to a position in the *paPoslist position list are removed. If this
146794: ** leaves 0 positions, zero is returned. Otherwise, non-zero.
146795: **
146796: ** Before returning, *paPoslist is set to point to the position lsit 
146797: ** associated with pPhrase. And *pnToken is set to the number of tokens in
146798: ** pPhrase.
146799: */
146800: static int fts3EvalNearTrim(
146801:   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
146802:   char *aTmp,                     /* Temporary space to use */
146803:   char **paPoslist,               /* IN/OUT: Position list */
146804:   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
146805:   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
146806: ){
146807:   int nParam1 = nNear + pPhrase->nToken;
146808:   int nParam2 = nNear + *pnToken;
146809:   int nNew;
146810:   char *p2; 
146811:   char *pOut; 
146812:   int res;
146813: 
146814:   assert( pPhrase->doclist.pList );
146815: 
146816:   p2 = pOut = pPhrase->doclist.pList;
146817:   res = fts3PoslistNearMerge(
146818:     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
146819:   );
146820:   if( res ){
146821:     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
146822:     assert( pPhrase->doclist.pList[nNew]=='\0' );
146823:     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
146824:     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
146825:     pPhrase->doclist.nList = nNew;
146826:     *paPoslist = pPhrase->doclist.pList;
146827:     *pnToken = pPhrase->nToken;
146828:   }
146829: 
146830:   return res;
146831: }
146832: 
146833: /*
146834: ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
146835: ** Otherwise, it advances the expression passed as the second argument to
146836: ** point to the next matching row in the database. Expressions iterate through
146837: ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
146838: ** or descending if it is non-zero.
146839: **
146840: ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
146841: ** successful, the following variables in pExpr are set:
146842: **
146843: **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
146844: **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
146845: **
146846: ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
146847: ** at EOF, then the following variables are populated with the position list
146848: ** for the phrase for the visited row:
146849: **
146850: **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
146851: **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
146852: **
146853: ** It says above that this function advances the expression to the next
146854: ** matching row. This is usually true, but there are the following exceptions:
146855: **
146856: **   1. Deferred tokens are not taken into account. If a phrase consists
146857: **      entirely of deferred tokens, it is assumed to match every row in
146858: **      the db. In this case the position-list is not populated at all. 
146859: **
146860: **      Or, if a phrase contains one or more deferred tokens and one or
146861: **      more non-deferred tokens, then the expression is advanced to the 
146862: **      next possible match, considering only non-deferred tokens. In other
146863: **      words, if the phrase is "A B C", and "B" is deferred, the expression
146864: **      is advanced to the next row that contains an instance of "A * C", 
146865: **      where "*" may match any single token. The position list in this case
146866: **      is populated as for "A * C" before returning.
146867: **
146868: **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
146869: **      advanced to point to the next row that matches "x AND y".
146870: ** 
146871: ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
146872: ** really a match, taking into account deferred tokens and NEAR operators.
146873: */
146874: static void fts3EvalNextRow(
146875:   Fts3Cursor *pCsr,               /* FTS Cursor handle */
146876:   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
146877:   int *pRc                        /* IN/OUT: Error code */
146878: ){
146879:   if( *pRc==SQLITE_OK ){
146880:     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
146881:     assert( pExpr->bEof==0 );
146882:     pExpr->bStart = 1;
146883: 
146884:     switch( pExpr->eType ){
146885:       case FTSQUERY_NEAR:
146886:       case FTSQUERY_AND: {
146887:         Fts3Expr *pLeft = pExpr->pLeft;
146888:         Fts3Expr *pRight = pExpr->pRight;
146889:         assert( !pLeft->bDeferred || !pRight->bDeferred );
146890: 
146891:         if( pLeft->bDeferred ){
146892:           /* LHS is entirely deferred. So we assume it matches every row.
146893:           ** Advance the RHS iterator to find the next row visited. */
146894:           fts3EvalNextRow(pCsr, pRight, pRc);
146895:           pExpr->iDocid = pRight->iDocid;
146896:           pExpr->bEof = pRight->bEof;
146897:         }else if( pRight->bDeferred ){
146898:           /* RHS is entirely deferred. So we assume it matches every row.
146899:           ** Advance the LHS iterator to find the next row visited. */
146900:           fts3EvalNextRow(pCsr, pLeft, pRc);
146901:           pExpr->iDocid = pLeft->iDocid;
146902:           pExpr->bEof = pLeft->bEof;
146903:         }else{
146904:           /* Neither the RHS or LHS are deferred. */
146905:           fts3EvalNextRow(pCsr, pLeft, pRc);
146906:           fts3EvalNextRow(pCsr, pRight, pRc);
146907:           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
146908:             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146909:             if( iDiff==0 ) break;
146910:             if( iDiff<0 ){
146911:               fts3EvalNextRow(pCsr, pLeft, pRc);
146912:             }else{
146913:               fts3EvalNextRow(pCsr, pRight, pRc);
146914:             }
146915:           }
146916:           pExpr->iDocid = pLeft->iDocid;
146917:           pExpr->bEof = (pLeft->bEof || pRight->bEof);
146918:           if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
146919:             if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
146920:               Fts3Doclist *pDl = &pRight->pPhrase->doclist;
146921:               while( *pRc==SQLITE_OK && pRight->bEof==0 ){
146922:                 memset(pDl->pList, 0, pDl->nList);
146923:                 fts3EvalNextRow(pCsr, pRight, pRc);
146924:               }
146925:             }
146926:             if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
146927:               Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
146928:               while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
146929:                 memset(pDl->pList, 0, pDl->nList);
146930:                 fts3EvalNextRow(pCsr, pLeft, pRc);
146931:               }
146932:             }
146933:           }
146934:         }
146935:         break;
146936:       }
146937:   
146938:       case FTSQUERY_OR: {
146939:         Fts3Expr *pLeft = pExpr->pLeft;
146940:         Fts3Expr *pRight = pExpr->pRight;
146941:         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146942: 
146943:         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
146944:         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
146945: 
146946:         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
146947:           fts3EvalNextRow(pCsr, pLeft, pRc);
146948:         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
146949:           fts3EvalNextRow(pCsr, pRight, pRc);
146950:         }else{
146951:           fts3EvalNextRow(pCsr, pLeft, pRc);
146952:           fts3EvalNextRow(pCsr, pRight, pRc);
146953:         }
146954: 
146955:         pExpr->bEof = (pLeft->bEof && pRight->bEof);
146956:         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146957:         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
146958:           pExpr->iDocid = pLeft->iDocid;
146959:         }else{
146960:           pExpr->iDocid = pRight->iDocid;
146961:         }
146962: 
146963:         break;
146964:       }
146965: 
146966:       case FTSQUERY_NOT: {
146967:         Fts3Expr *pLeft = pExpr->pLeft;
146968:         Fts3Expr *pRight = pExpr->pRight;
146969: 
146970:         if( pRight->bStart==0 ){
146971:           fts3EvalNextRow(pCsr, pRight, pRc);
146972:           assert( *pRc!=SQLITE_OK || pRight->bStart );
146973:         }
146974: 
146975:         fts3EvalNextRow(pCsr, pLeft, pRc);
146976:         if( pLeft->bEof==0 ){
146977:           while( !*pRc 
146978:               && !pRight->bEof 
146979:               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
146980:           ){
146981:             fts3EvalNextRow(pCsr, pRight, pRc);
146982:           }
146983:         }
146984:         pExpr->iDocid = pLeft->iDocid;
146985:         pExpr->bEof = pLeft->bEof;
146986:         break;
146987:       }
146988: 
146989:       default: {
146990:         Fts3Phrase *pPhrase = pExpr->pPhrase;
146991:         fts3EvalInvalidatePoslist(pPhrase);
146992:         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
146993:         pExpr->iDocid = pPhrase->doclist.iDocid;
146994:         break;
146995:       }
146996:     }
146997:   }
146998: }
146999: 
147000: /*
147001: ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
147002: ** cluster, then this function returns 1 immediately.
147003: **
147004: ** Otherwise, it checks if the current row really does match the NEAR 
147005: ** expression, using the data currently stored in the position lists 
147006: ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
147007: **
147008: ** If the current row is a match, the position list associated with each
147009: ** phrase in the NEAR expression is edited in place to contain only those
147010: ** phrase instances sufficiently close to their peers to satisfy all NEAR
147011: ** constraints. In this case it returns 1. If the NEAR expression does not 
147012: ** match the current row, 0 is returned. The position lists may or may not
147013: ** be edited if 0 is returned.
147014: */
147015: static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
147016:   int res = 1;
147017: 
147018:   /* The following block runs if pExpr is the root of a NEAR query.
147019:   ** For example, the query:
147020:   **
147021:   **         "w" NEAR "x" NEAR "y" NEAR "z"
147022:   **
147023:   ** which is represented in tree form as:
147024:   **
147025:   **                               |
147026:   **                          +--NEAR--+      <-- root of NEAR query
147027:   **                          |        |
147028:   **                     +--NEAR--+   "z"
147029:   **                     |        |
147030:   **                +--NEAR--+   "y"
147031:   **                |        |
147032:   **               "w"      "x"
147033:   **
147034:   ** The right-hand child of a NEAR node is always a phrase. The 
147035:   ** left-hand child may be either a phrase or a NEAR node. There are
147036:   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
147037:   */
147038:   if( *pRc==SQLITE_OK 
147039:    && pExpr->eType==FTSQUERY_NEAR 
147040:    && pExpr->bEof==0
147041:    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
147042:   ){
147043:     Fts3Expr *p; 
147044:     int nTmp = 0;                 /* Bytes of temp space */
147045:     char *aTmp;                   /* Temp space for PoslistNearMerge() */
147046: 
147047:     /* Allocate temporary working space. */
147048:     for(p=pExpr; p->pLeft; p=p->pLeft){
147049:       nTmp += p->pRight->pPhrase->doclist.nList;
147050:     }
147051:     nTmp += p->pPhrase->doclist.nList;
147052:     if( nTmp==0 ){
147053:       res = 0;
147054:     }else{
147055:       aTmp = sqlite3_malloc(nTmp*2);
147056:       if( !aTmp ){
147057:         *pRc = SQLITE_NOMEM;
147058:         res = 0;
147059:       }else{
147060:         char *aPoslist = p->pPhrase->doclist.pList;
147061:         int nToken = p->pPhrase->nToken;
147062: 
147063:         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
147064:           Fts3Phrase *pPhrase = p->pRight->pPhrase;
147065:           int nNear = p->nNear;
147066:           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
147067:         }
147068: 
147069:         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
147070:         nToken = pExpr->pRight->pPhrase->nToken;
147071:         for(p=pExpr->pLeft; p && res; p=p->pLeft){
147072:           int nNear;
147073:           Fts3Phrase *pPhrase;
147074:           assert( p->pParent && p->pParent->pLeft==p );
147075:           nNear = p->pParent->nNear;
147076:           pPhrase = (
147077:               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
147078:               );
147079:           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
147080:         }
147081:       }
147082: 
147083:       sqlite3_free(aTmp);
147084:     }
147085:   }
147086: 
147087:   return res;
147088: }
147089: 
147090: /*
147091: ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
147092: ** Assuming no error occurs or has occurred, It returns non-zero if the
147093: ** expression passed as the second argument matches the row that pCsr 
147094: ** currently points to, or zero if it does not.
147095: **
147096: ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147097: ** If an error occurs during execution of this function, *pRc is set to 
147098: ** the appropriate SQLite error code. In this case the returned value is 
147099: ** undefined.
147100: */
147101: static int fts3EvalTestExpr(
147102:   Fts3Cursor *pCsr,               /* FTS cursor handle */
147103:   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
147104:   int *pRc                        /* IN/OUT: Error code */
147105: ){
147106:   int bHit = 1;                   /* Return value */
147107:   if( *pRc==SQLITE_OK ){
147108:     switch( pExpr->eType ){
147109:       case FTSQUERY_NEAR:
147110:       case FTSQUERY_AND:
147111:         bHit = (
147112:             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
147113:          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
147114:          && fts3EvalNearTest(pExpr, pRc)
147115:         );
147116: 
147117:         /* If the NEAR expression does not match any rows, zero the doclist for 
147118:         ** all phrases involved in the NEAR. This is because the snippet(),
147119:         ** offsets() and matchinfo() functions are not supposed to recognize 
147120:         ** any instances of phrases that are part of unmatched NEAR queries. 
147121:         ** For example if this expression:
147122:         **
147123:         **    ... MATCH 'a OR (b NEAR c)'
147124:         **
147125:         ** is matched against a row containing:
147126:         **
147127:         **        'a b d e'
147128:         **
147129:         ** then any snippet() should ony highlight the "a" term, not the "b"
147130:         ** (as "b" is part of a non-matching NEAR clause).
147131:         */
147132:         if( bHit==0 
147133:          && pExpr->eType==FTSQUERY_NEAR 
147134:          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
147135:         ){
147136:           Fts3Expr *p;
147137:           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
147138:             if( p->pRight->iDocid==pCsr->iPrevId ){
147139:               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
147140:             }
147141:           }
147142:           if( p->iDocid==pCsr->iPrevId ){
147143:             fts3EvalInvalidatePoslist(p->pPhrase);
147144:           }
147145:         }
147146: 
147147:         break;
147148: 
147149:       case FTSQUERY_OR: {
147150:         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
147151:         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
147152:         bHit = bHit1 || bHit2;
147153:         break;
147154:       }
147155: 
147156:       case FTSQUERY_NOT:
147157:         bHit = (
147158:             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
147159:          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
147160:         );
147161:         break;
147162: 
147163:       default: {
147164: #ifndef SQLITE_DISABLE_FTS4_DEFERRED
147165:         if( pCsr->pDeferred 
147166:          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
147167:         ){
147168:           Fts3Phrase *pPhrase = pExpr->pPhrase;
147169:           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
147170:           if( pExpr->bDeferred ){
147171:             fts3EvalInvalidatePoslist(pPhrase);
147172:           }
147173:           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
147174:           bHit = (pPhrase->doclist.pList!=0);
147175:           pExpr->iDocid = pCsr->iPrevId;
147176:         }else
147177: #endif
147178:         {
147179:           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
147180:         }
147181:         break;
147182:       }
147183:     }
147184:   }
147185:   return bHit;
147186: }
147187: 
147188: /*
147189: ** This function is called as the second part of each xNext operation when
147190: ** iterating through the results of a full-text query. At this point the
147191: ** cursor points to a row that matches the query expression, with the
147192: ** following caveats:
147193: **
147194: **   * Up until this point, "NEAR" operators in the expression have been
147195: **     treated as "AND".
147196: **
147197: **   * Deferred tokens have not yet been considered.
147198: **
147199: ** If *pRc is not SQLITE_OK when this function is called, it immediately
147200: ** returns 0. Otherwise, it tests whether or not after considering NEAR
147201: ** operators and deferred tokens the current row is still a match for the
147202: ** expression. It returns 1 if both of the following are true:
147203: **
147204: **   1. *pRc is SQLITE_OK when this function returns, and
147205: **
147206: **   2. After scanning the current FTS table row for the deferred tokens,
147207: **      it is determined that the row does *not* match the query.
147208: **
147209: ** Or, if no error occurs and it seems the current row does match the FTS
147210: ** query, return 0.
147211: */
147212: SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
147213:   int rc = *pRc;
147214:   int bMiss = 0;
147215:   if( rc==SQLITE_OK ){
147216: 
147217:     /* If there are one or more deferred tokens, load the current row into
147218:     ** memory and scan it to determine the position list for each deferred
147219:     ** token. Then, see if this row is really a match, considering deferred
147220:     ** tokens and NEAR operators (neither of which were taken into account
147221:     ** earlier, by fts3EvalNextRow()). 
147222:     */
147223:     if( pCsr->pDeferred ){
147224:       rc = fts3CursorSeek(0, pCsr);
147225:       if( rc==SQLITE_OK ){
147226:         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
147227:       }
147228:     }
147229:     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
147230: 
147231:     /* Free the position-lists accumulated for each deferred token above. */
147232:     sqlite3Fts3FreeDeferredDoclists(pCsr);
147233:     *pRc = rc;
147234:   }
147235:   return (rc==SQLITE_OK && bMiss);
147236: }
147237: 
147238: /*
147239: ** Advance to the next document that matches the FTS expression in
147240: ** Fts3Cursor.pExpr.
147241: */
147242: static int fts3EvalNext(Fts3Cursor *pCsr){
147243:   int rc = SQLITE_OK;             /* Return Code */
147244:   Fts3Expr *pExpr = pCsr->pExpr;
147245:   assert( pCsr->isEof==0 );
147246:   if( pExpr==0 ){
147247:     pCsr->isEof = 1;
147248:   }else{
147249:     do {
147250:       if( pCsr->isRequireSeek==0 ){
147251:         sqlite3_reset(pCsr->pStmt);
147252:       }
147253:       assert( sqlite3_data_count(pCsr->pStmt)==0 );
147254:       fts3EvalNextRow(pCsr, pExpr, &rc);
147255:       pCsr->isEof = pExpr->bEof;
147256:       pCsr->isRequireSeek = 1;
147257:       pCsr->isMatchinfoNeeded = 1;
147258:       pCsr->iPrevId = pExpr->iDocid;
147259:     }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
147260:   }
147261: 
147262:   /* Check if the cursor is past the end of the docid range specified
147263:   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
147264:   if( rc==SQLITE_OK && (
147265:         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
147266:      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
147267:   )){
147268:     pCsr->isEof = 1;
147269:   }
147270: 
147271:   return rc;
147272: }
147273: 
147274: /*
147275: ** Restart interation for expression pExpr so that the next call to
147276: ** fts3EvalNext() visits the first row. Do not allow incremental 
147277: ** loading or merging of phrase doclists for this iteration.
147278: **
147279: ** If *pRc is other than SQLITE_OK when this function is called, it is
147280: ** a no-op. If an error occurs within this function, *pRc is set to an
147281: ** SQLite error code before returning.
147282: */
147283: static void fts3EvalRestart(
147284:   Fts3Cursor *pCsr,
147285:   Fts3Expr *pExpr,
147286:   int *pRc
147287: ){
147288:   if( pExpr && *pRc==SQLITE_OK ){
147289:     Fts3Phrase *pPhrase = pExpr->pPhrase;
147290: 
147291:     if( pPhrase ){
147292:       fts3EvalInvalidatePoslist(pPhrase);
147293:       if( pPhrase->bIncr ){
147294:         int i;
147295:         for(i=0; i<pPhrase->nToken; i++){
147296:           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
147297:           assert( pToken->pDeferred==0 );
147298:           if( pToken->pSegcsr ){
147299:             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
147300:           }
147301:         }
147302:         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
147303:       }
147304:       pPhrase->doclist.pNextDocid = 0;
147305:       pPhrase->doclist.iDocid = 0;
147306:       pPhrase->pOrPoslist = 0;
147307:     }
147308: 
147309:     pExpr->iDocid = 0;
147310:     pExpr->bEof = 0;
147311:     pExpr->bStart = 0;
147312: 
147313:     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
147314:     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
147315:   }
147316: }
147317: 
147318: /*
147319: ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
147320: ** expression rooted at pExpr, the cursor iterates through all rows matched
147321: ** by pExpr, calling this function for each row. This function increments
147322: ** the values in Fts3Expr.aMI[] according to the position-list currently
147323: ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
147324: ** expression nodes.
147325: */
147326: static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
147327:   if( pExpr ){
147328:     Fts3Phrase *pPhrase = pExpr->pPhrase;
147329:     if( pPhrase && pPhrase->doclist.pList ){
147330:       int iCol = 0;
147331:       char *p = pPhrase->doclist.pList;
147332: 
147333:       assert( *p );
147334:       while( 1 ){
147335:         u8 c = 0;
147336:         int iCnt = 0;
147337:         while( 0xFE & (*p | c) ){
147338:           if( (c&0x80)==0 ) iCnt++;
147339:           c = *p++ & 0x80;
147340:         }
147341: 
147342:         /* aMI[iCol*3 + 1] = Number of occurrences
147343:         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
147344:         */
147345:         pExpr->aMI[iCol*3 + 1] += iCnt;
147346:         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
147347:         if( *p==0x00 ) break;
147348:         p++;
147349:         p += fts3GetVarint32(p, &iCol);
147350:       }
147351:     }
147352: 
147353:     fts3EvalUpdateCounts(pExpr->pLeft);
147354:     fts3EvalUpdateCounts(pExpr->pRight);
147355:   }
147356: }
147357: 
147358: /*
147359: ** Expression pExpr must be of type FTSQUERY_PHRASE.
147360: **
147361: ** If it is not already allocated and populated, this function allocates and
147362: ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
147363: ** of a NEAR expression, then it also allocates and populates the same array
147364: ** for all other phrases that are part of the NEAR expression.
147365: **
147366: ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
147367: ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
147368: */
147369: static int fts3EvalGatherStats(
147370:   Fts3Cursor *pCsr,               /* Cursor object */
147371:   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
147372: ){
147373:   int rc = SQLITE_OK;             /* Return code */
147374: 
147375:   assert( pExpr->eType==FTSQUERY_PHRASE );
147376:   if( pExpr->aMI==0 ){
147377:     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147378:     Fts3Expr *pRoot;                /* Root of NEAR expression */
147379:     Fts3Expr *p;                    /* Iterator used for several purposes */
147380: 
147381:     sqlite3_int64 iPrevId = pCsr->iPrevId;
147382:     sqlite3_int64 iDocid;
147383:     u8 bEof;
147384: 
147385:     /* Find the root of the NEAR expression */
147386:     pRoot = pExpr;
147387:     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
147388:       pRoot = pRoot->pParent;
147389:     }
147390:     iDocid = pRoot->iDocid;
147391:     bEof = pRoot->bEof;
147392:     assert( pRoot->bStart );
147393: 
147394:     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
147395:     for(p=pRoot; p; p=p->pLeft){
147396:       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
147397:       assert( pE->aMI==0 );
147398:       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
147399:       if( !pE->aMI ) return SQLITE_NOMEM;
147400:       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
147401:     }
147402: 
147403:     fts3EvalRestart(pCsr, pRoot, &rc);
147404: 
147405:     while( pCsr->isEof==0 && rc==SQLITE_OK ){
147406: 
147407:       do {
147408:         /* Ensure the %_content statement is reset. */
147409:         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
147410:         assert( sqlite3_data_count(pCsr->pStmt)==0 );
147411: 
147412:         /* Advance to the next document */
147413:         fts3EvalNextRow(pCsr, pRoot, &rc);
147414:         pCsr->isEof = pRoot->bEof;
147415:         pCsr->isRequireSeek = 1;
147416:         pCsr->isMatchinfoNeeded = 1;
147417:         pCsr->iPrevId = pRoot->iDocid;
147418:       }while( pCsr->isEof==0 
147419:            && pRoot->eType==FTSQUERY_NEAR 
147420:            && sqlite3Fts3EvalTestDeferred(pCsr, &rc) 
147421:       );
147422: 
147423:       if( rc==SQLITE_OK && pCsr->isEof==0 ){
147424:         fts3EvalUpdateCounts(pRoot);
147425:       }
147426:     }
147427: 
147428:     pCsr->isEof = 0;
147429:     pCsr->iPrevId = iPrevId;
147430: 
147431:     if( bEof ){
147432:       pRoot->bEof = bEof;
147433:     }else{
147434:       /* Caution: pRoot may iterate through docids in ascending or descending
147435:       ** order. For this reason, even though it seems more defensive, the 
147436:       ** do loop can not be written:
147437:       **
147438:       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
147439:       */
147440:       fts3EvalRestart(pCsr, pRoot, &rc);
147441:       do {
147442:         fts3EvalNextRow(pCsr, pRoot, &rc);
147443:         assert( pRoot->bEof==0 );
147444:       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
147445:     }
147446:   }
147447:   return rc;
147448: }
147449: 
147450: /*
147451: ** This function is used by the matchinfo() module to query a phrase 
147452: ** expression node for the following information:
147453: **
147454: **   1. The total number of occurrences of the phrase in each column of 
147455: **      the FTS table (considering all rows), and
147456: **
147457: **   2. For each column, the number of rows in the table for which the
147458: **      column contains at least one instance of the phrase.
147459: **
147460: ** If no error occurs, SQLITE_OK is returned and the values for each column
147461: ** written into the array aiOut as follows:
147462: **
147463: **   aiOut[iCol*3 + 1] = Number of occurrences
147464: **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
147465: **
147466: ** Caveats:
147467: **
147468: **   * If a phrase consists entirely of deferred tokens, then all output 
147469: **     values are set to the number of documents in the table. In other
147470: **     words we assume that very common tokens occur exactly once in each 
147471: **     column of each row of the table.
147472: **
147473: **   * If a phrase contains some deferred tokens (and some non-deferred 
147474: **     tokens), count the potential occurrence identified by considering
147475: **     the non-deferred tokens instead of actual phrase occurrences.
147476: **
147477: **   * If the phrase is part of a NEAR expression, then only phrase instances
147478: **     that meet the NEAR constraint are included in the counts.
147479: */
147480: SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
147481:   Fts3Cursor *pCsr,               /* FTS cursor handle */
147482:   Fts3Expr *pExpr,                /* Phrase expression */
147483:   u32 *aiOut                      /* Array to write results into (see above) */
147484: ){
147485:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147486:   int rc = SQLITE_OK;
147487:   int iCol;
147488: 
147489:   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
147490:     assert( pCsr->nDoc>0 );
147491:     for(iCol=0; iCol<pTab->nColumn; iCol++){
147492:       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
147493:       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
147494:     }
147495:   }else{
147496:     rc = fts3EvalGatherStats(pCsr, pExpr);
147497:     if( rc==SQLITE_OK ){
147498:       assert( pExpr->aMI );
147499:       for(iCol=0; iCol<pTab->nColumn; iCol++){
147500:         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
147501:         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
147502:       }
147503:     }
147504:   }
147505: 
147506:   return rc;
147507: }
147508: 
147509: /*
147510: ** The expression pExpr passed as the second argument to this function
147511: ** must be of type FTSQUERY_PHRASE. 
147512: **
147513: ** The returned value is either NULL or a pointer to a buffer containing
147514: ** a position-list indicating the occurrences of the phrase in column iCol
147515: ** of the current row. 
147516: **
147517: ** More specifically, the returned buffer contains 1 varint for each 
147518: ** occurrence of the phrase in the column, stored using the normal (delta+2) 
147519: ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
147520: ** if the requested column contains "a b X c d X X" and the position-list
147521: ** for 'X' is requested, the buffer returned may contain:
147522: **
147523: **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
147524: **
147525: ** This function works regardless of whether or not the phrase is deferred,
147526: ** incremental, or neither.
147527: */
147528: SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
147529:   Fts3Cursor *pCsr,               /* FTS3 cursor object */
147530:   Fts3Expr *pExpr,                /* Phrase to return doclist for */
147531:   int iCol,                       /* Column to return position list for */
147532:   char **ppOut                    /* OUT: Pointer to position list */
147533: ){
147534:   Fts3Phrase *pPhrase = pExpr->pPhrase;
147535:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
147536:   char *pIter;
147537:   int iThis;
147538:   sqlite3_int64 iDocid;
147539: 
147540:   /* If this phrase is applies specifically to some column other than 
147541:   ** column iCol, return a NULL pointer.  */
147542:   *ppOut = 0;
147543:   assert( iCol>=0 && iCol<pTab->nColumn );
147544:   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
147545:     return SQLITE_OK;
147546:   }
147547: 
147548:   iDocid = pExpr->iDocid;
147549:   pIter = pPhrase->doclist.pList;
147550:   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
147551:     int rc = SQLITE_OK;
147552:     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
147553:     int bOr = 0;
147554:     u8 bTreeEof = 0;
147555:     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
147556:     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
147557:     int bMatch;
147558: 
147559:     /* Check if this phrase descends from an OR expression node. If not, 
147560:     ** return NULL. Otherwise, the entry that corresponds to docid 
147561:     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
147562:     ** tree that the node is part of has been marked as EOF, but the node
147563:     ** itself is not EOF, then it may point to an earlier entry. */
147564:     pNear = pExpr;
147565:     for(p=pExpr->pParent; p; p=p->pParent){
147566:       if( p->eType==FTSQUERY_OR ) bOr = 1;
147567:       if( p->eType==FTSQUERY_NEAR ) pNear = p;
147568:       if( p->bEof ) bTreeEof = 1;
147569:     }
147570:     if( bOr==0 ) return SQLITE_OK;
147571: 
147572:     /* This is the descendent of an OR node. In this case we cannot use
147573:     ** an incremental phrase. Load the entire doclist for the phrase
147574:     ** into memory in this case.  */
147575:     if( pPhrase->bIncr ){
147576:       int bEofSave = pNear->bEof;
147577:       fts3EvalRestart(pCsr, pNear, &rc);
147578:       while( rc==SQLITE_OK && !pNear->bEof ){
147579:         fts3EvalNextRow(pCsr, pNear, &rc);
147580:         if( bEofSave==0 && pNear->iDocid==iDocid ) break;
147581:       }
147582:       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
147583:     }
147584:     if( bTreeEof ){
147585:       while( rc==SQLITE_OK && !pNear->bEof ){
147586:         fts3EvalNextRow(pCsr, pNear, &rc);
147587:       }
147588:     }
147589:     if( rc!=SQLITE_OK ) return rc;
147590: 
147591:     bMatch = 1;
147592:     for(p=pNear; p; p=p->pLeft){
147593:       u8 bEof = 0;
147594:       Fts3Expr *pTest = p;
147595:       Fts3Phrase *pPh;
147596:       assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
147597:       if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
147598:       assert( pTest->eType==FTSQUERY_PHRASE );
147599:       pPh = pTest->pPhrase;
147600: 
147601:       pIter = pPh->pOrPoslist;
147602:       iDocid = pPh->iOrDocid;
147603:       if( pCsr->bDesc==bDescDoclist ){
147604:         bEof = !pPh->doclist.nAll ||
147605:           (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
147606:         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
147607:           sqlite3Fts3DoclistNext(
147608:               bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
147609:               &pIter, &iDocid, &bEof
147610:           );
147611:         }
147612:       }else{
147613:         bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
147614:         while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
147615:           int dummy;
147616:           sqlite3Fts3DoclistPrev(
147617:               bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll, 
147618:               &pIter, &iDocid, &dummy, &bEof
147619:               );
147620:         }
147621:       }
147622:       pPh->pOrPoslist = pIter;
147623:       pPh->iOrDocid = iDocid;
147624:       if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
147625:     }
147626: 
147627:     if( bMatch ){
147628:       pIter = pPhrase->pOrPoslist;
147629:     }else{
147630:       pIter = 0;
147631:     }
147632:   }
147633:   if( pIter==0 ) return SQLITE_OK;
147634: 
147635:   if( *pIter==0x01 ){
147636:     pIter++;
147637:     pIter += fts3GetVarint32(pIter, &iThis);
147638:   }else{
147639:     iThis = 0;
147640:   }
147641:   while( iThis<iCol ){
147642:     fts3ColumnlistCopy(0, &pIter);
147643:     if( *pIter==0x00 ) return SQLITE_OK;
147644:     pIter++;
147645:     pIter += fts3GetVarint32(pIter, &iThis);
147646:   }
147647:   if( *pIter==0x00 ){
147648:     pIter = 0;
147649:   }
147650: 
147651:   *ppOut = ((iCol==iThis)?pIter:0);
147652:   return SQLITE_OK;
147653: }
147654: 
147655: /*
147656: ** Free all components of the Fts3Phrase structure that were allocated by
147657: ** the eval module. Specifically, this means to free:
147658: **
147659: **   * the contents of pPhrase->doclist, and
147660: **   * any Fts3MultiSegReader objects held by phrase tokens.
147661: */
147662: SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
147663:   if( pPhrase ){
147664:     int i;
147665:     sqlite3_free(pPhrase->doclist.aAll);
147666:     fts3EvalInvalidatePoslist(pPhrase);
147667:     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
147668:     for(i=0; i<pPhrase->nToken; i++){
147669:       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
147670:       pPhrase->aToken[i].pSegcsr = 0;
147671:     }
147672:   }
147673: }
147674: 
147675: 
147676: /*
147677: ** Return SQLITE_CORRUPT_VTAB.
147678: */
147679: #ifdef SQLITE_DEBUG
147680: SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
147681:   return SQLITE_CORRUPT_VTAB;
147682: }
147683: #endif
147684: 
147685: #if !SQLITE_CORE
147686: /*
147687: ** Initialize API pointer table, if required.
147688: */
147689: #ifdef _WIN32
147690: __declspec(dllexport)
147691: #endif
147692: SQLITE_API int sqlite3_fts3_init(
147693:   sqlite3 *db, 
147694:   char **pzErrMsg,
147695:   const sqlite3_api_routines *pApi
147696: ){
147697:   SQLITE_EXTENSION_INIT2(pApi)
147698:   return sqlite3Fts3Init(db);
147699: }
147700: #endif
147701: 
147702: #endif
147703: 
147704: /************** End of fts3.c ************************************************/
147705: /************** Begin file fts3_aux.c ****************************************/
147706: /*
147707: ** 2011 Jan 27
147708: **
147709: ** The author disclaims copyright to this source code.  In place of
147710: ** a legal notice, here is a blessing:
147711: **
147712: **    May you do good and not evil.
147713: **    May you find forgiveness for yourself and forgive others.
147714: **    May you share freely, never taking more than you give.
147715: **
147716: ******************************************************************************
147717: **
147718: */
147719: /* #include "fts3Int.h" */
147720: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147721: 
147722: /* #include <string.h> */
147723: /* #include <assert.h> */
147724: 
147725: typedef struct Fts3auxTable Fts3auxTable;
147726: typedef struct Fts3auxCursor Fts3auxCursor;
147727: 
147728: struct Fts3auxTable {
147729:   sqlite3_vtab base;              /* Base class used by SQLite core */
147730:   Fts3Table *pFts3Tab;
147731: };
147732: 
147733: struct Fts3auxCursor {
147734:   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
147735:   Fts3MultiSegReader csr;        /* Must be right after "base" */
147736:   Fts3SegFilter filter;
147737:   char *zStop;
147738:   int nStop;                      /* Byte-length of string zStop */
147739:   int iLangid;                    /* Language id to query */
147740:   int isEof;                      /* True if cursor is at EOF */
147741:   sqlite3_int64 iRowid;           /* Current rowid */
147742: 
147743:   int iCol;                       /* Current value of 'col' column */
147744:   int nStat;                      /* Size of aStat[] array */
147745:   struct Fts3auxColstats {
147746:     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
147747:     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
147748:   } *aStat;
147749: };
147750: 
147751: /*
147752: ** Schema of the terms table.
147753: */
147754: #define FTS3_AUX_SCHEMA \
147755:   "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
147756: 
147757: /*
147758: ** This function does all the work for both the xConnect and xCreate methods.
147759: ** These tables have no persistent representation of their own, so xConnect
147760: ** and xCreate are identical operations.
147761: */
147762: static int fts3auxConnectMethod(
147763:   sqlite3 *db,                    /* Database connection */
147764:   void *pUnused,                  /* Unused */
147765:   int argc,                       /* Number of elements in argv array */
147766:   const char * const *argv,       /* xCreate/xConnect argument array */
147767:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
147768:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
147769: ){
147770:   char const *zDb;                /* Name of database (e.g. "main") */
147771:   char const *zFts3;              /* Name of fts3 table */
147772:   int nDb;                        /* Result of strlen(zDb) */
147773:   int nFts3;                      /* Result of strlen(zFts3) */
147774:   int nByte;                      /* Bytes of space to allocate here */
147775:   int rc;                         /* value returned by declare_vtab() */
147776:   Fts3auxTable *p;                /* Virtual table object to return */
147777: 
147778:   UNUSED_PARAMETER(pUnused);
147779: 
147780:   /* The user should invoke this in one of two forms:
147781:   **
147782:   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
147783:   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
147784:   */
147785:   if( argc!=4 && argc!=5 ) goto bad_args;
147786: 
147787:   zDb = argv[1]; 
147788:   nDb = (int)strlen(zDb);
147789:   if( argc==5 ){
147790:     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
147791:       zDb = argv[3]; 
147792:       nDb = (int)strlen(zDb);
147793:       zFts3 = argv[4];
147794:     }else{
147795:       goto bad_args;
147796:     }
147797:   }else{
147798:     zFts3 = argv[3];
147799:   }
147800:   nFts3 = (int)strlen(zFts3);
147801: 
147802:   rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
147803:   if( rc!=SQLITE_OK ) return rc;
147804: 
147805:   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
147806:   p = (Fts3auxTable *)sqlite3_malloc(nByte);
147807:   if( !p ) return SQLITE_NOMEM;
147808:   memset(p, 0, nByte);
147809: 
147810:   p->pFts3Tab = (Fts3Table *)&p[1];
147811:   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
147812:   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
147813:   p->pFts3Tab->db = db;
147814:   p->pFts3Tab->nIndex = 1;
147815: 
147816:   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
147817:   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
147818:   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
147819: 
147820:   *ppVtab = (sqlite3_vtab *)p;
147821:   return SQLITE_OK;
147822: 
147823:  bad_args:
147824:   sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
147825:   return SQLITE_ERROR;
147826: }
147827: 
147828: /*
147829: ** This function does the work for both the xDisconnect and xDestroy methods.
147830: ** These tables have no persistent representation of their own, so xDisconnect
147831: ** and xDestroy are identical operations.
147832: */
147833: static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
147834:   Fts3auxTable *p = (Fts3auxTable *)pVtab;
147835:   Fts3Table *pFts3 = p->pFts3Tab;
147836:   int i;
147837: 
147838:   /* Free any prepared statements held */
147839:   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
147840:     sqlite3_finalize(pFts3->aStmt[i]);
147841:   }
147842:   sqlite3_free(pFts3->zSegmentsTbl);
147843:   sqlite3_free(p);
147844:   return SQLITE_OK;
147845: }
147846: 
147847: #define FTS4AUX_EQ_CONSTRAINT 1
147848: #define FTS4AUX_GE_CONSTRAINT 2
147849: #define FTS4AUX_LE_CONSTRAINT 4
147850: 
147851: /*
147852: ** xBestIndex - Analyze a WHERE and ORDER BY clause.
147853: */
147854: static int fts3auxBestIndexMethod(
147855:   sqlite3_vtab *pVTab, 
147856:   sqlite3_index_info *pInfo
147857: ){
147858:   int i;
147859:   int iEq = -1;
147860:   int iGe = -1;
147861:   int iLe = -1;
147862:   int iLangid = -1;
147863:   int iNext = 1;                  /* Next free argvIndex value */
147864: 
147865:   UNUSED_PARAMETER(pVTab);
147866: 
147867:   /* This vtab delivers always results in "ORDER BY term ASC" order. */
147868:   if( pInfo->nOrderBy==1 
147869:    && pInfo->aOrderBy[0].iColumn==0 
147870:    && pInfo->aOrderBy[0].desc==0
147871:   ){
147872:     pInfo->orderByConsumed = 1;
147873:   }
147874: 
147875:   /* Search for equality and range constraints on the "term" column. 
147876:   ** And equality constraints on the hidden "languageid" column. */
147877:   for(i=0; i<pInfo->nConstraint; i++){
147878:     if( pInfo->aConstraint[i].usable ){
147879:       int op = pInfo->aConstraint[i].op;
147880:       int iCol = pInfo->aConstraint[i].iColumn;
147881: 
147882:       if( iCol==0 ){
147883:         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
147884:         if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
147885:         if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
147886:         if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
147887:         if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
147888:       }
147889:       if( iCol==4 ){
147890:         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
147891:       }
147892:     }
147893:   }
147894: 
147895:   if( iEq>=0 ){
147896:     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
147897:     pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
147898:     pInfo->estimatedCost = 5;
147899:   }else{
147900:     pInfo->idxNum = 0;
147901:     pInfo->estimatedCost = 20000;
147902:     if( iGe>=0 ){
147903:       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
147904:       pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
147905:       pInfo->estimatedCost /= 2;
147906:     }
147907:     if( iLe>=0 ){
147908:       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
147909:       pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
147910:       pInfo->estimatedCost /= 2;
147911:     }
147912:   }
147913:   if( iLangid>=0 ){
147914:     pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
147915:     pInfo->estimatedCost--;
147916:   }
147917: 
147918:   return SQLITE_OK;
147919: }
147920: 
147921: /*
147922: ** xOpen - Open a cursor.
147923: */
147924: static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
147925:   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
147926: 
147927:   UNUSED_PARAMETER(pVTab);
147928: 
147929:   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
147930:   if( !pCsr ) return SQLITE_NOMEM;
147931:   memset(pCsr, 0, sizeof(Fts3auxCursor));
147932: 
147933:   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
147934:   return SQLITE_OK;
147935: }
147936: 
147937: /*
147938: ** xClose - Close a cursor.
147939: */
147940: static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
147941:   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147942:   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147943: 
147944:   sqlite3Fts3SegmentsClose(pFts3);
147945:   sqlite3Fts3SegReaderFinish(&pCsr->csr);
147946:   sqlite3_free((void *)pCsr->filter.zTerm);
147947:   sqlite3_free(pCsr->zStop);
147948:   sqlite3_free(pCsr->aStat);
147949:   sqlite3_free(pCsr);
147950:   return SQLITE_OK;
147951: }
147952: 
147953: static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
147954:   if( nSize>pCsr->nStat ){
147955:     struct Fts3auxColstats *aNew;
147956:     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
147957:         sizeof(struct Fts3auxColstats) * nSize
147958:     );
147959:     if( aNew==0 ) return SQLITE_NOMEM;
147960:     memset(&aNew[pCsr->nStat], 0, 
147961:         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
147962:     );
147963:     pCsr->aStat = aNew;
147964:     pCsr->nStat = nSize;
147965:   }
147966:   return SQLITE_OK;
147967: }
147968: 
147969: /*
147970: ** xNext - Advance the cursor to the next row, if any.
147971: */
147972: static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
147973:   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147974:   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147975:   int rc;
147976: 
147977:   /* Increment our pretend rowid value. */
147978:   pCsr->iRowid++;
147979: 
147980:   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
147981:     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
147982:   }
147983: 
147984:   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
147985:   if( rc==SQLITE_ROW ){
147986:     int i = 0;
147987:     int nDoclist = pCsr->csr.nDoclist;
147988:     char *aDoclist = pCsr->csr.aDoclist;
147989:     int iCol;
147990: 
147991:     int eState = 0;
147992: 
147993:     if( pCsr->zStop ){
147994:       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
147995:       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
147996:       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
147997:         pCsr->isEof = 1;
147998:         return SQLITE_OK;
147999:       }
148000:     }
148001: 
148002:     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
148003:     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
148004:     iCol = 0;
148005: 
148006:     while( i<nDoclist ){
148007:       sqlite3_int64 v = 0;
148008: 
148009:       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
148010:       switch( eState ){
148011:         /* State 0. In this state the integer just read was a docid. */
148012:         case 0:
148013:           pCsr->aStat[0].nDoc++;
148014:           eState = 1;
148015:           iCol = 0;
148016:           break;
148017: 
148018:         /* State 1. In this state we are expecting either a 1, indicating
148019:         ** that the following integer will be a column number, or the
148020:         ** start of a position list for column 0.  
148021:         ** 
148022:         ** The only difference between state 1 and state 2 is that if the
148023:         ** integer encountered in state 1 is not 0 or 1, then we need to
148024:         ** increment the column 0 "nDoc" count for this term.
148025:         */
148026:         case 1:
148027:           assert( iCol==0 );
148028:           if( v>1 ){
148029:             pCsr->aStat[1].nDoc++;
148030:           }
148031:           eState = 2;
148032:           /* fall through */
148033: 
148034:         case 2:
148035:           if( v==0 ){       /* 0x00. Next integer will be a docid. */
148036:             eState = 0;
148037:           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
148038:             eState = 3;
148039:           }else{            /* 2 or greater. A position. */
148040:             pCsr->aStat[iCol+1].nOcc++;
148041:             pCsr->aStat[0].nOcc++;
148042:           }
148043:           break;
148044: 
148045:         /* State 3. The integer just read is a column number. */
148046:         default: assert( eState==3 );
148047:           iCol = (int)v;
148048:           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
148049:           pCsr->aStat[iCol+1].nDoc++;
148050:           eState = 2;
148051:           break;
148052:       }
148053:     }
148054: 
148055:     pCsr->iCol = 0;
148056:     rc = SQLITE_OK;
148057:   }else{
148058:     pCsr->isEof = 1;
148059:   }
148060:   return rc;
148061: }
148062: 
148063: /*
148064: ** xFilter - Initialize a cursor to point at the start of its data.
148065: */
148066: static int fts3auxFilterMethod(
148067:   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
148068:   int idxNum,                     /* Strategy index */
148069:   const char *idxStr,             /* Unused */
148070:   int nVal,                       /* Number of elements in apVal */
148071:   sqlite3_value **apVal           /* Arguments for the indexing scheme */
148072: ){
148073:   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148074:   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
148075:   int rc;
148076:   int isScan = 0;
148077:   int iLangVal = 0;               /* Language id to query */
148078: 
148079:   int iEq = -1;                   /* Index of term=? value in apVal */
148080:   int iGe = -1;                   /* Index of term>=? value in apVal */
148081:   int iLe = -1;                   /* Index of term<=? value in apVal */
148082:   int iLangid = -1;               /* Index of languageid=? value in apVal */
148083:   int iNext = 0;
148084: 
148085:   UNUSED_PARAMETER(nVal);
148086:   UNUSED_PARAMETER(idxStr);
148087: 
148088:   assert( idxStr==0 );
148089:   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
148090:        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
148091:        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
148092:   );
148093: 
148094:   if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
148095:     iEq = iNext++;
148096:   }else{
148097:     isScan = 1;
148098:     if( idxNum & FTS4AUX_GE_CONSTRAINT ){
148099:       iGe = iNext++;
148100:     }
148101:     if( idxNum & FTS4AUX_LE_CONSTRAINT ){
148102:       iLe = iNext++;
148103:     }
148104:   }
148105:   if( iNext<nVal ){
148106:     iLangid = iNext++;
148107:   }
148108: 
148109:   /* In case this cursor is being reused, close and zero it. */
148110:   testcase(pCsr->filter.zTerm);
148111:   sqlite3Fts3SegReaderFinish(&pCsr->csr);
148112:   sqlite3_free((void *)pCsr->filter.zTerm);
148113:   sqlite3_free(pCsr->aStat);
148114:   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
148115: 
148116:   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
148117:   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
148118: 
148119:   if( iEq>=0 || iGe>=0 ){
148120:     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
148121:     assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
148122:     if( zStr ){
148123:       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
148124:       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
148125:       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
148126:     }
148127:   }
148128: 
148129:   if( iLe>=0 ){
148130:     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
148131:     pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
148132:     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
148133:   }
148134:   
148135:   if( iLangid>=0 ){
148136:     iLangVal = sqlite3_value_int(apVal[iLangid]);
148137: 
148138:     /* If the user specified a negative value for the languageid, use zero
148139:     ** instead. This works, as the "languageid=?" constraint will also
148140:     ** be tested by the VDBE layer. The test will always be false (since
148141:     ** this module will not return a row with a negative languageid), and
148142:     ** so the overall query will return zero rows.  */
148143:     if( iLangVal<0 ) iLangVal = 0;
148144:   }
148145:   pCsr->iLangid = iLangVal;
148146: 
148147:   rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
148148:       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
148149:   );
148150:   if( rc==SQLITE_OK ){
148151:     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
148152:   }
148153: 
148154:   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
148155:   return rc;
148156: }
148157: 
148158: /*
148159: ** xEof - Return true if the cursor is at EOF, or false otherwise.
148160: */
148161: static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
148162:   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148163:   return pCsr->isEof;
148164: }
148165: 
148166: /*
148167: ** xColumn - Return a column value.
148168: */
148169: static int fts3auxColumnMethod(
148170:   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
148171:   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
148172:   int iCol                        /* Index of column to read value from */
148173: ){
148174:   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
148175: 
148176:   assert( p->isEof==0 );
148177:   switch( iCol ){
148178:     case 0: /* term */
148179:       sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
148180:       break;
148181: 
148182:     case 1: /* col */
148183:       if( p->iCol ){
148184:         sqlite3_result_int(pCtx, p->iCol-1);
148185:       }else{
148186:         sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
148187:       }
148188:       break;
148189: 
148190:     case 2: /* documents */
148191:       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
148192:       break;
148193: 
148194:     case 3: /* occurrences */
148195:       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
148196:       break;
148197: 
148198:     default: /* languageid */
148199:       assert( iCol==4 );
148200:       sqlite3_result_int(pCtx, p->iLangid);
148201:       break;
148202:   }
148203: 
148204:   return SQLITE_OK;
148205: }
148206: 
148207: /*
148208: ** xRowid - Return the current rowid for the cursor.
148209: */
148210: static int fts3auxRowidMethod(
148211:   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
148212:   sqlite_int64 *pRowid            /* OUT: Rowid value */
148213: ){
148214:   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
148215:   *pRowid = pCsr->iRowid;
148216:   return SQLITE_OK;
148217: }
148218: 
148219: /*
148220: ** Register the fts3aux module with database connection db. Return SQLITE_OK
148221: ** if successful or an error code if sqlite3_create_module() fails.
148222: */
148223: SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
148224:   static const sqlite3_module fts3aux_module = {
148225:      0,                           /* iVersion      */
148226:      fts3auxConnectMethod,        /* xCreate       */
148227:      fts3auxConnectMethod,        /* xConnect      */
148228:      fts3auxBestIndexMethod,      /* xBestIndex    */
148229:      fts3auxDisconnectMethod,     /* xDisconnect   */
148230:      fts3auxDisconnectMethod,     /* xDestroy      */
148231:      fts3auxOpenMethod,           /* xOpen         */
148232:      fts3auxCloseMethod,          /* xClose        */
148233:      fts3auxFilterMethod,         /* xFilter       */
148234:      fts3auxNextMethod,           /* xNext         */
148235:      fts3auxEofMethod,            /* xEof          */
148236:      fts3auxColumnMethod,         /* xColumn       */
148237:      fts3auxRowidMethod,          /* xRowid        */
148238:      0,                           /* xUpdate       */
148239:      0,                           /* xBegin        */
148240:      0,                           /* xSync         */
148241:      0,                           /* xCommit       */
148242:      0,                           /* xRollback     */
148243:      0,                           /* xFindFunction */
148244:      0,                           /* xRename       */
148245:      0,                           /* xSavepoint    */
148246:      0,                           /* xRelease      */
148247:      0                            /* xRollbackTo   */
148248:   };
148249:   int rc;                         /* Return code */
148250: 
148251:   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
148252:   return rc;
148253: }
148254: 
148255: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
148256: 
148257: /************** End of fts3_aux.c ********************************************/
148258: /************** Begin file fts3_expr.c ***************************************/
148259: /*
148260: ** 2008 Nov 28
148261: **
148262: ** The author disclaims copyright to this source code.  In place of
148263: ** a legal notice, here is a blessing:
148264: **
148265: **    May you do good and not evil.
148266: **    May you find forgiveness for yourself and forgive others.
148267: **    May you share freely, never taking more than you give.
148268: **
148269: ******************************************************************************
148270: **
148271: ** This module contains code that implements a parser for fts3 query strings
148272: ** (the right-hand argument to the MATCH operator). Because the supported 
148273: ** syntax is relatively simple, the whole tokenizer/parser system is
148274: ** hand-coded. 
148275: */
148276: /* #include "fts3Int.h" */
148277: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
148278: 
148279: /*
148280: ** By default, this module parses the legacy syntax that has been 
148281: ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
148282: ** is defined, then it uses the new syntax. The differences between
148283: ** the new and the old syntaxes are:
148284: **
148285: **  a) The new syntax supports parenthesis. The old does not.
148286: **
148287: **  b) The new syntax supports the AND and NOT operators. The old does not.
148288: **
148289: **  c) The old syntax supports the "-" token qualifier. This is not 
148290: **     supported by the new syntax (it is replaced by the NOT operator).
148291: **
148292: **  d) When using the old syntax, the OR operator has a greater precedence
148293: **     than an implicit AND. When using the new, both implicity and explicit
148294: **     AND operators have a higher precedence than OR.
148295: **
148296: ** If compiled with SQLITE_TEST defined, then this module exports the
148297: ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
148298: ** to zero causes the module to use the old syntax. If it is set to 
148299: ** non-zero the new syntax is activated. This is so both syntaxes can
148300: ** be tested using a single build of testfixture.
148301: **
148302: ** The following describes the syntax supported by the fts3 MATCH
148303: ** operator in a similar format to that used by the lemon parser
148304: ** generator. This module does not use actually lemon, it uses a
148305: ** custom parser.
148306: **
148307: **   query ::= andexpr (OR andexpr)*.
148308: **
148309: **   andexpr ::= notexpr (AND? notexpr)*.
148310: **
148311: **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
148312: **   notexpr ::= LP query RP.
148313: **
148314: **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
148315: **
148316: **   distance_opt ::= .
148317: **   distance_opt ::= / INTEGER.
148318: **
148319: **   phrase ::= TOKEN.
148320: **   phrase ::= COLUMN:TOKEN.
148321: **   phrase ::= "TOKEN TOKEN TOKEN...".
148322: */
148323: 
148324: #ifdef SQLITE_TEST
148325: SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
148326: #else
148327: # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
148328: #  define sqlite3_fts3_enable_parentheses 1
148329: # else
148330: #  define sqlite3_fts3_enable_parentheses 0
148331: # endif
148332: #endif
148333: 
148334: /*
148335: ** Default span for NEAR operators.
148336: */
148337: #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
148338: 
148339: /* #include <string.h> */
148340: /* #include <assert.h> */
148341: 
148342: /*
148343: ** isNot:
148344: **   This variable is used by function getNextNode(). When getNextNode() is
148345: **   called, it sets ParseContext.isNot to true if the 'next node' is a 
148346: **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
148347: **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
148348: **   zero.
148349: */
148350: typedef struct ParseContext ParseContext;
148351: struct ParseContext {
148352:   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
148353:   int iLangid;                        /* Language id used with tokenizer */
148354:   const char **azCol;                 /* Array of column names for fts3 table */
148355:   int bFts4;                          /* True to allow FTS4-only syntax */
148356:   int nCol;                           /* Number of entries in azCol[] */
148357:   int iDefaultCol;                    /* Default column to query */
148358:   int isNot;                          /* True if getNextNode() sees a unary - */
148359:   sqlite3_context *pCtx;              /* Write error message here */
148360:   int nNest;                          /* Number of nested brackets */
148361: };
148362: 
148363: /*
148364: ** This function is equivalent to the standard isspace() function. 
148365: **
148366: ** The standard isspace() can be awkward to use safely, because although it
148367: ** is defined to accept an argument of type int, its behavior when passed
148368: ** an integer that falls outside of the range of the unsigned char type
148369: ** is undefined (and sometimes, "undefined" means segfault). This wrapper
148370: ** is defined to accept an argument of type char, and always returns 0 for
148371: ** any values that fall outside of the range of the unsigned char type (i.e.
148372: ** negative values).
148373: */
148374: static int fts3isspace(char c){
148375:   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
148376: }
148377: 
148378: /*
148379: ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
148380: ** zero the memory before returning a pointer to it. If unsuccessful, 
148381: ** return NULL.
148382: */
148383: static void *fts3MallocZero(int nByte){
148384:   void *pRet = sqlite3_malloc(nByte);
148385:   if( pRet ) memset(pRet, 0, nByte);
148386:   return pRet;
148387: }
148388: 
148389: SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
148390:   sqlite3_tokenizer *pTokenizer,
148391:   int iLangid,
148392:   const char *z,
148393:   int n,
148394:   sqlite3_tokenizer_cursor **ppCsr
148395: ){
148396:   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148397:   sqlite3_tokenizer_cursor *pCsr = 0;
148398:   int rc;
148399: 
148400:   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
148401:   assert( rc==SQLITE_OK || pCsr==0 );
148402:   if( rc==SQLITE_OK ){
148403:     pCsr->pTokenizer = pTokenizer;
148404:     if( pModule->iVersion>=1 ){
148405:       rc = pModule->xLanguageid(pCsr, iLangid);
148406:       if( rc!=SQLITE_OK ){
148407:         pModule->xClose(pCsr);
148408:         pCsr = 0;
148409:       }
148410:     }
148411:   }
148412:   *ppCsr = pCsr;
148413:   return rc;
148414: }
148415: 
148416: /*
148417: ** Function getNextNode(), which is called by fts3ExprParse(), may itself
148418: ** call fts3ExprParse(). So this forward declaration is required.
148419: */
148420: static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
148421: 
148422: /*
148423: ** Extract the next token from buffer z (length n) using the tokenizer
148424: ** and other information (column names etc.) in pParse. Create an Fts3Expr
148425: ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
148426: ** single token and set *ppExpr to point to it. If the end of the buffer is
148427: ** reached before a token is found, set *ppExpr to zero. It is the
148428: ** responsibility of the caller to eventually deallocate the allocated 
148429: ** Fts3Expr structure (if any) by passing it to sqlite3_free().
148430: **
148431: ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
148432: ** fails.
148433: */
148434: static int getNextToken(
148435:   ParseContext *pParse,                   /* fts3 query parse context */
148436:   int iCol,                               /* Value for Fts3Phrase.iColumn */
148437:   const char *z, int n,                   /* Input string */
148438:   Fts3Expr **ppExpr,                      /* OUT: expression */
148439:   int *pnConsumed                         /* OUT: Number of bytes consumed */
148440: ){
148441:   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
148442:   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148443:   int rc;
148444:   sqlite3_tokenizer_cursor *pCursor;
148445:   Fts3Expr *pRet = 0;
148446:   int i = 0;
148447: 
148448:   /* Set variable i to the maximum number of bytes of input to tokenize. */
148449:   for(i=0; i<n; i++){
148450:     if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
148451:     if( z[i]=='"' ) break;
148452:   }
148453: 
148454:   *pnConsumed = i;
148455:   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
148456:   if( rc==SQLITE_OK ){
148457:     const char *zToken;
148458:     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
148459:     int nByte;                               /* total space to allocate */
148460: 
148461:     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
148462:     if( rc==SQLITE_OK ){
148463:       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
148464:       pRet = (Fts3Expr *)fts3MallocZero(nByte);
148465:       if( !pRet ){
148466:         rc = SQLITE_NOMEM;
148467:       }else{
148468:         pRet->eType = FTSQUERY_PHRASE;
148469:         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
148470:         pRet->pPhrase->nToken = 1;
148471:         pRet->pPhrase->iColumn = iCol;
148472:         pRet->pPhrase->aToken[0].n = nToken;
148473:         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
148474:         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
148475: 
148476:         if( iEnd<n && z[iEnd]=='*' ){
148477:           pRet->pPhrase->aToken[0].isPrefix = 1;
148478:           iEnd++;
148479:         }
148480: 
148481:         while( 1 ){
148482:           if( !sqlite3_fts3_enable_parentheses 
148483:            && iStart>0 && z[iStart-1]=='-' 
148484:           ){
148485:             pParse->isNot = 1;
148486:             iStart--;
148487:           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
148488:             pRet->pPhrase->aToken[0].bFirst = 1;
148489:             iStart--;
148490:           }else{
148491:             break;
148492:           }
148493:         }
148494: 
148495:       }
148496:       *pnConsumed = iEnd;
148497:     }else if( i && rc==SQLITE_DONE ){
148498:       rc = SQLITE_OK;
148499:     }
148500: 
148501:     pModule->xClose(pCursor);
148502:   }
148503:   
148504:   *ppExpr = pRet;
148505:   return rc;
148506: }
148507: 
148508: 
148509: /*
148510: ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
148511: ** then free the old allocation.
148512: */
148513: static void *fts3ReallocOrFree(void *pOrig, int nNew){
148514:   void *pRet = sqlite3_realloc(pOrig, nNew);
148515:   if( !pRet ){
148516:     sqlite3_free(pOrig);
148517:   }
148518:   return pRet;
148519: }
148520: 
148521: /*
148522: ** Buffer zInput, length nInput, contains the contents of a quoted string
148523: ** that appeared as part of an fts3 query expression. Neither quote character
148524: ** is included in the buffer. This function attempts to tokenize the entire
148525: ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
148526: ** containing the results.
148527: **
148528: ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
148529: ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
148530: ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
148531: ** to 0.
148532: */
148533: static int getNextString(
148534:   ParseContext *pParse,                   /* fts3 query parse context */
148535:   const char *zInput, int nInput,         /* Input string */
148536:   Fts3Expr **ppExpr                       /* OUT: expression */
148537: ){
148538:   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
148539:   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
148540:   int rc;
148541:   Fts3Expr *p = 0;
148542:   sqlite3_tokenizer_cursor *pCursor = 0;
148543:   char *zTemp = 0;
148544:   int nTemp = 0;
148545: 
148546:   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
148547:   int nToken = 0;
148548: 
148549:   /* The final Fts3Expr data structure, including the Fts3Phrase,
148550:   ** Fts3PhraseToken structures token buffers are all stored as a single 
148551:   ** allocation so that the expression can be freed with a single call to
148552:   ** sqlite3_free(). Setting this up requires a two pass approach.
148553:   **
148554:   ** The first pass, in the block below, uses a tokenizer cursor to iterate
148555:   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
148556:   ** to assemble data in two dynamic buffers:
148557:   **
148558:   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
148559:   **             structure, followed by the array of Fts3PhraseToken 
148560:   **             structures. This pass only populates the Fts3PhraseToken array.
148561:   **
148562:   **   Buffer zTemp: Contains copies of all tokens.
148563:   **
148564:   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
148565:   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
148566:   ** structures.
148567:   */
148568:   rc = sqlite3Fts3OpenTokenizer(
148569:       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
148570:   if( rc==SQLITE_OK ){
148571:     int ii;
148572:     for(ii=0; rc==SQLITE_OK; ii++){
148573:       const char *zByte;
148574:       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
148575:       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
148576:       if( rc==SQLITE_OK ){
148577:         Fts3PhraseToken *pToken;
148578: 
148579:         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
148580:         if( !p ) goto no_mem;
148581: 
148582:         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
148583:         if( !zTemp ) goto no_mem;
148584: 
148585:         assert( nToken==ii );
148586:         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
148587:         memset(pToken, 0, sizeof(Fts3PhraseToken));
148588: 
148589:         memcpy(&zTemp[nTemp], zByte, nByte);
148590:         nTemp += nByte;
148591: 
148592:         pToken->n = nByte;
148593:         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
148594:         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
148595:         nToken = ii+1;
148596:       }
148597:     }
148598: 
148599:     pModule->xClose(pCursor);
148600:     pCursor = 0;
148601:   }
148602: 
148603:   if( rc==SQLITE_DONE ){
148604:     int jj;
148605:     char *zBuf = 0;
148606: 
148607:     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
148608:     if( !p ) goto no_mem;
148609:     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
148610:     p->eType = FTSQUERY_PHRASE;
148611:     p->pPhrase = (Fts3Phrase *)&p[1];
148612:     p->pPhrase->iColumn = pParse->iDefaultCol;
148613:     p->pPhrase->nToken = nToken;
148614: 
148615:     zBuf = (char *)&p->pPhrase->aToken[nToken];
148616:     if( zTemp ){
148617:       memcpy(zBuf, zTemp, nTemp);
148618:       sqlite3_free(zTemp);
148619:     }else{
148620:       assert( nTemp==0 );
148621:     }
148622: 
148623:     for(jj=0; jj<p->pPhrase->nToken; jj++){
148624:       p->pPhrase->aToken[jj].z = zBuf;
148625:       zBuf += p->pPhrase->aToken[jj].n;
148626:     }
148627:     rc = SQLITE_OK;
148628:   }
148629: 
148630:   *ppExpr = p;
148631:   return rc;
148632: no_mem:
148633: 
148634:   if( pCursor ){
148635:     pModule->xClose(pCursor);
148636:   }
148637:   sqlite3_free(zTemp);
148638:   sqlite3_free(p);
148639:   *ppExpr = 0;
148640:   return SQLITE_NOMEM;
148641: }
148642: 
148643: /*
148644: ** The output variable *ppExpr is populated with an allocated Fts3Expr 
148645: ** structure, or set to 0 if the end of the input buffer is reached.
148646: **
148647: ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
148648: ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
148649: ** If SQLITE_ERROR is returned, pContext is populated with an error message.
148650: */
148651: static int getNextNode(
148652:   ParseContext *pParse,                   /* fts3 query parse context */
148653:   const char *z, int n,                   /* Input string */
148654:   Fts3Expr **ppExpr,                      /* OUT: expression */
148655:   int *pnConsumed                         /* OUT: Number of bytes consumed */
148656: ){
148657:   static const struct Fts3Keyword {
148658:     char *z;                              /* Keyword text */
148659:     unsigned char n;                      /* Length of the keyword */
148660:     unsigned char parenOnly;              /* Only valid in paren mode */
148661:     unsigned char eType;                  /* Keyword code */
148662:   } aKeyword[] = {
148663:     { "OR" ,  2, 0, FTSQUERY_OR   },
148664:     { "AND",  3, 1, FTSQUERY_AND  },
148665:     { "NOT",  3, 1, FTSQUERY_NOT  },
148666:     { "NEAR", 4, 0, FTSQUERY_NEAR }
148667:   };
148668:   int ii;
148669:   int iCol;
148670:   int iColLen;
148671:   int rc;
148672:   Fts3Expr *pRet = 0;
148673: 
148674:   const char *zInput = z;
148675:   int nInput = n;
148676: 
148677:   pParse->isNot = 0;
148678: 
148679:   /* Skip over any whitespace before checking for a keyword, an open or
148680:   ** close bracket, or a quoted string. 
148681:   */
148682:   while( nInput>0 && fts3isspace(*zInput) ){
148683:     nInput--;
148684:     zInput++;
148685:   }
148686:   if( nInput==0 ){
148687:     return SQLITE_DONE;
148688:   }
148689: 
148690:   /* See if we are dealing with a keyword. */
148691:   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
148692:     const struct Fts3Keyword *pKey = &aKeyword[ii];
148693: 
148694:     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
148695:       continue;
148696:     }
148697: 
148698:     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
148699:       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
148700:       int nKey = pKey->n;
148701:       char cNext;
148702: 
148703:       /* If this is a "NEAR" keyword, check for an explicit nearness. */
148704:       if( pKey->eType==FTSQUERY_NEAR ){
148705:         assert( nKey==4 );
148706:         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
148707:           nNear = 0;
148708:           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
148709:             nNear = nNear * 10 + (zInput[nKey] - '0');
148710:           }
148711:         }
148712:       }
148713: 
148714:       /* At this point this is probably a keyword. But for that to be true,
148715:       ** the next byte must contain either whitespace, an open or close
148716:       ** parenthesis, a quote character, or EOF. 
148717:       */
148718:       cNext = zInput[nKey];
148719:       if( fts3isspace(cNext) 
148720:        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
148721:       ){
148722:         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
148723:         if( !pRet ){
148724:           return SQLITE_NOMEM;
148725:         }
148726:         pRet->eType = pKey->eType;
148727:         pRet->nNear = nNear;
148728:         *ppExpr = pRet;
148729:         *pnConsumed = (int)((zInput - z) + nKey);
148730:         return SQLITE_OK;
148731:       }
148732: 
148733:       /* Turns out that wasn't a keyword after all. This happens if the
148734:       ** user has supplied a token such as "ORacle". Continue.
148735:       */
148736:     }
148737:   }
148738: 
148739:   /* See if we are dealing with a quoted phrase. If this is the case, then
148740:   ** search for the closing quote and pass the whole string to getNextString()
148741:   ** for processing. This is easy to do, as fts3 has no syntax for escaping
148742:   ** a quote character embedded in a string.
148743:   */
148744:   if( *zInput=='"' ){
148745:     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
148746:     *pnConsumed = (int)((zInput - z) + ii + 1);
148747:     if( ii==nInput ){
148748:       return SQLITE_ERROR;
148749:     }
148750:     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
148751:   }
148752: 
148753:   if( sqlite3_fts3_enable_parentheses ){
148754:     if( *zInput=='(' ){
148755:       int nConsumed = 0;
148756:       pParse->nNest++;
148757:       rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
148758:       if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
148759:       *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
148760:       return rc;
148761:     }else if( *zInput==')' ){
148762:       pParse->nNest--;
148763:       *pnConsumed = (int)((zInput - z) + 1);
148764:       *ppExpr = 0;
148765:       return SQLITE_DONE;
148766:     }
148767:   }
148768: 
148769:   /* If control flows to this point, this must be a regular token, or 
148770:   ** the end of the input. Read a regular token using the sqlite3_tokenizer
148771:   ** interface. Before doing so, figure out if there is an explicit
148772:   ** column specifier for the token. 
148773:   **
148774:   ** TODO: Strangely, it is not possible to associate a column specifier
148775:   ** with a quoted phrase, only with a single token. Not sure if this was
148776:   ** an implementation artifact or an intentional decision when fts3 was
148777:   ** first implemented. Whichever it was, this module duplicates the 
148778:   ** limitation.
148779:   */
148780:   iCol = pParse->iDefaultCol;
148781:   iColLen = 0;
148782:   for(ii=0; ii<pParse->nCol; ii++){
148783:     const char *zStr = pParse->azCol[ii];
148784:     int nStr = (int)strlen(zStr);
148785:     if( nInput>nStr && zInput[nStr]==':' 
148786:      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
148787:     ){
148788:       iCol = ii;
148789:       iColLen = (int)((zInput - z) + nStr + 1);
148790:       break;
148791:     }
148792:   }
148793:   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
148794:   *pnConsumed += iColLen;
148795:   return rc;
148796: }
148797: 
148798: /*
148799: ** The argument is an Fts3Expr structure for a binary operator (any type
148800: ** except an FTSQUERY_PHRASE). Return an integer value representing the
148801: ** precedence of the operator. Lower values have a higher precedence (i.e.
148802: ** group more tightly). For example, in the C language, the == operator
148803: ** groups more tightly than ||, and would therefore have a higher precedence.
148804: **
148805: ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
148806: ** is defined), the order of the operators in precedence from highest to
148807: ** lowest is:
148808: **
148809: **   NEAR
148810: **   NOT
148811: **   AND (including implicit ANDs)
148812: **   OR
148813: **
148814: ** Note that when using the old query syntax, the OR operator has a higher
148815: ** precedence than the AND operator.
148816: */
148817: static int opPrecedence(Fts3Expr *p){
148818:   assert( p->eType!=FTSQUERY_PHRASE );
148819:   if( sqlite3_fts3_enable_parentheses ){
148820:     return p->eType;
148821:   }else if( p->eType==FTSQUERY_NEAR ){
148822:     return 1;
148823:   }else if( p->eType==FTSQUERY_OR ){
148824:     return 2;
148825:   }
148826:   assert( p->eType==FTSQUERY_AND );
148827:   return 3;
148828: }
148829: 
148830: /*
148831: ** Argument ppHead contains a pointer to the current head of a query 
148832: ** expression tree being parsed. pPrev is the expression node most recently
148833: ** inserted into the tree. This function adds pNew, which is always a binary
148834: ** operator node, into the expression tree based on the relative precedence
148835: ** of pNew and the existing nodes of the tree. This may result in the head
148836: ** of the tree changing, in which case *ppHead is set to the new root node.
148837: */
148838: static void insertBinaryOperator(
148839:   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
148840:   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
148841:   Fts3Expr *pNew           /* New binary node to insert into expression tree */
148842: ){
148843:   Fts3Expr *pSplit = pPrev;
148844:   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
148845:     pSplit = pSplit->pParent;
148846:   }
148847: 
148848:   if( pSplit->pParent ){
148849:     assert( pSplit->pParent->pRight==pSplit );
148850:     pSplit->pParent->pRight = pNew;
148851:     pNew->pParent = pSplit->pParent;
148852:   }else{
148853:     *ppHead = pNew;
148854:   }
148855:   pNew->pLeft = pSplit;
148856:   pSplit->pParent = pNew;
148857: }
148858: 
148859: /*
148860: ** Parse the fts3 query expression found in buffer z, length n. This function
148861: ** returns either when the end of the buffer is reached or an unmatched 
148862: ** closing bracket - ')' - is encountered.
148863: **
148864: ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
148865: ** parsed form of the expression and *pnConsumed is set to the number of
148866: ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
148867: ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
148868: */
148869: static int fts3ExprParse(
148870:   ParseContext *pParse,                   /* fts3 query parse context */
148871:   const char *z, int n,                   /* Text of MATCH query */
148872:   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
148873:   int *pnConsumed                         /* OUT: Number of bytes consumed */
148874: ){
148875:   Fts3Expr *pRet = 0;
148876:   Fts3Expr *pPrev = 0;
148877:   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
148878:   int nIn = n;
148879:   const char *zIn = z;
148880:   int rc = SQLITE_OK;
148881:   int isRequirePhrase = 1;
148882: 
148883:   while( rc==SQLITE_OK ){
148884:     Fts3Expr *p = 0;
148885:     int nByte = 0;
148886: 
148887:     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
148888:     assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
148889:     if( rc==SQLITE_OK ){
148890:       if( p ){
148891:         int isPhrase;
148892: 
148893:         if( !sqlite3_fts3_enable_parentheses 
148894:             && p->eType==FTSQUERY_PHRASE && pParse->isNot 
148895:         ){
148896:           /* Create an implicit NOT operator. */
148897:           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
148898:           if( !pNot ){
148899:             sqlite3Fts3ExprFree(p);
148900:             rc = SQLITE_NOMEM;
148901:             goto exprparse_out;
148902:           }
148903:           pNot->eType = FTSQUERY_NOT;
148904:           pNot->pRight = p;
148905:           p->pParent = pNot;
148906:           if( pNotBranch ){
148907:             pNot->pLeft = pNotBranch;
148908:             pNotBranch->pParent = pNot;
148909:           }
148910:           pNotBranch = pNot;
148911:           p = pPrev;
148912:         }else{
148913:           int eType = p->eType;
148914:           isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
148915: 
148916:           /* The isRequirePhrase variable is set to true if a phrase or
148917:           ** an expression contained in parenthesis is required. If a
148918:           ** binary operator (AND, OR, NOT or NEAR) is encounted when
148919:           ** isRequirePhrase is set, this is a syntax error.
148920:           */
148921:           if( !isPhrase && isRequirePhrase ){
148922:             sqlite3Fts3ExprFree(p);
148923:             rc = SQLITE_ERROR;
148924:             goto exprparse_out;
148925:           }
148926: 
148927:           if( isPhrase && !isRequirePhrase ){
148928:             /* Insert an implicit AND operator. */
148929:             Fts3Expr *pAnd;
148930:             assert( pRet && pPrev );
148931:             pAnd = fts3MallocZero(sizeof(Fts3Expr));
148932:             if( !pAnd ){
148933:               sqlite3Fts3ExprFree(p);
148934:               rc = SQLITE_NOMEM;
148935:               goto exprparse_out;
148936:             }
148937:             pAnd->eType = FTSQUERY_AND;
148938:             insertBinaryOperator(&pRet, pPrev, pAnd);
148939:             pPrev = pAnd;
148940:           }
148941: 
148942:           /* This test catches attempts to make either operand of a NEAR
148943:            ** operator something other than a phrase. For example, either of
148944:            ** the following:
148945:            **
148946:            **    (bracketed expression) NEAR phrase
148947:            **    phrase NEAR (bracketed expression)
148948:            **
148949:            ** Return an error in either case.
148950:            */
148951:           if( pPrev && (
148952:             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
148953:          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
148954:           )){
148955:             sqlite3Fts3ExprFree(p);
148956:             rc = SQLITE_ERROR;
148957:             goto exprparse_out;
148958:           }
148959: 
148960:           if( isPhrase ){
148961:             if( pRet ){
148962:               assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
148963:               pPrev->pRight = p;
148964:               p->pParent = pPrev;
148965:             }else{
148966:               pRet = p;
148967:             }
148968:           }else{
148969:             insertBinaryOperator(&pRet, pPrev, p);
148970:           }
148971:           isRequirePhrase = !isPhrase;
148972:         }
148973:         pPrev = p;
148974:       }
148975:       assert( nByte>0 );
148976:     }
148977:     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
148978:     nIn -= nByte;
148979:     zIn += nByte;
148980:   }
148981: 
148982:   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
148983:     rc = SQLITE_ERROR;
148984:   }
148985: 
148986:   if( rc==SQLITE_DONE ){
148987:     rc = SQLITE_OK;
148988:     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
148989:       if( !pRet ){
148990:         rc = SQLITE_ERROR;
148991:       }else{
148992:         Fts3Expr *pIter = pNotBranch;
148993:         while( pIter->pLeft ){
148994:           pIter = pIter->pLeft;
148995:         }
148996:         pIter->pLeft = pRet;
148997:         pRet->pParent = pIter;
148998:         pRet = pNotBranch;
148999:       }
149000:     }
149001:   }
149002:   *pnConsumed = n - nIn;
149003: 
149004: exprparse_out:
149005:   if( rc!=SQLITE_OK ){
149006:     sqlite3Fts3ExprFree(pRet);
149007:     sqlite3Fts3ExprFree(pNotBranch);
149008:     pRet = 0;
149009:   }
149010:   *ppExpr = pRet;
149011:   return rc;
149012: }
149013: 
149014: /*
149015: ** Return SQLITE_ERROR if the maximum depth of the expression tree passed 
149016: ** as the only argument is more than nMaxDepth.
149017: */
149018: static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
149019:   int rc = SQLITE_OK;
149020:   if( p ){
149021:     if( nMaxDepth<0 ){ 
149022:       rc = SQLITE_TOOBIG;
149023:     }else{
149024:       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
149025:       if( rc==SQLITE_OK ){
149026:         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
149027:       }
149028:     }
149029:   }
149030:   return rc;
149031: }
149032: 
149033: /*
149034: ** This function attempts to transform the expression tree at (*pp) to
149035: ** an equivalent but more balanced form. The tree is modified in place.
149036: ** If successful, SQLITE_OK is returned and (*pp) set to point to the 
149037: ** new root expression node. 
149038: **
149039: ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
149040: **
149041: ** Otherwise, if an error occurs, an SQLite error code is returned and 
149042: ** expression (*pp) freed.
149043: */
149044: static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
149045:   int rc = SQLITE_OK;             /* Return code */
149046:   Fts3Expr *pRoot = *pp;          /* Initial root node */
149047:   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
149048:   int eType = pRoot->eType;       /* Type of node in this tree */
149049: 
149050:   if( nMaxDepth==0 ){
149051:     rc = SQLITE_ERROR;
149052:   }
149053: 
149054:   if( rc==SQLITE_OK ){
149055:     if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
149056:       Fts3Expr **apLeaf;
149057:       apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
149058:       if( 0==apLeaf ){
149059:         rc = SQLITE_NOMEM;
149060:       }else{
149061:         memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
149062:       }
149063: 
149064:       if( rc==SQLITE_OK ){
149065:         int i;
149066:         Fts3Expr *p;
149067: 
149068:         /* Set $p to point to the left-most leaf in the tree of eType nodes. */
149069:         for(p=pRoot; p->eType==eType; p=p->pLeft){
149070:           assert( p->pParent==0 || p->pParent->pLeft==p );
149071:           assert( p->pLeft && p->pRight );
149072:         }
149073: 
149074:         /* This loop runs once for each leaf in the tree of eType nodes. */
149075:         while( 1 ){
149076:           int iLvl;
149077:           Fts3Expr *pParent = p->pParent;     /* Current parent of p */
149078: 
149079:           assert( pParent==0 || pParent->pLeft==p );
149080:           p->pParent = 0;
149081:           if( pParent ){
149082:             pParent->pLeft = 0;
149083:           }else{
149084:             pRoot = 0;
149085:           }
149086:           rc = fts3ExprBalance(&p, nMaxDepth-1);
149087:           if( rc!=SQLITE_OK ) break;
149088: 
149089:           for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
149090:             if( apLeaf[iLvl]==0 ){
149091:               apLeaf[iLvl] = p;
149092:               p = 0;
149093:             }else{
149094:               assert( pFree );
149095:               pFree->pLeft = apLeaf[iLvl];
149096:               pFree->pRight = p;
149097:               pFree->pLeft->pParent = pFree;
149098:               pFree->pRight->pParent = pFree;
149099: 
149100:               p = pFree;
149101:               pFree = pFree->pParent;
149102:               p->pParent = 0;
149103:               apLeaf[iLvl] = 0;
149104:             }
149105:           }
149106:           if( p ){
149107:             sqlite3Fts3ExprFree(p);
149108:             rc = SQLITE_TOOBIG;
149109:             break;
149110:           }
149111: 
149112:           /* If that was the last leaf node, break out of the loop */
149113:           if( pParent==0 ) break;
149114: 
149115:           /* Set $p to point to the next leaf in the tree of eType nodes */
149116:           for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
149117: 
149118:           /* Remove pParent from the original tree. */
149119:           assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
149120:           pParent->pRight->pParent = pParent->pParent;
149121:           if( pParent->pParent ){
149122:             pParent->pParent->pLeft = pParent->pRight;
149123:           }else{
149124:             assert( pParent==pRoot );
149125:             pRoot = pParent->pRight;
149126:           }
149127: 
149128:           /* Link pParent into the free node list. It will be used as an
149129:           ** internal node of the new tree.  */
149130:           pParent->pParent = pFree;
149131:           pFree = pParent;
149132:         }
149133: 
149134:         if( rc==SQLITE_OK ){
149135:           p = 0;
149136:           for(i=0; i<nMaxDepth; i++){
149137:             if( apLeaf[i] ){
149138:               if( p==0 ){
149139:                 p = apLeaf[i];
149140:                 p->pParent = 0;
149141:               }else{
149142:                 assert( pFree!=0 );
149143:                 pFree->pRight = p;
149144:                 pFree->pLeft = apLeaf[i];
149145:                 pFree->pLeft->pParent = pFree;
149146:                 pFree->pRight->pParent = pFree;
149147: 
149148:                 p = pFree;
149149:                 pFree = pFree->pParent;
149150:                 p->pParent = 0;
149151:               }
149152:             }
149153:           }
149154:           pRoot = p;
149155:         }else{
149156:           /* An error occurred. Delete the contents of the apLeaf[] array 
149157:           ** and pFree list. Everything else is cleaned up by the call to
149158:           ** sqlite3Fts3ExprFree(pRoot) below.  */
149159:           Fts3Expr *pDel;
149160:           for(i=0; i<nMaxDepth; i++){
149161:             sqlite3Fts3ExprFree(apLeaf[i]);
149162:           }
149163:           while( (pDel=pFree)!=0 ){
149164:             pFree = pDel->pParent;
149165:             sqlite3_free(pDel);
149166:           }
149167:         }
149168: 
149169:         assert( pFree==0 );
149170:         sqlite3_free( apLeaf );
149171:       }
149172:     }else if( eType==FTSQUERY_NOT ){
149173:       Fts3Expr *pLeft = pRoot->pLeft;
149174:       Fts3Expr *pRight = pRoot->pRight;
149175: 
149176:       pRoot->pLeft = 0;
149177:       pRoot->pRight = 0;
149178:       pLeft->pParent = 0;
149179:       pRight->pParent = 0;
149180: 
149181:       rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
149182:       if( rc==SQLITE_OK ){
149183:         rc = fts3ExprBalance(&pRight, nMaxDepth-1);
149184:       }
149185: 
149186:       if( rc!=SQLITE_OK ){
149187:         sqlite3Fts3ExprFree(pRight);
149188:         sqlite3Fts3ExprFree(pLeft);
149189:       }else{
149190:         assert( pLeft && pRight );
149191:         pRoot->pLeft = pLeft;
149192:         pLeft->pParent = pRoot;
149193:         pRoot->pRight = pRight;
149194:         pRight->pParent = pRoot;
149195:       }
149196:     }
149197:   }
149198:   
149199:   if( rc!=SQLITE_OK ){
149200:     sqlite3Fts3ExprFree(pRoot);
149201:     pRoot = 0;
149202:   }
149203:   *pp = pRoot;
149204:   return rc;
149205: }
149206: 
149207: /*
149208: ** This function is similar to sqlite3Fts3ExprParse(), with the following
149209: ** differences:
149210: **
149211: **   1. It does not do expression rebalancing.
149212: **   2. It does not check that the expression does not exceed the 
149213: **      maximum allowable depth.
149214: **   3. Even if it fails, *ppExpr may still be set to point to an 
149215: **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
149216: **      in this case.
149217: */
149218: static int fts3ExprParseUnbalanced(
149219:   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
149220:   int iLangid,                        /* Language id for tokenizer */
149221:   char **azCol,                       /* Array of column names for fts3 table */
149222:   int bFts4,                          /* True to allow FTS4-only syntax */
149223:   int nCol,                           /* Number of entries in azCol[] */
149224:   int iDefaultCol,                    /* Default column to query */
149225:   const char *z, int n,               /* Text of MATCH query */
149226:   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
149227: ){
149228:   int nParsed;
149229:   int rc;
149230:   ParseContext sParse;
149231: 
149232:   memset(&sParse, 0, sizeof(ParseContext));
149233:   sParse.pTokenizer = pTokenizer;
149234:   sParse.iLangid = iLangid;
149235:   sParse.azCol = (const char **)azCol;
149236:   sParse.nCol = nCol;
149237:   sParse.iDefaultCol = iDefaultCol;
149238:   sParse.bFts4 = bFts4;
149239:   if( z==0 ){
149240:     *ppExpr = 0;
149241:     return SQLITE_OK;
149242:   }
149243:   if( n<0 ){
149244:     n = (int)strlen(z);
149245:   }
149246:   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
149247:   assert( rc==SQLITE_OK || *ppExpr==0 );
149248: 
149249:   /* Check for mismatched parenthesis */
149250:   if( rc==SQLITE_OK && sParse.nNest ){
149251:     rc = SQLITE_ERROR;
149252:   }
149253:   
149254:   return rc;
149255: }
149256: 
149257: /*
149258: ** Parameters z and n contain a pointer to and length of a buffer containing
149259: ** an fts3 query expression, respectively. This function attempts to parse the
149260: ** query expression and create a tree of Fts3Expr structures representing the
149261: ** parsed expression. If successful, *ppExpr is set to point to the head
149262: ** of the parsed expression tree and SQLITE_OK is returned. If an error
149263: ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
149264: ** error) is returned and *ppExpr is set to 0.
149265: **
149266: ** If parameter n is a negative number, then z is assumed to point to a
149267: ** nul-terminated string and the length is determined using strlen().
149268: **
149269: ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
149270: ** use to normalize query tokens while parsing the expression. The azCol[]
149271: ** array, which is assumed to contain nCol entries, should contain the names
149272: ** of each column in the target fts3 table, in order from left to right. 
149273: ** Column names must be nul-terminated strings.
149274: **
149275: ** The iDefaultCol parameter should be passed the index of the table column
149276: ** that appears on the left-hand-side of the MATCH operator (the default
149277: ** column to match against for tokens for which a column name is not explicitly
149278: ** specified as part of the query string), or -1 if tokens may by default
149279: ** match any table column.
149280: */
149281: SQLITE_PRIVATE int sqlite3Fts3ExprParse(
149282:   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
149283:   int iLangid,                        /* Language id for tokenizer */
149284:   char **azCol,                       /* Array of column names for fts3 table */
149285:   int bFts4,                          /* True to allow FTS4-only syntax */
149286:   int nCol,                           /* Number of entries in azCol[] */
149287:   int iDefaultCol,                    /* Default column to query */
149288:   const char *z, int n,               /* Text of MATCH query */
149289:   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
149290:   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
149291: ){
149292:   int rc = fts3ExprParseUnbalanced(
149293:       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
149294:   );
149295:   
149296:   /* Rebalance the expression. And check that its depth does not exceed
149297:   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
149298:   if( rc==SQLITE_OK && *ppExpr ){
149299:     rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
149300:     if( rc==SQLITE_OK ){
149301:       rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
149302:     }
149303:   }
149304: 
149305:   if( rc!=SQLITE_OK ){
149306:     sqlite3Fts3ExprFree(*ppExpr);
149307:     *ppExpr = 0;
149308:     if( rc==SQLITE_TOOBIG ){
149309:       sqlite3Fts3ErrMsg(pzErr,
149310:           "FTS expression tree is too large (maximum depth %d)", 
149311:           SQLITE_FTS3_MAX_EXPR_DEPTH
149312:       );
149313:       rc = SQLITE_ERROR;
149314:     }else if( rc==SQLITE_ERROR ){
149315:       sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
149316:     }
149317:   }
149318: 
149319:   return rc;
149320: }
149321: 
149322: /*
149323: ** Free a single node of an expression tree.
149324: */
149325: static void fts3FreeExprNode(Fts3Expr *p){
149326:   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
149327:   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
149328:   sqlite3_free(p->aMI);
149329:   sqlite3_free(p);
149330: }
149331: 
149332: /*
149333: ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
149334: **
149335: ** This function would be simpler if it recursively called itself. But
149336: ** that would mean passing a sufficiently large expression to ExprParse()
149337: ** could cause a stack overflow.
149338: */
149339: SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
149340:   Fts3Expr *p;
149341:   assert( pDel==0 || pDel->pParent==0 );
149342:   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
149343:     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
149344:   }
149345:   while( p ){
149346:     Fts3Expr *pParent = p->pParent;
149347:     fts3FreeExprNode(p);
149348:     if( pParent && p==pParent->pLeft && pParent->pRight ){
149349:       p = pParent->pRight;
149350:       while( p && (p->pLeft || p->pRight) ){
149351:         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
149352:         p = (p->pLeft ? p->pLeft : p->pRight);
149353:       }
149354:     }else{
149355:       p = pParent;
149356:     }
149357:   }
149358: }
149359: 
149360: /****************************************************************************
149361: *****************************************************************************
149362: ** Everything after this point is just test code.
149363: */
149364: 
149365: #ifdef SQLITE_TEST
149366: 
149367: /* #include <stdio.h> */
149368: 
149369: /*
149370: ** Function to query the hash-table of tokenizers (see README.tokenizers).
149371: */
149372: static int queryTestTokenizer(
149373:   sqlite3 *db, 
149374:   const char *zName,  
149375:   const sqlite3_tokenizer_module **pp
149376: ){
149377:   int rc;
149378:   sqlite3_stmt *pStmt;
149379:   const char zSql[] = "SELECT fts3_tokenizer(?)";
149380: 
149381:   *pp = 0;
149382:   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
149383:   if( rc!=SQLITE_OK ){
149384:     return rc;
149385:   }
149386: 
149387:   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
149388:   if( SQLITE_ROW==sqlite3_step(pStmt) ){
149389:     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
149390:       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
149391:     }
149392:   }
149393: 
149394:   return sqlite3_finalize(pStmt);
149395: }
149396: 
149397: /*
149398: ** Return a pointer to a buffer containing a text representation of the
149399: ** expression passed as the first argument. The buffer is obtained from
149400: ** sqlite3_malloc(). It is the responsibility of the caller to use 
149401: ** sqlite3_free() to release the memory. If an OOM condition is encountered,
149402: ** NULL is returned.
149403: **
149404: ** If the second argument is not NULL, then its contents are prepended to 
149405: ** the returned expression text and then freed using sqlite3_free().
149406: */
149407: static char *exprToString(Fts3Expr *pExpr, char *zBuf){
149408:   if( pExpr==0 ){
149409:     return sqlite3_mprintf("");
149410:   }
149411:   switch( pExpr->eType ){
149412:     case FTSQUERY_PHRASE: {
149413:       Fts3Phrase *pPhrase = pExpr->pPhrase;
149414:       int i;
149415:       zBuf = sqlite3_mprintf(
149416:           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
149417:       for(i=0; zBuf && i<pPhrase->nToken; i++){
149418:         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
149419:             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
149420:             (pPhrase->aToken[i].isPrefix?"+":"")
149421:         );
149422:       }
149423:       return zBuf;
149424:     }
149425: 
149426:     case FTSQUERY_NEAR:
149427:       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
149428:       break;
149429:     case FTSQUERY_NOT:
149430:       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
149431:       break;
149432:     case FTSQUERY_AND:
149433:       zBuf = sqlite3_mprintf("%zAND ", zBuf);
149434:       break;
149435:     case FTSQUERY_OR:
149436:       zBuf = sqlite3_mprintf("%zOR ", zBuf);
149437:       break;
149438:   }
149439: 
149440:   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
149441:   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
149442:   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
149443: 
149444:   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
149445:   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
149446: 
149447:   return zBuf;
149448: }
149449: 
149450: /*
149451: ** This is the implementation of a scalar SQL function used to test the 
149452: ** expression parser. It should be called as follows:
149453: **
149454: **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
149455: **
149456: ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
149457: ** to parse the query expression (see README.tokenizers). The second argument
149458: ** is the query expression to parse. Each subsequent argument is the name
149459: ** of a column of the fts3 table that the query expression may refer to.
149460: ** For example:
149461: **
149462: **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
149463: */
149464: static void fts3ExprTest(
149465:   sqlite3_context *context,
149466:   int argc,
149467:   sqlite3_value **argv
149468: ){
149469:   sqlite3_tokenizer_module const *pModule = 0;
149470:   sqlite3_tokenizer *pTokenizer = 0;
149471:   int rc;
149472:   char **azCol = 0;
149473:   const char *zExpr;
149474:   int nExpr;
149475:   int nCol;
149476:   int ii;
149477:   Fts3Expr *pExpr;
149478:   char *zBuf = 0;
149479:   sqlite3 *db = sqlite3_context_db_handle(context);
149480: 
149481:   if( argc<3 ){
149482:     sqlite3_result_error(context, 
149483:         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
149484:     );
149485:     return;
149486:   }
149487: 
149488:   rc = queryTestTokenizer(db,
149489:                           (const char *)sqlite3_value_text(argv[0]), &pModule);
149490:   if( rc==SQLITE_NOMEM ){
149491:     sqlite3_result_error_nomem(context);
149492:     goto exprtest_out;
149493:   }else if( !pModule ){
149494:     sqlite3_result_error(context, "No such tokenizer module", -1);
149495:     goto exprtest_out;
149496:   }
149497: 
149498:   rc = pModule->xCreate(0, 0, &pTokenizer);
149499:   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
149500:   if( rc==SQLITE_NOMEM ){
149501:     sqlite3_result_error_nomem(context);
149502:     goto exprtest_out;
149503:   }
149504:   pTokenizer->pModule = pModule;
149505: 
149506:   zExpr = (const char *)sqlite3_value_text(argv[1]);
149507:   nExpr = sqlite3_value_bytes(argv[1]);
149508:   nCol = argc-2;
149509:   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
149510:   if( !azCol ){
149511:     sqlite3_result_error_nomem(context);
149512:     goto exprtest_out;
149513:   }
149514:   for(ii=0; ii<nCol; ii++){
149515:     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
149516:   }
149517: 
149518:   if( sqlite3_user_data(context) ){
149519:     char *zDummy = 0;
149520:     rc = sqlite3Fts3ExprParse(
149521:         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
149522:     );
149523:     assert( rc==SQLITE_OK || pExpr==0 );
149524:     sqlite3_free(zDummy);
149525:   }else{
149526:     rc = fts3ExprParseUnbalanced(
149527:         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
149528:     );
149529:   }
149530: 
149531:   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
149532:     sqlite3Fts3ExprFree(pExpr);
149533:     sqlite3_result_error(context, "Error parsing expression", -1);
149534:   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
149535:     sqlite3_result_error_nomem(context);
149536:   }else{
149537:     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
149538:     sqlite3_free(zBuf);
149539:   }
149540: 
149541:   sqlite3Fts3ExprFree(pExpr);
149542: 
149543: exprtest_out:
149544:   if( pModule && pTokenizer ){
149545:     rc = pModule->xDestroy(pTokenizer);
149546:   }
149547:   sqlite3_free(azCol);
149548: }
149549: 
149550: /*
149551: ** Register the query expression parser test function fts3_exprtest() 
149552: ** with database connection db. 
149553: */
149554: SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
149555:   int rc = sqlite3_create_function(
149556:       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
149557:   );
149558:   if( rc==SQLITE_OK ){
149559:     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
149560:         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
149561:     );
149562:   }
149563:   return rc;
149564: }
149565: 
149566: #endif
149567: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149568: 
149569: /************** End of fts3_expr.c *******************************************/
149570: /************** Begin file fts3_hash.c ***************************************/
149571: /*
149572: ** 2001 September 22
149573: **
149574: ** The author disclaims copyright to this source code.  In place of
149575: ** a legal notice, here is a blessing:
149576: **
149577: **    May you do good and not evil.
149578: **    May you find forgiveness for yourself and forgive others.
149579: **    May you share freely, never taking more than you give.
149580: **
149581: *************************************************************************
149582: ** This is the implementation of generic hash-tables used in SQLite.
149583: ** We've modified it slightly to serve as a standalone hash table
149584: ** implementation for the full-text indexing module.
149585: */
149586: 
149587: /*
149588: ** The code in this file is only compiled if:
149589: **
149590: **     * The FTS3 module is being built as an extension
149591: **       (in which case SQLITE_CORE is not defined), or
149592: **
149593: **     * The FTS3 module is being built into the core of
149594: **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149595: */
149596: /* #include "fts3Int.h" */
149597: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149598: 
149599: /* #include <assert.h> */
149600: /* #include <stdlib.h> */
149601: /* #include <string.h> */
149602: 
149603: /* #include "fts3_hash.h" */
149604: 
149605: /*
149606: ** Malloc and Free functions
149607: */
149608: static void *fts3HashMalloc(int n){
149609:   void *p = sqlite3_malloc(n);
149610:   if( p ){
149611:     memset(p, 0, n);
149612:   }
149613:   return p;
149614: }
149615: static void fts3HashFree(void *p){
149616:   sqlite3_free(p);
149617: }
149618: 
149619: /* Turn bulk memory into a hash table object by initializing the
149620: ** fields of the Hash structure.
149621: **
149622: ** "pNew" is a pointer to the hash table that is to be initialized.
149623: ** keyClass is one of the constants 
149624: ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
149625: ** determines what kind of key the hash table will use.  "copyKey" is
149626: ** true if the hash table should make its own private copy of keys and
149627: ** false if it should just use the supplied pointer.
149628: */
149629: SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
149630:   assert( pNew!=0 );
149631:   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
149632:   pNew->keyClass = keyClass;
149633:   pNew->copyKey = copyKey;
149634:   pNew->first = 0;
149635:   pNew->count = 0;
149636:   pNew->htsize = 0;
149637:   pNew->ht = 0;
149638: }
149639: 
149640: /* Remove all entries from a hash table.  Reclaim all memory.
149641: ** Call this routine to delete a hash table or to reset a hash table
149642: ** to the empty state.
149643: */
149644: SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
149645:   Fts3HashElem *elem;         /* For looping over all elements of the table */
149646: 
149647:   assert( pH!=0 );
149648:   elem = pH->first;
149649:   pH->first = 0;
149650:   fts3HashFree(pH->ht);
149651:   pH->ht = 0;
149652:   pH->htsize = 0;
149653:   while( elem ){
149654:     Fts3HashElem *next_elem = elem->next;
149655:     if( pH->copyKey && elem->pKey ){
149656:       fts3HashFree(elem->pKey);
149657:     }
149658:     fts3HashFree(elem);
149659:     elem = next_elem;
149660:   }
149661:   pH->count = 0;
149662: }
149663: 
149664: /*
149665: ** Hash and comparison functions when the mode is FTS3_HASH_STRING
149666: */
149667: static int fts3StrHash(const void *pKey, int nKey){
149668:   const char *z = (const char *)pKey;
149669:   unsigned h = 0;
149670:   if( nKey<=0 ) nKey = (int) strlen(z);
149671:   while( nKey > 0  ){
149672:     h = (h<<3) ^ h ^ *z++;
149673:     nKey--;
149674:   }
149675:   return (int)(h & 0x7fffffff);
149676: }
149677: static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
149678:   if( n1!=n2 ) return 1;
149679:   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
149680: }
149681: 
149682: /*
149683: ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
149684: */
149685: static int fts3BinHash(const void *pKey, int nKey){
149686:   int h = 0;
149687:   const char *z = (const char *)pKey;
149688:   while( nKey-- > 0 ){
149689:     h = (h<<3) ^ h ^ *(z++);
149690:   }
149691:   return h & 0x7fffffff;
149692: }
149693: static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
149694:   if( n1!=n2 ) return 1;
149695:   return memcmp(pKey1,pKey2,n1);
149696: }
149697: 
149698: /*
149699: ** Return a pointer to the appropriate hash function given the key class.
149700: **
149701: ** The C syntax in this function definition may be unfamilar to some 
149702: ** programmers, so we provide the following additional explanation:
149703: **
149704: ** The name of the function is "ftsHashFunction".  The function takes a
149705: ** single parameter "keyClass".  The return value of ftsHashFunction()
149706: ** is a pointer to another function.  Specifically, the return value
149707: ** of ftsHashFunction() is a pointer to a function that takes two parameters
149708: ** with types "const void*" and "int" and returns an "int".
149709: */
149710: static int (*ftsHashFunction(int keyClass))(const void*,int){
149711:   if( keyClass==FTS3_HASH_STRING ){
149712:     return &fts3StrHash;
149713:   }else{
149714:     assert( keyClass==FTS3_HASH_BINARY );
149715:     return &fts3BinHash;
149716:   }
149717: }
149718: 
149719: /*
149720: ** Return a pointer to the appropriate hash function given the key class.
149721: **
149722: ** For help in interpreted the obscure C code in the function definition,
149723: ** see the header comment on the previous function.
149724: */
149725: static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
149726:   if( keyClass==FTS3_HASH_STRING ){
149727:     return &fts3StrCompare;
149728:   }else{
149729:     assert( keyClass==FTS3_HASH_BINARY );
149730:     return &fts3BinCompare;
149731:   }
149732: }
149733: 
149734: /* Link an element into the hash table
149735: */
149736: static void fts3HashInsertElement(
149737:   Fts3Hash *pH,            /* The complete hash table */
149738:   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
149739:   Fts3HashElem *pNew       /* The element to be inserted */
149740: ){
149741:   Fts3HashElem *pHead;     /* First element already in pEntry */
149742:   pHead = pEntry->chain;
149743:   if( pHead ){
149744:     pNew->next = pHead;
149745:     pNew->prev = pHead->prev;
149746:     if( pHead->prev ){ pHead->prev->next = pNew; }
149747:     else             { pH->first = pNew; }
149748:     pHead->prev = pNew;
149749:   }else{
149750:     pNew->next = pH->first;
149751:     if( pH->first ){ pH->first->prev = pNew; }
149752:     pNew->prev = 0;
149753:     pH->first = pNew;
149754:   }
149755:   pEntry->count++;
149756:   pEntry->chain = pNew;
149757: }
149758: 
149759: 
149760: /* Resize the hash table so that it cantains "new_size" buckets.
149761: ** "new_size" must be a power of 2.  The hash table might fail 
149762: ** to resize if sqliteMalloc() fails.
149763: **
149764: ** Return non-zero if a memory allocation error occurs.
149765: */
149766: static int fts3Rehash(Fts3Hash *pH, int new_size){
149767:   struct _fts3ht *new_ht;          /* The new hash table */
149768:   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
149769:   int (*xHash)(const void*,int);   /* The hash function */
149770: 
149771:   assert( (new_size & (new_size-1))==0 );
149772:   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
149773:   if( new_ht==0 ) return 1;
149774:   fts3HashFree(pH->ht);
149775:   pH->ht = new_ht;
149776:   pH->htsize = new_size;
149777:   xHash = ftsHashFunction(pH->keyClass);
149778:   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
149779:     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
149780:     next_elem = elem->next;
149781:     fts3HashInsertElement(pH, &new_ht[h], elem);
149782:   }
149783:   return 0;
149784: }
149785: 
149786: /* This function (for internal use only) locates an element in an
149787: ** hash table that matches the given key.  The hash for this key has
149788: ** already been computed and is passed as the 4th parameter.
149789: */
149790: static Fts3HashElem *fts3FindElementByHash(
149791:   const Fts3Hash *pH, /* The pH to be searched */
149792:   const void *pKey,   /* The key we are searching for */
149793:   int nKey,
149794:   int h               /* The hash for this key. */
149795: ){
149796:   Fts3HashElem *elem;            /* Used to loop thru the element list */
149797:   int count;                     /* Number of elements left to test */
149798:   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
149799: 
149800:   if( pH->ht ){
149801:     struct _fts3ht *pEntry = &pH->ht[h];
149802:     elem = pEntry->chain;
149803:     count = pEntry->count;
149804:     xCompare = ftsCompareFunction(pH->keyClass);
149805:     while( count-- && elem ){
149806:       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
149807:         return elem;
149808:       }
149809:       elem = elem->next;
149810:     }
149811:   }
149812:   return 0;
149813: }
149814: 
149815: /* Remove a single entry from the hash table given a pointer to that
149816: ** element and a hash on the element's key.
149817: */
149818: static void fts3RemoveElementByHash(
149819:   Fts3Hash *pH,         /* The pH containing "elem" */
149820:   Fts3HashElem* elem,   /* The element to be removed from the pH */
149821:   int h                 /* Hash value for the element */
149822: ){
149823:   struct _fts3ht *pEntry;
149824:   if( elem->prev ){
149825:     elem->prev->next = elem->next; 
149826:   }else{
149827:     pH->first = elem->next;
149828:   }
149829:   if( elem->next ){
149830:     elem->next->prev = elem->prev;
149831:   }
149832:   pEntry = &pH->ht[h];
149833:   if( pEntry->chain==elem ){
149834:     pEntry->chain = elem->next;
149835:   }
149836:   pEntry->count--;
149837:   if( pEntry->count<=0 ){
149838:     pEntry->chain = 0;
149839:   }
149840:   if( pH->copyKey && elem->pKey ){
149841:     fts3HashFree(elem->pKey);
149842:   }
149843:   fts3HashFree( elem );
149844:   pH->count--;
149845:   if( pH->count<=0 ){
149846:     assert( pH->first==0 );
149847:     assert( pH->count==0 );
149848:     fts3HashClear(pH);
149849:   }
149850: }
149851: 
149852: SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
149853:   const Fts3Hash *pH, 
149854:   const void *pKey, 
149855:   int nKey
149856: ){
149857:   int h;                          /* A hash on key */
149858:   int (*xHash)(const void*,int);  /* The hash function */
149859: 
149860:   if( pH==0 || pH->ht==0 ) return 0;
149861:   xHash = ftsHashFunction(pH->keyClass);
149862:   assert( xHash!=0 );
149863:   h = (*xHash)(pKey,nKey);
149864:   assert( (pH->htsize & (pH->htsize-1))==0 );
149865:   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
149866: }
149867: 
149868: /* 
149869: ** Attempt to locate an element of the hash table pH with a key
149870: ** that matches pKey,nKey.  Return the data for this element if it is
149871: ** found, or NULL if there is no match.
149872: */
149873: SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
149874:   Fts3HashElem *pElem;            /* The element that matches key (if any) */
149875: 
149876:   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
149877:   return pElem ? pElem->data : 0;
149878: }
149879: 
149880: /* Insert an element into the hash table pH.  The key is pKey,nKey
149881: ** and the data is "data".
149882: **
149883: ** If no element exists with a matching key, then a new
149884: ** element is created.  A copy of the key is made if the copyKey
149885: ** flag is set.  NULL is returned.
149886: **
149887: ** If another element already exists with the same key, then the
149888: ** new data replaces the old data and the old data is returned.
149889: ** The key is not copied in this instance.  If a malloc fails, then
149890: ** the new data is returned and the hash table is unchanged.
149891: **
149892: ** If the "data" parameter to this function is NULL, then the
149893: ** element corresponding to "key" is removed from the hash table.
149894: */
149895: SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
149896:   Fts3Hash *pH,        /* The hash table to insert into */
149897:   const void *pKey,    /* The key */
149898:   int nKey,            /* Number of bytes in the key */
149899:   void *data           /* The data */
149900: ){
149901:   int hraw;                 /* Raw hash value of the key */
149902:   int h;                    /* the hash of the key modulo hash table size */
149903:   Fts3HashElem *elem;       /* Used to loop thru the element list */
149904:   Fts3HashElem *new_elem;   /* New element added to the pH */
149905:   int (*xHash)(const void*,int);  /* The hash function */
149906: 
149907:   assert( pH!=0 );
149908:   xHash = ftsHashFunction(pH->keyClass);
149909:   assert( xHash!=0 );
149910:   hraw = (*xHash)(pKey, nKey);
149911:   assert( (pH->htsize & (pH->htsize-1))==0 );
149912:   h = hraw & (pH->htsize-1);
149913:   elem = fts3FindElementByHash(pH,pKey,nKey,h);
149914:   if( elem ){
149915:     void *old_data = elem->data;
149916:     if( data==0 ){
149917:       fts3RemoveElementByHash(pH,elem,h);
149918:     }else{
149919:       elem->data = data;
149920:     }
149921:     return old_data;
149922:   }
149923:   if( data==0 ) return 0;
149924:   if( (pH->htsize==0 && fts3Rehash(pH,8))
149925:    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
149926:   ){
149927:     pH->count = 0;
149928:     return data;
149929:   }
149930:   assert( pH->htsize>0 );
149931:   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
149932:   if( new_elem==0 ) return data;
149933:   if( pH->copyKey && pKey!=0 ){
149934:     new_elem->pKey = fts3HashMalloc( nKey );
149935:     if( new_elem->pKey==0 ){
149936:       fts3HashFree(new_elem);
149937:       return data;
149938:     }
149939:     memcpy((void*)new_elem->pKey, pKey, nKey);
149940:   }else{
149941:     new_elem->pKey = (void*)pKey;
149942:   }
149943:   new_elem->nKey = nKey;
149944:   pH->count++;
149945:   assert( pH->htsize>0 );
149946:   assert( (pH->htsize & (pH->htsize-1))==0 );
149947:   h = hraw & (pH->htsize-1);
149948:   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
149949:   new_elem->data = data;
149950:   return 0;
149951: }
149952: 
149953: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149954: 
149955: /************** End of fts3_hash.c *******************************************/
149956: /************** Begin file fts3_porter.c *************************************/
149957: /*
149958: ** 2006 September 30
149959: **
149960: ** The author disclaims copyright to this source code.  In place of
149961: ** a legal notice, here is a blessing:
149962: **
149963: **    May you do good and not evil.
149964: **    May you find forgiveness for yourself and forgive others.
149965: **    May you share freely, never taking more than you give.
149966: **
149967: *************************************************************************
149968: ** Implementation of the full-text-search tokenizer that implements
149969: ** a Porter stemmer.
149970: */
149971: 
149972: /*
149973: ** The code in this file is only compiled if:
149974: **
149975: **     * The FTS3 module is being built as an extension
149976: **       (in which case SQLITE_CORE is not defined), or
149977: **
149978: **     * The FTS3 module is being built into the core of
149979: **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149980: */
149981: /* #include "fts3Int.h" */
149982: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149983: 
149984: /* #include <assert.h> */
149985: /* #include <stdlib.h> */
149986: /* #include <stdio.h> */
149987: /* #include <string.h> */
149988: 
149989: /* #include "fts3_tokenizer.h" */
149990: 
149991: /*
149992: ** Class derived from sqlite3_tokenizer
149993: */
149994: typedef struct porter_tokenizer {
149995:   sqlite3_tokenizer base;      /* Base class */
149996: } porter_tokenizer;
149997: 
149998: /*
149999: ** Class derived from sqlite3_tokenizer_cursor
150000: */
150001: typedef struct porter_tokenizer_cursor {
150002:   sqlite3_tokenizer_cursor base;
150003:   const char *zInput;          /* input we are tokenizing */
150004:   int nInput;                  /* size of the input */
150005:   int iOffset;                 /* current position in zInput */
150006:   int iToken;                  /* index of next token to be returned */
150007:   char *zToken;                /* storage for current token */
150008:   int nAllocated;              /* space allocated to zToken buffer */
150009: } porter_tokenizer_cursor;
150010: 
150011: 
150012: /*
150013: ** Create a new tokenizer instance.
150014: */
150015: static int porterCreate(
150016:   int argc, const char * const *argv,
150017:   sqlite3_tokenizer **ppTokenizer
150018: ){
150019:   porter_tokenizer *t;
150020: 
150021:   UNUSED_PARAMETER(argc);
150022:   UNUSED_PARAMETER(argv);
150023: 
150024:   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
150025:   if( t==NULL ) return SQLITE_NOMEM;
150026:   memset(t, 0, sizeof(*t));
150027:   *ppTokenizer = &t->base;
150028:   return SQLITE_OK;
150029: }
150030: 
150031: /*
150032: ** Destroy a tokenizer
150033: */
150034: static int porterDestroy(sqlite3_tokenizer *pTokenizer){
150035:   sqlite3_free(pTokenizer);
150036:   return SQLITE_OK;
150037: }
150038: 
150039: /*
150040: ** Prepare to begin tokenizing a particular string.  The input
150041: ** string to be tokenized is zInput[0..nInput-1].  A cursor
150042: ** used to incrementally tokenize this string is returned in 
150043: ** *ppCursor.
150044: */
150045: static int porterOpen(
150046:   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
150047:   const char *zInput, int nInput,        /* String to be tokenized */
150048:   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
150049: ){
150050:   porter_tokenizer_cursor *c;
150051: 
150052:   UNUSED_PARAMETER(pTokenizer);
150053: 
150054:   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
150055:   if( c==NULL ) return SQLITE_NOMEM;
150056: 
150057:   c->zInput = zInput;
150058:   if( zInput==0 ){
150059:     c->nInput = 0;
150060:   }else if( nInput<0 ){
150061:     c->nInput = (int)strlen(zInput);
150062:   }else{
150063:     c->nInput = nInput;
150064:   }
150065:   c->iOffset = 0;                 /* start tokenizing at the beginning */
150066:   c->iToken = 0;
150067:   c->zToken = NULL;               /* no space allocated, yet. */
150068:   c->nAllocated = 0;
150069: 
150070:   *ppCursor = &c->base;
150071:   return SQLITE_OK;
150072: }
150073: 
150074: /*
150075: ** Close a tokenization cursor previously opened by a call to
150076: ** porterOpen() above.
150077: */
150078: static int porterClose(sqlite3_tokenizer_cursor *pCursor){
150079:   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
150080:   sqlite3_free(c->zToken);
150081:   sqlite3_free(c);
150082:   return SQLITE_OK;
150083: }
150084: /*
150085: ** Vowel or consonant
150086: */
150087: static const char cType[] = {
150088:    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
150089:    1, 1, 1, 2, 1
150090: };
150091: 
150092: /*
150093: ** isConsonant() and isVowel() determine if their first character in
150094: ** the string they point to is a consonant or a vowel, according
150095: ** to Porter ruls.  
150096: **
150097: ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
150098: ** 'Y' is a consonant unless it follows another consonant,
150099: ** in which case it is a vowel.
150100: **
150101: ** In these routine, the letters are in reverse order.  So the 'y' rule
150102: ** is that 'y' is a consonant unless it is followed by another
150103: ** consonent.
150104: */
150105: static int isVowel(const char*);
150106: static int isConsonant(const char *z){
150107:   int j;
150108:   char x = *z;
150109:   if( x==0 ) return 0;
150110:   assert( x>='a' && x<='z' );
150111:   j = cType[x-'a'];
150112:   if( j<2 ) return j;
150113:   return z[1]==0 || isVowel(z + 1);
150114: }
150115: static int isVowel(const char *z){
150116:   int j;
150117:   char x = *z;
150118:   if( x==0 ) return 0;
150119:   assert( x>='a' && x<='z' );
150120:   j = cType[x-'a'];
150121:   if( j<2 ) return 1-j;
150122:   return isConsonant(z + 1);
150123: }
150124: 
150125: /*
150126: ** Let any sequence of one or more vowels be represented by V and let
150127: ** C be sequence of one or more consonants.  Then every word can be
150128: ** represented as:
150129: **
150130: **           [C] (VC){m} [V]
150131: **
150132: ** In prose:  A word is an optional consonant followed by zero or
150133: ** vowel-consonant pairs followed by an optional vowel.  "m" is the
150134: ** number of vowel consonant pairs.  This routine computes the value
150135: ** of m for the first i bytes of a word.
150136: **
150137: ** Return true if the m-value for z is 1 or more.  In other words,
150138: ** return true if z contains at least one vowel that is followed
150139: ** by a consonant.
150140: **
150141: ** In this routine z[] is in reverse order.  So we are really looking
150142: ** for an instance of a consonant followed by a vowel.
150143: */
150144: static int m_gt_0(const char *z){
150145:   while( isVowel(z) ){ z++; }
150146:   if( *z==0 ) return 0;
150147:   while( isConsonant(z) ){ z++; }
150148:   return *z!=0;
150149: }
150150: 
150151: /* Like mgt0 above except we are looking for a value of m which is
150152: ** exactly 1
150153: */
150154: static int m_eq_1(const char *z){
150155:   while( isVowel(z) ){ z++; }
150156:   if( *z==0 ) return 0;
150157:   while( isConsonant(z) ){ z++; }
150158:   if( *z==0 ) return 0;
150159:   while( isVowel(z) ){ z++; }
150160:   if( *z==0 ) return 1;
150161:   while( isConsonant(z) ){ z++; }
150162:   return *z==0;
150163: }
150164: 
150165: /* Like mgt0 above except we are looking for a value of m>1 instead
150166: ** or m>0
150167: */
150168: static int m_gt_1(const char *z){
150169:   while( isVowel(z) ){ z++; }
150170:   if( *z==0 ) return 0;
150171:   while( isConsonant(z) ){ z++; }
150172:   if( *z==0 ) return 0;
150173:   while( isVowel(z) ){ z++; }
150174:   if( *z==0 ) return 0;
150175:   while( isConsonant(z) ){ z++; }
150176:   return *z!=0;
150177: }
150178: 
150179: /*
150180: ** Return TRUE if there is a vowel anywhere within z[0..n-1]
150181: */
150182: static int hasVowel(const char *z){
150183:   while( isConsonant(z) ){ z++; }
150184:   return *z!=0;
150185: }
150186: 
150187: /*
150188: ** Return TRUE if the word ends in a double consonant.
150189: **
150190: ** The text is reversed here. So we are really looking at
150191: ** the first two characters of z[].
150192: */
150193: static int doubleConsonant(const char *z){
150194:   return isConsonant(z) && z[0]==z[1];
150195: }
150196: 
150197: /*
150198: ** Return TRUE if the word ends with three letters which
150199: ** are consonant-vowel-consonent and where the final consonant
150200: ** is not 'w', 'x', or 'y'.
150201: **
150202: ** The word is reversed here.  So we are really checking the
150203: ** first three letters and the first one cannot be in [wxy].
150204: */
150205: static int star_oh(const char *z){
150206:   return
150207:     isConsonant(z) &&
150208:     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
150209:     isVowel(z+1) &&
150210:     isConsonant(z+2);
150211: }
150212: 
150213: /*
150214: ** If the word ends with zFrom and xCond() is true for the stem
150215: ** of the word that preceeds the zFrom ending, then change the 
150216: ** ending to zTo.
150217: **
150218: ** The input word *pz and zFrom are both in reverse order.  zTo
150219: ** is in normal order. 
150220: **
150221: ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
150222: ** match.  Not that TRUE is returned even if xCond() fails and
150223: ** no substitution occurs.
150224: */
150225: static int stem(
150226:   char **pz,             /* The word being stemmed (Reversed) */
150227:   const char *zFrom,     /* If the ending matches this... (Reversed) */
150228:   const char *zTo,       /* ... change the ending to this (not reversed) */
150229:   int (*xCond)(const char*)   /* Condition that must be true */
150230: ){
150231:   char *z = *pz;
150232:   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
150233:   if( *zFrom!=0 ) return 0;
150234:   if( xCond && !xCond(z) ) return 1;
150235:   while( *zTo ){
150236:     *(--z) = *(zTo++);
150237:   }
150238:   *pz = z;
150239:   return 1;
150240: }
150241: 
150242: /*
150243: ** This is the fallback stemmer used when the porter stemmer is
150244: ** inappropriate.  The input word is copied into the output with
150245: ** US-ASCII case folding.  If the input word is too long (more
150246: ** than 20 bytes if it contains no digits or more than 6 bytes if
150247: ** it contains digits) then word is truncated to 20 or 6 bytes
150248: ** by taking 10 or 3 bytes from the beginning and end.
150249: */
150250: static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
150251:   int i, mx, j;
150252:   int hasDigit = 0;
150253:   for(i=0; i<nIn; i++){
150254:     char c = zIn[i];
150255:     if( c>='A' && c<='Z' ){
150256:       zOut[i] = c - 'A' + 'a';
150257:     }else{
150258:       if( c>='0' && c<='9' ) hasDigit = 1;
150259:       zOut[i] = c;
150260:     }
150261:   }
150262:   mx = hasDigit ? 3 : 10;
150263:   if( nIn>mx*2 ){
150264:     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
150265:       zOut[j] = zOut[i];
150266:     }
150267:     i = j;
150268:   }
150269:   zOut[i] = 0;
150270:   *pnOut = i;
150271: }
150272: 
150273: 
150274: /*
150275: ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
150276: ** zOut is at least big enough to hold nIn bytes.  Write the actual
150277: ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
150278: **
150279: ** Any upper-case characters in the US-ASCII character set ([A-Z])
150280: ** are converted to lower case.  Upper-case UTF characters are
150281: ** unchanged.
150282: **
150283: ** Words that are longer than about 20 bytes are stemmed by retaining
150284: ** a few bytes from the beginning and the end of the word.  If the
150285: ** word contains digits, 3 bytes are taken from the beginning and
150286: ** 3 bytes from the end.  For long words without digits, 10 bytes
150287: ** are taken from each end.  US-ASCII case folding still applies.
150288: ** 
150289: ** If the input word contains not digits but does characters not 
150290: ** in [a-zA-Z] then no stemming is attempted and this routine just 
150291: ** copies the input into the input into the output with US-ASCII
150292: ** case folding.
150293: **
150294: ** Stemming never increases the length of the word.  So there is
150295: ** no chance of overflowing the zOut buffer.
150296: */
150297: static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
150298:   int i, j;
150299:   char zReverse[28];
150300:   char *z, *z2;
150301:   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
150302:     /* The word is too big or too small for the porter stemmer.
150303:     ** Fallback to the copy stemmer */
150304:     copy_stemmer(zIn, nIn, zOut, pnOut);
150305:     return;
150306:   }
150307:   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
150308:     char c = zIn[i];
150309:     if( c>='A' && c<='Z' ){
150310:       zReverse[j] = c + 'a' - 'A';
150311:     }else if( c>='a' && c<='z' ){
150312:       zReverse[j] = c;
150313:     }else{
150314:       /* The use of a character not in [a-zA-Z] means that we fallback
150315:       ** to the copy stemmer */
150316:       copy_stemmer(zIn, nIn, zOut, pnOut);
150317:       return;
150318:     }
150319:   }
150320:   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
150321:   z = &zReverse[j+1];
150322: 
150323: 
150324:   /* Step 1a */
150325:   if( z[0]=='s' ){
150326:     if(
150327:      !stem(&z, "sess", "ss", 0) &&
150328:      !stem(&z, "sei", "i", 0)  &&
150329:      !stem(&z, "ss", "ss", 0)
150330:     ){
150331:       z++;
150332:     }
150333:   }
150334: 
150335:   /* Step 1b */  
150336:   z2 = z;
150337:   if( stem(&z, "dee", "ee", m_gt_0) ){
150338:     /* Do nothing.  The work was all in the test */
150339:   }else if( 
150340:      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
150341:       && z!=z2
150342:   ){
150343:      if( stem(&z, "ta", "ate", 0) ||
150344:          stem(&z, "lb", "ble", 0) ||
150345:          stem(&z, "zi", "ize", 0) ){
150346:        /* Do nothing.  The work was all in the test */
150347:      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
150348:        z++;
150349:      }else if( m_eq_1(z) && star_oh(z) ){
150350:        *(--z) = 'e';
150351:      }
150352:   }
150353: 
150354:   /* Step 1c */
150355:   if( z[0]=='y' && hasVowel(z+1) ){
150356:     z[0] = 'i';
150357:   }
150358: 
150359:   /* Step 2 */
150360:   switch( z[1] ){
150361:    case 'a':
150362:      if( !stem(&z, "lanoita", "ate", m_gt_0) ){
150363:        stem(&z, "lanoit", "tion", m_gt_0);
150364:      }
150365:      break;
150366:    case 'c':
150367:      if( !stem(&z, "icne", "ence", m_gt_0) ){
150368:        stem(&z, "icna", "ance", m_gt_0);
150369:      }
150370:      break;
150371:    case 'e':
150372:      stem(&z, "rezi", "ize", m_gt_0);
150373:      break;
150374:    case 'g':
150375:      stem(&z, "igol", "log", m_gt_0);
150376:      break;
150377:    case 'l':
150378:      if( !stem(&z, "ilb", "ble", m_gt_0) 
150379:       && !stem(&z, "illa", "al", m_gt_0)
150380:       && !stem(&z, "iltne", "ent", m_gt_0)
150381:       && !stem(&z, "ile", "e", m_gt_0)
150382:      ){
150383:        stem(&z, "ilsuo", "ous", m_gt_0);
150384:      }
150385:      break;
150386:    case 'o':
150387:      if( !stem(&z, "noitazi", "ize", m_gt_0)
150388:       && !stem(&z, "noita", "ate", m_gt_0)
150389:      ){
150390:        stem(&z, "rota", "ate", m_gt_0);
150391:      }
150392:      break;
150393:    case 's':
150394:      if( !stem(&z, "msila", "al", m_gt_0)
150395:       && !stem(&z, "ssenevi", "ive", m_gt_0)
150396:       && !stem(&z, "ssenluf", "ful", m_gt_0)
150397:      ){
150398:        stem(&z, "ssensuo", "ous", m_gt_0);
150399:      }
150400:      break;
150401:    case 't':
150402:      if( !stem(&z, "itila", "al", m_gt_0)
150403:       && !stem(&z, "itivi", "ive", m_gt_0)
150404:      ){
150405:        stem(&z, "itilib", "ble", m_gt_0);
150406:      }
150407:      break;
150408:   }
150409: 
150410:   /* Step 3 */
150411:   switch( z[0] ){
150412:    case 'e':
150413:      if( !stem(&z, "etaci", "ic", m_gt_0)
150414:       && !stem(&z, "evita", "", m_gt_0)
150415:      ){
150416:        stem(&z, "ezila", "al", m_gt_0);
150417:      }
150418:      break;
150419:    case 'i':
150420:      stem(&z, "itici", "ic", m_gt_0);
150421:      break;
150422:    case 'l':
150423:      if( !stem(&z, "laci", "ic", m_gt_0) ){
150424:        stem(&z, "luf", "", m_gt_0);
150425:      }
150426:      break;
150427:    case 's':
150428:      stem(&z, "ssen", "", m_gt_0);
150429:      break;
150430:   }
150431: 
150432:   /* Step 4 */
150433:   switch( z[1] ){
150434:    case 'a':
150435:      if( z[0]=='l' && m_gt_1(z+2) ){
150436:        z += 2;
150437:      }
150438:      break;
150439:    case 'c':
150440:      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
150441:        z += 4;
150442:      }
150443:      break;
150444:    case 'e':
150445:      if( z[0]=='r' && m_gt_1(z+2) ){
150446:        z += 2;
150447:      }
150448:      break;
150449:    case 'i':
150450:      if( z[0]=='c' && m_gt_1(z+2) ){
150451:        z += 2;
150452:      }
150453:      break;
150454:    case 'l':
150455:      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
150456:        z += 4;
150457:      }
150458:      break;
150459:    case 'n':
150460:      if( z[0]=='t' ){
150461:        if( z[2]=='a' ){
150462:          if( m_gt_1(z+3) ){
150463:            z += 3;
150464:          }
150465:        }else if( z[2]=='e' ){
150466:          if( !stem(&z, "tneme", "", m_gt_1)
150467:           && !stem(&z, "tnem", "", m_gt_1)
150468:          ){
150469:            stem(&z, "tne", "", m_gt_1);
150470:          }
150471:        }
150472:      }
150473:      break;
150474:    case 'o':
150475:      if( z[0]=='u' ){
150476:        if( m_gt_1(z+2) ){
150477:          z += 2;
150478:        }
150479:      }else if( z[3]=='s' || z[3]=='t' ){
150480:        stem(&z, "noi", "", m_gt_1);
150481:      }
150482:      break;
150483:    case 's':
150484:      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
150485:        z += 3;
150486:      }
150487:      break;
150488:    case 't':
150489:      if( !stem(&z, "eta", "", m_gt_1) ){
150490:        stem(&z, "iti", "", m_gt_1);
150491:      }
150492:      break;
150493:    case 'u':
150494:      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
150495:        z += 3;
150496:      }
150497:      break;
150498:    case 'v':
150499:    case 'z':
150500:      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
150501:        z += 3;
150502:      }
150503:      break;
150504:   }
150505: 
150506:   /* Step 5a */
150507:   if( z[0]=='e' ){
150508:     if( m_gt_1(z+1) ){
150509:       z++;
150510:     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
150511:       z++;
150512:     }
150513:   }
150514: 
150515:   /* Step 5b */
150516:   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
150517:     z++;
150518:   }
150519: 
150520:   /* z[] is now the stemmed word in reverse order.  Flip it back
150521:   ** around into forward order and return.
150522:   */
150523:   *pnOut = i = (int)strlen(z);
150524:   zOut[i] = 0;
150525:   while( *z ){
150526:     zOut[--i] = *(z++);
150527:   }
150528: }
150529: 
150530: /*
150531: ** Characters that can be part of a token.  We assume any character
150532: ** whose value is greater than 0x80 (any UTF character) can be
150533: ** part of a token.  In other words, delimiters all must have
150534: ** values of 0x7f or lower.
150535: */
150536: static const char porterIdChar[] = {
150537: /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
150538:     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
150539:     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
150540:     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
150541:     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
150542:     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
150543: };
150544: #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
150545: 
150546: /*
150547: ** Extract the next token from a tokenization cursor.  The cursor must
150548: ** have been opened by a prior call to porterOpen().
150549: */
150550: static int porterNext(
150551:   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
150552:   const char **pzToken,               /* OUT: *pzToken is the token text */
150553:   int *pnBytes,                       /* OUT: Number of bytes in token */
150554:   int *piStartOffset,                 /* OUT: Starting offset of token */
150555:   int *piEndOffset,                   /* OUT: Ending offset of token */
150556:   int *piPosition                     /* OUT: Position integer of token */
150557: ){
150558:   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
150559:   const char *z = c->zInput;
150560: 
150561:   while( c->iOffset<c->nInput ){
150562:     int iStartOffset, ch;
150563: 
150564:     /* Scan past delimiter characters */
150565:     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
150566:       c->iOffset++;
150567:     }
150568: 
150569:     /* Count non-delimiter characters. */
150570:     iStartOffset = c->iOffset;
150571:     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
150572:       c->iOffset++;
150573:     }
150574: 
150575:     if( c->iOffset>iStartOffset ){
150576:       int n = c->iOffset-iStartOffset;
150577:       if( n>c->nAllocated ){
150578:         char *pNew;
150579:         c->nAllocated = n+20;
150580:         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
150581:         if( !pNew ) return SQLITE_NOMEM;
150582:         c->zToken = pNew;
150583:       }
150584:       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
150585:       *pzToken = c->zToken;
150586:       *piStartOffset = iStartOffset;
150587:       *piEndOffset = c->iOffset;
150588:       *piPosition = c->iToken++;
150589:       return SQLITE_OK;
150590:     }
150591:   }
150592:   return SQLITE_DONE;
150593: }
150594: 
150595: /*
150596: ** The set of routines that implement the porter-stemmer tokenizer
150597: */
150598: static const sqlite3_tokenizer_module porterTokenizerModule = {
150599:   0,
150600:   porterCreate,
150601:   porterDestroy,
150602:   porterOpen,
150603:   porterClose,
150604:   porterNext,
150605:   0
150606: };
150607: 
150608: /*
150609: ** Allocate a new porter tokenizer.  Return a pointer to the new
150610: ** tokenizer in *ppModule
150611: */
150612: SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
150613:   sqlite3_tokenizer_module const**ppModule
150614: ){
150615:   *ppModule = &porterTokenizerModule;
150616: }
150617: 
150618: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150619: 
150620: /************** End of fts3_porter.c *****************************************/
150621: /************** Begin file fts3_tokenizer.c **********************************/
150622: /*
150623: ** 2007 June 22
150624: **
150625: ** The author disclaims copyright to this source code.  In place of
150626: ** a legal notice, here is a blessing:
150627: **
150628: **    May you do good and not evil.
150629: **    May you find forgiveness for yourself and forgive others.
150630: **    May you share freely, never taking more than you give.
150631: **
150632: ******************************************************************************
150633: **
150634: ** This is part of an SQLite module implementing full-text search.
150635: ** This particular file implements the generic tokenizer interface.
150636: */
150637: 
150638: /*
150639: ** The code in this file is only compiled if:
150640: **
150641: **     * The FTS3 module is being built as an extension
150642: **       (in which case SQLITE_CORE is not defined), or
150643: **
150644: **     * The FTS3 module is being built into the core of
150645: **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
150646: */
150647: /* #include "fts3Int.h" */
150648: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150649: 
150650: /* #include <assert.h> */
150651: /* #include <string.h> */
150652: 
150653: /*
150654: ** Return true if the two-argument version of fts3_tokenizer()
150655: ** has been activated via a prior call to sqlite3_db_config(db,
150656: ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
150657: */
150658: static int fts3TokenizerEnabled(sqlite3_context *context){
150659:   sqlite3 *db = sqlite3_context_db_handle(context);
150660:   int isEnabled = 0;
150661:   sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
150662:   return isEnabled;
150663: }
150664: 
150665: /*
150666: ** Implementation of the SQL scalar function for accessing the underlying 
150667: ** hash table. This function may be called as follows:
150668: **
150669: **   SELECT <function-name>(<key-name>);
150670: **   SELECT <function-name>(<key-name>, <pointer>);
150671: **
150672: ** where <function-name> is the name passed as the second argument
150673: ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
150674: **
150675: ** If the <pointer> argument is specified, it must be a blob value
150676: ** containing a pointer to be stored as the hash data corresponding
150677: ** to the string <key-name>. If <pointer> is not specified, then
150678: ** the string <key-name> must already exist in the has table. Otherwise,
150679: ** an error is returned.
150680: **
150681: ** Whether or not the <pointer> argument is specified, the value returned
150682: ** is a blob containing the pointer stored as the hash data corresponding
150683: ** to string <key-name> (after the hash-table is updated, if applicable).
150684: */
150685: static void fts3TokenizerFunc(
150686:   sqlite3_context *context,
150687:   int argc,
150688:   sqlite3_value **argv
150689: ){
150690:   Fts3Hash *pHash;
150691:   void *pPtr = 0;
150692:   const unsigned char *zName;
150693:   int nName;
150694: 
150695:   assert( argc==1 || argc==2 );
150696: 
150697:   pHash = (Fts3Hash *)sqlite3_user_data(context);
150698: 
150699:   zName = sqlite3_value_text(argv[0]);
150700:   nName = sqlite3_value_bytes(argv[0])+1;
150701: 
150702:   if( argc==2 ){
150703:     if( fts3TokenizerEnabled(context) ){
150704:       void *pOld;
150705:       int n = sqlite3_value_bytes(argv[1]);
150706:       if( zName==0 || n!=sizeof(pPtr) ){
150707:         sqlite3_result_error(context, "argument type mismatch", -1);
150708:         return;
150709:       }
150710:       pPtr = *(void **)sqlite3_value_blob(argv[1]);
150711:       pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
150712:       if( pOld==pPtr ){
150713:         sqlite3_result_error(context, "out of memory", -1);
150714:       }
150715:     }else{
150716:       sqlite3_result_error(context, "fts3tokenize disabled", -1);
150717:       return;
150718:     }
150719:   }else{
150720:     if( zName ){
150721:       pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
150722:     }
150723:     if( !pPtr ){
150724:       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
150725:       sqlite3_result_error(context, zErr, -1);
150726:       sqlite3_free(zErr);
150727:       return;
150728:     }
150729:   }
150730:   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
150731: }
150732: 
150733: SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
150734:   static const char isFtsIdChar[] = {
150735:       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
150736:       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
150737:       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
150738:       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
150739:       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
150740:       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
150741:       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
150742:       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
150743:   };
150744:   return (c&0x80 || isFtsIdChar[(int)(c)]);
150745: }
150746: 
150747: SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
150748:   const char *z1;
150749:   const char *z2 = 0;
150750: 
150751:   /* Find the start of the next token. */
150752:   z1 = zStr;
150753:   while( z2==0 ){
150754:     char c = *z1;
150755:     switch( c ){
150756:       case '\0': return 0;        /* No more tokens here */
150757:       case '\'':
150758:       case '"':
150759:       case '`': {
150760:         z2 = z1;
150761:         while( *++z2 && (*z2!=c || *++z2==c) );
150762:         break;
150763:       }
150764:       case '[':
150765:         z2 = &z1[1];
150766:         while( *z2 && z2[0]!=']' ) z2++;
150767:         if( *z2 ) z2++;
150768:         break;
150769: 
150770:       default:
150771:         if( sqlite3Fts3IsIdChar(*z1) ){
150772:           z2 = &z1[1];
150773:           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
150774:         }else{
150775:           z1++;
150776:         }
150777:     }
150778:   }
150779: 
150780:   *pn = (int)(z2-z1);
150781:   return z1;
150782: }
150783: 
150784: SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
150785:   Fts3Hash *pHash,                /* Tokenizer hash table */
150786:   const char *zArg,               /* Tokenizer name */
150787:   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
150788:   char **pzErr                    /* OUT: Set to malloced error message */
150789: ){
150790:   int rc;
150791:   char *z = (char *)zArg;
150792:   int n = 0;
150793:   char *zCopy;
150794:   char *zEnd;                     /* Pointer to nul-term of zCopy */
150795:   sqlite3_tokenizer_module *m;
150796: 
150797:   zCopy = sqlite3_mprintf("%s", zArg);
150798:   if( !zCopy ) return SQLITE_NOMEM;
150799:   zEnd = &zCopy[strlen(zCopy)];
150800: 
150801:   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
150802:   if( z==0 ){
150803:     assert( n==0 );
150804:     z = zCopy;
150805:   }
150806:   z[n] = '\0';
150807:   sqlite3Fts3Dequote(z);
150808: 
150809:   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
150810:   if( !m ){
150811:     sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
150812:     rc = SQLITE_ERROR;
150813:   }else{
150814:     char const **aArg = 0;
150815:     int iArg = 0;
150816:     z = &z[n+1];
150817:     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
150818:       int nNew = sizeof(char *)*(iArg+1);
150819:       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
150820:       if( !aNew ){
150821:         sqlite3_free(zCopy);
150822:         sqlite3_free((void *)aArg);
150823:         return SQLITE_NOMEM;
150824:       }
150825:       aArg = aNew;
150826:       aArg[iArg++] = z;
150827:       z[n] = '\0';
150828:       sqlite3Fts3Dequote(z);
150829:       z = &z[n+1];
150830:     }
150831:     rc = m->xCreate(iArg, aArg, ppTok);
150832:     assert( rc!=SQLITE_OK || *ppTok );
150833:     if( rc!=SQLITE_OK ){
150834:       sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
150835:     }else{
150836:       (*ppTok)->pModule = m; 
150837:     }
150838:     sqlite3_free((void *)aArg);
150839:   }
150840: 
150841:   sqlite3_free(zCopy);
150842:   return rc;
150843: }
150844: 
150845: 
150846: #ifdef SQLITE_TEST
150847: 
150848: #if defined(INCLUDE_SQLITE_TCL_H)
150849: #  include "sqlite_tcl.h"
150850: #else
150851: #  include "tcl.h"
150852: #endif
150853: /* #include <string.h> */
150854: 
150855: /*
150856: ** Implementation of a special SQL scalar function for testing tokenizers 
150857: ** designed to be used in concert with the Tcl testing framework. This
150858: ** function must be called with two or more arguments:
150859: **
150860: **   SELECT <function-name>(<key-name>, ..., <input-string>);
150861: **
150862: ** where <function-name> is the name passed as the second argument
150863: ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
150864: ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
150865: **
150866: ** The return value is a string that may be interpreted as a Tcl
150867: ** list. For each token in the <input-string>, three elements are
150868: ** added to the returned list. The first is the token position, the 
150869: ** second is the token text (folded, stemmed, etc.) and the third is the
150870: ** substring of <input-string> associated with the token. For example, 
150871: ** using the built-in "simple" tokenizer:
150872: **
150873: **   SELECT fts_tokenizer_test('simple', 'I don't see how');
150874: **
150875: ** will return the string:
150876: **
150877: **   "{0 i I 1 dont don't 2 see see 3 how how}"
150878: **   
150879: */
150880: static void testFunc(
150881:   sqlite3_context *context,
150882:   int argc,
150883:   sqlite3_value **argv
150884: ){
150885:   Fts3Hash *pHash;
150886:   sqlite3_tokenizer_module *p;
150887:   sqlite3_tokenizer *pTokenizer = 0;
150888:   sqlite3_tokenizer_cursor *pCsr = 0;
150889: 
150890:   const char *zErr = 0;
150891: 
150892:   const char *zName;
150893:   int nName;
150894:   const char *zInput;
150895:   int nInput;
150896: 
150897:   const char *azArg[64];
150898: 
150899:   const char *zToken;
150900:   int nToken = 0;
150901:   int iStart = 0;
150902:   int iEnd = 0;
150903:   int iPos = 0;
150904:   int i;
150905: 
150906:   Tcl_Obj *pRet;
150907: 
150908:   if( argc<2 ){
150909:     sqlite3_result_error(context, "insufficient arguments", -1);
150910:     return;
150911:   }
150912: 
150913:   nName = sqlite3_value_bytes(argv[0]);
150914:   zName = (const char *)sqlite3_value_text(argv[0]);
150915:   nInput = sqlite3_value_bytes(argv[argc-1]);
150916:   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
150917: 
150918:   pHash = (Fts3Hash *)sqlite3_user_data(context);
150919:   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
150920: 
150921:   if( !p ){
150922:     char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
150923:     sqlite3_result_error(context, zErr2, -1);
150924:     sqlite3_free(zErr2);
150925:     return;
150926:   }
150927: 
150928:   pRet = Tcl_NewObj();
150929:   Tcl_IncrRefCount(pRet);
150930: 
150931:   for(i=1; i<argc-1; i++){
150932:     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
150933:   }
150934: 
150935:   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
150936:     zErr = "error in xCreate()";
150937:     goto finish;
150938:   }
150939:   pTokenizer->pModule = p;
150940:   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
150941:     zErr = "error in xOpen()";
150942:     goto finish;
150943:   }
150944: 
150945:   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
150946:     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
150947:     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
150948:     zToken = &zInput[iStart];
150949:     nToken = iEnd-iStart;
150950:     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
150951:   }
150952: 
150953:   if( SQLITE_OK!=p->xClose(pCsr) ){
150954:     zErr = "error in xClose()";
150955:     goto finish;
150956:   }
150957:   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
150958:     zErr = "error in xDestroy()";
150959:     goto finish;
150960:   }
150961: 
150962: finish:
150963:   if( zErr ){
150964:     sqlite3_result_error(context, zErr, -1);
150965:   }else{
150966:     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
150967:   }
150968:   Tcl_DecrRefCount(pRet);
150969: }
150970: 
150971: static
150972: int registerTokenizer(
150973:   sqlite3 *db, 
150974:   char *zName, 
150975:   const sqlite3_tokenizer_module *p
150976: ){
150977:   int rc;
150978:   sqlite3_stmt *pStmt;
150979:   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
150980: 
150981:   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150982:   if( rc!=SQLITE_OK ){
150983:     return rc;
150984:   }
150985: 
150986:   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150987:   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
150988:   sqlite3_step(pStmt);
150989: 
150990:   return sqlite3_finalize(pStmt);
150991: }
150992: 
150993: 
150994: static
150995: int queryTokenizer(
150996:   sqlite3 *db, 
150997:   char *zName,  
150998:   const sqlite3_tokenizer_module **pp
150999: ){
151000:   int rc;
151001:   sqlite3_stmt *pStmt;
151002:   const char zSql[] = "SELECT fts3_tokenizer(?)";
151003: 
151004:   *pp = 0;
151005:   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
151006:   if( rc!=SQLITE_OK ){
151007:     return rc;
151008:   }
151009: 
151010:   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
151011:   if( SQLITE_ROW==sqlite3_step(pStmt) ){
151012:     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
151013:       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
151014:     }
151015:   }
151016: 
151017:   return sqlite3_finalize(pStmt);
151018: }
151019: 
151020: SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
151021: 
151022: /*
151023: ** Implementation of the scalar function fts3_tokenizer_internal_test().
151024: ** This function is used for testing only, it is not included in the
151025: ** build unless SQLITE_TEST is defined.
151026: **
151027: ** The purpose of this is to test that the fts3_tokenizer() function
151028: ** can be used as designed by the C-code in the queryTokenizer and
151029: ** registerTokenizer() functions above. These two functions are repeated
151030: ** in the README.tokenizer file as an example, so it is important to
151031: ** test them.
151032: **
151033: ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
151034: ** function with no arguments. An assert() will fail if a problem is
151035: ** detected. i.e.:
151036: **
151037: **     SELECT fts3_tokenizer_internal_test();
151038: **
151039: */
151040: static void intTestFunc(
151041:   sqlite3_context *context,
151042:   int argc,
151043:   sqlite3_value **argv
151044: ){
151045:   int rc;
151046:   const sqlite3_tokenizer_module *p1;
151047:   const sqlite3_tokenizer_module *p2;
151048:   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
151049: 
151050:   UNUSED_PARAMETER(argc);
151051:   UNUSED_PARAMETER(argv);
151052: 
151053:   /* Test the query function */
151054:   sqlite3Fts3SimpleTokenizerModule(&p1);
151055:   rc = queryTokenizer(db, "simple", &p2);
151056:   assert( rc==SQLITE_OK );
151057:   assert( p1==p2 );
151058:   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
151059:   assert( rc==SQLITE_ERROR );
151060:   assert( p2==0 );
151061:   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
151062: 
151063:   /* Test the storage function */
151064:   if( fts3TokenizerEnabled(context) ){
151065:     rc = registerTokenizer(db, "nosuchtokenizer", p1);
151066:     assert( rc==SQLITE_OK );
151067:     rc = queryTokenizer(db, "nosuchtokenizer", &p2);
151068:     assert( rc==SQLITE_OK );
151069:     assert( p2==p1 );
151070:   }
151071: 
151072:   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
151073: }
151074: 
151075: #endif
151076: 
151077: /*
151078: ** Set up SQL objects in database db used to access the contents of
151079: ** the hash table pointed to by argument pHash. The hash table must
151080: ** been initialized to use string keys, and to take a private copy 
151081: ** of the key when a value is inserted. i.e. by a call similar to:
151082: **
151083: **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
151084: **
151085: ** This function adds a scalar function (see header comment above
151086: ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
151087: ** defined at compilation time, a temporary virtual table (see header 
151088: ** comment above struct HashTableVtab) to the database schema. Both 
151089: ** provide read/write access to the contents of *pHash.
151090: **
151091: ** The third argument to this function, zName, is used as the name
151092: ** of both the scalar and, if created, the virtual table.
151093: */
151094: SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
151095:   sqlite3 *db, 
151096:   Fts3Hash *pHash, 
151097:   const char *zName
151098: ){
151099:   int rc = SQLITE_OK;
151100:   void *p = (void *)pHash;
151101:   const int any = SQLITE_ANY;
151102: 
151103: #ifdef SQLITE_TEST
151104:   char *zTest = 0;
151105:   char *zTest2 = 0;
151106:   void *pdb = (void *)db;
151107:   zTest = sqlite3_mprintf("%s_test", zName);
151108:   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
151109:   if( !zTest || !zTest2 ){
151110:     rc = SQLITE_NOMEM;
151111:   }
151112: #endif
151113: 
151114:   if( SQLITE_OK==rc ){
151115:     rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
151116:   }
151117:   if( SQLITE_OK==rc ){
151118:     rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
151119:   }
151120: #ifdef SQLITE_TEST
151121:   if( SQLITE_OK==rc ){
151122:     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
151123:   }
151124:   if( SQLITE_OK==rc ){
151125:     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
151126:   }
151127: #endif
151128: 
151129: #ifdef SQLITE_TEST
151130:   sqlite3_free(zTest);
151131:   sqlite3_free(zTest2);
151132: #endif
151133: 
151134:   return rc;
151135: }
151136: 
151137: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151138: 
151139: /************** End of fts3_tokenizer.c **************************************/
151140: /************** Begin file fts3_tokenizer1.c *********************************/
151141: /*
151142: ** 2006 Oct 10
151143: **
151144: ** The author disclaims copyright to this source code.  In place of
151145: ** a legal notice, here is a blessing:
151146: **
151147: **    May you do good and not evil.
151148: **    May you find forgiveness for yourself and forgive others.
151149: **    May you share freely, never taking more than you give.
151150: **
151151: ******************************************************************************
151152: **
151153: ** Implementation of the "simple" full-text-search tokenizer.
151154: */
151155: 
151156: /*
151157: ** The code in this file is only compiled if:
151158: **
151159: **     * The FTS3 module is being built as an extension
151160: **       (in which case SQLITE_CORE is not defined), or
151161: **
151162: **     * The FTS3 module is being built into the core of
151163: **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
151164: */
151165: /* #include "fts3Int.h" */
151166: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151167: 
151168: /* #include <assert.h> */
151169: /* #include <stdlib.h> */
151170: /* #include <stdio.h> */
151171: /* #include <string.h> */
151172: 
151173: /* #include "fts3_tokenizer.h" */
151174: 
151175: typedef struct simple_tokenizer {
151176:   sqlite3_tokenizer base;
151177:   char delim[128];             /* flag ASCII delimiters */
151178: } simple_tokenizer;
151179: 
151180: typedef struct simple_tokenizer_cursor {
151181:   sqlite3_tokenizer_cursor base;
151182:   const char *pInput;          /* input we are tokenizing */
151183:   int nBytes;                  /* size of the input */
151184:   int iOffset;                 /* current position in pInput */
151185:   int iToken;                  /* index of next token to be returned */
151186:   char *pToken;                /* storage for current token */
151187:   int nTokenAllocated;         /* space allocated to zToken buffer */
151188: } simple_tokenizer_cursor;
151189: 
151190: 
151191: static int simpleDelim(simple_tokenizer *t, unsigned char c){
151192:   return c<0x80 && t->delim[c];
151193: }
151194: static int fts3_isalnum(int x){
151195:   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
151196: }
151197: 
151198: /*
151199: ** Create a new tokenizer instance.
151200: */
151201: static int simpleCreate(
151202:   int argc, const char * const *argv,
151203:   sqlite3_tokenizer **ppTokenizer
151204: ){
151205:   simple_tokenizer *t;
151206: 
151207:   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
151208:   if( t==NULL ) return SQLITE_NOMEM;
151209:   memset(t, 0, sizeof(*t));
151210: 
151211:   /* TODO(shess) Delimiters need to remain the same from run to run,
151212:   ** else we need to reindex.  One solution would be a meta-table to
151213:   ** track such information in the database, then we'd only want this
151214:   ** information on the initial create.
151215:   */
151216:   if( argc>1 ){
151217:     int i, n = (int)strlen(argv[1]);
151218:     for(i=0; i<n; i++){
151219:       unsigned char ch = argv[1][i];
151220:       /* We explicitly don't support UTF-8 delimiters for now. */
151221:       if( ch>=0x80 ){
151222:         sqlite3_free(t);
151223:         return SQLITE_ERROR;
151224:       }
151225:       t->delim[ch] = 1;
151226:     }
151227:   } else {
151228:     /* Mark non-alphanumeric ASCII characters as delimiters */
151229:     int i;
151230:     for(i=1; i<0x80; i++){
151231:       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
151232:     }
151233:   }
151234: 
151235:   *ppTokenizer = &t->base;
151236:   return SQLITE_OK;
151237: }
151238: 
151239: /*
151240: ** Destroy a tokenizer
151241: */
151242: static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
151243:   sqlite3_free(pTokenizer);
151244:   return SQLITE_OK;
151245: }
151246: 
151247: /*
151248: ** Prepare to begin tokenizing a particular string.  The input
151249: ** string to be tokenized is pInput[0..nBytes-1].  A cursor
151250: ** used to incrementally tokenize this string is returned in 
151251: ** *ppCursor.
151252: */
151253: static int simpleOpen(
151254:   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
151255:   const char *pInput, int nBytes,        /* String to be tokenized */
151256:   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
151257: ){
151258:   simple_tokenizer_cursor *c;
151259: 
151260:   UNUSED_PARAMETER(pTokenizer);
151261: 
151262:   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
151263:   if( c==NULL ) return SQLITE_NOMEM;
151264: 
151265:   c->pInput = pInput;
151266:   if( pInput==0 ){
151267:     c->nBytes = 0;
151268:   }else if( nBytes<0 ){
151269:     c->nBytes = (int)strlen(pInput);
151270:   }else{
151271:     c->nBytes = nBytes;
151272:   }
151273:   c->iOffset = 0;                 /* start tokenizing at the beginning */
151274:   c->iToken = 0;
151275:   c->pToken = NULL;               /* no space allocated, yet. */
151276:   c->nTokenAllocated = 0;
151277: 
151278:   *ppCursor = &c->base;
151279:   return SQLITE_OK;
151280: }
151281: 
151282: /*
151283: ** Close a tokenization cursor previously opened by a call to
151284: ** simpleOpen() above.
151285: */
151286: static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
151287:   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
151288:   sqlite3_free(c->pToken);
151289:   sqlite3_free(c);
151290:   return SQLITE_OK;
151291: }
151292: 
151293: /*
151294: ** Extract the next token from a tokenization cursor.  The cursor must
151295: ** have been opened by a prior call to simpleOpen().
151296: */
151297: static int simpleNext(
151298:   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
151299:   const char **ppToken,               /* OUT: *ppToken is the token text */
151300:   int *pnBytes,                       /* OUT: Number of bytes in token */
151301:   int *piStartOffset,                 /* OUT: Starting offset of token */
151302:   int *piEndOffset,                   /* OUT: Ending offset of token */
151303:   int *piPosition                     /* OUT: Position integer of token */
151304: ){
151305:   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
151306:   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
151307:   unsigned char *p = (unsigned char *)c->pInput;
151308: 
151309:   while( c->iOffset<c->nBytes ){
151310:     int iStartOffset;
151311: 
151312:     /* Scan past delimiter characters */
151313:     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
151314:       c->iOffset++;
151315:     }
151316: 
151317:     /* Count non-delimiter characters. */
151318:     iStartOffset = c->iOffset;
151319:     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
151320:       c->iOffset++;
151321:     }
151322: 
151323:     if( c->iOffset>iStartOffset ){
151324:       int i, n = c->iOffset-iStartOffset;
151325:       if( n>c->nTokenAllocated ){
151326:         char *pNew;
151327:         c->nTokenAllocated = n+20;
151328:         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
151329:         if( !pNew ) return SQLITE_NOMEM;
151330:         c->pToken = pNew;
151331:       }
151332:       for(i=0; i<n; i++){
151333:         /* TODO(shess) This needs expansion to handle UTF-8
151334:         ** case-insensitivity.
151335:         */
151336:         unsigned char ch = p[iStartOffset+i];
151337:         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
151338:       }
151339:       *ppToken = c->pToken;
151340:       *pnBytes = n;
151341:       *piStartOffset = iStartOffset;
151342:       *piEndOffset = c->iOffset;
151343:       *piPosition = c->iToken++;
151344: 
151345:       return SQLITE_OK;
151346:     }
151347:   }
151348:   return SQLITE_DONE;
151349: }
151350: 
151351: /*
151352: ** The set of routines that implement the simple tokenizer
151353: */
151354: static const sqlite3_tokenizer_module simpleTokenizerModule = {
151355:   0,
151356:   simpleCreate,
151357:   simpleDestroy,
151358:   simpleOpen,
151359:   simpleClose,
151360:   simpleNext,
151361:   0,
151362: };
151363: 
151364: /*
151365: ** Allocate a new simple tokenizer.  Return a pointer to the new
151366: ** tokenizer in *ppModule
151367: */
151368: SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
151369:   sqlite3_tokenizer_module const**ppModule
151370: ){
151371:   *ppModule = &simpleTokenizerModule;
151372: }
151373: 
151374: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151375: 
151376: /************** End of fts3_tokenizer1.c *************************************/
151377: /************** Begin file fts3_tokenize_vtab.c ******************************/
151378: /*
151379: ** 2013 Apr 22
151380: **
151381: ** The author disclaims copyright to this source code.  In place of
151382: ** a legal notice, here is a blessing:
151383: **
151384: **    May you do good and not evil.
151385: **    May you find forgiveness for yourself and forgive others.
151386: **    May you share freely, never taking more than you give.
151387: **
151388: ******************************************************************************
151389: **
151390: ** This file contains code for the "fts3tokenize" virtual table module.
151391: ** An fts3tokenize virtual table is created as follows:
151392: **
151393: **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
151394: **       <tokenizer-name>, <arg-1>, ...
151395: **   );
151396: **
151397: ** The table created has the following schema:
151398: **
151399: **   CREATE TABLE <tbl>(input, token, start, end, position)
151400: **
151401: ** When queried, the query must include a WHERE clause of type:
151402: **
151403: **   input = <string>
151404: **
151405: ** The virtual table module tokenizes this <string>, using the FTS3 
151406: ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE 
151407: ** statement and returns one row for each token in the result. With
151408: ** fields set as follows:
151409: **
151410: **   input:   Always set to a copy of <string>
151411: **   token:   A token from the input.
151412: **   start:   Byte offset of the token within the input <string>.
151413: **   end:     Byte offset of the byte immediately following the end of the
151414: **            token within the input string.
151415: **   pos:     Token offset of token within input.
151416: **
151417: */
151418: /* #include "fts3Int.h" */
151419: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151420: 
151421: /* #include <string.h> */
151422: /* #include <assert.h> */
151423: 
151424: typedef struct Fts3tokTable Fts3tokTable;
151425: typedef struct Fts3tokCursor Fts3tokCursor;
151426: 
151427: /*
151428: ** Virtual table structure.
151429: */
151430: struct Fts3tokTable {
151431:   sqlite3_vtab base;              /* Base class used by SQLite core */
151432:   const sqlite3_tokenizer_module *pMod;
151433:   sqlite3_tokenizer *pTok;
151434: };
151435: 
151436: /*
151437: ** Virtual table cursor structure.
151438: */
151439: struct Fts3tokCursor {
151440:   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
151441:   char *zInput;                   /* Input string */
151442:   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
151443:   int iRowid;                     /* Current 'rowid' value */
151444:   const char *zToken;             /* Current 'token' value */
151445:   int nToken;                     /* Size of zToken in bytes */
151446:   int iStart;                     /* Current 'start' value */
151447:   int iEnd;                       /* Current 'end' value */
151448:   int iPos;                       /* Current 'pos' value */
151449: };
151450: 
151451: /*
151452: ** Query FTS for the tokenizer implementation named zName.
151453: */
151454: static int fts3tokQueryTokenizer(
151455:   Fts3Hash *pHash,
151456:   const char *zName,
151457:   const sqlite3_tokenizer_module **pp,
151458:   char **pzErr
151459: ){
151460:   sqlite3_tokenizer_module *p;
151461:   int nName = (int)strlen(zName);
151462: 
151463:   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
151464:   if( !p ){
151465:     sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
151466:     return SQLITE_ERROR;
151467:   }
151468: 
151469:   *pp = p;
151470:   return SQLITE_OK;
151471: }
151472: 
151473: /*
151474: ** The second argument, argv[], is an array of pointers to nul-terminated
151475: ** strings. This function makes a copy of the array and strings into a 
151476: ** single block of memory. It then dequotes any of the strings that appear
151477: ** to be quoted.
151478: **
151479: ** If successful, output parameter *pazDequote is set to point at the
151480: ** array of dequoted strings and SQLITE_OK is returned. The caller is
151481: ** responsible for eventually calling sqlite3_free() to free the array
151482: ** in this case. Or, if an error occurs, an SQLite error code is returned.
151483: ** The final value of *pazDequote is undefined in this case.
151484: */
151485: static int fts3tokDequoteArray(
151486:   int argc,                       /* Number of elements in argv[] */
151487:   const char * const *argv,       /* Input array */
151488:   char ***pazDequote              /* Output array */
151489: ){
151490:   int rc = SQLITE_OK;             /* Return code */
151491:   if( argc==0 ){
151492:     *pazDequote = 0;
151493:   }else{
151494:     int i;
151495:     int nByte = 0;
151496:     char **azDequote;
151497: 
151498:     for(i=0; i<argc; i++){
151499:       nByte += (int)(strlen(argv[i]) + 1);
151500:     }
151501: 
151502:     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
151503:     if( azDequote==0 ){
151504:       rc = SQLITE_NOMEM;
151505:     }else{
151506:       char *pSpace = (char *)&azDequote[argc];
151507:       for(i=0; i<argc; i++){
151508:         int n = (int)strlen(argv[i]);
151509:         azDequote[i] = pSpace;
151510:         memcpy(pSpace, argv[i], n+1);
151511:         sqlite3Fts3Dequote(pSpace);
151512:         pSpace += (n+1);
151513:       }
151514:     }
151515:   }
151516: 
151517:   return rc;
151518: }
151519: 
151520: /*
151521: ** Schema of the tokenizer table.
151522: */
151523: #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
151524: 
151525: /*
151526: ** This function does all the work for both the xConnect and xCreate methods.
151527: ** These tables have no persistent representation of their own, so xConnect
151528: ** and xCreate are identical operations.
151529: **
151530: **   argv[0]: module name
151531: **   argv[1]: database name 
151532: **   argv[2]: table name
151533: **   argv[3]: first argument (tokenizer name)
151534: */
151535: static int fts3tokConnectMethod(
151536:   sqlite3 *db,                    /* Database connection */
151537:   void *pHash,                    /* Hash table of tokenizers */
151538:   int argc,                       /* Number of elements in argv array */
151539:   const char * const *argv,       /* xCreate/xConnect argument array */
151540:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
151541:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
151542: ){
151543:   Fts3tokTable *pTab = 0;
151544:   const sqlite3_tokenizer_module *pMod = 0;
151545:   sqlite3_tokenizer *pTok = 0;
151546:   int rc;
151547:   char **azDequote = 0;
151548:   int nDequote;
151549: 
151550:   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
151551:   if( rc!=SQLITE_OK ) return rc;
151552: 
151553:   nDequote = argc-3;
151554:   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
151555: 
151556:   if( rc==SQLITE_OK ){
151557:     const char *zModule;
151558:     if( nDequote<1 ){
151559:       zModule = "simple";
151560:     }else{
151561:       zModule = azDequote[0];
151562:     }
151563:     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
151564:   }
151565: 
151566:   assert( (rc==SQLITE_OK)==(pMod!=0) );
151567:   if( rc==SQLITE_OK ){
151568:     const char * const *azArg = (const char * const *)&azDequote[1];
151569:     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
151570:   }
151571: 
151572:   if( rc==SQLITE_OK ){
151573:     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
151574:     if( pTab==0 ){
151575:       rc = SQLITE_NOMEM;
151576:     }
151577:   }
151578: 
151579:   if( rc==SQLITE_OK ){
151580:     memset(pTab, 0, sizeof(Fts3tokTable));
151581:     pTab->pMod = pMod;
151582:     pTab->pTok = pTok;
151583:     *ppVtab = &pTab->base;
151584:   }else{
151585:     if( pTok ){
151586:       pMod->xDestroy(pTok);
151587:     }
151588:   }
151589: 
151590:   sqlite3_free(azDequote);
151591:   return rc;
151592: }
151593: 
151594: /*
151595: ** This function does the work for both the xDisconnect and xDestroy methods.
151596: ** These tables have no persistent representation of their own, so xDisconnect
151597: ** and xDestroy are identical operations.
151598: */
151599: static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
151600:   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
151601: 
151602:   pTab->pMod->xDestroy(pTab->pTok);
151603:   sqlite3_free(pTab);
151604:   return SQLITE_OK;
151605: }
151606: 
151607: /*
151608: ** xBestIndex - Analyze a WHERE and ORDER BY clause.
151609: */
151610: static int fts3tokBestIndexMethod(
151611:   sqlite3_vtab *pVTab, 
151612:   sqlite3_index_info *pInfo
151613: ){
151614:   int i;
151615:   UNUSED_PARAMETER(pVTab);
151616: 
151617:   for(i=0; i<pInfo->nConstraint; i++){
151618:     if( pInfo->aConstraint[i].usable 
151619:      && pInfo->aConstraint[i].iColumn==0 
151620:      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ 
151621:     ){
151622:       pInfo->idxNum = 1;
151623:       pInfo->aConstraintUsage[i].argvIndex = 1;
151624:       pInfo->aConstraintUsage[i].omit = 1;
151625:       pInfo->estimatedCost = 1;
151626:       return SQLITE_OK;
151627:     }
151628:   }
151629: 
151630:   pInfo->idxNum = 0;
151631:   assert( pInfo->estimatedCost>1000000.0 );
151632: 
151633:   return SQLITE_OK;
151634: }
151635: 
151636: /*
151637: ** xOpen - Open a cursor.
151638: */
151639: static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
151640:   Fts3tokCursor *pCsr;
151641:   UNUSED_PARAMETER(pVTab);
151642: 
151643:   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
151644:   if( pCsr==0 ){
151645:     return SQLITE_NOMEM;
151646:   }
151647:   memset(pCsr, 0, sizeof(Fts3tokCursor));
151648: 
151649:   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
151650:   return SQLITE_OK;
151651: }
151652: 
151653: /*
151654: ** Reset the tokenizer cursor passed as the only argument. As if it had
151655: ** just been returned by fts3tokOpenMethod().
151656: */
151657: static void fts3tokResetCursor(Fts3tokCursor *pCsr){
151658:   if( pCsr->pCsr ){
151659:     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
151660:     pTab->pMod->xClose(pCsr->pCsr);
151661:     pCsr->pCsr = 0;
151662:   }
151663:   sqlite3_free(pCsr->zInput);
151664:   pCsr->zInput = 0;
151665:   pCsr->zToken = 0;
151666:   pCsr->nToken = 0;
151667:   pCsr->iStart = 0;
151668:   pCsr->iEnd = 0;
151669:   pCsr->iPos = 0;
151670:   pCsr->iRowid = 0;
151671: }
151672: 
151673: /*
151674: ** xClose - Close a cursor.
151675: */
151676: static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
151677:   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151678: 
151679:   fts3tokResetCursor(pCsr);
151680:   sqlite3_free(pCsr);
151681:   return SQLITE_OK;
151682: }
151683: 
151684: /*
151685: ** xNext - Advance the cursor to the next row, if any.
151686: */
151687: static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
151688:   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151689:   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
151690:   int rc;                         /* Return code */
151691: 
151692:   pCsr->iRowid++;
151693:   rc = pTab->pMod->xNext(pCsr->pCsr,
151694:       &pCsr->zToken, &pCsr->nToken,
151695:       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
151696:   );
151697: 
151698:   if( rc!=SQLITE_OK ){
151699:     fts3tokResetCursor(pCsr);
151700:     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
151701:   }
151702: 
151703:   return rc;
151704: }
151705: 
151706: /*
151707: ** xFilter - Initialize a cursor to point at the start of its data.
151708: */
151709: static int fts3tokFilterMethod(
151710:   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
151711:   int idxNum,                     /* Strategy index */
151712:   const char *idxStr,             /* Unused */
151713:   int nVal,                       /* Number of elements in apVal */
151714:   sqlite3_value **apVal           /* Arguments for the indexing scheme */
151715: ){
151716:   int rc = SQLITE_ERROR;
151717:   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151718:   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
151719:   UNUSED_PARAMETER(idxStr);
151720:   UNUSED_PARAMETER(nVal);
151721: 
151722:   fts3tokResetCursor(pCsr);
151723:   if( idxNum==1 ){
151724:     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
151725:     int nByte = sqlite3_value_bytes(apVal[0]);
151726:     pCsr->zInput = sqlite3_malloc(nByte+1);
151727:     if( pCsr->zInput==0 ){
151728:       rc = SQLITE_NOMEM;
151729:     }else{
151730:       memcpy(pCsr->zInput, zByte, nByte);
151731:       pCsr->zInput[nByte] = 0;
151732:       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
151733:       if( rc==SQLITE_OK ){
151734:         pCsr->pCsr->pTokenizer = pTab->pTok;
151735:       }
151736:     }
151737:   }
151738: 
151739:   if( rc!=SQLITE_OK ) return rc;
151740:   return fts3tokNextMethod(pCursor);
151741: }
151742: 
151743: /*
151744: ** xEof - Return true if the cursor is at EOF, or false otherwise.
151745: */
151746: static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
151747:   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151748:   return (pCsr->zToken==0);
151749: }
151750: 
151751: /*
151752: ** xColumn - Return a column value.
151753: */
151754: static int fts3tokColumnMethod(
151755:   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151756:   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
151757:   int iCol                        /* Index of column to read value from */
151758: ){
151759:   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151760: 
151761:   /* CREATE TABLE x(input, token, start, end, position) */
151762:   switch( iCol ){
151763:     case 0:
151764:       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
151765:       break;
151766:     case 1:
151767:       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
151768:       break;
151769:     case 2:
151770:       sqlite3_result_int(pCtx, pCsr->iStart);
151771:       break;
151772:     case 3:
151773:       sqlite3_result_int(pCtx, pCsr->iEnd);
151774:       break;
151775:     default:
151776:       assert( iCol==4 );
151777:       sqlite3_result_int(pCtx, pCsr->iPos);
151778:       break;
151779:   }
151780:   return SQLITE_OK;
151781: }
151782: 
151783: /*
151784: ** xRowid - Return the current rowid for the cursor.
151785: */
151786: static int fts3tokRowidMethod(
151787:   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
151788:   sqlite_int64 *pRowid            /* OUT: Rowid value */
151789: ){
151790:   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
151791:   *pRowid = (sqlite3_int64)pCsr->iRowid;
151792:   return SQLITE_OK;
151793: }
151794: 
151795: /*
151796: ** Register the fts3tok module with database connection db. Return SQLITE_OK
151797: ** if successful or an error code if sqlite3_create_module() fails.
151798: */
151799: SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
151800:   static const sqlite3_module fts3tok_module = {
151801:      0,                           /* iVersion      */
151802:      fts3tokConnectMethod,        /* xCreate       */
151803:      fts3tokConnectMethod,        /* xConnect      */
151804:      fts3tokBestIndexMethod,      /* xBestIndex    */
151805:      fts3tokDisconnectMethod,     /* xDisconnect   */
151806:      fts3tokDisconnectMethod,     /* xDestroy      */
151807:      fts3tokOpenMethod,           /* xOpen         */
151808:      fts3tokCloseMethod,          /* xClose        */
151809:      fts3tokFilterMethod,         /* xFilter       */
151810:      fts3tokNextMethod,           /* xNext         */
151811:      fts3tokEofMethod,            /* xEof          */
151812:      fts3tokColumnMethod,         /* xColumn       */
151813:      fts3tokRowidMethod,          /* xRowid        */
151814:      0,                           /* xUpdate       */
151815:      0,                           /* xBegin        */
151816:      0,                           /* xSync         */
151817:      0,                           /* xCommit       */
151818:      0,                           /* xRollback     */
151819:      0,                           /* xFindFunction */
151820:      0,                           /* xRename       */
151821:      0,                           /* xSavepoint    */
151822:      0,                           /* xRelease      */
151823:      0                            /* xRollbackTo   */
151824:   };
151825:   int rc;                         /* Return code */
151826: 
151827:   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
151828:   return rc;
151829: }
151830: 
151831: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
151832: 
151833: /************** End of fts3_tokenize_vtab.c **********************************/
151834: /************** Begin file fts3_write.c **************************************/
151835: /*
151836: ** 2009 Oct 23
151837: **
151838: ** The author disclaims copyright to this source code.  In place of
151839: ** a legal notice, here is a blessing:
151840: **
151841: **    May you do good and not evil.
151842: **    May you find forgiveness for yourself and forgive others.
151843: **    May you share freely, never taking more than you give.
151844: **
151845: ******************************************************************************
151846: **
151847: ** This file is part of the SQLite FTS3 extension module. Specifically,
151848: ** this file contains code to insert, update and delete rows from FTS3
151849: ** tables. It also contains code to merge FTS3 b-tree segments. Some
151850: ** of the sub-routines used to merge segments are also used by the query 
151851: ** code in fts3.c.
151852: */
151853: 
151854: /* #include "fts3Int.h" */
151855: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
151856: 
151857: /* #include <string.h> */
151858: /* #include <assert.h> */
151859: /* #include <stdlib.h> */
151860: 
151861: 
151862: #define FTS_MAX_APPENDABLE_HEIGHT 16
151863: 
151864: /*
151865: ** When full-text index nodes are loaded from disk, the buffer that they
151866: ** are loaded into has the following number of bytes of padding at the end 
151867: ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
151868: ** of 920 bytes is allocated for it.
151869: **
151870: ** This means that if we have a pointer into a buffer containing node data,
151871: ** it is always safe to read up to two varints from it without risking an
151872: ** overread, even if the node data is corrupted.
151873: */
151874: #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
151875: 
151876: /*
151877: ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
151878: ** memory incrementally instead of all at once. This can be a big performance
151879: ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
151880: ** method before retrieving all query results (as may happen, for example,
151881: ** if a query has a LIMIT clause).
151882: **
151883: ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
151884: ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
151885: ** The code is written so that the hard lower-limit for each of these values 
151886: ** is 1. Clearly such small values would be inefficient, but can be useful 
151887: ** for testing purposes.
151888: **
151889: ** If this module is built with SQLITE_TEST defined, these constants may
151890: ** be overridden at runtime for testing purposes. File fts3_test.c contains
151891: ** a Tcl interface to read and write the values.
151892: */
151893: #ifdef SQLITE_TEST
151894: int test_fts3_node_chunksize = (4*1024);
151895: int test_fts3_node_chunk_threshold = (4*1024)*4;
151896: # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
151897: # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
151898: #else
151899: # define FTS3_NODE_CHUNKSIZE (4*1024) 
151900: # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
151901: #endif
151902: 
151903: /*
151904: ** The two values that may be meaningfully bound to the :1 parameter in
151905: ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
151906: */
151907: #define FTS_STAT_DOCTOTAL      0
151908: #define FTS_STAT_INCRMERGEHINT 1
151909: #define FTS_STAT_AUTOINCRMERGE 2
151910: 
151911: /*
151912: ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
151913: ** and incremental merge operation that takes place. This is used for 
151914: ** debugging FTS only, it should not usually be turned on in production
151915: ** systems.
151916: */
151917: #ifdef FTS3_LOG_MERGES
151918: static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
151919:   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
151920: }
151921: #else
151922: #define fts3LogMerge(x, y)
151923: #endif
151924: 
151925: 
151926: typedef struct PendingList PendingList;
151927: typedef struct SegmentNode SegmentNode;
151928: typedef struct SegmentWriter SegmentWriter;
151929: 
151930: /*
151931: ** An instance of the following data structure is used to build doclists
151932: ** incrementally. See function fts3PendingListAppend() for details.
151933: */
151934: struct PendingList {
151935:   int nData;
151936:   char *aData;
151937:   int nSpace;
151938:   sqlite3_int64 iLastDocid;
151939:   sqlite3_int64 iLastCol;
151940:   sqlite3_int64 iLastPos;
151941: };
151942: 
151943: 
151944: /*
151945: ** Each cursor has a (possibly empty) linked list of the following objects.
151946: */
151947: struct Fts3DeferredToken {
151948:   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
151949:   int iCol;                       /* Column token must occur in */
151950:   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
151951:   PendingList *pList;             /* Doclist is assembled here */
151952: };
151953: 
151954: /*
151955: ** An instance of this structure is used to iterate through the terms on
151956: ** a contiguous set of segment b-tree leaf nodes. Although the details of
151957: ** this structure are only manipulated by code in this file, opaque handles
151958: ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
151959: ** terms when querying the full-text index. See functions:
151960: **
151961: **   sqlite3Fts3SegReaderNew()
151962: **   sqlite3Fts3SegReaderFree()
151963: **   sqlite3Fts3SegReaderIterate()
151964: **
151965: ** Methods used to manipulate Fts3SegReader structures:
151966: **
151967: **   fts3SegReaderNext()
151968: **   fts3SegReaderFirstDocid()
151969: **   fts3SegReaderNextDocid()
151970: */
151971: struct Fts3SegReader {
151972:   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
151973:   u8 bLookup;                     /* True for a lookup only */
151974:   u8 rootOnly;                    /* True for a root-only reader */
151975: 
151976:   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
151977:   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
151978:   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
151979:   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
151980: 
151981:   char *aNode;                    /* Pointer to node data (or NULL) */
151982:   int nNode;                      /* Size of buffer at aNode (or 0) */
151983:   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
151984:   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
151985: 
151986:   Fts3HashElem **ppNextElem;
151987: 
151988:   /* Variables set by fts3SegReaderNext(). These may be read directly
151989:   ** by the caller. They are valid from the time SegmentReaderNew() returns
151990:   ** until SegmentReaderNext() returns something other than SQLITE_OK
151991:   ** (i.e. SQLITE_DONE).
151992:   */
151993:   int nTerm;                      /* Number of bytes in current term */
151994:   char *zTerm;                    /* Pointer to current term */
151995:   int nTermAlloc;                 /* Allocated size of zTerm buffer */
151996:   char *aDoclist;                 /* Pointer to doclist of current entry */
151997:   int nDoclist;                   /* Size of doclist in current entry */
151998: 
151999:   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
152000:   ** through the current doclist (aDoclist/nDoclist).
152001:   */
152002:   char *pOffsetList;
152003:   int nOffsetList;                /* For descending pending seg-readers only */
152004:   sqlite3_int64 iDocid;
152005: };
152006: 
152007: #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
152008: #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
152009: 
152010: /*
152011: ** An instance of this structure is used to create a segment b-tree in the
152012: ** database. The internal details of this type are only accessed by the
152013: ** following functions:
152014: **
152015: **   fts3SegWriterAdd()
152016: **   fts3SegWriterFlush()
152017: **   fts3SegWriterFree()
152018: */
152019: struct SegmentWriter {
152020:   SegmentNode *pTree;             /* Pointer to interior tree structure */
152021:   sqlite3_int64 iFirst;           /* First slot in %_segments written */
152022:   sqlite3_int64 iFree;            /* Next free slot in %_segments */
152023:   char *zTerm;                    /* Pointer to previous term buffer */
152024:   int nTerm;                      /* Number of bytes in zTerm */
152025:   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
152026:   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
152027:   int nSize;                      /* Size of allocation at aData */
152028:   int nData;                      /* Bytes of data in aData */
152029:   char *aData;                    /* Pointer to block from malloc() */
152030:   i64 nLeafData;                  /* Number of bytes of leaf data written */
152031: };
152032: 
152033: /*
152034: ** Type SegmentNode is used by the following three functions to create
152035: ** the interior part of the segment b+-tree structures (everything except
152036: ** the leaf nodes). These functions and type are only ever used by code
152037: ** within the fts3SegWriterXXX() family of functions described above.
152038: **
152039: **   fts3NodeAddTerm()
152040: **   fts3NodeWrite()
152041: **   fts3NodeFree()
152042: **
152043: ** When a b+tree is written to the database (either as a result of a merge
152044: ** or the pending-terms table being flushed), leaves are written into the 
152045: ** database file as soon as they are completely populated. The interior of
152046: ** the tree is assembled in memory and written out only once all leaves have
152047: ** been populated and stored. This is Ok, as the b+-tree fanout is usually
152048: ** very large, meaning that the interior of the tree consumes relatively 
152049: ** little memory.
152050: */
152051: struct SegmentNode {
152052:   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
152053:   SegmentNode *pRight;            /* Pointer to right-sibling */
152054:   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
152055:   int nEntry;                     /* Number of terms written to node so far */
152056:   char *zTerm;                    /* Pointer to previous term buffer */
152057:   int nTerm;                      /* Number of bytes in zTerm */
152058:   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
152059:   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
152060:   int nData;                      /* Bytes of valid data so far */
152061:   char *aData;                    /* Node data */
152062: };
152063: 
152064: /*
152065: ** Valid values for the second argument to fts3SqlStmt().
152066: */
152067: #define SQL_DELETE_CONTENT             0
152068: #define SQL_IS_EMPTY                   1
152069: #define SQL_DELETE_ALL_CONTENT         2 
152070: #define SQL_DELETE_ALL_SEGMENTS        3
152071: #define SQL_DELETE_ALL_SEGDIR          4
152072: #define SQL_DELETE_ALL_DOCSIZE         5
152073: #define SQL_DELETE_ALL_STAT            6
152074: #define SQL_SELECT_CONTENT_BY_ROWID    7
152075: #define SQL_NEXT_SEGMENT_INDEX         8
152076: #define SQL_INSERT_SEGMENTS            9
152077: #define SQL_NEXT_SEGMENTS_ID          10
152078: #define SQL_INSERT_SEGDIR             11
152079: #define SQL_SELECT_LEVEL              12
152080: #define SQL_SELECT_LEVEL_RANGE        13
152081: #define SQL_SELECT_LEVEL_COUNT        14
152082: #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
152083: #define SQL_DELETE_SEGDIR_LEVEL       16
152084: #define SQL_DELETE_SEGMENTS_RANGE     17
152085: #define SQL_CONTENT_INSERT            18
152086: #define SQL_DELETE_DOCSIZE            19
152087: #define SQL_REPLACE_DOCSIZE           20
152088: #define SQL_SELECT_DOCSIZE            21
152089: #define SQL_SELECT_STAT               22
152090: #define SQL_REPLACE_STAT              23
152091: 
152092: #define SQL_SELECT_ALL_PREFIX_LEVEL   24
152093: #define SQL_DELETE_ALL_TERMS_SEGDIR   25
152094: #define SQL_DELETE_SEGDIR_RANGE       26
152095: #define SQL_SELECT_ALL_LANGID         27
152096: #define SQL_FIND_MERGE_LEVEL          28
152097: #define SQL_MAX_LEAF_NODE_ESTIMATE    29
152098: #define SQL_DELETE_SEGDIR_ENTRY       30
152099: #define SQL_SHIFT_SEGDIR_ENTRY        31
152100: #define SQL_SELECT_SEGDIR             32
152101: #define SQL_CHOMP_SEGDIR              33
152102: #define SQL_SEGMENT_IS_APPENDABLE     34
152103: #define SQL_SELECT_INDEXES            35
152104: #define SQL_SELECT_MXLEVEL            36
152105: 
152106: #define SQL_SELECT_LEVEL_RANGE2       37
152107: #define SQL_UPDATE_LEVEL_IDX          38
152108: #define SQL_UPDATE_LEVEL              39
152109: 
152110: /*
152111: ** This function is used to obtain an SQLite prepared statement handle
152112: ** for the statement identified by the second argument. If successful,
152113: ** *pp is set to the requested statement handle and SQLITE_OK returned.
152114: ** Otherwise, an SQLite error code is returned and *pp is set to 0.
152115: **
152116: ** If argument apVal is not NULL, then it must point to an array with
152117: ** at least as many entries as the requested statement has bound 
152118: ** parameters. The values are bound to the statements parameters before
152119: ** returning.
152120: */
152121: static int fts3SqlStmt(
152122:   Fts3Table *p,                   /* Virtual table handle */
152123:   int eStmt,                      /* One of the SQL_XXX constants above */
152124:   sqlite3_stmt **pp,              /* OUT: Statement handle */
152125:   sqlite3_value **apVal           /* Values to bind to statement */
152126: ){
152127:   const char *azSql[] = {
152128: /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
152129: /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
152130: /* 2  */  "DELETE FROM %Q.'%q_content'",
152131: /* 3  */  "DELETE FROM %Q.'%q_segments'",
152132: /* 4  */  "DELETE FROM %Q.'%q_segdir'",
152133: /* 5  */  "DELETE FROM %Q.'%q_docsize'",
152134: /* 6  */  "DELETE FROM %Q.'%q_stat'",
152135: /* 7  */  "SELECT %s WHERE rowid=?",
152136: /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
152137: /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
152138: /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
152139: /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
152140: 
152141:           /* Return segments in order from oldest to newest.*/ 
152142: /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152143:             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
152144: /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152145:             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
152146:             "ORDER BY level DESC, idx ASC",
152147: 
152148: /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
152149: /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
152150: 
152151: /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
152152: /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
152153: /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
152154: /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
152155: /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
152156: /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
152157: /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
152158: /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
152159: /* 24 */  "",
152160: /* 25 */  "",
152161: 
152162: /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
152163: /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
152164: 
152165: /* This statement is used to determine which level to read the input from
152166: ** when performing an incremental merge. It returns the absolute level number
152167: ** of the oldest level in the db that contains at least ? segments. Or,
152168: ** if no level in the FTS index contains more than ? segments, the statement
152169: ** returns zero rows.  */
152170: /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
152171:          "  GROUP BY level HAVING cnt>=?"
152172:          "  ORDER BY (level %% 1024) ASC LIMIT 1",
152173: 
152174: /* Estimate the upper limit on the number of leaf nodes in a new segment
152175: ** created by merging the oldest :2 segments from absolute level :1. See 
152176: ** function sqlite3Fts3Incrmerge() for details.  */
152177: /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
152178:          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
152179: 
152180: /* SQL_DELETE_SEGDIR_ENTRY
152181: **   Delete the %_segdir entry on absolute level :1 with index :2.  */
152182: /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
152183: 
152184: /* SQL_SHIFT_SEGDIR_ENTRY
152185: **   Modify the idx value for the segment with idx=:3 on absolute level :2
152186: **   to :1.  */
152187: /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
152188: 
152189: /* SQL_SELECT_SEGDIR
152190: **   Read a single entry from the %_segdir table. The entry from absolute 
152191: **   level :1 with index value :2.  */
152192: /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
152193:             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
152194: 
152195: /* SQL_CHOMP_SEGDIR
152196: **   Update the start_block (:1) and root (:2) fields of the %_segdir
152197: **   entry located on absolute level :3 with index :4.  */
152198: /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
152199:             "WHERE level = ? AND idx = ?",
152200: 
152201: /* SQL_SEGMENT_IS_APPENDABLE
152202: **   Return a single row if the segment with end_block=? is appendable. Or
152203: **   no rows otherwise.  */
152204: /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
152205: 
152206: /* SQL_SELECT_INDEXES
152207: **   Return the list of valid segment indexes for absolute level ?  */
152208: /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
152209: 
152210: /* SQL_SELECT_MXLEVEL
152211: **   Return the largest relative level in the FTS index or indexes.  */
152212: /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
152213: 
152214:           /* Return segments in order from oldest to newest.*/ 
152215: /* 37 */  "SELECT level, idx, end_block "
152216:             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
152217:             "ORDER BY level DESC, idx ASC",
152218: 
152219:           /* Update statements used while promoting segments */
152220: /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
152221:             "WHERE level=? AND idx=?",
152222: /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
152223: 
152224:   };
152225:   int rc = SQLITE_OK;
152226:   sqlite3_stmt *pStmt;
152227: 
152228:   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
152229:   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
152230:   
152231:   pStmt = p->aStmt[eStmt];
152232:   if( !pStmt ){
152233:     char *zSql;
152234:     if( eStmt==SQL_CONTENT_INSERT ){
152235:       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
152236:     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
152237:       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
152238:     }else{
152239:       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
152240:     }
152241:     if( !zSql ){
152242:       rc = SQLITE_NOMEM;
152243:     }else{
152244:       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
152245:       sqlite3_free(zSql);
152246:       assert( rc==SQLITE_OK || pStmt==0 );
152247:       p->aStmt[eStmt] = pStmt;
152248:     }
152249:   }
152250:   if( apVal ){
152251:     int i;
152252:     int nParam = sqlite3_bind_parameter_count(pStmt);
152253:     for(i=0; rc==SQLITE_OK && i<nParam; i++){
152254:       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
152255:     }
152256:   }
152257:   *pp = pStmt;
152258:   return rc;
152259: }
152260: 
152261: 
152262: static int fts3SelectDocsize(
152263:   Fts3Table *pTab,                /* FTS3 table handle */
152264:   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
152265:   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152266: ){
152267:   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
152268:   int rc;                         /* Return code */
152269: 
152270:   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
152271:   if( rc==SQLITE_OK ){
152272:     sqlite3_bind_int64(pStmt, 1, iDocid);
152273:     rc = sqlite3_step(pStmt);
152274:     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
152275:       rc = sqlite3_reset(pStmt);
152276:       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
152277:       pStmt = 0;
152278:     }else{
152279:       rc = SQLITE_OK;
152280:     }
152281:   }
152282: 
152283:   *ppStmt = pStmt;
152284:   return rc;
152285: }
152286: 
152287: SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
152288:   Fts3Table *pTab,                /* Fts3 table handle */
152289:   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152290: ){
152291:   sqlite3_stmt *pStmt = 0;
152292:   int rc;
152293:   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
152294:   if( rc==SQLITE_OK ){
152295:     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
152296:     if( sqlite3_step(pStmt)!=SQLITE_ROW
152297:      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
152298:     ){
152299:       rc = sqlite3_reset(pStmt);
152300:       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
152301:       pStmt = 0;
152302:     }
152303:   }
152304:   *ppStmt = pStmt;
152305:   return rc;
152306: }
152307: 
152308: SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
152309:   Fts3Table *pTab,                /* Fts3 table handle */
152310:   sqlite3_int64 iDocid,           /* Docid to read size data for */
152311:   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
152312: ){
152313:   return fts3SelectDocsize(pTab, iDocid, ppStmt);
152314: }
152315: 
152316: /*
152317: ** Similar to fts3SqlStmt(). Except, after binding the parameters in
152318: ** array apVal[] to the SQL statement identified by eStmt, the statement
152319: ** is executed.
152320: **
152321: ** Returns SQLITE_OK if the statement is successfully executed, or an
152322: ** SQLite error code otherwise.
152323: */
152324: static void fts3SqlExec(
152325:   int *pRC,                /* Result code */
152326:   Fts3Table *p,            /* The FTS3 table */
152327:   int eStmt,               /* Index of statement to evaluate */
152328:   sqlite3_value **apVal    /* Parameters to bind */
152329: ){
152330:   sqlite3_stmt *pStmt;
152331:   int rc;
152332:   if( *pRC ) return;
152333:   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
152334:   if( rc==SQLITE_OK ){
152335:     sqlite3_step(pStmt);
152336:     rc = sqlite3_reset(pStmt);
152337:   }
152338:   *pRC = rc;
152339: }
152340: 
152341: 
152342: /*
152343: ** This function ensures that the caller has obtained an exclusive 
152344: ** shared-cache table-lock on the %_segdir table. This is required before 
152345: ** writing data to the fts3 table. If this lock is not acquired first, then
152346: ** the caller may end up attempting to take this lock as part of committing
152347: ** a transaction, causing SQLite to return SQLITE_LOCKED or 
152348: ** LOCKED_SHAREDCACHEto a COMMIT command.
152349: **
152350: ** It is best to avoid this because if FTS3 returns any error when 
152351: ** committing a transaction, the whole transaction will be rolled back. 
152352: ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. 
152353: ** It can still happen if the user locks the underlying tables directly 
152354: ** instead of accessing them via FTS.
152355: */
152356: static int fts3Writelock(Fts3Table *p){
152357:   int rc = SQLITE_OK;
152358:   
152359:   if( p->nPendingData==0 ){
152360:     sqlite3_stmt *pStmt;
152361:     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
152362:     if( rc==SQLITE_OK ){
152363:       sqlite3_bind_null(pStmt, 1);
152364:       sqlite3_step(pStmt);
152365:       rc = sqlite3_reset(pStmt);
152366:     }
152367:   }
152368: 
152369:   return rc;
152370: }
152371: 
152372: /*
152373: ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
152374: ** Within each language id, a separate index is maintained to store the
152375: ** document terms, and each configured prefix size (configured the FTS 
152376: ** "prefix=" option). And each index consists of multiple levels ("relative
152377: ** levels").
152378: **
152379: ** All three of these values (the language id, the specific index and the
152380: ** level within the index) are encoded in 64-bit integer values stored
152381: ** in the %_segdir table on disk. This function is used to convert three
152382: ** separate component values into the single 64-bit integer value that
152383: ** can be used to query the %_segdir table.
152384: **
152385: ** Specifically, each language-id/index combination is allocated 1024 
152386: ** 64-bit integer level values ("absolute levels"). The main terms index
152387: ** for language-id 0 is allocate values 0-1023. The first prefix index
152388: ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
152389: ** Language 1 indexes are allocated immediately following language 0.
152390: **
152391: ** So, for a system with nPrefix prefix indexes configured, the block of
152392: ** absolute levels that corresponds to language-id iLangid and index 
152393: ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
152394: */
152395: static sqlite3_int64 getAbsoluteLevel(
152396:   Fts3Table *p,                   /* FTS3 table handle */
152397:   int iLangid,                    /* Language id */
152398:   int iIndex,                     /* Index in p->aIndex[] */
152399:   int iLevel                      /* Level of segments */
152400: ){
152401:   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
152402:   assert( iLangid>=0 );
152403:   assert( p->nIndex>0 );
152404:   assert( iIndex>=0 && iIndex<p->nIndex );
152405: 
152406:   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
152407:   return iBase + iLevel;
152408: }
152409: 
152410: /*
152411: ** Set *ppStmt to a statement handle that may be used to iterate through
152412: ** all rows in the %_segdir table, from oldest to newest. If successful,
152413: ** return SQLITE_OK. If an error occurs while preparing the statement, 
152414: ** return an SQLite error code.
152415: **
152416: ** There is only ever one instance of this SQL statement compiled for
152417: ** each FTS3 table.
152418: **
152419: ** The statement returns the following columns from the %_segdir table:
152420: **
152421: **   0: idx
152422: **   1: start_block
152423: **   2: leaves_end_block
152424: **   3: end_block
152425: **   4: root
152426: */
152427: SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
152428:   Fts3Table *p,                   /* FTS3 table */
152429:   int iLangid,                    /* Language being queried */
152430:   int iIndex,                     /* Index for p->aIndex[] */
152431:   int iLevel,                     /* Level to select (relative level) */
152432:   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
152433: ){
152434:   int rc;
152435:   sqlite3_stmt *pStmt = 0;
152436: 
152437:   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
152438:   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
152439:   assert( iIndex>=0 && iIndex<p->nIndex );
152440: 
152441:   if( iLevel<0 ){
152442:     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
152443:     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
152444:     if( rc==SQLITE_OK ){ 
152445:       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
152446:       sqlite3_bind_int64(pStmt, 2, 
152447:           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
152448:       );
152449:     }
152450:   }else{
152451:     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
152452:     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
152453:     if( rc==SQLITE_OK ){ 
152454:       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
152455:     }
152456:   }
152457:   *ppStmt = pStmt;
152458:   return rc;
152459: }
152460: 
152461: 
152462: /*
152463: ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
152464: ** if successful, or an SQLite error code otherwise.
152465: **
152466: ** This function also serves to allocate the PendingList structure itself.
152467: ** For example, to create a new PendingList structure containing two
152468: ** varints:
152469: **
152470: **   PendingList *p = 0;
152471: **   fts3PendingListAppendVarint(&p, 1);
152472: **   fts3PendingListAppendVarint(&p, 2);
152473: */
152474: static int fts3PendingListAppendVarint(
152475:   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
152476:   sqlite3_int64 i                 /* Value to append to data */
152477: ){
152478:   PendingList *p = *pp;
152479: 
152480:   /* Allocate or grow the PendingList as required. */
152481:   if( !p ){
152482:     p = sqlite3_malloc(sizeof(*p) + 100);
152483:     if( !p ){
152484:       return SQLITE_NOMEM;
152485:     }
152486:     p->nSpace = 100;
152487:     p->aData = (char *)&p[1];
152488:     p->nData = 0;
152489:   }
152490:   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
152491:     int nNew = p->nSpace * 2;
152492:     p = sqlite3_realloc(p, sizeof(*p) + nNew);
152493:     if( !p ){
152494:       sqlite3_free(*pp);
152495:       *pp = 0;
152496:       return SQLITE_NOMEM;
152497:     }
152498:     p->nSpace = nNew;
152499:     p->aData = (char *)&p[1];
152500:   }
152501: 
152502:   /* Append the new serialized varint to the end of the list. */
152503:   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
152504:   p->aData[p->nData] = '\0';
152505:   *pp = p;
152506:   return SQLITE_OK;
152507: }
152508: 
152509: /*
152510: ** Add a docid/column/position entry to a PendingList structure. Non-zero
152511: ** is returned if the structure is sqlite3_realloced as part of adding
152512: ** the entry. Otherwise, zero.
152513: **
152514: ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
152515: ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
152516: ** it is set to SQLITE_OK.
152517: */
152518: static int fts3PendingListAppend(
152519:   PendingList **pp,               /* IN/OUT: PendingList structure */
152520:   sqlite3_int64 iDocid,           /* Docid for entry to add */
152521:   sqlite3_int64 iCol,             /* Column for entry to add */
152522:   sqlite3_int64 iPos,             /* Position of term for entry to add */
152523:   int *pRc                        /* OUT: Return code */
152524: ){
152525:   PendingList *p = *pp;
152526:   int rc = SQLITE_OK;
152527: 
152528:   assert( !p || p->iLastDocid<=iDocid );
152529: 
152530:   if( !p || p->iLastDocid!=iDocid ){
152531:     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
152532:     if( p ){
152533:       assert( p->nData<p->nSpace );
152534:       assert( p->aData[p->nData]==0 );
152535:       p->nData++;
152536:     }
152537:     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
152538:       goto pendinglistappend_out;
152539:     }
152540:     p->iLastCol = -1;
152541:     p->iLastPos = 0;
152542:     p->iLastDocid = iDocid;
152543:   }
152544:   if( iCol>0 && p->iLastCol!=iCol ){
152545:     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
152546:      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
152547:     ){
152548:       goto pendinglistappend_out;
152549:     }
152550:     p->iLastCol = iCol;
152551:     p->iLastPos = 0;
152552:   }
152553:   if( iCol>=0 ){
152554:     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
152555:     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
152556:     if( rc==SQLITE_OK ){
152557:       p->iLastPos = iPos;
152558:     }
152559:   }
152560: 
152561:  pendinglistappend_out:
152562:   *pRc = rc;
152563:   if( p!=*pp ){
152564:     *pp = p;
152565:     return 1;
152566:   }
152567:   return 0;
152568: }
152569: 
152570: /*
152571: ** Free a PendingList object allocated by fts3PendingListAppend().
152572: */
152573: static void fts3PendingListDelete(PendingList *pList){
152574:   sqlite3_free(pList);
152575: }
152576: 
152577: /*
152578: ** Add an entry to one of the pending-terms hash tables.
152579: */
152580: static int fts3PendingTermsAddOne(
152581:   Fts3Table *p,
152582:   int iCol,
152583:   int iPos,
152584:   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
152585:   const char *zToken,
152586:   int nToken
152587: ){
152588:   PendingList *pList;
152589:   int rc = SQLITE_OK;
152590: 
152591:   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
152592:   if( pList ){
152593:     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
152594:   }
152595:   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
152596:     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
152597:       /* Malloc failed while inserting the new entry. This can only 
152598:       ** happen if there was no previous entry for this token.
152599:       */
152600:       assert( 0==fts3HashFind(pHash, zToken, nToken) );
152601:       sqlite3_free(pList);
152602:       rc = SQLITE_NOMEM;
152603:     }
152604:   }
152605:   if( rc==SQLITE_OK ){
152606:     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
152607:   }
152608:   return rc;
152609: }
152610: 
152611: /*
152612: ** Tokenize the nul-terminated string zText and add all tokens to the
152613: ** pending-terms hash-table. The docid used is that currently stored in
152614: ** p->iPrevDocid, and the column is specified by argument iCol.
152615: **
152616: ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
152617: */
152618: static int fts3PendingTermsAdd(
152619:   Fts3Table *p,                   /* Table into which text will be inserted */
152620:   int iLangid,                    /* Language id to use */
152621:   const char *zText,              /* Text of document to be inserted */
152622:   int iCol,                       /* Column into which text is being inserted */
152623:   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
152624: ){
152625:   int rc;
152626:   int iStart = 0;
152627:   int iEnd = 0;
152628:   int iPos = 0;
152629:   int nWord = 0;
152630: 
152631:   char const *zToken;
152632:   int nToken = 0;
152633: 
152634:   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
152635:   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
152636:   sqlite3_tokenizer_cursor *pCsr;
152637:   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
152638:       const char**,int*,int*,int*,int*);
152639: 
152640:   assert( pTokenizer && pModule );
152641: 
152642:   /* If the user has inserted a NULL value, this function may be called with
152643:   ** zText==0. In this case, add zero token entries to the hash table and 
152644:   ** return early. */
152645:   if( zText==0 ){
152646:     *pnWord = 0;
152647:     return SQLITE_OK;
152648:   }
152649: 
152650:   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
152651:   if( rc!=SQLITE_OK ){
152652:     return rc;
152653:   }
152654: 
152655:   xNext = pModule->xNext;
152656:   while( SQLITE_OK==rc
152657:       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
152658:   ){
152659:     int i;
152660:     if( iPos>=nWord ) nWord = iPos+1;
152661: 
152662:     /* Positions cannot be negative; we use -1 as a terminator internally.
152663:     ** Tokens must have a non-zero length.
152664:     */
152665:     if( iPos<0 || !zToken || nToken<=0 ){
152666:       rc = SQLITE_ERROR;
152667:       break;
152668:     }
152669: 
152670:     /* Add the term to the terms index */
152671:     rc = fts3PendingTermsAddOne(
152672:         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
152673:     );
152674:     
152675:     /* Add the term to each of the prefix indexes that it is not too 
152676:     ** short for. */
152677:     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
152678:       struct Fts3Index *pIndex = &p->aIndex[i];
152679:       if( nToken<pIndex->nPrefix ) continue;
152680:       rc = fts3PendingTermsAddOne(
152681:           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
152682:       );
152683:     }
152684:   }
152685: 
152686:   pModule->xClose(pCsr);
152687:   *pnWord += nWord;
152688:   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
152689: }
152690: 
152691: /* 
152692: ** Calling this function indicates that subsequent calls to 
152693: ** fts3PendingTermsAdd() are to add term/position-list pairs for the
152694: ** contents of the document with docid iDocid.
152695: */
152696: static int fts3PendingTermsDocid(
152697:   Fts3Table *p,                   /* Full-text table handle */
152698:   int bDelete,                    /* True if this op is a delete */
152699:   int iLangid,                    /* Language id of row being written */
152700:   sqlite_int64 iDocid             /* Docid of row being written */
152701: ){
152702:   assert( iLangid>=0 );
152703:   assert( bDelete==1 || bDelete==0 );
152704: 
152705:   /* TODO(shess) Explore whether partially flushing the buffer on
152706:   ** forced-flush would provide better performance.  I suspect that if
152707:   ** we ordered the doclists by size and flushed the largest until the
152708:   ** buffer was half empty, that would let the less frequent terms
152709:   ** generate longer doclists.
152710:   */
152711:   if( iDocid<p->iPrevDocid 
152712:    || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
152713:    || p->iPrevLangid!=iLangid
152714:    || p->nPendingData>p->nMaxPendingData 
152715:   ){
152716:     int rc = sqlite3Fts3PendingTermsFlush(p);
152717:     if( rc!=SQLITE_OK ) return rc;
152718:   }
152719:   p->iPrevDocid = iDocid;
152720:   p->iPrevLangid = iLangid;
152721:   p->bPrevDelete = bDelete;
152722:   return SQLITE_OK;
152723: }
152724: 
152725: /*
152726: ** Discard the contents of the pending-terms hash tables. 
152727: */
152728: SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
152729:   int i;
152730:   for(i=0; i<p->nIndex; i++){
152731:     Fts3HashElem *pElem;
152732:     Fts3Hash *pHash = &p->aIndex[i].hPending;
152733:     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
152734:       PendingList *pList = (PendingList *)fts3HashData(pElem);
152735:       fts3PendingListDelete(pList);
152736:     }
152737:     fts3HashClear(pHash);
152738:   }
152739:   p->nPendingData = 0;
152740: }
152741: 
152742: /*
152743: ** This function is called by the xUpdate() method as part of an INSERT
152744: ** operation. It adds entries for each term in the new record to the
152745: ** pendingTerms hash table.
152746: **
152747: ** Argument apVal is the same as the similarly named argument passed to
152748: ** fts3InsertData(). Parameter iDocid is the docid of the new row.
152749: */
152750: static int fts3InsertTerms(
152751:   Fts3Table *p, 
152752:   int iLangid, 
152753:   sqlite3_value **apVal, 
152754:   u32 *aSz
152755: ){
152756:   int i;                          /* Iterator variable */
152757:   for(i=2; i<p->nColumn+2; i++){
152758:     int iCol = i-2;
152759:     if( p->abNotindexed[iCol]==0 ){
152760:       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
152761:       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
152762:       if( rc!=SQLITE_OK ){
152763:         return rc;
152764:       }
152765:       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
152766:     }
152767:   }
152768:   return SQLITE_OK;
152769: }
152770: 
152771: /*
152772: ** This function is called by the xUpdate() method for an INSERT operation.
152773: ** The apVal parameter is passed a copy of the apVal argument passed by
152774: ** SQLite to the xUpdate() method. i.e:
152775: **
152776: **   apVal[0]                Not used for INSERT.
152777: **   apVal[1]                rowid
152778: **   apVal[2]                Left-most user-defined column
152779: **   ...
152780: **   apVal[p->nColumn+1]     Right-most user-defined column
152781: **   apVal[p->nColumn+2]     Hidden column with same name as table
152782: **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
152783: **   apVal[p->nColumn+4]     Hidden languageid column
152784: */
152785: static int fts3InsertData(
152786:   Fts3Table *p,                   /* Full-text table */
152787:   sqlite3_value **apVal,          /* Array of values to insert */
152788:   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
152789: ){
152790:   int rc;                         /* Return code */
152791:   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
152792: 
152793:   if( p->zContentTbl ){
152794:     sqlite3_value *pRowid = apVal[p->nColumn+3];
152795:     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
152796:       pRowid = apVal[1];
152797:     }
152798:     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
152799:       return SQLITE_CONSTRAINT;
152800:     }
152801:     *piDocid = sqlite3_value_int64(pRowid);
152802:     return SQLITE_OK;
152803:   }
152804: 
152805:   /* Locate the statement handle used to insert data into the %_content
152806:   ** table. The SQL for this statement is:
152807:   **
152808:   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
152809:   **
152810:   ** The statement features N '?' variables, where N is the number of user
152811:   ** defined columns in the FTS3 table, plus one for the docid field.
152812:   */
152813:   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
152814:   if( rc==SQLITE_OK && p->zLanguageid ){
152815:     rc = sqlite3_bind_int(
152816:         pContentInsert, p->nColumn+2, 
152817:         sqlite3_value_int(apVal[p->nColumn+4])
152818:     );
152819:   }
152820:   if( rc!=SQLITE_OK ) return rc;
152821: 
152822:   /* There is a quirk here. The users INSERT statement may have specified
152823:   ** a value for the "rowid" field, for the "docid" field, or for both.
152824:   ** Which is a problem, since "rowid" and "docid" are aliases for the
152825:   ** same value. For example:
152826:   **
152827:   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
152828:   **
152829:   ** In FTS3, this is an error. It is an error to specify non-NULL values
152830:   ** for both docid and some other rowid alias.
152831:   */
152832:   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
152833:     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
152834:      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
152835:     ){
152836:       /* A rowid/docid conflict. */
152837:       return SQLITE_ERROR;
152838:     }
152839:     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
152840:     if( rc!=SQLITE_OK ) return rc;
152841:   }
152842: 
152843:   /* Execute the statement to insert the record. Set *piDocid to the 
152844:   ** new docid value. 
152845:   */
152846:   sqlite3_step(pContentInsert);
152847:   rc = sqlite3_reset(pContentInsert);
152848: 
152849:   *piDocid = sqlite3_last_insert_rowid(p->db);
152850:   return rc;
152851: }
152852: 
152853: 
152854: 
152855: /*
152856: ** Remove all data from the FTS3 table. Clear the hash table containing
152857: ** pending terms.
152858: */
152859: static int fts3DeleteAll(Fts3Table *p, int bContent){
152860:   int rc = SQLITE_OK;             /* Return code */
152861: 
152862:   /* Discard the contents of the pending-terms hash table. */
152863:   sqlite3Fts3PendingTermsClear(p);
152864: 
152865:   /* Delete everything from the shadow tables. Except, leave %_content as
152866:   ** is if bContent is false.  */
152867:   assert( p->zContentTbl==0 || bContent==0 );
152868:   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
152869:   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
152870:   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
152871:   if( p->bHasDocsize ){
152872:     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
152873:   }
152874:   if( p->bHasStat ){
152875:     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
152876:   }
152877:   return rc;
152878: }
152879: 
152880: /*
152881: **
152882: */
152883: static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
152884:   int iLangid = 0;
152885:   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
152886:   return iLangid;
152887: }
152888: 
152889: /*
152890: ** The first element in the apVal[] array is assumed to contain the docid
152891: ** (an integer) of a row about to be deleted. Remove all terms from the
152892: ** full-text index.
152893: */
152894: static void fts3DeleteTerms( 
152895:   int *pRC,               /* Result code */
152896:   Fts3Table *p,           /* The FTS table to delete from */
152897:   sqlite3_value *pRowid,  /* The docid to be deleted */
152898:   u32 *aSz,               /* Sizes of deleted document written here */
152899:   int *pbFound            /* OUT: Set to true if row really does exist */
152900: ){
152901:   int rc;
152902:   sqlite3_stmt *pSelect;
152903: 
152904:   assert( *pbFound==0 );
152905:   if( *pRC ) return;
152906:   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
152907:   if( rc==SQLITE_OK ){
152908:     if( SQLITE_ROW==sqlite3_step(pSelect) ){
152909:       int i;
152910:       int iLangid = langidFromSelect(p, pSelect);
152911:       i64 iDocid = sqlite3_column_int64(pSelect, 0);
152912:       rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
152913:       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
152914:         int iCol = i-1;
152915:         if( p->abNotindexed[iCol]==0 ){
152916:           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
152917:           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
152918:           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
152919:         }
152920:       }
152921:       if( rc!=SQLITE_OK ){
152922:         sqlite3_reset(pSelect);
152923:         *pRC = rc;
152924:         return;
152925:       }
152926:       *pbFound = 1;
152927:     }
152928:     rc = sqlite3_reset(pSelect);
152929:   }else{
152930:     sqlite3_reset(pSelect);
152931:   }
152932:   *pRC = rc;
152933: }
152934: 
152935: /*
152936: ** Forward declaration to account for the circular dependency between
152937: ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
152938: */
152939: static int fts3SegmentMerge(Fts3Table *, int, int, int);
152940: 
152941: /* 
152942: ** This function allocates a new level iLevel index in the segdir table.
152943: ** Usually, indexes are allocated within a level sequentially starting
152944: ** with 0, so the allocated index is one greater than the value returned
152945: ** by:
152946: **
152947: **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
152948: **
152949: ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
152950: ** level, they are merged into a single level (iLevel+1) segment and the 
152951: ** allocated index is 0.
152952: **
152953: ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
152954: ** returned. Otherwise, an SQLite error code is returned.
152955: */
152956: static int fts3AllocateSegdirIdx(
152957:   Fts3Table *p, 
152958:   int iLangid,                    /* Language id */
152959:   int iIndex,                     /* Index for p->aIndex */
152960:   int iLevel, 
152961:   int *piIdx
152962: ){
152963:   int rc;                         /* Return Code */
152964:   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
152965:   int iNext = 0;                  /* Result of query pNextIdx */
152966: 
152967:   assert( iLangid>=0 );
152968:   assert( p->nIndex>=1 );
152969: 
152970:   /* Set variable iNext to the next available segdir index at level iLevel. */
152971:   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
152972:   if( rc==SQLITE_OK ){
152973:     sqlite3_bind_int64(
152974:         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
152975:     );
152976:     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
152977:       iNext = sqlite3_column_int(pNextIdx, 0);
152978:     }
152979:     rc = sqlite3_reset(pNextIdx);
152980:   }
152981: 
152982:   if( rc==SQLITE_OK ){
152983:     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
152984:     ** full, merge all segments in level iLevel into a single iLevel+1
152985:     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
152986:     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
152987:     */
152988:     if( iNext>=FTS3_MERGE_COUNT ){
152989:       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
152990:       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
152991:       *piIdx = 0;
152992:     }else{
152993:       *piIdx = iNext;
152994:     }
152995:   }
152996: 
152997:   return rc;
152998: }
152999: 
153000: /*
153001: ** The %_segments table is declared as follows:
153002: **
153003: **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
153004: **
153005: ** This function reads data from a single row of the %_segments table. The
153006: ** specific row is identified by the iBlockid parameter. If paBlob is not
153007: ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
153008: ** with the contents of the blob stored in the "block" column of the 
153009: ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
153010: ** to the size of the blob in bytes before returning.
153011: **
153012: ** If an error occurs, or the table does not contain the specified row,
153013: ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
153014: ** paBlob is non-NULL, then it is the responsibility of the caller to
153015: ** eventually free the returned buffer.
153016: **
153017: ** This function may leave an open sqlite3_blob* handle in the
153018: ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
153019: ** to this function. The handle may be closed by calling the
153020: ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
153021: ** performance improvement, but the blob handle should always be closed
153022: ** before control is returned to the user (to prevent a lock being held
153023: ** on the database file for longer than necessary). Thus, any virtual table
153024: ** method (xFilter etc.) that may directly or indirectly call this function
153025: ** must call sqlite3Fts3SegmentsClose() before returning.
153026: */
153027: SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
153028:   Fts3Table *p,                   /* FTS3 table handle */
153029:   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
153030:   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
153031:   int *pnBlob,                    /* OUT: Size of blob data */
153032:   int *pnLoad                     /* OUT: Bytes actually loaded */
153033: ){
153034:   int rc;                         /* Return code */
153035: 
153036:   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
153037:   assert( pnBlob );
153038: 
153039:   if( p->pSegments ){
153040:     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
153041:   }else{
153042:     if( 0==p->zSegmentsTbl ){
153043:       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
153044:       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
153045:     }
153046:     rc = sqlite3_blob_open(
153047:        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
153048:     );
153049:   }
153050: 
153051:   if( rc==SQLITE_OK ){
153052:     int nByte = sqlite3_blob_bytes(p->pSegments);
153053:     *pnBlob = nByte;
153054:     if( paBlob ){
153055:       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
153056:       if( !aByte ){
153057:         rc = SQLITE_NOMEM;
153058:       }else{
153059:         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
153060:           nByte = FTS3_NODE_CHUNKSIZE;
153061:           *pnLoad = nByte;
153062:         }
153063:         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
153064:         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
153065:         if( rc!=SQLITE_OK ){
153066:           sqlite3_free(aByte);
153067:           aByte = 0;
153068:         }
153069:       }
153070:       *paBlob = aByte;
153071:     }
153072:   }
153073: 
153074:   return rc;
153075: }
153076: 
153077: /*
153078: ** Close the blob handle at p->pSegments, if it is open. See comments above
153079: ** the sqlite3Fts3ReadBlock() function for details.
153080: */
153081: SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
153082:   sqlite3_blob_close(p->pSegments);
153083:   p->pSegments = 0;
153084: }
153085:     
153086: static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
153087:   int nRead;                      /* Number of bytes to read */
153088:   int rc;                         /* Return code */
153089: 
153090:   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
153091:   rc = sqlite3_blob_read(
153092:       pReader->pBlob, 
153093:       &pReader->aNode[pReader->nPopulate],
153094:       nRead,
153095:       pReader->nPopulate
153096:   );
153097: 
153098:   if( rc==SQLITE_OK ){
153099:     pReader->nPopulate += nRead;
153100:     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
153101:     if( pReader->nPopulate==pReader->nNode ){
153102:       sqlite3_blob_close(pReader->pBlob);
153103:       pReader->pBlob = 0;
153104:       pReader->nPopulate = 0;
153105:     }
153106:   }
153107:   return rc;
153108: }
153109: 
153110: static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
153111:   int rc = SQLITE_OK;
153112:   assert( !pReader->pBlob 
153113:        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
153114:   );
153115:   while( pReader->pBlob && rc==SQLITE_OK 
153116:      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
153117:   ){
153118:     rc = fts3SegReaderIncrRead(pReader);
153119:   }
153120:   return rc;
153121: }
153122: 
153123: /*
153124: ** Set an Fts3SegReader cursor to point at EOF.
153125: */
153126: static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
153127:   if( !fts3SegReaderIsRootOnly(pSeg) ){
153128:     sqlite3_free(pSeg->aNode);
153129:     sqlite3_blob_close(pSeg->pBlob);
153130:     pSeg->pBlob = 0;
153131:   }
153132:   pSeg->aNode = 0;
153133: }
153134: 
153135: /*
153136: ** Move the iterator passed as the first argument to the next term in the
153137: ** segment. If successful, SQLITE_OK is returned. If there is no next term,
153138: ** SQLITE_DONE. Otherwise, an SQLite error code.
153139: */
153140: static int fts3SegReaderNext(
153141:   Fts3Table *p, 
153142:   Fts3SegReader *pReader,
153143:   int bIncr
153144: ){
153145:   int rc;                         /* Return code of various sub-routines */
153146:   char *pNext;                    /* Cursor variable */
153147:   int nPrefix;                    /* Number of bytes in term prefix */
153148:   int nSuffix;                    /* Number of bytes in term suffix */
153149: 
153150:   if( !pReader->aDoclist ){
153151:     pNext = pReader->aNode;
153152:   }else{
153153:     pNext = &pReader->aDoclist[pReader->nDoclist];
153154:   }
153155: 
153156:   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
153157: 
153158:     if( fts3SegReaderIsPending(pReader) ){
153159:       Fts3HashElem *pElem = *(pReader->ppNextElem);
153160:       sqlite3_free(pReader->aNode);
153161:       pReader->aNode = 0;
153162:       if( pElem ){
153163:         char *aCopy;
153164:         PendingList *pList = (PendingList *)fts3HashData(pElem);
153165:         int nCopy = pList->nData+1;
153166:         pReader->zTerm = (char *)fts3HashKey(pElem);
153167:         pReader->nTerm = fts3HashKeysize(pElem);
153168:         aCopy = (char*)sqlite3_malloc(nCopy);
153169:         if( !aCopy ) return SQLITE_NOMEM;
153170:         memcpy(aCopy, pList->aData, nCopy);
153171:         pReader->nNode = pReader->nDoclist = nCopy;
153172:         pReader->aNode = pReader->aDoclist = aCopy;
153173:         pReader->ppNextElem++;
153174:         assert( pReader->aNode );
153175:       }
153176:       return SQLITE_OK;
153177:     }
153178: 
153179:     fts3SegReaderSetEof(pReader);
153180: 
153181:     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
153182:     ** blocks have already been traversed.  */
153183:     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
153184:     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
153185:       return SQLITE_OK;
153186:     }
153187: 
153188:     rc = sqlite3Fts3ReadBlock(
153189:         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
153190:         (bIncr ? &pReader->nPopulate : 0)
153191:     );
153192:     if( rc!=SQLITE_OK ) return rc;
153193:     assert( pReader->pBlob==0 );
153194:     if( bIncr && pReader->nPopulate<pReader->nNode ){
153195:       pReader->pBlob = p->pSegments;
153196:       p->pSegments = 0;
153197:     }
153198:     pNext = pReader->aNode;
153199:   }
153200: 
153201:   assert( !fts3SegReaderIsPending(pReader) );
153202: 
153203:   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
153204:   if( rc!=SQLITE_OK ) return rc;
153205:   
153206:   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
153207:   ** safe (no risk of overread) even if the node data is corrupted. */
153208:   pNext += fts3GetVarint32(pNext, &nPrefix);
153209:   pNext += fts3GetVarint32(pNext, &nSuffix);
153210:   if( nPrefix<0 || nSuffix<=0 
153211:    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
153212:   ){
153213:     return FTS_CORRUPT_VTAB;
153214:   }
153215: 
153216:   if( nPrefix+nSuffix>pReader->nTermAlloc ){
153217:     int nNew = (nPrefix+nSuffix)*2;
153218:     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
153219:     if( !zNew ){
153220:       return SQLITE_NOMEM;
153221:     }
153222:     pReader->zTerm = zNew;
153223:     pReader->nTermAlloc = nNew;
153224:   }
153225: 
153226:   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
153227:   if( rc!=SQLITE_OK ) return rc;
153228: 
153229:   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
153230:   pReader->nTerm = nPrefix+nSuffix;
153231:   pNext += nSuffix;
153232:   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
153233:   pReader->aDoclist = pNext;
153234:   pReader->pOffsetList = 0;
153235: 
153236:   /* Check that the doclist does not appear to extend past the end of the
153237:   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
153238:   ** of these statements is untrue, then the data structure is corrupt.
153239:   */
153240:   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
153241:    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
153242:   ){
153243:     return FTS_CORRUPT_VTAB;
153244:   }
153245:   return SQLITE_OK;
153246: }
153247: 
153248: /*
153249: ** Set the SegReader to point to the first docid in the doclist associated
153250: ** with the current term.
153251: */
153252: static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
153253:   int rc = SQLITE_OK;
153254:   assert( pReader->aDoclist );
153255:   assert( !pReader->pOffsetList );
153256:   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
153257:     u8 bEof = 0;
153258:     pReader->iDocid = 0;
153259:     pReader->nOffsetList = 0;
153260:     sqlite3Fts3DoclistPrev(0,
153261:         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
153262:         &pReader->iDocid, &pReader->nOffsetList, &bEof
153263:     );
153264:   }else{
153265:     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
153266:     if( rc==SQLITE_OK ){
153267:       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
153268:       pReader->pOffsetList = &pReader->aDoclist[n];
153269:     }
153270:   }
153271:   return rc;
153272: }
153273: 
153274: /*
153275: ** Advance the SegReader to point to the next docid in the doclist
153276: ** associated with the current term.
153277: ** 
153278: ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
153279: ** *ppOffsetList is set to point to the first column-offset list
153280: ** in the doclist entry (i.e. immediately past the docid varint).
153281: ** *pnOffsetList is set to the length of the set of column-offset
153282: ** lists, not including the nul-terminator byte. For example:
153283: */
153284: static int fts3SegReaderNextDocid(
153285:   Fts3Table *pTab,
153286:   Fts3SegReader *pReader,         /* Reader to advance to next docid */
153287:   char **ppOffsetList,            /* OUT: Pointer to current position-list */
153288:   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
153289: ){
153290:   int rc = SQLITE_OK;
153291:   char *p = pReader->pOffsetList;
153292:   char c = 0;
153293: 
153294:   assert( p );
153295: 
153296:   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
153297:     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
153298:     ** Pending-terms doclists are always built up in ascending order, so
153299:     ** we have to iterate through them backwards here. */
153300:     u8 bEof = 0;
153301:     if( ppOffsetList ){
153302:       *ppOffsetList = pReader->pOffsetList;
153303:       *pnOffsetList = pReader->nOffsetList - 1;
153304:     }
153305:     sqlite3Fts3DoclistPrev(0,
153306:         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
153307:         &pReader->nOffsetList, &bEof
153308:     );
153309:     if( bEof ){
153310:       pReader->pOffsetList = 0;
153311:     }else{
153312:       pReader->pOffsetList = p;
153313:     }
153314:   }else{
153315:     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
153316: 
153317:     /* Pointer p currently points at the first byte of an offset list. The
153318:     ** following block advances it to point one byte past the end of
153319:     ** the same offset list. */
153320:     while( 1 ){
153321:   
153322:       /* The following line of code (and the "p++" below the while() loop) is
153323:       ** normally all that is required to move pointer p to the desired 
153324:       ** position. The exception is if this node is being loaded from disk
153325:       ** incrementally and pointer "p" now points to the first byte past
153326:       ** the populated part of pReader->aNode[].
153327:       */
153328:       while( *p | c ) c = *p++ & 0x80;
153329:       assert( *p==0 );
153330:   
153331:       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
153332:       rc = fts3SegReaderIncrRead(pReader);
153333:       if( rc!=SQLITE_OK ) return rc;
153334:     }
153335:     p++;
153336:   
153337:     /* If required, populate the output variables with a pointer to and the
153338:     ** size of the previous offset-list.
153339:     */
153340:     if( ppOffsetList ){
153341:       *ppOffsetList = pReader->pOffsetList;
153342:       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
153343:     }
153344: 
153345:     /* List may have been edited in place by fts3EvalNearTrim() */
153346:     while( p<pEnd && *p==0 ) p++;
153347:   
153348:     /* If there are no more entries in the doclist, set pOffsetList to
153349:     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
153350:     ** Fts3SegReader.pOffsetList to point to the next offset list before
153351:     ** returning.
153352:     */
153353:     if( p>=pEnd ){
153354:       pReader->pOffsetList = 0;
153355:     }else{
153356:       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
153357:       if( rc==SQLITE_OK ){
153358:         sqlite3_int64 iDelta;
153359:         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
153360:         if( pTab->bDescIdx ){
153361:           pReader->iDocid -= iDelta;
153362:         }else{
153363:           pReader->iDocid += iDelta;
153364:         }
153365:       }
153366:     }
153367:   }
153368: 
153369:   return SQLITE_OK;
153370: }
153371: 
153372: 
153373: SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
153374:   Fts3Cursor *pCsr, 
153375:   Fts3MultiSegReader *pMsr,
153376:   int *pnOvfl
153377: ){
153378:   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
153379:   int nOvfl = 0;
153380:   int ii;
153381:   int rc = SQLITE_OK;
153382:   int pgsz = p->nPgsz;
153383: 
153384:   assert( p->bFts4 );
153385:   assert( pgsz>0 );
153386: 
153387:   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
153388:     Fts3SegReader *pReader = pMsr->apSegment[ii];
153389:     if( !fts3SegReaderIsPending(pReader) 
153390:      && !fts3SegReaderIsRootOnly(pReader) 
153391:     ){
153392:       sqlite3_int64 jj;
153393:       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
153394:         int nBlob;
153395:         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
153396:         if( rc!=SQLITE_OK ) break;
153397:         if( (nBlob+35)>pgsz ){
153398:           nOvfl += (nBlob + 34)/pgsz;
153399:         }
153400:       }
153401:     }
153402:   }
153403:   *pnOvfl = nOvfl;
153404:   return rc;
153405: }
153406: 
153407: /*
153408: ** Free all allocations associated with the iterator passed as the 
153409: ** second argument.
153410: */
153411: SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
153412:   if( pReader ){
153413:     if( !fts3SegReaderIsPending(pReader) ){
153414:       sqlite3_free(pReader->zTerm);
153415:     }
153416:     if( !fts3SegReaderIsRootOnly(pReader) ){
153417:       sqlite3_free(pReader->aNode);
153418:     }
153419:     sqlite3_blob_close(pReader->pBlob);
153420:   }
153421:   sqlite3_free(pReader);
153422: }
153423: 
153424: /*
153425: ** Allocate a new SegReader object.
153426: */
153427: SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
153428:   int iAge,                       /* Segment "age". */
153429:   int bLookup,                    /* True for a lookup only */
153430:   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
153431:   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
153432:   sqlite3_int64 iEndBlock,        /* Final block of segment */
153433:   const char *zRoot,              /* Buffer containing root node */
153434:   int nRoot,                      /* Size of buffer containing root node */
153435:   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
153436: ){
153437:   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
153438:   int nExtra = 0;                 /* Bytes to allocate segment root node */
153439: 
153440:   assert( iStartLeaf<=iEndLeaf );
153441:   if( iStartLeaf==0 ){
153442:     nExtra = nRoot + FTS3_NODE_PADDING;
153443:   }
153444: 
153445:   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
153446:   if( !pReader ){
153447:     return SQLITE_NOMEM;
153448:   }
153449:   memset(pReader, 0, sizeof(Fts3SegReader));
153450:   pReader->iIdx = iAge;
153451:   pReader->bLookup = bLookup!=0;
153452:   pReader->iStartBlock = iStartLeaf;
153453:   pReader->iLeafEndBlock = iEndLeaf;
153454:   pReader->iEndBlock = iEndBlock;
153455: 
153456:   if( nExtra ){
153457:     /* The entire segment is stored in the root node. */
153458:     pReader->aNode = (char *)&pReader[1];
153459:     pReader->rootOnly = 1;
153460:     pReader->nNode = nRoot;
153461:     memcpy(pReader->aNode, zRoot, nRoot);
153462:     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
153463:   }else{
153464:     pReader->iCurrentBlock = iStartLeaf-1;
153465:   }
153466:   *ppReader = pReader;
153467:   return SQLITE_OK;
153468: }
153469: 
153470: /*
153471: ** This is a comparison function used as a qsort() callback when sorting
153472: ** an array of pending terms by term. This occurs as part of flushing
153473: ** the contents of the pending-terms hash table to the database.
153474: */
153475: static int SQLITE_CDECL fts3CompareElemByTerm(
153476:   const void *lhs,
153477:   const void *rhs
153478: ){
153479:   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
153480:   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
153481:   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
153482:   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
153483: 
153484:   int n = (n1<n2 ? n1 : n2);
153485:   int c = memcmp(z1, z2, n);
153486:   if( c==0 ){
153487:     c = n1 - n2;
153488:   }
153489:   return c;
153490: }
153491: 
153492: /*
153493: ** This function is used to allocate an Fts3SegReader that iterates through
153494: ** a subset of the terms stored in the Fts3Table.pendingTerms array.
153495: **
153496: ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
153497: ** through each term in the pending-terms table. Or, if isPrefixIter is
153498: ** non-zero, it iterates through each term and its prefixes. For example, if
153499: ** the pending terms hash table contains the terms "sqlite", "mysql" and
153500: ** "firebird", then the iterator visits the following 'terms' (in the order
153501: ** shown):
153502: **
153503: **   f fi fir fire fireb firebi firebir firebird
153504: **   m my mys mysq mysql
153505: **   s sq sql sqli sqlit sqlite
153506: **
153507: ** Whereas if isPrefixIter is zero, the terms visited are:
153508: **
153509: **   firebird mysql sqlite
153510: */
153511: SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
153512:   Fts3Table *p,                   /* Virtual table handle */
153513:   int iIndex,                     /* Index for p->aIndex */
153514:   const char *zTerm,              /* Term to search for */
153515:   int nTerm,                      /* Size of buffer zTerm */
153516:   int bPrefix,                    /* True for a prefix iterator */
153517:   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
153518: ){
153519:   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
153520:   Fts3HashElem *pE;               /* Iterator variable */
153521:   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
153522:   int nElem = 0;                  /* Size of array at aElem */
153523:   int rc = SQLITE_OK;             /* Return Code */
153524:   Fts3Hash *pHash;
153525: 
153526:   pHash = &p->aIndex[iIndex].hPending;
153527:   if( bPrefix ){
153528:     int nAlloc = 0;               /* Size of allocated array at aElem */
153529: 
153530:     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
153531:       char *zKey = (char *)fts3HashKey(pE);
153532:       int nKey = fts3HashKeysize(pE);
153533:       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
153534:         if( nElem==nAlloc ){
153535:           Fts3HashElem **aElem2;
153536:           nAlloc += 16;
153537:           aElem2 = (Fts3HashElem **)sqlite3_realloc(
153538:               aElem, nAlloc*sizeof(Fts3HashElem *)
153539:           );
153540:           if( !aElem2 ){
153541:             rc = SQLITE_NOMEM;
153542:             nElem = 0;
153543:             break;
153544:           }
153545:           aElem = aElem2;
153546:         }
153547: 
153548:         aElem[nElem++] = pE;
153549:       }
153550:     }
153551: 
153552:     /* If more than one term matches the prefix, sort the Fts3HashElem
153553:     ** objects in term order using qsort(). This uses the same comparison
153554:     ** callback as is used when flushing terms to disk.
153555:     */
153556:     if( nElem>1 ){
153557:       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
153558:     }
153559: 
153560:   }else{
153561:     /* The query is a simple term lookup that matches at most one term in
153562:     ** the index. All that is required is a straight hash-lookup. 
153563:     **
153564:     ** Because the stack address of pE may be accessed via the aElem pointer
153565:     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
153566:     ** within this entire function, not just this "else{...}" block.
153567:     */
153568:     pE = fts3HashFindElem(pHash, zTerm, nTerm);
153569:     if( pE ){
153570:       aElem = &pE;
153571:       nElem = 1;
153572:     }
153573:   }
153574: 
153575:   if( nElem>0 ){
153576:     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
153577:     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
153578:     if( !pReader ){
153579:       rc = SQLITE_NOMEM;
153580:     }else{
153581:       memset(pReader, 0, nByte);
153582:       pReader->iIdx = 0x7FFFFFFF;
153583:       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
153584:       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
153585:     }
153586:   }
153587: 
153588:   if( bPrefix ){
153589:     sqlite3_free(aElem);
153590:   }
153591:   *ppReader = pReader;
153592:   return rc;
153593: }
153594: 
153595: /*
153596: ** Compare the entries pointed to by two Fts3SegReader structures. 
153597: ** Comparison is as follows:
153598: **
153599: **   1) EOF is greater than not EOF.
153600: **
153601: **   2) The current terms (if any) are compared using memcmp(). If one
153602: **      term is a prefix of another, the longer term is considered the
153603: **      larger.
153604: **
153605: **   3) By segment age. An older segment is considered larger.
153606: */
153607: static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153608:   int rc;
153609:   if( pLhs->aNode && pRhs->aNode ){
153610:     int rc2 = pLhs->nTerm - pRhs->nTerm;
153611:     if( rc2<0 ){
153612:       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
153613:     }else{
153614:       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
153615:     }
153616:     if( rc==0 ){
153617:       rc = rc2;
153618:     }
153619:   }else{
153620:     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
153621:   }
153622:   if( rc==0 ){
153623:     rc = pRhs->iIdx - pLhs->iIdx;
153624:   }
153625:   assert( rc!=0 );
153626:   return rc;
153627: }
153628: 
153629: /*
153630: ** A different comparison function for SegReader structures. In this
153631: ** version, it is assumed that each SegReader points to an entry in
153632: ** a doclist for identical terms. Comparison is made as follows:
153633: **
153634: **   1) EOF (end of doclist in this case) is greater than not EOF.
153635: **
153636: **   2) By current docid.
153637: **
153638: **   3) By segment age. An older segment is considered larger.
153639: */
153640: static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153641:   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
153642:   if( rc==0 ){
153643:     if( pLhs->iDocid==pRhs->iDocid ){
153644:       rc = pRhs->iIdx - pLhs->iIdx;
153645:     }else{
153646:       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
153647:     }
153648:   }
153649:   assert( pLhs->aNode && pRhs->aNode );
153650:   return rc;
153651: }
153652: static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
153653:   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
153654:   if( rc==0 ){
153655:     if( pLhs->iDocid==pRhs->iDocid ){
153656:       rc = pRhs->iIdx - pLhs->iIdx;
153657:     }else{
153658:       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
153659:     }
153660:   }
153661:   assert( pLhs->aNode && pRhs->aNode );
153662:   return rc;
153663: }
153664: 
153665: /*
153666: ** Compare the term that the Fts3SegReader object passed as the first argument
153667: ** points to with the term specified by arguments zTerm and nTerm. 
153668: **
153669: ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
153670: ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
153671: ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
153672: */
153673: static int fts3SegReaderTermCmp(
153674:   Fts3SegReader *pSeg,            /* Segment reader object */
153675:   const char *zTerm,              /* Term to compare to */
153676:   int nTerm                       /* Size of term zTerm in bytes */
153677: ){
153678:   int res = 0;
153679:   if( pSeg->aNode ){
153680:     if( pSeg->nTerm>nTerm ){
153681:       res = memcmp(pSeg->zTerm, zTerm, nTerm);
153682:     }else{
153683:       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
153684:     }
153685:     if( res==0 ){
153686:       res = pSeg->nTerm-nTerm;
153687:     }
153688:   }
153689:   return res;
153690: }
153691: 
153692: /*
153693: ** Argument apSegment is an array of nSegment elements. It is known that
153694: ** the final (nSegment-nSuspect) members are already in sorted order
153695: ** (according to the comparison function provided). This function shuffles
153696: ** the array around until all entries are in sorted order.
153697: */
153698: static void fts3SegReaderSort(
153699:   Fts3SegReader **apSegment,                     /* Array to sort entries of */
153700:   int nSegment,                                  /* Size of apSegment array */
153701:   int nSuspect,                                  /* Unsorted entry count */
153702:   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
153703: ){
153704:   int i;                          /* Iterator variable */
153705: 
153706:   assert( nSuspect<=nSegment );
153707: 
153708:   if( nSuspect==nSegment ) nSuspect--;
153709:   for(i=nSuspect-1; i>=0; i--){
153710:     int j;
153711:     for(j=i; j<(nSegment-1); j++){
153712:       Fts3SegReader *pTmp;
153713:       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
153714:       pTmp = apSegment[j+1];
153715:       apSegment[j+1] = apSegment[j];
153716:       apSegment[j] = pTmp;
153717:     }
153718:   }
153719: 
153720: #ifndef NDEBUG
153721:   /* Check that the list really is sorted now. */
153722:   for(i=0; i<(nSuspect-1); i++){
153723:     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
153724:   }
153725: #endif
153726: }
153727: 
153728: /* 
153729: ** Insert a record into the %_segments table.
153730: */
153731: static int fts3WriteSegment(
153732:   Fts3Table *p,                   /* Virtual table handle */
153733:   sqlite3_int64 iBlock,           /* Block id for new block */
153734:   char *z,                        /* Pointer to buffer containing block data */
153735:   int n                           /* Size of buffer z in bytes */
153736: ){
153737:   sqlite3_stmt *pStmt;
153738:   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
153739:   if( rc==SQLITE_OK ){
153740:     sqlite3_bind_int64(pStmt, 1, iBlock);
153741:     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
153742:     sqlite3_step(pStmt);
153743:     rc = sqlite3_reset(pStmt);
153744:   }
153745:   return rc;
153746: }
153747: 
153748: /*
153749: ** Find the largest relative level number in the table. If successful, set
153750: ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
153751: ** set *pnMax to zero and return an SQLite error code.
153752: */
153753: SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
153754:   int rc;
153755:   int mxLevel = 0;
153756:   sqlite3_stmt *pStmt = 0;
153757: 
153758:   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
153759:   if( rc==SQLITE_OK ){
153760:     if( SQLITE_ROW==sqlite3_step(pStmt) ){
153761:       mxLevel = sqlite3_column_int(pStmt, 0);
153762:     }
153763:     rc = sqlite3_reset(pStmt);
153764:   }
153765:   *pnMax = mxLevel;
153766:   return rc;
153767: }
153768: 
153769: /* 
153770: ** Insert a record into the %_segdir table.
153771: */
153772: static int fts3WriteSegdir(
153773:   Fts3Table *p,                   /* Virtual table handle */
153774:   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
153775:   int iIdx,                       /* Value for "idx" field */
153776:   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
153777:   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
153778:   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
153779:   sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
153780:   char *zRoot,                    /* Blob value for "root" field */
153781:   int nRoot                       /* Number of bytes in buffer zRoot */
153782: ){
153783:   sqlite3_stmt *pStmt;
153784:   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
153785:   if( rc==SQLITE_OK ){
153786:     sqlite3_bind_int64(pStmt, 1, iLevel);
153787:     sqlite3_bind_int(pStmt, 2, iIdx);
153788:     sqlite3_bind_int64(pStmt, 3, iStartBlock);
153789:     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
153790:     if( nLeafData==0 ){
153791:       sqlite3_bind_int64(pStmt, 5, iEndBlock);
153792:     }else{
153793:       char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
153794:       if( !zEnd ) return SQLITE_NOMEM;
153795:       sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
153796:     }
153797:     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
153798:     sqlite3_step(pStmt);
153799:     rc = sqlite3_reset(pStmt);
153800:   }
153801:   return rc;
153802: }
153803: 
153804: /*
153805: ** Return the size of the common prefix (if any) shared by zPrev and
153806: ** zNext, in bytes. For example, 
153807: **
153808: **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
153809: **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
153810: **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
153811: */
153812: static int fts3PrefixCompress(
153813:   const char *zPrev,              /* Buffer containing previous term */
153814:   int nPrev,                      /* Size of buffer zPrev in bytes */
153815:   const char *zNext,              /* Buffer containing next term */
153816:   int nNext                       /* Size of buffer zNext in bytes */
153817: ){
153818:   int n;
153819:   UNUSED_PARAMETER(nNext);
153820:   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
153821:   return n;
153822: }
153823: 
153824: /*
153825: ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
153826: ** (according to memcmp) than the previous term.
153827: */
153828: static int fts3NodeAddTerm(
153829:   Fts3Table *p,                   /* Virtual table handle */
153830:   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
153831:   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
153832:   const char *zTerm,              /* Pointer to buffer containing term */
153833:   int nTerm                       /* Size of term in bytes */
153834: ){
153835:   SegmentNode *pTree = *ppTree;
153836:   int rc;
153837:   SegmentNode *pNew;
153838: 
153839:   /* First try to append the term to the current node. Return early if 
153840:   ** this is possible.
153841:   */
153842:   if( pTree ){
153843:     int nData = pTree->nData;     /* Current size of node in bytes */
153844:     int nReq = nData;             /* Required space after adding zTerm */
153845:     int nPrefix;                  /* Number of bytes of prefix compression */
153846:     int nSuffix;                  /* Suffix length */
153847: 
153848:     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
153849:     nSuffix = nTerm-nPrefix;
153850: 
153851:     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
153852:     if( nReq<=p->nNodeSize || !pTree->zTerm ){
153853: 
153854:       if( nReq>p->nNodeSize ){
153855:         /* An unusual case: this is the first term to be added to the node
153856:         ** and the static node buffer (p->nNodeSize bytes) is not large
153857:         ** enough. Use a separately malloced buffer instead This wastes
153858:         ** p->nNodeSize bytes, but since this scenario only comes about when
153859:         ** the database contain two terms that share a prefix of almost 2KB, 
153860:         ** this is not expected to be a serious problem. 
153861:         */
153862:         assert( pTree->aData==(char *)&pTree[1] );
153863:         pTree->aData = (char *)sqlite3_malloc(nReq);
153864:         if( !pTree->aData ){
153865:           return SQLITE_NOMEM;
153866:         }
153867:       }
153868: 
153869:       if( pTree->zTerm ){
153870:         /* There is no prefix-length field for first term in a node */
153871:         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
153872:       }
153873: 
153874:       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
153875:       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
153876:       pTree->nData = nData + nSuffix;
153877:       pTree->nEntry++;
153878: 
153879:       if( isCopyTerm ){
153880:         if( pTree->nMalloc<nTerm ){
153881:           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
153882:           if( !zNew ){
153883:             return SQLITE_NOMEM;
153884:           }
153885:           pTree->nMalloc = nTerm*2;
153886:           pTree->zMalloc = zNew;
153887:         }
153888:         pTree->zTerm = pTree->zMalloc;
153889:         memcpy(pTree->zTerm, zTerm, nTerm);
153890:         pTree->nTerm = nTerm;
153891:       }else{
153892:         pTree->zTerm = (char *)zTerm;
153893:         pTree->nTerm = nTerm;
153894:       }
153895:       return SQLITE_OK;
153896:     }
153897:   }
153898: 
153899:   /* If control flows to here, it was not possible to append zTerm to the
153900:   ** current node. Create a new node (a right-sibling of the current node).
153901:   ** If this is the first node in the tree, the term is added to it.
153902:   **
153903:   ** Otherwise, the term is not added to the new node, it is left empty for
153904:   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
153905:   ** has no parent, one is created here.
153906:   */
153907:   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
153908:   if( !pNew ){
153909:     return SQLITE_NOMEM;
153910:   }
153911:   memset(pNew, 0, sizeof(SegmentNode));
153912:   pNew->nData = 1 + FTS3_VARINT_MAX;
153913:   pNew->aData = (char *)&pNew[1];
153914: 
153915:   if( pTree ){
153916:     SegmentNode *pParent = pTree->pParent;
153917:     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
153918:     if( pTree->pParent==0 ){
153919:       pTree->pParent = pParent;
153920:     }
153921:     pTree->pRight = pNew;
153922:     pNew->pLeftmost = pTree->pLeftmost;
153923:     pNew->pParent = pParent;
153924:     pNew->zMalloc = pTree->zMalloc;
153925:     pNew->nMalloc = pTree->nMalloc;
153926:     pTree->zMalloc = 0;
153927:   }else{
153928:     pNew->pLeftmost = pNew;
153929:     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
153930:   }
153931: 
153932:   *ppTree = pNew;
153933:   return rc;
153934: }
153935: 
153936: /*
153937: ** Helper function for fts3NodeWrite().
153938: */
153939: static int fts3TreeFinishNode(
153940:   SegmentNode *pTree, 
153941:   int iHeight, 
153942:   sqlite3_int64 iLeftChild
153943: ){
153944:   int nStart;
153945:   assert( iHeight>=1 && iHeight<128 );
153946:   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
153947:   pTree->aData[nStart] = (char)iHeight;
153948:   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
153949:   return nStart;
153950: }
153951: 
153952: /*
153953: ** Write the buffer for the segment node pTree and all of its peers to the
153954: ** database. Then call this function recursively to write the parent of 
153955: ** pTree and its peers to the database. 
153956: **
153957: ** Except, if pTree is a root node, do not write it to the database. Instead,
153958: ** set output variables *paRoot and *pnRoot to contain the root node.
153959: **
153960: ** If successful, SQLITE_OK is returned and output variable *piLast is
153961: ** set to the largest blockid written to the database (or zero if no
153962: ** blocks were written to the db). Otherwise, an SQLite error code is 
153963: ** returned.
153964: */
153965: static int fts3NodeWrite(
153966:   Fts3Table *p,                   /* Virtual table handle */
153967:   SegmentNode *pTree,             /* SegmentNode handle */
153968:   int iHeight,                    /* Height of this node in tree */
153969:   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
153970:   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
153971:   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
153972:   char **paRoot,                  /* OUT: Data for root node */
153973:   int *pnRoot                     /* OUT: Size of root node in bytes */
153974: ){
153975:   int rc = SQLITE_OK;
153976: 
153977:   if( !pTree->pParent ){
153978:     /* Root node of the tree. */
153979:     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
153980:     *piLast = iFree-1;
153981:     *pnRoot = pTree->nData - nStart;
153982:     *paRoot = &pTree->aData[nStart];
153983:   }else{
153984:     SegmentNode *pIter;
153985:     sqlite3_int64 iNextFree = iFree;
153986:     sqlite3_int64 iNextLeaf = iLeaf;
153987:     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
153988:       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
153989:       int nWrite = pIter->nData - nStart;
153990:   
153991:       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
153992:       iNextFree++;
153993:       iNextLeaf += (pIter->nEntry+1);
153994:     }
153995:     if( rc==SQLITE_OK ){
153996:       assert( iNextLeaf==iFree );
153997:       rc = fts3NodeWrite(
153998:           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
153999:       );
154000:     }
154001:   }
154002: 
154003:   return rc;
154004: }
154005: 
154006: /*
154007: ** Free all memory allocations associated with the tree pTree.
154008: */
154009: static void fts3NodeFree(SegmentNode *pTree){
154010:   if( pTree ){
154011:     SegmentNode *p = pTree->pLeftmost;
154012:     fts3NodeFree(p->pParent);
154013:     while( p ){
154014:       SegmentNode *pRight = p->pRight;
154015:       if( p->aData!=(char *)&p[1] ){
154016:         sqlite3_free(p->aData);
154017:       }
154018:       assert( pRight==0 || p->zMalloc==0 );
154019:       sqlite3_free(p->zMalloc);
154020:       sqlite3_free(p);
154021:       p = pRight;
154022:     }
154023:   }
154024: }
154025: 
154026: /*
154027: ** Add a term to the segment being constructed by the SegmentWriter object
154028: ** *ppWriter. When adding the first term to a segment, *ppWriter should
154029: ** be passed NULL. This function will allocate a new SegmentWriter object
154030: ** and return it via the input/output variable *ppWriter in this case.
154031: **
154032: ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
154033: */
154034: static int fts3SegWriterAdd(
154035:   Fts3Table *p,                   /* Virtual table handle */
154036:   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
154037:   int isCopyTerm,                 /* True if buffer zTerm must be copied */
154038:   const char *zTerm,              /* Pointer to buffer containing term */
154039:   int nTerm,                      /* Size of term in bytes */
154040:   const char *aDoclist,           /* Pointer to buffer containing doclist */
154041:   int nDoclist                    /* Size of doclist in bytes */
154042: ){
154043:   int nPrefix;                    /* Size of term prefix in bytes */
154044:   int nSuffix;                    /* Size of term suffix in bytes */
154045:   int nReq;                       /* Number of bytes required on leaf page */
154046:   int nData;
154047:   SegmentWriter *pWriter = *ppWriter;
154048: 
154049:   if( !pWriter ){
154050:     int rc;
154051:     sqlite3_stmt *pStmt;
154052: 
154053:     /* Allocate the SegmentWriter structure */
154054:     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
154055:     if( !pWriter ) return SQLITE_NOMEM;
154056:     memset(pWriter, 0, sizeof(SegmentWriter));
154057:     *ppWriter = pWriter;
154058: 
154059:     /* Allocate a buffer in which to accumulate data */
154060:     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
154061:     if( !pWriter->aData ) return SQLITE_NOMEM;
154062:     pWriter->nSize = p->nNodeSize;
154063: 
154064:     /* Find the next free blockid in the %_segments table */
154065:     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
154066:     if( rc!=SQLITE_OK ) return rc;
154067:     if( SQLITE_ROW==sqlite3_step(pStmt) ){
154068:       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
154069:       pWriter->iFirst = pWriter->iFree;
154070:     }
154071:     rc = sqlite3_reset(pStmt);
154072:     if( rc!=SQLITE_OK ) return rc;
154073:   }
154074:   nData = pWriter->nData;
154075: 
154076:   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
154077:   nSuffix = nTerm-nPrefix;
154078: 
154079:   /* Figure out how many bytes are required by this new entry */
154080:   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
154081:     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
154082:     nSuffix +                               /* Term suffix */
154083:     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
154084:     nDoclist;                               /* Doclist data */
154085: 
154086:   if( nData>0 && nData+nReq>p->nNodeSize ){
154087:     int rc;
154088: 
154089:     /* The current leaf node is full. Write it out to the database. */
154090:     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
154091:     if( rc!=SQLITE_OK ) return rc;
154092:     p->nLeafAdd++;
154093: 
154094:     /* Add the current term to the interior node tree. The term added to
154095:     ** the interior tree must:
154096:     **
154097:     **   a) be greater than the largest term on the leaf node just written
154098:     **      to the database (still available in pWriter->zTerm), and
154099:     **
154100:     **   b) be less than or equal to the term about to be added to the new
154101:     **      leaf node (zTerm/nTerm).
154102:     **
154103:     ** In other words, it must be the prefix of zTerm 1 byte longer than
154104:     ** the common prefix (if any) of zTerm and pWriter->zTerm.
154105:     */
154106:     assert( nPrefix<nTerm );
154107:     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
154108:     if( rc!=SQLITE_OK ) return rc;
154109: 
154110:     nData = 0;
154111:     pWriter->nTerm = 0;
154112: 
154113:     nPrefix = 0;
154114:     nSuffix = nTerm;
154115:     nReq = 1 +                              /* varint containing prefix size */
154116:       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
154117:       nTerm +                               /* Term suffix */
154118:       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
154119:       nDoclist;                             /* Doclist data */
154120:   }
154121: 
154122:   /* Increase the total number of bytes written to account for the new entry. */
154123:   pWriter->nLeafData += nReq;
154124: 
154125:   /* If the buffer currently allocated is too small for this entry, realloc
154126:   ** the buffer to make it large enough.
154127:   */
154128:   if( nReq>pWriter->nSize ){
154129:     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
154130:     if( !aNew ) return SQLITE_NOMEM;
154131:     pWriter->aData = aNew;
154132:     pWriter->nSize = nReq;
154133:   }
154134:   assert( nData+nReq<=pWriter->nSize );
154135: 
154136:   /* Append the prefix-compressed term and doclist to the buffer. */
154137:   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
154138:   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
154139:   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
154140:   nData += nSuffix;
154141:   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
154142:   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
154143:   pWriter->nData = nData + nDoclist;
154144: 
154145:   /* Save the current term so that it can be used to prefix-compress the next.
154146:   ** If the isCopyTerm parameter is true, then the buffer pointed to by
154147:   ** zTerm is transient, so take a copy of the term data. Otherwise, just
154148:   ** store a copy of the pointer.
154149:   */
154150:   if( isCopyTerm ){
154151:     if( nTerm>pWriter->nMalloc ){
154152:       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
154153:       if( !zNew ){
154154:         return SQLITE_NOMEM;
154155:       }
154156:       pWriter->nMalloc = nTerm*2;
154157:       pWriter->zMalloc = zNew;
154158:       pWriter->zTerm = zNew;
154159:     }
154160:     assert( pWriter->zTerm==pWriter->zMalloc );
154161:     memcpy(pWriter->zTerm, zTerm, nTerm);
154162:   }else{
154163:     pWriter->zTerm = (char *)zTerm;
154164:   }
154165:   pWriter->nTerm = nTerm;
154166: 
154167:   return SQLITE_OK;
154168: }
154169: 
154170: /*
154171: ** Flush all data associated with the SegmentWriter object pWriter to the
154172: ** database. This function must be called after all terms have been added
154173: ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
154174: ** returned. Otherwise, an SQLite error code.
154175: */
154176: static int fts3SegWriterFlush(
154177:   Fts3Table *p,                   /* Virtual table handle */
154178:   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
154179:   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
154180:   int iIdx                        /* Value for 'idx' column of %_segdir */
154181: ){
154182:   int rc;                         /* Return code */
154183:   if( pWriter->pTree ){
154184:     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
154185:     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
154186:     char *zRoot = NULL;           /* Pointer to buffer containing root node */
154187:     int nRoot = 0;                /* Size of buffer zRoot */
154188: 
154189:     iLastLeaf = pWriter->iFree;
154190:     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
154191:     if( rc==SQLITE_OK ){
154192:       rc = fts3NodeWrite(p, pWriter->pTree, 1,
154193:           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
154194:     }
154195:     if( rc==SQLITE_OK ){
154196:       rc = fts3WriteSegdir(p, iLevel, iIdx, 
154197:           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
154198:     }
154199:   }else{
154200:     /* The entire tree fits on the root node. Write it to the segdir table. */
154201:     rc = fts3WriteSegdir(p, iLevel, iIdx, 
154202:         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
154203:   }
154204:   p->nLeafAdd++;
154205:   return rc;
154206: }
154207: 
154208: /*
154209: ** Release all memory held by the SegmentWriter object passed as the 
154210: ** first argument.
154211: */
154212: static void fts3SegWriterFree(SegmentWriter *pWriter){
154213:   if( pWriter ){
154214:     sqlite3_free(pWriter->aData);
154215:     sqlite3_free(pWriter->zMalloc);
154216:     fts3NodeFree(pWriter->pTree);
154217:     sqlite3_free(pWriter);
154218:   }
154219: }
154220: 
154221: /*
154222: ** The first value in the apVal[] array is assumed to contain an integer.
154223: ** This function tests if there exist any documents with docid values that
154224: ** are different from that integer. i.e. if deleting the document with docid
154225: ** pRowid would mean the FTS3 table were empty.
154226: **
154227: ** If successful, *pisEmpty is set to true if the table is empty except for
154228: ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
154229: ** error occurs, an SQLite error code is returned.
154230: */
154231: static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
154232:   sqlite3_stmt *pStmt;
154233:   int rc;
154234:   if( p->zContentTbl ){
154235:     /* If using the content=xxx option, assume the table is never empty */
154236:     *pisEmpty = 0;
154237:     rc = SQLITE_OK;
154238:   }else{
154239:     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
154240:     if( rc==SQLITE_OK ){
154241:       if( SQLITE_ROW==sqlite3_step(pStmt) ){
154242:         *pisEmpty = sqlite3_column_int(pStmt, 0);
154243:       }
154244:       rc = sqlite3_reset(pStmt);
154245:     }
154246:   }
154247:   return rc;
154248: }
154249: 
154250: /*
154251: ** Set *pnMax to the largest segment level in the database for the index
154252: ** iIndex.
154253: **
154254: ** Segment levels are stored in the 'level' column of the %_segdir table.
154255: **
154256: ** Return SQLITE_OK if successful, or an SQLite error code if not.
154257: */
154258: static int fts3SegmentMaxLevel(
154259:   Fts3Table *p, 
154260:   int iLangid,
154261:   int iIndex, 
154262:   sqlite3_int64 *pnMax
154263: ){
154264:   sqlite3_stmt *pStmt;
154265:   int rc;
154266:   assert( iIndex>=0 && iIndex<p->nIndex );
154267: 
154268:   /* Set pStmt to the compiled version of:
154269:   **
154270:   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
154271:   **
154272:   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
154273:   */
154274:   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
154275:   if( rc!=SQLITE_OK ) return rc;
154276:   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
154277:   sqlite3_bind_int64(pStmt, 2, 
154278:       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
154279:   );
154280:   if( SQLITE_ROW==sqlite3_step(pStmt) ){
154281:     *pnMax = sqlite3_column_int64(pStmt, 0);
154282:   }
154283:   return sqlite3_reset(pStmt);
154284: }
154285: 
154286: /*
154287: ** iAbsLevel is an absolute level that may be assumed to exist within
154288: ** the database. This function checks if it is the largest level number
154289: ** within its index. Assuming no error occurs, *pbMax is set to 1 if
154290: ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
154291: ** is returned. If an error occurs, an error code is returned and the
154292: ** final value of *pbMax is undefined.
154293: */
154294: static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
154295: 
154296:   /* Set pStmt to the compiled version of:
154297:   **
154298:   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
154299:   **
154300:   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
154301:   */
154302:   sqlite3_stmt *pStmt;
154303:   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
154304:   if( rc!=SQLITE_OK ) return rc;
154305:   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
154306:   sqlite3_bind_int64(pStmt, 2, 
154307:       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
154308:   );
154309: 
154310:   *pbMax = 0;
154311:   if( SQLITE_ROW==sqlite3_step(pStmt) ){
154312:     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
154313:   }
154314:   return sqlite3_reset(pStmt);
154315: }
154316: 
154317: /*
154318: ** Delete all entries in the %_segments table associated with the segment
154319: ** opened with seg-reader pSeg. This function does not affect the contents
154320: ** of the %_segdir table.
154321: */
154322: static int fts3DeleteSegment(
154323:   Fts3Table *p,                   /* FTS table handle */
154324:   Fts3SegReader *pSeg             /* Segment to delete */
154325: ){
154326:   int rc = SQLITE_OK;             /* Return code */
154327:   if( pSeg->iStartBlock ){
154328:     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
154329:     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
154330:     if( rc==SQLITE_OK ){
154331:       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
154332:       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
154333:       sqlite3_step(pDelete);
154334:       rc = sqlite3_reset(pDelete);
154335:     }
154336:   }
154337:   return rc;
154338: }
154339: 
154340: /*
154341: ** This function is used after merging multiple segments into a single large
154342: ** segment to delete the old, now redundant, segment b-trees. Specifically,
154343: ** it:
154344: ** 
154345: **   1) Deletes all %_segments entries for the segments associated with 
154346: **      each of the SegReader objects in the array passed as the third 
154347: **      argument, and
154348: **
154349: **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
154350: **      entries regardless of level if (iLevel<0).
154351: **
154352: ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
154353: */
154354: static int fts3DeleteSegdir(
154355:   Fts3Table *p,                   /* Virtual table handle */
154356:   int iLangid,                    /* Language id */
154357:   int iIndex,                     /* Index for p->aIndex */
154358:   int iLevel,                     /* Level of %_segdir entries to delete */
154359:   Fts3SegReader **apSegment,      /* Array of SegReader objects */
154360:   int nReader                     /* Size of array apSegment */
154361: ){
154362:   int rc = SQLITE_OK;             /* Return Code */
154363:   int i;                          /* Iterator variable */
154364:   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
154365: 
154366:   for(i=0; rc==SQLITE_OK && i<nReader; i++){
154367:     rc = fts3DeleteSegment(p, apSegment[i]);
154368:   }
154369:   if( rc!=SQLITE_OK ){
154370:     return rc;
154371:   }
154372: 
154373:   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
154374:   if( iLevel==FTS3_SEGCURSOR_ALL ){
154375:     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
154376:     if( rc==SQLITE_OK ){
154377:       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
154378:       sqlite3_bind_int64(pDelete, 2, 
154379:           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
154380:       );
154381:     }
154382:   }else{
154383:     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
154384:     if( rc==SQLITE_OK ){
154385:       sqlite3_bind_int64(
154386:           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
154387:       );
154388:     }
154389:   }
154390: 
154391:   if( rc==SQLITE_OK ){
154392:     sqlite3_step(pDelete);
154393:     rc = sqlite3_reset(pDelete);
154394:   }
154395: 
154396:   return rc;
154397: }
154398: 
154399: /*
154400: ** When this function is called, buffer *ppList (size *pnList bytes) contains 
154401: ** a position list that may (or may not) feature multiple columns. This
154402: ** function adjusts the pointer *ppList and the length *pnList so that they
154403: ** identify the subset of the position list that corresponds to column iCol.
154404: **
154405: ** If there are no entries in the input position list for column iCol, then
154406: ** *pnList is set to zero before returning.
154407: **
154408: ** If parameter bZero is non-zero, then any part of the input list following
154409: ** the end of the output list is zeroed before returning.
154410: */
154411: static void fts3ColumnFilter(
154412:   int iCol,                       /* Column to filter on */
154413:   int bZero,                      /* Zero out anything following *ppList */
154414:   char **ppList,                  /* IN/OUT: Pointer to position list */
154415:   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
154416: ){
154417:   char *pList = *ppList;
154418:   int nList = *pnList;
154419:   char *pEnd = &pList[nList];
154420:   int iCurrent = 0;
154421:   char *p = pList;
154422: 
154423:   assert( iCol>=0 );
154424:   while( 1 ){
154425:     char c = 0;
154426:     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
154427:   
154428:     if( iCol==iCurrent ){
154429:       nList = (int)(p - pList);
154430:       break;
154431:     }
154432: 
154433:     nList -= (int)(p - pList);
154434:     pList = p;
154435:     if( nList==0 ){
154436:       break;
154437:     }
154438:     p = &pList[1];
154439:     p += fts3GetVarint32(p, &iCurrent);
154440:   }
154441: 
154442:   if( bZero && &pList[nList]!=pEnd ){
154443:     memset(&pList[nList], 0, pEnd - &pList[nList]);
154444:   }
154445:   *ppList = pList;
154446:   *pnList = nList;
154447: }
154448: 
154449: /*
154450: ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
154451: ** existing data). Grow the buffer if required.
154452: **
154453: ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
154454: ** trying to resize the buffer, return SQLITE_NOMEM.
154455: */
154456: static int fts3MsrBufferData(
154457:   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
154458:   char *pList,
154459:   int nList
154460: ){
154461:   if( nList>pMsr->nBuffer ){
154462:     char *pNew;
154463:     pMsr->nBuffer = nList*2;
154464:     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
154465:     if( !pNew ) return SQLITE_NOMEM;
154466:     pMsr->aBuffer = pNew;
154467:   }
154468: 
154469:   memcpy(pMsr->aBuffer, pList, nList);
154470:   return SQLITE_OK;
154471: }
154472: 
154473: SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
154474:   Fts3Table *p,                   /* Virtual table handle */
154475:   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
154476:   sqlite3_int64 *piDocid,         /* OUT: Docid value */
154477:   char **paPoslist,               /* OUT: Pointer to position list */
154478:   int *pnPoslist                  /* OUT: Size of position list in bytes */
154479: ){
154480:   int nMerge = pMsr->nAdvance;
154481:   Fts3SegReader **apSegment = pMsr->apSegment;
154482:   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154483:     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154484:   );
154485: 
154486:   if( nMerge==0 ){
154487:     *paPoslist = 0;
154488:     return SQLITE_OK;
154489:   }
154490: 
154491:   while( 1 ){
154492:     Fts3SegReader *pSeg;
154493:     pSeg = pMsr->apSegment[0];
154494: 
154495:     if( pSeg->pOffsetList==0 ){
154496:       *paPoslist = 0;
154497:       break;
154498:     }else{
154499:       int rc;
154500:       char *pList;
154501:       int nList;
154502:       int j;
154503:       sqlite3_int64 iDocid = apSegment[0]->iDocid;
154504: 
154505:       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
154506:       j = 1;
154507:       while( rc==SQLITE_OK 
154508:         && j<nMerge
154509:         && apSegment[j]->pOffsetList
154510:         && apSegment[j]->iDocid==iDocid
154511:       ){
154512:         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
154513:         j++;
154514:       }
154515:       if( rc!=SQLITE_OK ) return rc;
154516:       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
154517: 
154518:       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
154519:         rc = fts3MsrBufferData(pMsr, pList, nList+1);
154520:         if( rc!=SQLITE_OK ) return rc;
154521:         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
154522:         pList = pMsr->aBuffer;
154523:       }
154524: 
154525:       if( pMsr->iColFilter>=0 ){
154526:         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
154527:       }
154528: 
154529:       if( nList>0 ){
154530:         *paPoslist = pList;
154531:         *piDocid = iDocid;
154532:         *pnPoslist = nList;
154533:         break;
154534:       }
154535:     }
154536:   }
154537: 
154538:   return SQLITE_OK;
154539: }
154540: 
154541: static int fts3SegReaderStart(
154542:   Fts3Table *p,                   /* Virtual table handle */
154543:   Fts3MultiSegReader *pCsr,       /* Cursor object */
154544:   const char *zTerm,              /* Term searched for (or NULL) */
154545:   int nTerm                       /* Length of zTerm in bytes */
154546: ){
154547:   int i;
154548:   int nSeg = pCsr->nSegment;
154549: 
154550:   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
154551:   ** for, then advance each segment iterator until it points to a term of
154552:   ** equal or greater value than the specified term. This prevents many
154553:   ** unnecessary merge/sort operations for the case where single segment
154554:   ** b-tree leaf nodes contain more than one term.
154555:   */
154556:   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
154557:     int res = 0;
154558:     Fts3SegReader *pSeg = pCsr->apSegment[i];
154559:     do {
154560:       int rc = fts3SegReaderNext(p, pSeg, 0);
154561:       if( rc!=SQLITE_OK ) return rc;
154562:     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
154563: 
154564:     if( pSeg->bLookup && res!=0 ){
154565:       fts3SegReaderSetEof(pSeg);
154566:     }
154567:   }
154568:   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
154569: 
154570:   return SQLITE_OK;
154571: }
154572: 
154573: SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
154574:   Fts3Table *p,                   /* Virtual table handle */
154575:   Fts3MultiSegReader *pCsr,       /* Cursor object */
154576:   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
154577: ){
154578:   pCsr->pFilter = pFilter;
154579:   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
154580: }
154581: 
154582: SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
154583:   Fts3Table *p,                   /* Virtual table handle */
154584:   Fts3MultiSegReader *pCsr,       /* Cursor object */
154585:   int iCol,                       /* Column to match on. */
154586:   const char *zTerm,              /* Term to iterate through a doclist for */
154587:   int nTerm                       /* Number of bytes in zTerm */
154588: ){
154589:   int i;
154590:   int rc;
154591:   int nSegment = pCsr->nSegment;
154592:   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154593:     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154594:   );
154595: 
154596:   assert( pCsr->pFilter==0 );
154597:   assert( zTerm && nTerm>0 );
154598: 
154599:   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
154600:   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
154601:   if( rc!=SQLITE_OK ) return rc;
154602: 
154603:   /* Determine how many of the segments actually point to zTerm/nTerm. */
154604:   for(i=0; i<nSegment; i++){
154605:     Fts3SegReader *pSeg = pCsr->apSegment[i];
154606:     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
154607:       break;
154608:     }
154609:   }
154610:   pCsr->nAdvance = i;
154611: 
154612:   /* Advance each of the segments to point to the first docid. */
154613:   for(i=0; i<pCsr->nAdvance; i++){
154614:     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
154615:     if( rc!=SQLITE_OK ) return rc;
154616:   }
154617:   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
154618: 
154619:   assert( iCol<0 || iCol<p->nColumn );
154620:   pCsr->iColFilter = iCol;
154621: 
154622:   return SQLITE_OK;
154623: }
154624: 
154625: /*
154626: ** This function is called on a MultiSegReader that has been started using
154627: ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
154628: ** have been made. Calling this function puts the MultiSegReader in such
154629: ** a state that if the next two calls are:
154630: **
154631: **   sqlite3Fts3SegReaderStart()
154632: **   sqlite3Fts3SegReaderStep()
154633: **
154634: ** then the entire doclist for the term is available in 
154635: ** MultiSegReader.aDoclist/nDoclist.
154636: */
154637: SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
154638:   int i;                          /* Used to iterate through segment-readers */
154639: 
154640:   assert( pCsr->zTerm==0 );
154641:   assert( pCsr->nTerm==0 );
154642:   assert( pCsr->aDoclist==0 );
154643:   assert( pCsr->nDoclist==0 );
154644: 
154645:   pCsr->nAdvance = 0;
154646:   pCsr->bRestart = 1;
154647:   for(i=0; i<pCsr->nSegment; i++){
154648:     pCsr->apSegment[i]->pOffsetList = 0;
154649:     pCsr->apSegment[i]->nOffsetList = 0;
154650:     pCsr->apSegment[i]->iDocid = 0;
154651:   }
154652: 
154653:   return SQLITE_OK;
154654: }
154655: 
154656: 
154657: SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
154658:   Fts3Table *p,                   /* Virtual table handle */
154659:   Fts3MultiSegReader *pCsr        /* Cursor object */
154660: ){
154661:   int rc = SQLITE_OK;
154662: 
154663:   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
154664:   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
154665:   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
154666:   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
154667:   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
154668:   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
154669: 
154670:   Fts3SegReader **apSegment = pCsr->apSegment;
154671:   int nSegment = pCsr->nSegment;
154672:   Fts3SegFilter *pFilter = pCsr->pFilter;
154673:   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
154674:     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
154675:   );
154676: 
154677:   if( pCsr->nSegment==0 ) return SQLITE_OK;
154678: 
154679:   do {
154680:     int nMerge;
154681:     int i;
154682:   
154683:     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
154684:     ** forward. Then sort the list in order of current term again.  
154685:     */
154686:     for(i=0; i<pCsr->nAdvance; i++){
154687:       Fts3SegReader *pSeg = apSegment[i];
154688:       if( pSeg->bLookup ){
154689:         fts3SegReaderSetEof(pSeg);
154690:       }else{
154691:         rc = fts3SegReaderNext(p, pSeg, 0);
154692:       }
154693:       if( rc!=SQLITE_OK ) return rc;
154694:     }
154695:     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
154696:     pCsr->nAdvance = 0;
154697: 
154698:     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
154699:     assert( rc==SQLITE_OK );
154700:     if( apSegment[0]->aNode==0 ) break;
154701: 
154702:     pCsr->nTerm = apSegment[0]->nTerm;
154703:     pCsr->zTerm = apSegment[0]->zTerm;
154704: 
154705:     /* If this is a prefix-search, and if the term that apSegment[0] points
154706:     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
154707:     ** required callbacks have been made. In this case exit early.
154708:     **
154709:     ** Similarly, if this is a search for an exact match, and the first term
154710:     ** of segment apSegment[0] is not a match, exit early.
154711:     */
154712:     if( pFilter->zTerm && !isScan ){
154713:       if( pCsr->nTerm<pFilter->nTerm 
154714:        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
154715:        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
154716:       ){
154717:         break;
154718:       }
154719:     }
154720: 
154721:     nMerge = 1;
154722:     while( nMerge<nSegment 
154723:         && apSegment[nMerge]->aNode
154724:         && apSegment[nMerge]->nTerm==pCsr->nTerm 
154725:         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
154726:     ){
154727:       nMerge++;
154728:     }
154729: 
154730:     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
154731:     if( nMerge==1 
154732:      && !isIgnoreEmpty 
154733:      && !isFirst 
154734:      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
154735:     ){
154736:       pCsr->nDoclist = apSegment[0]->nDoclist;
154737:       if( fts3SegReaderIsPending(apSegment[0]) ){
154738:         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
154739:         pCsr->aDoclist = pCsr->aBuffer;
154740:       }else{
154741:         pCsr->aDoclist = apSegment[0]->aDoclist;
154742:       }
154743:       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
154744:     }else{
154745:       int nDoclist = 0;           /* Size of doclist */
154746:       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
154747: 
154748:       /* The current term of the first nMerge entries in the array
154749:       ** of Fts3SegReader objects is the same. The doclists must be merged
154750:       ** and a single term returned with the merged doclist.
154751:       */
154752:       for(i=0; i<nMerge; i++){
154753:         fts3SegReaderFirstDocid(p, apSegment[i]);
154754:       }
154755:       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
154756:       while( apSegment[0]->pOffsetList ){
154757:         int j;                    /* Number of segments that share a docid */
154758:         char *pList = 0;
154759:         int nList = 0;
154760:         int nByte;
154761:         sqlite3_int64 iDocid = apSegment[0]->iDocid;
154762:         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
154763:         j = 1;
154764:         while( j<nMerge
154765:             && apSegment[j]->pOffsetList
154766:             && apSegment[j]->iDocid==iDocid
154767:         ){
154768:           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
154769:           j++;
154770:         }
154771: 
154772:         if( isColFilter ){
154773:           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
154774:         }
154775: 
154776:         if( !isIgnoreEmpty || nList>0 ){
154777: 
154778:           /* Calculate the 'docid' delta value to write into the merged 
154779:           ** doclist. */
154780:           sqlite3_int64 iDelta;
154781:           if( p->bDescIdx && nDoclist>0 ){
154782:             iDelta = iPrev - iDocid;
154783:           }else{
154784:             iDelta = iDocid - iPrev;
154785:           }
154786:           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
154787:           assert( nDoclist>0 || iDelta==iDocid );
154788: 
154789:           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
154790:           if( nDoclist+nByte>pCsr->nBuffer ){
154791:             char *aNew;
154792:             pCsr->nBuffer = (nDoclist+nByte)*2;
154793:             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
154794:             if( !aNew ){
154795:               return SQLITE_NOMEM;
154796:             }
154797:             pCsr->aBuffer = aNew;
154798:           }
154799: 
154800:           if( isFirst ){
154801:             char *a = &pCsr->aBuffer[nDoclist];
154802:             int nWrite;
154803:            
154804:             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
154805:             if( nWrite ){
154806:               iPrev = iDocid;
154807:               nDoclist += nWrite;
154808:             }
154809:           }else{
154810:             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
154811:             iPrev = iDocid;
154812:             if( isRequirePos ){
154813:               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
154814:               nDoclist += nList;
154815:               pCsr->aBuffer[nDoclist++] = '\0';
154816:             }
154817:           }
154818:         }
154819: 
154820:         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
154821:       }
154822:       if( nDoclist>0 ){
154823:         pCsr->aDoclist = pCsr->aBuffer;
154824:         pCsr->nDoclist = nDoclist;
154825:         rc = SQLITE_ROW;
154826:       }
154827:     }
154828:     pCsr->nAdvance = nMerge;
154829:   }while( rc==SQLITE_OK );
154830: 
154831:   return rc;
154832: }
154833: 
154834: 
154835: SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
154836:   Fts3MultiSegReader *pCsr       /* Cursor object */
154837: ){
154838:   if( pCsr ){
154839:     int i;
154840:     for(i=0; i<pCsr->nSegment; i++){
154841:       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
154842:     }
154843:     sqlite3_free(pCsr->apSegment);
154844:     sqlite3_free(pCsr->aBuffer);
154845: 
154846:     pCsr->nSegment = 0;
154847:     pCsr->apSegment = 0;
154848:     pCsr->aBuffer = 0;
154849:   }
154850: }
154851: 
154852: /*
154853: ** Decode the "end_block" field, selected by column iCol of the SELECT 
154854: ** statement passed as the first argument. 
154855: **
154856: ** The "end_block" field may contain either an integer, or a text field
154857: ** containing the text representation of two non-negative integers separated 
154858: ** by one or more space (0x20) characters. In the first case, set *piEndBlock 
154859: ** to the integer value and *pnByte to zero before returning. In the second, 
154860: ** set *piEndBlock to the first value and *pnByte to the second.
154861: */
154862: static void fts3ReadEndBlockField(
154863:   sqlite3_stmt *pStmt, 
154864:   int iCol, 
154865:   i64 *piEndBlock,
154866:   i64 *pnByte
154867: ){
154868:   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
154869:   if( zText ){
154870:     int i;
154871:     int iMul = 1;
154872:     i64 iVal = 0;
154873:     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
154874:       iVal = iVal*10 + (zText[i] - '0');
154875:     }
154876:     *piEndBlock = iVal;
154877:     while( zText[i]==' ' ) i++;
154878:     iVal = 0;
154879:     if( zText[i]=='-' ){
154880:       i++;
154881:       iMul = -1;
154882:     }
154883:     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
154884:       iVal = iVal*10 + (zText[i] - '0');
154885:     }
154886:     *pnByte = (iVal * (i64)iMul);
154887:   }
154888: }
154889: 
154890: 
154891: /*
154892: ** A segment of size nByte bytes has just been written to absolute level
154893: ** iAbsLevel. Promote any segments that should be promoted as a result.
154894: */
154895: static int fts3PromoteSegments(
154896:   Fts3Table *p,                   /* FTS table handle */
154897:   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
154898:   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
154899: ){
154900:   int rc = SQLITE_OK;
154901:   sqlite3_stmt *pRange;
154902: 
154903:   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
154904: 
154905:   if( rc==SQLITE_OK ){
154906:     int bOk = 0;
154907:     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
154908:     i64 nLimit = (nByte*3)/2;
154909: 
154910:     /* Loop through all entries in the %_segdir table corresponding to 
154911:     ** segments in this index on levels greater than iAbsLevel. If there is
154912:     ** at least one such segment, and it is possible to determine that all 
154913:     ** such segments are smaller than nLimit bytes in size, they will be 
154914:     ** promoted to level iAbsLevel.  */
154915:     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
154916:     sqlite3_bind_int64(pRange, 2, iLast);
154917:     while( SQLITE_ROW==sqlite3_step(pRange) ){
154918:       i64 nSize = 0, dummy;
154919:       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
154920:       if( nSize<=0 || nSize>nLimit ){
154921:         /* If nSize==0, then the %_segdir.end_block field does not not 
154922:         ** contain a size value. This happens if it was written by an
154923:         ** old version of FTS. In this case it is not possible to determine
154924:         ** the size of the segment, and so segment promotion does not
154925:         ** take place.  */
154926:         bOk = 0;
154927:         break;
154928:       }
154929:       bOk = 1;
154930:     }
154931:     rc = sqlite3_reset(pRange);
154932: 
154933:     if( bOk ){
154934:       int iIdx = 0;
154935:       sqlite3_stmt *pUpdate1 = 0;
154936:       sqlite3_stmt *pUpdate2 = 0;
154937: 
154938:       if( rc==SQLITE_OK ){
154939:         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
154940:       }
154941:       if( rc==SQLITE_OK ){
154942:         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
154943:       }
154944: 
154945:       if( rc==SQLITE_OK ){
154946: 
154947:         /* Loop through all %_segdir entries for segments in this index with
154948:         ** levels equal to or greater than iAbsLevel. As each entry is visited,
154949:         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
154950:         ** oldest segment in the range, 1 for the next oldest, and so on.
154951:         **
154952:         ** In other words, move all segments being promoted to level -1,
154953:         ** setting the "idx" fields as appropriate to keep them in the same
154954:         ** order. The contents of level -1 (which is never used, except
154955:         ** transiently here), will be moved back to level iAbsLevel below.  */
154956:         sqlite3_bind_int64(pRange, 1, iAbsLevel);
154957:         while( SQLITE_ROW==sqlite3_step(pRange) ){
154958:           sqlite3_bind_int(pUpdate1, 1, iIdx++);
154959:           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
154960:           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
154961:           sqlite3_step(pUpdate1);
154962:           rc = sqlite3_reset(pUpdate1);
154963:           if( rc!=SQLITE_OK ){
154964:             sqlite3_reset(pRange);
154965:             break;
154966:           }
154967:         }
154968:       }
154969:       if( rc==SQLITE_OK ){
154970:         rc = sqlite3_reset(pRange);
154971:       }
154972: 
154973:       /* Move level -1 to level iAbsLevel */
154974:       if( rc==SQLITE_OK ){
154975:         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
154976:         sqlite3_step(pUpdate2);
154977:         rc = sqlite3_reset(pUpdate2);
154978:       }
154979:     }
154980:   }
154981: 
154982: 
154983:   return rc;
154984: }
154985: 
154986: /*
154987: ** Merge all level iLevel segments in the database into a single 
154988: ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
154989: ** single segment with a level equal to the numerically largest level 
154990: ** currently present in the database.
154991: **
154992: ** If this function is called with iLevel<0, but there is only one
154993: ** segment in the database, SQLITE_DONE is returned immediately. 
154994: ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
154995: ** an SQLite error code is returned.
154996: */
154997: static int fts3SegmentMerge(
154998:   Fts3Table *p, 
154999:   int iLangid,                    /* Language id to merge */
155000:   int iIndex,                     /* Index in p->aIndex[] to merge */
155001:   int iLevel                      /* Level to merge */
155002: ){
155003:   int rc;                         /* Return code */
155004:   int iIdx = 0;                   /* Index of new segment */
155005:   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
155006:   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
155007:   Fts3SegFilter filter;           /* Segment term filter condition */
155008:   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
155009:   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
155010:   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
155011: 
155012:   assert( iLevel==FTS3_SEGCURSOR_ALL
155013:        || iLevel==FTS3_SEGCURSOR_PENDING
155014:        || iLevel>=0
155015:   );
155016:   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
155017:   assert( iIndex>=0 && iIndex<p->nIndex );
155018: 
155019:   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
155020:   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
155021: 
155022:   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
155023:     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
155024:     if( rc!=SQLITE_OK ) goto finished;
155025:   }
155026: 
155027:   if( iLevel==FTS3_SEGCURSOR_ALL ){
155028:     /* This call is to merge all segments in the database to a single
155029:     ** segment. The level of the new segment is equal to the numerically
155030:     ** greatest segment level currently present in the database for this
155031:     ** index. The idx of the new segment is always 0.  */
155032:     if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
155033:       rc = SQLITE_DONE;
155034:       goto finished;
155035:     }
155036:     iNewLevel = iMaxLevel;
155037:     bIgnoreEmpty = 1;
155038: 
155039:   }else{
155040:     /* This call is to merge all segments at level iLevel. find the next
155041:     ** available segment index at level iLevel+1. The call to
155042:     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
155043:     ** a single iLevel+2 segment if necessary.  */
155044:     assert( FTS3_SEGCURSOR_PENDING==-1 );
155045:     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
155046:     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
155047:     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
155048:   }
155049:   if( rc!=SQLITE_OK ) goto finished;
155050: 
155051:   assert( csr.nSegment>0 );
155052:   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
155053:   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
155054: 
155055:   memset(&filter, 0, sizeof(Fts3SegFilter));
155056:   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
155057:   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
155058: 
155059:   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
155060:   while( SQLITE_OK==rc ){
155061:     rc = sqlite3Fts3SegReaderStep(p, &csr);
155062:     if( rc!=SQLITE_ROW ) break;
155063:     rc = fts3SegWriterAdd(p, &pWriter, 1, 
155064:         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
155065:   }
155066:   if( rc!=SQLITE_OK ) goto finished;
155067:   assert( pWriter || bIgnoreEmpty );
155068: 
155069:   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
155070:     rc = fts3DeleteSegdir(
155071:         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
155072:     );
155073:     if( rc!=SQLITE_OK ) goto finished;
155074:   }
155075:   if( pWriter ){
155076:     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
155077:     if( rc==SQLITE_OK ){
155078:       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
155079:         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
155080:       }
155081:     }
155082:   }
155083: 
155084:  finished:
155085:   fts3SegWriterFree(pWriter);
155086:   sqlite3Fts3SegReaderFinish(&csr);
155087:   return rc;
155088: }
155089: 
155090: 
155091: /* 
155092: ** Flush the contents of pendingTerms to level 0 segments. 
155093: */
155094: SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
155095:   int rc = SQLITE_OK;
155096:   int i;
155097:         
155098:   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
155099:     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
155100:     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
155101:   }
155102:   sqlite3Fts3PendingTermsClear(p);
155103: 
155104:   /* Determine the auto-incr-merge setting if unknown.  If enabled,
155105:   ** estimate the number of leaf blocks of content to be written
155106:   */
155107:   if( rc==SQLITE_OK && p->bHasStat
155108:    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
155109:   ){
155110:     sqlite3_stmt *pStmt = 0;
155111:     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
155112:     if( rc==SQLITE_OK ){
155113:       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
155114:       rc = sqlite3_step(pStmt);
155115:       if( rc==SQLITE_ROW ){
155116:         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
155117:         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
155118:       }else if( rc==SQLITE_DONE ){
155119:         p->nAutoincrmerge = 0;
155120:       }
155121:       rc = sqlite3_reset(pStmt);
155122:     }
155123:   }
155124:   return rc;
155125: }
155126: 
155127: /*
155128: ** Encode N integers as varints into a blob.
155129: */
155130: static void fts3EncodeIntArray(
155131:   int N,             /* The number of integers to encode */
155132:   u32 *a,            /* The integer values */
155133:   char *zBuf,        /* Write the BLOB here */
155134:   int *pNBuf         /* Write number of bytes if zBuf[] used here */
155135: ){
155136:   int i, j;
155137:   for(i=j=0; i<N; i++){
155138:     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
155139:   }
155140:   *pNBuf = j;
155141: }
155142: 
155143: /*
155144: ** Decode a blob of varints into N integers
155145: */
155146: static void fts3DecodeIntArray(
155147:   int N,             /* The number of integers to decode */
155148:   u32 *a,            /* Write the integer values */
155149:   const char *zBuf,  /* The BLOB containing the varints */
155150:   int nBuf           /* size of the BLOB */
155151: ){
155152:   int i, j;
155153:   UNUSED_PARAMETER(nBuf);
155154:   for(i=j=0; i<N; i++){
155155:     sqlite3_int64 x;
155156:     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
155157:     assert(j<=nBuf);
155158:     a[i] = (u32)(x & 0xffffffff);
155159:   }
155160: }
155161: 
155162: /*
155163: ** Insert the sizes (in tokens) for each column of the document
155164: ** with docid equal to p->iPrevDocid.  The sizes are encoded as
155165: ** a blob of varints.
155166: */
155167: static void fts3InsertDocsize(
155168:   int *pRC,                       /* Result code */
155169:   Fts3Table *p,                   /* Table into which to insert */
155170:   u32 *aSz                        /* Sizes of each column, in tokens */
155171: ){
155172:   char *pBlob;             /* The BLOB encoding of the document size */
155173:   int nBlob;               /* Number of bytes in the BLOB */
155174:   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
155175:   int rc;                  /* Result code from subfunctions */
155176: 
155177:   if( *pRC ) return;
155178:   pBlob = sqlite3_malloc( 10*p->nColumn );
155179:   if( pBlob==0 ){
155180:     *pRC = SQLITE_NOMEM;
155181:     return;
155182:   }
155183:   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
155184:   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
155185:   if( rc ){
155186:     sqlite3_free(pBlob);
155187:     *pRC = rc;
155188:     return;
155189:   }
155190:   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
155191:   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
155192:   sqlite3_step(pStmt);
155193:   *pRC = sqlite3_reset(pStmt);
155194: }
155195: 
155196: /*
155197: ** Record 0 of the %_stat table contains a blob consisting of N varints,
155198: ** where N is the number of user defined columns in the fts3 table plus
155199: ** two. If nCol is the number of user defined columns, then values of the 
155200: ** varints are set as follows:
155201: **
155202: **   Varint 0:       Total number of rows in the table.
155203: **
155204: **   Varint 1..nCol: For each column, the total number of tokens stored in
155205: **                   the column for all rows of the table.
155206: **
155207: **   Varint 1+nCol:  The total size, in bytes, of all text values in all
155208: **                   columns of all rows of the table.
155209: **
155210: */
155211: static void fts3UpdateDocTotals(
155212:   int *pRC,                       /* The result code */
155213:   Fts3Table *p,                   /* Table being updated */
155214:   u32 *aSzIns,                    /* Size increases */
155215:   u32 *aSzDel,                    /* Size decreases */
155216:   int nChng                       /* Change in the number of documents */
155217: ){
155218:   char *pBlob;             /* Storage for BLOB written into %_stat */
155219:   int nBlob;               /* Size of BLOB written into %_stat */
155220:   u32 *a;                  /* Array of integers that becomes the BLOB */
155221:   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
155222:   int i;                   /* Loop counter */
155223:   int rc;                  /* Result code from subfunctions */
155224: 
155225:   const int nStat = p->nColumn+2;
155226: 
155227:   if( *pRC ) return;
155228:   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
155229:   if( a==0 ){
155230:     *pRC = SQLITE_NOMEM;
155231:     return;
155232:   }
155233:   pBlob = (char*)&a[nStat];
155234:   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
155235:   if( rc ){
155236:     sqlite3_free(a);
155237:     *pRC = rc;
155238:     return;
155239:   }
155240:   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
155241:   if( sqlite3_step(pStmt)==SQLITE_ROW ){
155242:     fts3DecodeIntArray(nStat, a,
155243:          sqlite3_column_blob(pStmt, 0),
155244:          sqlite3_column_bytes(pStmt, 0));
155245:   }else{
155246:     memset(a, 0, sizeof(u32)*(nStat) );
155247:   }
155248:   rc = sqlite3_reset(pStmt);
155249:   if( rc!=SQLITE_OK ){
155250:     sqlite3_free(a);
155251:     *pRC = rc;
155252:     return;
155253:   }
155254:   if( nChng<0 && a[0]<(u32)(-nChng) ){
155255:     a[0] = 0;
155256:   }else{
155257:     a[0] += nChng;
155258:   }
155259:   for(i=0; i<p->nColumn+1; i++){
155260:     u32 x = a[i+1];
155261:     if( x+aSzIns[i] < aSzDel[i] ){
155262:       x = 0;
155263:     }else{
155264:       x = x + aSzIns[i] - aSzDel[i];
155265:     }
155266:     a[i+1] = x;
155267:   }
155268:   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
155269:   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
155270:   if( rc ){
155271:     sqlite3_free(a);
155272:     *pRC = rc;
155273:     return;
155274:   }
155275:   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
155276:   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
155277:   sqlite3_step(pStmt);
155278:   *pRC = sqlite3_reset(pStmt);
155279:   sqlite3_free(a);
155280: }
155281: 
155282: /*
155283: ** Merge the entire database so that there is one segment for each 
155284: ** iIndex/iLangid combination.
155285: */
155286: static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
155287:   int bSeenDone = 0;
155288:   int rc;
155289:   sqlite3_stmt *pAllLangid = 0;
155290: 
155291:   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
155292:   if( rc==SQLITE_OK ){
155293:     int rc2;
155294:     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
155295:     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
155296:     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
155297:       int i;
155298:       int iLangid = sqlite3_column_int(pAllLangid, 0);
155299:       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
155300:         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
155301:         if( rc==SQLITE_DONE ){
155302:           bSeenDone = 1;
155303:           rc = SQLITE_OK;
155304:         }
155305:       }
155306:     }
155307:     rc2 = sqlite3_reset(pAllLangid);
155308:     if( rc==SQLITE_OK ) rc = rc2;
155309:   }
155310: 
155311:   sqlite3Fts3SegmentsClose(p);
155312:   sqlite3Fts3PendingTermsClear(p);
155313: 
155314:   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
155315: }
155316: 
155317: /*
155318: ** This function is called when the user executes the following statement:
155319: **
155320: **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
155321: **
155322: ** The entire FTS index is discarded and rebuilt. If the table is one 
155323: ** created using the content=xxx option, then the new index is based on
155324: ** the current contents of the xxx table. Otherwise, it is rebuilt based
155325: ** on the contents of the %_content table.
155326: */
155327: static int fts3DoRebuild(Fts3Table *p){
155328:   int rc;                         /* Return Code */
155329: 
155330:   rc = fts3DeleteAll(p, 0);
155331:   if( rc==SQLITE_OK ){
155332:     u32 *aSz = 0;
155333:     u32 *aSzIns = 0;
155334:     u32 *aSzDel = 0;
155335:     sqlite3_stmt *pStmt = 0;
155336:     int nEntry = 0;
155337: 
155338:     /* Compose and prepare an SQL statement to loop through the content table */
155339:     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
155340:     if( !zSql ){
155341:       rc = SQLITE_NOMEM;
155342:     }else{
155343:       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
155344:       sqlite3_free(zSql);
155345:     }
155346: 
155347:     if( rc==SQLITE_OK ){
155348:       int nByte = sizeof(u32) * (p->nColumn+1)*3;
155349:       aSz = (u32 *)sqlite3_malloc(nByte);
155350:       if( aSz==0 ){
155351:         rc = SQLITE_NOMEM;
155352:       }else{
155353:         memset(aSz, 0, nByte);
155354:         aSzIns = &aSz[p->nColumn+1];
155355:         aSzDel = &aSzIns[p->nColumn+1];
155356:       }
155357:     }
155358: 
155359:     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
155360:       int iCol;
155361:       int iLangid = langidFromSelect(p, pStmt);
155362:       rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
155363:       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
155364:       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
155365:         if( p->abNotindexed[iCol]==0 ){
155366:           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
155367:           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
155368:           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
155369:         }
155370:       }
155371:       if( p->bHasDocsize ){
155372:         fts3InsertDocsize(&rc, p, aSz);
155373:       }
155374:       if( rc!=SQLITE_OK ){
155375:         sqlite3_finalize(pStmt);
155376:         pStmt = 0;
155377:       }else{
155378:         nEntry++;
155379:         for(iCol=0; iCol<=p->nColumn; iCol++){
155380:           aSzIns[iCol] += aSz[iCol];
155381:         }
155382:       }
155383:     }
155384:     if( p->bFts4 ){
155385:       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
155386:     }
155387:     sqlite3_free(aSz);
155388: 
155389:     if( pStmt ){
155390:       int rc2 = sqlite3_finalize(pStmt);
155391:       if( rc==SQLITE_OK ){
155392:         rc = rc2;
155393:       }
155394:     }
155395:   }
155396: 
155397:   return rc;
155398: }
155399: 
155400: 
155401: /*
155402: ** This function opens a cursor used to read the input data for an 
155403: ** incremental merge operation. Specifically, it opens a cursor to scan
155404: ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
155405: ** level iAbsLevel.
155406: */
155407: static int fts3IncrmergeCsr(
155408:   Fts3Table *p,                   /* FTS3 table handle */
155409:   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
155410:   int nSeg,                       /* Number of segments to merge */
155411:   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
155412: ){
155413:   int rc;                         /* Return Code */
155414:   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
155415:   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
155416: 
155417:   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
155418:   memset(pCsr, 0, sizeof(*pCsr));
155419:   nByte = sizeof(Fts3SegReader *) * nSeg;
155420:   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
155421: 
155422:   if( pCsr->apSegment==0 ){
155423:     rc = SQLITE_NOMEM;
155424:   }else{
155425:     memset(pCsr->apSegment, 0, nByte);
155426:     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
155427:   }
155428:   if( rc==SQLITE_OK ){
155429:     int i;
155430:     int rc2;
155431:     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
155432:     assert( pCsr->nSegment==0 );
155433:     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
155434:       rc = sqlite3Fts3SegReaderNew(i, 0,
155435:           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
155436:           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
155437:           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
155438:           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
155439:           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
155440:           &pCsr->apSegment[i]
155441:       );
155442:       pCsr->nSegment++;
155443:     }
155444:     rc2 = sqlite3_reset(pStmt);
155445:     if( rc==SQLITE_OK ) rc = rc2;
155446:   }
155447: 
155448:   return rc;
155449: }
155450: 
155451: typedef struct IncrmergeWriter IncrmergeWriter;
155452: typedef struct NodeWriter NodeWriter;
155453: typedef struct Blob Blob;
155454: typedef struct NodeReader NodeReader;
155455: 
155456: /*
155457: ** An instance of the following structure is used as a dynamic buffer
155458: ** to build up nodes or other blobs of data in.
155459: **
155460: ** The function blobGrowBuffer() is used to extend the allocation.
155461: */
155462: struct Blob {
155463:   char *a;                        /* Pointer to allocation */
155464:   int n;                          /* Number of valid bytes of data in a[] */
155465:   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
155466: };
155467: 
155468: /*
155469: ** This structure is used to build up buffers containing segment b-tree 
155470: ** nodes (blocks).
155471: */
155472: struct NodeWriter {
155473:   sqlite3_int64 iBlock;           /* Current block id */
155474:   Blob key;                       /* Last key written to the current block */
155475:   Blob block;                     /* Current block image */
155476: };
155477: 
155478: /*
155479: ** An object of this type contains the state required to create or append
155480: ** to an appendable b-tree segment.
155481: */
155482: struct IncrmergeWriter {
155483:   int nLeafEst;                   /* Space allocated for leaf blocks */
155484:   int nWork;                      /* Number of leaf pages flushed */
155485:   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
155486:   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
155487:   sqlite3_int64 iStart;           /* Block number of first allocated block */
155488:   sqlite3_int64 iEnd;             /* Block number of last allocated block */
155489:   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
155490:   u8 bNoLeafData;                 /* If true, store 0 for segment size */
155491:   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
155492: };
155493: 
155494: /*
155495: ** An object of the following type is used to read data from a single
155496: ** FTS segment node. See the following functions:
155497: **
155498: **     nodeReaderInit()
155499: **     nodeReaderNext()
155500: **     nodeReaderRelease()
155501: */
155502: struct NodeReader {
155503:   const char *aNode;
155504:   int nNode;
155505:   int iOff;                       /* Current offset within aNode[] */
155506: 
155507:   /* Output variables. Containing the current node entry. */
155508:   sqlite3_int64 iChild;           /* Pointer to child node */
155509:   Blob term;                      /* Current term */
155510:   const char *aDoclist;           /* Pointer to doclist */
155511:   int nDoclist;                   /* Size of doclist in bytes */
155512: };
155513: 
155514: /*
155515: ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
155516: ** Otherwise, if the allocation at pBlob->a is not already at least nMin
155517: ** bytes in size, extend (realloc) it to be so.
155518: **
155519: ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
155520: ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
155521: ** to reflect the new size of the pBlob->a[] buffer.
155522: */
155523: static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
155524:   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
155525:     int nAlloc = nMin;
155526:     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
155527:     if( a ){
155528:       pBlob->nAlloc = nAlloc;
155529:       pBlob->a = a;
155530:     }else{
155531:       *pRc = SQLITE_NOMEM;
155532:     }
155533:   }
155534: }
155535: 
155536: /*
155537: ** Attempt to advance the node-reader object passed as the first argument to
155538: ** the next entry on the node. 
155539: **
155540: ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
155541: ** Otherwise return SQLITE_OK. If there is no next entry on the node
155542: ** (e.g. because the current entry is the last) set NodeReader->aNode to
155543: ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
155544: ** variables for the new entry.
155545: */
155546: static int nodeReaderNext(NodeReader *p){
155547:   int bFirst = (p->term.n==0);    /* True for first term on the node */
155548:   int nPrefix = 0;                /* Bytes to copy from previous term */
155549:   int nSuffix = 0;                /* Bytes to append to the prefix */
155550:   int rc = SQLITE_OK;             /* Return code */
155551: 
155552:   assert( p->aNode );
155553:   if( p->iChild && bFirst==0 ) p->iChild++;
155554:   if( p->iOff>=p->nNode ){
155555:     /* EOF */
155556:     p->aNode = 0;
155557:   }else{
155558:     if( bFirst==0 ){
155559:       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
155560:     }
155561:     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
155562: 
155563:     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
155564:     if( rc==SQLITE_OK ){
155565:       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
155566:       p->term.n = nPrefix+nSuffix;
155567:       p->iOff += nSuffix;
155568:       if( p->iChild==0 ){
155569:         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
155570:         p->aDoclist = &p->aNode[p->iOff];
155571:         p->iOff += p->nDoclist;
155572:       }
155573:     }
155574:   }
155575: 
155576:   assert( p->iOff<=p->nNode );
155577: 
155578:   return rc;
155579: }
155580: 
155581: /*
155582: ** Release all dynamic resources held by node-reader object *p.
155583: */
155584: static void nodeReaderRelease(NodeReader *p){
155585:   sqlite3_free(p->term.a);
155586: }
155587: 
155588: /*
155589: ** Initialize a node-reader object to read the node in buffer aNode/nNode.
155590: **
155591: ** If successful, SQLITE_OK is returned and the NodeReader object set to 
155592: ** point to the first entry on the node (if any). Otherwise, an SQLite
155593: ** error code is returned.
155594: */
155595: static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
155596:   memset(p, 0, sizeof(NodeReader));
155597:   p->aNode = aNode;
155598:   p->nNode = nNode;
155599: 
155600:   /* Figure out if this is a leaf or an internal node. */
155601:   if( p->aNode[0] ){
155602:     /* An internal node. */
155603:     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
155604:   }else{
155605:     p->iOff = 1;
155606:   }
155607: 
155608:   return nodeReaderNext(p);
155609: }
155610: 
155611: /*
155612: ** This function is called while writing an FTS segment each time a leaf o
155613: ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
155614: ** to be greater than the largest key on the node just written, but smaller
155615: ** than or equal to the first key that will be written to the next leaf
155616: ** node.
155617: **
155618: ** The block id of the leaf node just written to disk may be found in
155619: ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
155620: */
155621: static int fts3IncrmergePush(
155622:   Fts3Table *p,                   /* Fts3 table handle */
155623:   IncrmergeWriter *pWriter,       /* Writer object */
155624:   const char *zTerm,              /* Term to write to internal node */
155625:   int nTerm                       /* Bytes at zTerm */
155626: ){
155627:   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
155628:   int iLayer;
155629: 
155630:   assert( nTerm>0 );
155631:   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
155632:     sqlite3_int64 iNextPtr = 0;
155633:     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
155634:     int rc = SQLITE_OK;
155635:     int nPrefix;
155636:     int nSuffix;
155637:     int nSpace;
155638: 
155639:     /* Figure out how much space the key will consume if it is written to
155640:     ** the current node of layer iLayer. Due to the prefix compression, 
155641:     ** the space required changes depending on which node the key is to
155642:     ** be added to.  */
155643:     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
155644:     nSuffix = nTerm - nPrefix;
155645:     nSpace  = sqlite3Fts3VarintLen(nPrefix);
155646:     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155647: 
155648:     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
155649:       /* If the current node of layer iLayer contains zero keys, or if adding
155650:       ** the key to it will not cause it to grow to larger than nNodeSize 
155651:       ** bytes in size, write the key here.  */
155652: 
155653:       Blob *pBlk = &pNode->block;
155654:       if( pBlk->n==0 ){
155655:         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
155656:         if( rc==SQLITE_OK ){
155657:           pBlk->a[0] = (char)iLayer;
155658:           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
155659:         }
155660:       }
155661:       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
155662:       blobGrowBuffer(&pNode->key, nTerm, &rc);
155663: 
155664:       if( rc==SQLITE_OK ){
155665:         if( pNode->key.n ){
155666:           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
155667:         }
155668:         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
155669:         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
155670:         pBlk->n += nSuffix;
155671: 
155672:         memcpy(pNode->key.a, zTerm, nTerm);
155673:         pNode->key.n = nTerm;
155674:       }
155675:     }else{
155676:       /* Otherwise, flush the current node of layer iLayer to disk.
155677:       ** Then allocate a new, empty sibling node. The key will be written
155678:       ** into the parent of this node. */
155679:       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
155680: 
155681:       assert( pNode->block.nAlloc>=p->nNodeSize );
155682:       pNode->block.a[0] = (char)iLayer;
155683:       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
155684: 
155685:       iNextPtr = pNode->iBlock;
155686:       pNode->iBlock++;
155687:       pNode->key.n = 0;
155688:     }
155689: 
155690:     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
155691:     iPtr = iNextPtr;
155692:   }
155693: 
155694:   assert( 0 );
155695:   return 0;
155696: }
155697: 
155698: /*
155699: ** Append a term and (optionally) doclist to the FTS segment node currently
155700: ** stored in blob *pNode. The node need not contain any terms, but the
155701: ** header must be written before this function is called.
155702: **
155703: ** A node header is a single 0x00 byte for a leaf node, or a height varint
155704: ** followed by the left-hand-child varint for an internal node.
155705: **
155706: ** The term to be appended is passed via arguments zTerm/nTerm. For a 
155707: ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
155708: ** node, both aDoclist and nDoclist must be passed 0.
155709: **
155710: ** If the size of the value in blob pPrev is zero, then this is the first
155711: ** term written to the node. Otherwise, pPrev contains a copy of the 
155712: ** previous term. Before this function returns, it is updated to contain a
155713: ** copy of zTerm/nTerm.
155714: **
155715: ** It is assumed that the buffer associated with pNode is already large
155716: ** enough to accommodate the new entry. The buffer associated with pPrev
155717: ** is extended by this function if requrired.
155718: **
155719: ** If an error (i.e. OOM condition) occurs, an SQLite error code is
155720: ** returned. Otherwise, SQLITE_OK.
155721: */
155722: static int fts3AppendToNode(
155723:   Blob *pNode,                    /* Current node image to append to */
155724:   Blob *pPrev,                    /* Buffer containing previous term written */
155725:   const char *zTerm,              /* New term to write */
155726:   int nTerm,                      /* Size of zTerm in bytes */
155727:   const char *aDoclist,           /* Doclist (or NULL) to write */
155728:   int nDoclist                    /* Size of aDoclist in bytes */ 
155729: ){
155730:   int rc = SQLITE_OK;             /* Return code */
155731:   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
155732:   int nPrefix;                    /* Size of term prefix in bytes */
155733:   int nSuffix;                    /* Size of term suffix in bytes */
155734: 
155735:   /* Node must have already been started. There must be a doclist for a
155736:   ** leaf node, and there must not be a doclist for an internal node.  */
155737:   assert( pNode->n>0 );
155738:   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
155739: 
155740:   blobGrowBuffer(pPrev, nTerm, &rc);
155741:   if( rc!=SQLITE_OK ) return rc;
155742: 
155743:   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
155744:   nSuffix = nTerm - nPrefix;
155745:   memcpy(pPrev->a, zTerm, nTerm);
155746:   pPrev->n = nTerm;
155747: 
155748:   if( bFirst==0 ){
155749:     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
155750:   }
155751:   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
155752:   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
155753:   pNode->n += nSuffix;
155754: 
155755:   if( aDoclist ){
155756:     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
155757:     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
155758:     pNode->n += nDoclist;
155759:   }
155760: 
155761:   assert( pNode->n<=pNode->nAlloc );
155762: 
155763:   return SQLITE_OK;
155764: }
155765: 
155766: /*
155767: ** Append the current term and doclist pointed to by cursor pCsr to the
155768: ** appendable b-tree segment opened for writing by pWriter.
155769: **
155770: ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
155771: */
155772: static int fts3IncrmergeAppend(
155773:   Fts3Table *p,                   /* Fts3 table handle */
155774:   IncrmergeWriter *pWriter,       /* Writer object */
155775:   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
155776: ){
155777:   const char *zTerm = pCsr->zTerm;
155778:   int nTerm = pCsr->nTerm;
155779:   const char *aDoclist = pCsr->aDoclist;
155780:   int nDoclist = pCsr->nDoclist;
155781:   int rc = SQLITE_OK;           /* Return code */
155782:   int nSpace;                   /* Total space in bytes required on leaf */
155783:   int nPrefix;                  /* Size of prefix shared with previous term */
155784:   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
155785:   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
155786: 
155787:   pLeaf = &pWriter->aNodeWriter[0];
155788:   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
155789:   nSuffix = nTerm - nPrefix;
155790: 
155791:   nSpace  = sqlite3Fts3VarintLen(nPrefix);
155792:   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155793:   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
155794: 
155795:   /* If the current block is not empty, and if adding this term/doclist
155796:   ** to the current block would make it larger than Fts3Table.nNodeSize
155797:   ** bytes, write this block out to the database. */
155798:   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
155799:     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
155800:     pWriter->nWork++;
155801: 
155802:     /* Add the current term to the parent node. The term added to the 
155803:     ** parent must:
155804:     **
155805:     **   a) be greater than the largest term on the leaf node just written
155806:     **      to the database (still available in pLeaf->key), and
155807:     **
155808:     **   b) be less than or equal to the term about to be added to the new
155809:     **      leaf node (zTerm/nTerm).
155810:     **
155811:     ** In other words, it must be the prefix of zTerm 1 byte longer than
155812:     ** the common prefix (if any) of zTerm and pWriter->zTerm.
155813:     */
155814:     if( rc==SQLITE_OK ){
155815:       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
155816:     }
155817: 
155818:     /* Advance to the next output block */
155819:     pLeaf->iBlock++;
155820:     pLeaf->key.n = 0;
155821:     pLeaf->block.n = 0;
155822: 
155823:     nSuffix = nTerm;
155824:     nSpace  = 1;
155825:     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
155826:     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
155827:   }
155828: 
155829:   pWriter->nLeafData += nSpace;
155830:   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
155831:   if( rc==SQLITE_OK ){
155832:     if( pLeaf->block.n==0 ){
155833:       pLeaf->block.n = 1;
155834:       pLeaf->block.a[0] = '\0';
155835:     }
155836:     rc = fts3AppendToNode(
155837:         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
155838:     );
155839:   }
155840: 
155841:   return rc;
155842: }
155843: 
155844: /*
155845: ** This function is called to release all dynamic resources held by the
155846: ** merge-writer object pWriter, and if no error has occurred, to flush
155847: ** all outstanding node buffers held by pWriter to disk.
155848: **
155849: ** If *pRc is not SQLITE_OK when this function is called, then no attempt
155850: ** is made to write any data to disk. Instead, this function serves only
155851: ** to release outstanding resources.
155852: **
155853: ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
155854: ** flushing buffers to disk, *pRc is set to an SQLite error code before
155855: ** returning.
155856: */
155857: static void fts3IncrmergeRelease(
155858:   Fts3Table *p,                   /* FTS3 table handle */
155859:   IncrmergeWriter *pWriter,       /* Merge-writer object */
155860:   int *pRc                        /* IN/OUT: Error code */
155861: ){
155862:   int i;                          /* Used to iterate through non-root layers */
155863:   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
155864:   NodeWriter *pRoot;              /* NodeWriter for root node */
155865:   int rc = *pRc;                  /* Error code */
155866: 
155867:   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
155868:   ** root node. If the segment fits entirely on a single leaf node, iRoot
155869:   ** will be set to 0. If the root node is the parent of the leaves, iRoot
155870:   ** will be 1. And so on.  */
155871:   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
155872:     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
155873:     if( pNode->block.n>0 ) break;
155874:     assert( *pRc || pNode->block.nAlloc==0 );
155875:     assert( *pRc || pNode->key.nAlloc==0 );
155876:     sqlite3_free(pNode->block.a);
155877:     sqlite3_free(pNode->key.a);
155878:   }
155879: 
155880:   /* Empty output segment. This is a no-op. */
155881:   if( iRoot<0 ) return;
155882: 
155883:   /* The entire output segment fits on a single node. Normally, this means
155884:   ** the node would be stored as a blob in the "root" column of the %_segdir
155885:   ** table. However, this is not permitted in this case. The problem is that 
155886:   ** space has already been reserved in the %_segments table, and so the 
155887:   ** start_block and end_block fields of the %_segdir table must be populated. 
155888:   ** And, by design or by accident, released versions of FTS cannot handle 
155889:   ** segments that fit entirely on the root node with start_block!=0.
155890:   **
155891:   ** Instead, create a synthetic root node that contains nothing but a 
155892:   ** pointer to the single content node. So that the segment consists of a
155893:   ** single leaf and a single interior (root) node.
155894:   **
155895:   ** Todo: Better might be to defer allocating space in the %_segments 
155896:   ** table until we are sure it is needed.
155897:   */
155898:   if( iRoot==0 ){
155899:     Blob *pBlock = &pWriter->aNodeWriter[1].block;
155900:     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
155901:     if( rc==SQLITE_OK ){
155902:       pBlock->a[0] = 0x01;
155903:       pBlock->n = 1 + sqlite3Fts3PutVarint(
155904:           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
155905:       );
155906:     }
155907:     iRoot = 1;
155908:   }
155909:   pRoot = &pWriter->aNodeWriter[iRoot];
155910: 
155911:   /* Flush all currently outstanding nodes to disk. */
155912:   for(i=0; i<iRoot; i++){
155913:     NodeWriter *pNode = &pWriter->aNodeWriter[i];
155914:     if( pNode->block.n>0 && rc==SQLITE_OK ){
155915:       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
155916:     }
155917:     sqlite3_free(pNode->block.a);
155918:     sqlite3_free(pNode->key.a);
155919:   }
155920: 
155921:   /* Write the %_segdir record. */
155922:   if( rc==SQLITE_OK ){
155923:     rc = fts3WriteSegdir(p, 
155924:         pWriter->iAbsLevel+1,               /* level */
155925:         pWriter->iIdx,                      /* idx */
155926:         pWriter->iStart,                    /* start_block */
155927:         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
155928:         pWriter->iEnd,                      /* end_block */
155929:         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
155930:         pRoot->block.a, pRoot->block.n      /* root */
155931:     );
155932:   }
155933:   sqlite3_free(pRoot->block.a);
155934:   sqlite3_free(pRoot->key.a);
155935: 
155936:   *pRc = rc;
155937: }
155938: 
155939: /*
155940: ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
155941: ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
155942: ** the other, it is considered to be smaller than the other.
155943: **
155944: ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
155945: ** if it is greater.
155946: */
155947: static int fts3TermCmp(
155948:   const char *zLhs, int nLhs,     /* LHS of comparison */
155949:   const char *zRhs, int nRhs      /* RHS of comparison */
155950: ){
155951:   int nCmp = MIN(nLhs, nRhs);
155952:   int res;
155953: 
155954:   res = memcmp(zLhs, zRhs, nCmp);
155955:   if( res==0 ) res = nLhs - nRhs;
155956: 
155957:   return res;
155958: }
155959: 
155960: 
155961: /*
155962: ** Query to see if the entry in the %_segments table with blockid iEnd is 
155963: ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
155964: ** returning. Otherwise, set *pbRes to 0. 
155965: **
155966: ** Or, if an error occurs while querying the database, return an SQLite 
155967: ** error code. The final value of *pbRes is undefined in this case.
155968: **
155969: ** This is used to test if a segment is an "appendable" segment. If it
155970: ** is, then a NULL entry has been inserted into the %_segments table
155971: ** with blockid %_segdir.end_block.
155972: */
155973: static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
155974:   int bRes = 0;                   /* Result to set *pbRes to */
155975:   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
155976:   int rc;                         /* Return code */
155977: 
155978:   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
155979:   if( rc==SQLITE_OK ){
155980:     sqlite3_bind_int64(pCheck, 1, iEnd);
155981:     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
155982:     rc = sqlite3_reset(pCheck);
155983:   }
155984:   
155985:   *pbRes = bRes;
155986:   return rc;
155987: }
155988: 
155989: /*
155990: ** This function is called when initializing an incremental-merge operation.
155991: ** It checks if the existing segment with index value iIdx at absolute level 
155992: ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
155993: ** merge-writer object *pWriter is initialized to write to it.
155994: **
155995: ** An existing segment can be appended to by an incremental merge if:
155996: **
155997: **   * It was initially created as an appendable segment (with all required
155998: **     space pre-allocated), and
155999: **
156000: **   * The first key read from the input (arguments zKey and nKey) is 
156001: **     greater than the largest key currently stored in the potential
156002: **     output segment.
156003: */
156004: static int fts3IncrmergeLoad(
156005:   Fts3Table *p,                   /* Fts3 table handle */
156006:   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
156007:   int iIdx,                       /* Index of candidate output segment */
156008:   const char *zKey,               /* First key to write */
156009:   int nKey,                       /* Number of bytes in nKey */
156010:   IncrmergeWriter *pWriter        /* Populate this object */
156011: ){
156012:   int rc;                         /* Return code */
156013:   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
156014: 
156015:   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
156016:   if( rc==SQLITE_OK ){
156017:     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
156018:     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
156019:     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
156020:     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
156021:     int nRoot = 0;                /* Size of aRoot[] in bytes */
156022:     int rc2;                      /* Return code from sqlite3_reset() */
156023:     int bAppendable = 0;          /* Set to true if segment is appendable */
156024: 
156025:     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
156026:     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
156027:     sqlite3_bind_int(pSelect, 2, iIdx);
156028:     if( sqlite3_step(pSelect)==SQLITE_ROW ){
156029:       iStart = sqlite3_column_int64(pSelect, 1);
156030:       iLeafEnd = sqlite3_column_int64(pSelect, 2);
156031:       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
156032:       if( pWriter->nLeafData<0 ){
156033:         pWriter->nLeafData = pWriter->nLeafData * -1;
156034:       }
156035:       pWriter->bNoLeafData = (pWriter->nLeafData==0);
156036:       nRoot = sqlite3_column_bytes(pSelect, 4);
156037:       aRoot = sqlite3_column_blob(pSelect, 4);
156038:     }else{
156039:       return sqlite3_reset(pSelect);
156040:     }
156041: 
156042:     /* Check for the zero-length marker in the %_segments table */
156043:     rc = fts3IsAppendable(p, iEnd, &bAppendable);
156044: 
156045:     /* Check that zKey/nKey is larger than the largest key the candidate */
156046:     if( rc==SQLITE_OK && bAppendable ){
156047:       char *aLeaf = 0;
156048:       int nLeaf = 0;
156049: 
156050:       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
156051:       if( rc==SQLITE_OK ){
156052:         NodeReader reader;
156053:         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
156054:             rc==SQLITE_OK && reader.aNode;
156055:             rc = nodeReaderNext(&reader)
156056:         ){
156057:           assert( reader.aNode );
156058:         }
156059:         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
156060:           bAppendable = 0;
156061:         }
156062:         nodeReaderRelease(&reader);
156063:       }
156064:       sqlite3_free(aLeaf);
156065:     }
156066: 
156067:     if( rc==SQLITE_OK && bAppendable ){
156068:       /* It is possible to append to this segment. Set up the IncrmergeWriter
156069:       ** object to do so.  */
156070:       int i;
156071:       int nHeight = (int)aRoot[0];
156072:       NodeWriter *pNode;
156073: 
156074:       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
156075:       pWriter->iStart = iStart;
156076:       pWriter->iEnd = iEnd;
156077:       pWriter->iAbsLevel = iAbsLevel;
156078:       pWriter->iIdx = iIdx;
156079: 
156080:       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
156081:         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
156082:       }
156083: 
156084:       pNode = &pWriter->aNodeWriter[nHeight];
156085:       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
156086:       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
156087:       if( rc==SQLITE_OK ){
156088:         memcpy(pNode->block.a, aRoot, nRoot);
156089:         pNode->block.n = nRoot;
156090:       }
156091: 
156092:       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
156093:         NodeReader reader;
156094:         pNode = &pWriter->aNodeWriter[i];
156095: 
156096:         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
156097:         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
156098:         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
156099:         if( rc==SQLITE_OK ){
156100:           memcpy(pNode->key.a, reader.term.a, reader.term.n);
156101:           pNode->key.n = reader.term.n;
156102:           if( i>0 ){
156103:             char *aBlock = 0;
156104:             int nBlock = 0;
156105:             pNode = &pWriter->aNodeWriter[i-1];
156106:             pNode->iBlock = reader.iChild;
156107:             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
156108:             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
156109:             if( rc==SQLITE_OK ){
156110:               memcpy(pNode->block.a, aBlock, nBlock);
156111:               pNode->block.n = nBlock;
156112:             }
156113:             sqlite3_free(aBlock);
156114:           }
156115:         }
156116:         nodeReaderRelease(&reader);
156117:       }
156118:     }
156119: 
156120:     rc2 = sqlite3_reset(pSelect);
156121:     if( rc==SQLITE_OK ) rc = rc2;
156122:   }
156123: 
156124:   return rc;
156125: }
156126: 
156127: /*
156128: ** Determine the largest segment index value that exists within absolute
156129: ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
156130: ** one before returning SQLITE_OK. Or, if there are no segments at all 
156131: ** within level iAbsLevel, set *piIdx to zero.
156132: **
156133: ** If an error occurs, return an SQLite error code. The final value of
156134: ** *piIdx is undefined in this case.
156135: */
156136: static int fts3IncrmergeOutputIdx( 
156137:   Fts3Table *p,                   /* FTS Table handle */
156138:   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
156139:   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
156140: ){
156141:   int rc;
156142:   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
156143: 
156144:   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
156145:   if( rc==SQLITE_OK ){
156146:     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
156147:     sqlite3_step(pOutputIdx);
156148:     *piIdx = sqlite3_column_int(pOutputIdx, 0);
156149:     rc = sqlite3_reset(pOutputIdx);
156150:   }
156151: 
156152:   return rc;
156153: }
156154: 
156155: /* 
156156: ** Allocate an appendable output segment on absolute level iAbsLevel+1
156157: ** with idx value iIdx.
156158: **
156159: ** In the %_segdir table, a segment is defined by the values in three
156160: ** columns:
156161: **
156162: **     start_block
156163: **     leaves_end_block
156164: **     end_block
156165: **
156166: ** When an appendable segment is allocated, it is estimated that the
156167: ** maximum number of leaf blocks that may be required is the sum of the
156168: ** number of leaf blocks consumed by the input segments, plus the number
156169: ** of input segments, multiplied by two. This value is stored in stack 
156170: ** variable nLeafEst.
156171: **
156172: ** A total of 16*nLeafEst blocks are allocated when an appendable segment
156173: ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
156174: ** array of leaf nodes starts at the first block allocated. The array
156175: ** of interior nodes that are parents of the leaf nodes start at block
156176: ** (start_block + (1 + end_block - start_block) / 16). And so on.
156177: **
156178: ** In the actual code below, the value "16" is replaced with the 
156179: ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
156180: */
156181: static int fts3IncrmergeWriter( 
156182:   Fts3Table *p,                   /* Fts3 table handle */
156183:   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
156184:   int iIdx,                       /* Index of new output segment */
156185:   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
156186:   IncrmergeWriter *pWriter        /* Populate this object */
156187: ){
156188:   int rc;                         /* Return Code */
156189:   int i;                          /* Iterator variable */
156190:   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
156191:   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
156192:   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
156193: 
156194:   /* Calculate nLeafEst. */
156195:   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
156196:   if( rc==SQLITE_OK ){
156197:     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
156198:     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
156199:     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
156200:       nLeafEst = sqlite3_column_int(pLeafEst, 0);
156201:     }
156202:     rc = sqlite3_reset(pLeafEst);
156203:   }
156204:   if( rc!=SQLITE_OK ) return rc;
156205: 
156206:   /* Calculate the first block to use in the output segment */
156207:   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
156208:   if( rc==SQLITE_OK ){
156209:     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
156210:       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
156211:       pWriter->iEnd = pWriter->iStart - 1;
156212:       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
156213:     }
156214:     rc = sqlite3_reset(pFirstBlock);
156215:   }
156216:   if( rc!=SQLITE_OK ) return rc;
156217: 
156218:   /* Insert the marker in the %_segments table to make sure nobody tries
156219:   ** to steal the space just allocated. This is also used to identify 
156220:   ** appendable segments.  */
156221:   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
156222:   if( rc!=SQLITE_OK ) return rc;
156223: 
156224:   pWriter->iAbsLevel = iAbsLevel;
156225:   pWriter->nLeafEst = nLeafEst;
156226:   pWriter->iIdx = iIdx;
156227: 
156228:   /* Set up the array of NodeWriter objects */
156229:   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
156230:     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
156231:   }
156232:   return SQLITE_OK;
156233: }
156234: 
156235: /*
156236: ** Remove an entry from the %_segdir table. This involves running the 
156237: ** following two statements:
156238: **
156239: **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
156240: **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
156241: **
156242: ** The DELETE statement removes the specific %_segdir level. The UPDATE 
156243: ** statement ensures that the remaining segments have contiguously allocated
156244: ** idx values.
156245: */
156246: static int fts3RemoveSegdirEntry(
156247:   Fts3Table *p,                   /* FTS3 table handle */
156248:   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
156249:   int iIdx                        /* Index of %_segdir entry to delete */
156250: ){
156251:   int rc;                         /* Return code */
156252:   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
156253: 
156254:   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
156255:   if( rc==SQLITE_OK ){
156256:     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
156257:     sqlite3_bind_int(pDelete, 2, iIdx);
156258:     sqlite3_step(pDelete);
156259:     rc = sqlite3_reset(pDelete);
156260:   }
156261: 
156262:   return rc;
156263: }
156264: 
156265: /*
156266: ** One or more segments have just been removed from absolute level iAbsLevel.
156267: ** Update the 'idx' values of the remaining segments in the level so that
156268: ** the idx values are a contiguous sequence starting from 0.
156269: */
156270: static int fts3RepackSegdirLevel(
156271:   Fts3Table *p,                   /* FTS3 table handle */
156272:   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
156273: ){
156274:   int rc;                         /* Return code */
156275:   int *aIdx = 0;                  /* Array of remaining idx values */
156276:   int nIdx = 0;                   /* Valid entries in aIdx[] */
156277:   int nAlloc = 0;                 /* Allocated size of aIdx[] */
156278:   int i;                          /* Iterator variable */
156279:   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
156280:   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
156281: 
156282:   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
156283:   if( rc==SQLITE_OK ){
156284:     int rc2;
156285:     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
156286:     while( SQLITE_ROW==sqlite3_step(pSelect) ){
156287:       if( nIdx>=nAlloc ){
156288:         int *aNew;
156289:         nAlloc += 16;
156290:         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
156291:         if( !aNew ){
156292:           rc = SQLITE_NOMEM;
156293:           break;
156294:         }
156295:         aIdx = aNew;
156296:       }
156297:       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
156298:     }
156299:     rc2 = sqlite3_reset(pSelect);
156300:     if( rc==SQLITE_OK ) rc = rc2;
156301:   }
156302: 
156303:   if( rc==SQLITE_OK ){
156304:     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
156305:   }
156306:   if( rc==SQLITE_OK ){
156307:     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
156308:   }
156309: 
156310:   assert( p->bIgnoreSavepoint==0 );
156311:   p->bIgnoreSavepoint = 1;
156312:   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
156313:     if( aIdx[i]!=i ){
156314:       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
156315:       sqlite3_bind_int(pUpdate, 1, i);
156316:       sqlite3_step(pUpdate);
156317:       rc = sqlite3_reset(pUpdate);
156318:     }
156319:   }
156320:   p->bIgnoreSavepoint = 0;
156321: 
156322:   sqlite3_free(aIdx);
156323:   return rc;
156324: }
156325: 
156326: static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
156327:   pNode->a[0] = (char)iHeight;
156328:   if( iChild ){
156329:     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
156330:     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
156331:   }else{
156332:     assert( pNode->nAlloc>=1 );
156333:     pNode->n = 1;
156334:   }
156335: }
156336: 
156337: /*
156338: ** The first two arguments are a pointer to and the size of a segment b-tree
156339: ** node. The node may be a leaf or an internal node.
156340: **
156341: ** This function creates a new node image in blob object *pNew by copying
156342: ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
156343: ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
156344: */
156345: static int fts3TruncateNode(
156346:   const char *aNode,              /* Current node image */
156347:   int nNode,                      /* Size of aNode in bytes */
156348:   Blob *pNew,                     /* OUT: Write new node image here */
156349:   const char *zTerm,              /* Omit all terms smaller than this */
156350:   int nTerm,                      /* Size of zTerm in bytes */
156351:   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
156352: ){
156353:   NodeReader reader;              /* Reader object */
156354:   Blob prev = {0, 0, 0};          /* Previous term written to new node */
156355:   int rc = SQLITE_OK;             /* Return code */
156356:   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
156357: 
156358:   /* Allocate required output space */
156359:   blobGrowBuffer(pNew, nNode, &rc);
156360:   if( rc!=SQLITE_OK ) return rc;
156361:   pNew->n = 0;
156362: 
156363:   /* Populate new node buffer */
156364:   for(rc = nodeReaderInit(&reader, aNode, nNode); 
156365:       rc==SQLITE_OK && reader.aNode; 
156366:       rc = nodeReaderNext(&reader)
156367:   ){
156368:     if( pNew->n==0 ){
156369:       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
156370:       if( res<0 || (bLeaf==0 && res==0) ) continue;
156371:       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
156372:       *piBlock = reader.iChild;
156373:     }
156374:     rc = fts3AppendToNode(
156375:         pNew, &prev, reader.term.a, reader.term.n,
156376:         reader.aDoclist, reader.nDoclist
156377:     );
156378:     if( rc!=SQLITE_OK ) break;
156379:   }
156380:   if( pNew->n==0 ){
156381:     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
156382:     *piBlock = reader.iChild;
156383:   }
156384:   assert( pNew->n<=pNew->nAlloc );
156385: 
156386:   nodeReaderRelease(&reader);
156387:   sqlite3_free(prev.a);
156388:   return rc;
156389: }
156390: 
156391: /*
156392: ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
156393: ** level iAbsLevel. This may involve deleting entries from the %_segments
156394: ** table, and modifying existing entries in both the %_segments and %_segdir
156395: ** tables.
156396: **
156397: ** SQLITE_OK is returned if the segment is updated successfully. Or an
156398: ** SQLite error code otherwise.
156399: */
156400: static int fts3TruncateSegment(
156401:   Fts3Table *p,                   /* FTS3 table handle */
156402:   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
156403:   int iIdx,                       /* Index within level of segment to modify */
156404:   const char *zTerm,              /* Remove terms smaller than this */
156405:   int nTerm                      /* Number of bytes in buffer zTerm */
156406: ){
156407:   int rc = SQLITE_OK;             /* Return code */
156408:   Blob root = {0,0,0};            /* New root page image */
156409:   Blob block = {0,0,0};           /* Buffer used for any other block */
156410:   sqlite3_int64 iBlock = 0;       /* Block id */
156411:   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
156412:   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
156413:   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
156414: 
156415:   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
156416:   if( rc==SQLITE_OK ){
156417:     int rc2;                      /* sqlite3_reset() return code */
156418:     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
156419:     sqlite3_bind_int(pFetch, 2, iIdx);
156420:     if( SQLITE_ROW==sqlite3_step(pFetch) ){
156421:       const char *aRoot = sqlite3_column_blob(pFetch, 4);
156422:       int nRoot = sqlite3_column_bytes(pFetch, 4);
156423:       iOldStart = sqlite3_column_int64(pFetch, 1);
156424:       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
156425:     }
156426:     rc2 = sqlite3_reset(pFetch);
156427:     if( rc==SQLITE_OK ) rc = rc2;
156428:   }
156429: 
156430:   while( rc==SQLITE_OK && iBlock ){
156431:     char *aBlock = 0;
156432:     int nBlock = 0;
156433:     iNewStart = iBlock;
156434: 
156435:     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
156436:     if( rc==SQLITE_OK ){
156437:       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
156438:     }
156439:     if( rc==SQLITE_OK ){
156440:       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
156441:     }
156442:     sqlite3_free(aBlock);
156443:   }
156444: 
156445:   /* Variable iNewStart now contains the first valid leaf node. */
156446:   if( rc==SQLITE_OK && iNewStart ){
156447:     sqlite3_stmt *pDel = 0;
156448:     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
156449:     if( rc==SQLITE_OK ){
156450:       sqlite3_bind_int64(pDel, 1, iOldStart);
156451:       sqlite3_bind_int64(pDel, 2, iNewStart-1);
156452:       sqlite3_step(pDel);
156453:       rc = sqlite3_reset(pDel);
156454:     }
156455:   }
156456: 
156457:   if( rc==SQLITE_OK ){
156458:     sqlite3_stmt *pChomp = 0;
156459:     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
156460:     if( rc==SQLITE_OK ){
156461:       sqlite3_bind_int64(pChomp, 1, iNewStart);
156462:       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
156463:       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
156464:       sqlite3_bind_int(pChomp, 4, iIdx);
156465:       sqlite3_step(pChomp);
156466:       rc = sqlite3_reset(pChomp);
156467:     }
156468:   }
156469: 
156470:   sqlite3_free(root.a);
156471:   sqlite3_free(block.a);
156472:   return rc;
156473: }
156474: 
156475: /*
156476: ** This function is called after an incrmental-merge operation has run to
156477: ** merge (or partially merge) two or more segments from absolute level
156478: ** iAbsLevel.
156479: **
156480: ** Each input segment is either removed from the db completely (if all of
156481: ** its data was copied to the output segment by the incrmerge operation)
156482: ** or modified in place so that it no longer contains those entries that
156483: ** have been duplicated in the output segment.
156484: */
156485: static int fts3IncrmergeChomp(
156486:   Fts3Table *p,                   /* FTS table handle */
156487:   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
156488:   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
156489:   int *pnRem                      /* Number of segments not deleted */
156490: ){
156491:   int i;
156492:   int nRem = 0;
156493:   int rc = SQLITE_OK;
156494: 
156495:   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
156496:     Fts3SegReader *pSeg = 0;
156497:     int j;
156498: 
156499:     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
156500:     ** somewhere in the pCsr->apSegment[] array.  */
156501:     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
156502:       pSeg = pCsr->apSegment[j];
156503:       if( pSeg->iIdx==i ) break;
156504:     }
156505:     assert( j<pCsr->nSegment && pSeg->iIdx==i );
156506: 
156507:     if( pSeg->aNode==0 ){
156508:       /* Seg-reader is at EOF. Remove the entire input segment. */
156509:       rc = fts3DeleteSegment(p, pSeg);
156510:       if( rc==SQLITE_OK ){
156511:         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
156512:       }
156513:       *pnRem = 0;
156514:     }else{
156515:       /* The incremental merge did not copy all the data from this 
156516:       ** segment to the upper level. The segment is modified in place
156517:       ** so that it contains no keys smaller than zTerm/nTerm. */ 
156518:       const char *zTerm = pSeg->zTerm;
156519:       int nTerm = pSeg->nTerm;
156520:       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
156521:       nRem++;
156522:     }
156523:   }
156524: 
156525:   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
156526:     rc = fts3RepackSegdirLevel(p, iAbsLevel);
156527:   }
156528: 
156529:   *pnRem = nRem;
156530:   return rc;
156531: }
156532: 
156533: /*
156534: ** Store an incr-merge hint in the database.
156535: */
156536: static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
156537:   sqlite3_stmt *pReplace = 0;
156538:   int rc;                         /* Return code */
156539: 
156540:   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
156541:   if( rc==SQLITE_OK ){
156542:     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
156543:     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
156544:     sqlite3_step(pReplace);
156545:     rc = sqlite3_reset(pReplace);
156546:   }
156547: 
156548:   return rc;
156549: }
156550: 
156551: /*
156552: ** Load an incr-merge hint from the database. The incr-merge hint, if one 
156553: ** exists, is stored in the rowid==1 row of the %_stat table.
156554: **
156555: ** If successful, populate blob *pHint with the value read from the %_stat
156556: ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
156557: ** SQLite error code.
156558: */
156559: static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
156560:   sqlite3_stmt *pSelect = 0;
156561:   int rc;
156562: 
156563:   pHint->n = 0;
156564:   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
156565:   if( rc==SQLITE_OK ){
156566:     int rc2;
156567:     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
156568:     if( SQLITE_ROW==sqlite3_step(pSelect) ){
156569:       const char *aHint = sqlite3_column_blob(pSelect, 0);
156570:       int nHint = sqlite3_column_bytes(pSelect, 0);
156571:       if( aHint ){
156572:         blobGrowBuffer(pHint, nHint, &rc);
156573:         if( rc==SQLITE_OK ){
156574:           memcpy(pHint->a, aHint, nHint);
156575:           pHint->n = nHint;
156576:         }
156577:       }
156578:     }
156579:     rc2 = sqlite3_reset(pSelect);
156580:     if( rc==SQLITE_OK ) rc = rc2;
156581:   }
156582: 
156583:   return rc;
156584: }
156585: 
156586: /*
156587: ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
156588: ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
156589: ** consists of two varints, the absolute level number of the input segments 
156590: ** and the number of input segments.
156591: **
156592: ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
156593: ** set *pRc to an SQLite error code before returning.
156594: */
156595: static void fts3IncrmergeHintPush(
156596:   Blob *pHint,                    /* Hint blob to append to */
156597:   i64 iAbsLevel,                  /* First varint to store in hint */
156598:   int nInput,                     /* Second varint to store in hint */
156599:   int *pRc                        /* IN/OUT: Error code */
156600: ){
156601:   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
156602:   if( *pRc==SQLITE_OK ){
156603:     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
156604:     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
156605:   }
156606: }
156607: 
156608: /*
156609: ** Read the last entry (most recently pushed) from the hint blob *pHint
156610: ** and then remove the entry. Write the two values read to *piAbsLevel and 
156611: ** *pnInput before returning.
156612: **
156613: ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
156614: ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
156615: */
156616: static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
156617:   const int nHint = pHint->n;
156618:   int i;
156619: 
156620:   i = pHint->n-2;
156621:   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
156622:   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
156623: 
156624:   pHint->n = i;
156625:   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
156626:   i += fts3GetVarint32(&pHint->a[i], pnInput);
156627:   if( i!=nHint ) return FTS_CORRUPT_VTAB;
156628: 
156629:   return SQLITE_OK;
156630: }
156631: 
156632: 
156633: /*
156634: ** Attempt an incremental merge that writes nMerge leaf blocks.
156635: **
156636: ** Incremental merges happen nMin segments at a time. The segments 
156637: ** to be merged are the nMin oldest segments (the ones with the smallest 
156638: ** values for the _segdir.idx field) in the highest level that contains 
156639: ** at least nMin segments. Multiple merges might occur in an attempt to 
156640: ** write the quota of nMerge leaf blocks.
156641: */
156642: SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
156643:   int rc;                         /* Return code */
156644:   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
156645:   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
156646:   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
156647:   IncrmergeWriter *pWriter;       /* Writer object */
156648:   int nSeg = 0;                   /* Number of input segments */
156649:   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
156650:   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
156651:   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
156652: 
156653:   /* Allocate space for the cursor, filter and writer objects */
156654:   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
156655:   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
156656:   if( !pWriter ) return SQLITE_NOMEM;
156657:   pFilter = (Fts3SegFilter *)&pWriter[1];
156658:   pCsr = (Fts3MultiSegReader *)&pFilter[1];
156659: 
156660:   rc = fts3IncrmergeHintLoad(p, &hint);
156661:   while( rc==SQLITE_OK && nRem>0 ){
156662:     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
156663:     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
156664:     int bUseHint = 0;             /* True if attempting to append */
156665:     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
156666: 
156667:     /* Search the %_segdir table for the absolute level with the smallest
156668:     ** relative level number that contains at least nMin segments, if any.
156669:     ** If one is found, set iAbsLevel to the absolute level number and
156670:     ** nSeg to nMin. If no level with at least nMin segments can be found, 
156671:     ** set nSeg to -1.
156672:     */
156673:     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
156674:     sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
156675:     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
156676:       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
156677:       nSeg = sqlite3_column_int(pFindLevel, 1);
156678:       assert( nSeg>=2 );
156679:     }else{
156680:       nSeg = -1;
156681:     }
156682:     rc = sqlite3_reset(pFindLevel);
156683: 
156684:     /* If the hint read from the %_stat table is not empty, check if the
156685:     ** last entry in it specifies a relative level smaller than or equal
156686:     ** to the level identified by the block above (if any). If so, this 
156687:     ** iteration of the loop will work on merging at the hinted level.
156688:     */
156689:     if( rc==SQLITE_OK && hint.n ){
156690:       int nHint = hint.n;
156691:       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
156692:       int nHintSeg = 0;                     /* Hint number of segments */
156693: 
156694:       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
156695:       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
156696:         iAbsLevel = iHintAbsLevel;
156697:         nSeg = nHintSeg;
156698:         bUseHint = 1;
156699:         bDirtyHint = 1;
156700:       }else{
156701:         /* This undoes the effect of the HintPop() above - so that no entry
156702:         ** is removed from the hint blob.  */
156703:         hint.n = nHint;
156704:       }
156705:     }
156706: 
156707:     /* If nSeg is less that zero, then there is no level with at least
156708:     ** nMin segments and no hint in the %_stat table. No work to do.
156709:     ** Exit early in this case.  */
156710:     if( nSeg<0 ) break;
156711: 
156712:     /* Open a cursor to iterate through the contents of the oldest nSeg 
156713:     ** indexes of absolute level iAbsLevel. If this cursor is opened using 
156714:     ** the 'hint' parameters, it is possible that there are less than nSeg
156715:     ** segments available in level iAbsLevel. In this case, no work is
156716:     ** done on iAbsLevel - fall through to the next iteration of the loop 
156717:     ** to start work on some other level.  */
156718:     memset(pWriter, 0, nAlloc);
156719:     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
156720: 
156721:     if( rc==SQLITE_OK ){
156722:       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
156723:       assert( bUseHint==1 || bUseHint==0 );
156724:       if( iIdx==0 || (bUseHint && iIdx==1) ){
156725:         int bIgnore = 0;
156726:         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
156727:         if( bIgnore ){
156728:           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
156729:         }
156730:       }
156731:     }
156732: 
156733:     if( rc==SQLITE_OK ){
156734:       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
156735:     }
156736:     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
156737:      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
156738:      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
156739:     ){
156740:       if( bUseHint && iIdx>0 ){
156741:         const char *zKey = pCsr->zTerm;
156742:         int nKey = pCsr->nTerm;
156743:         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
156744:       }else{
156745:         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
156746:       }
156747: 
156748:       if( rc==SQLITE_OK && pWriter->nLeafEst ){
156749:         fts3LogMerge(nSeg, iAbsLevel);
156750:         do {
156751:           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
156752:           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
156753:           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
156754:         }while( rc==SQLITE_ROW );
156755: 
156756:         /* Update or delete the input segments */
156757:         if( rc==SQLITE_OK ){
156758:           nRem -= (1 + pWriter->nWork);
156759:           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
156760:           if( nSeg!=0 ){
156761:             bDirtyHint = 1;
156762:             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
156763:           }
156764:         }
156765:       }
156766: 
156767:       if( nSeg!=0 ){
156768:         pWriter->nLeafData = pWriter->nLeafData * -1;
156769:       }
156770:       fts3IncrmergeRelease(p, pWriter, &rc);
156771:       if( nSeg==0 && pWriter->bNoLeafData==0 ){
156772:         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
156773:       }
156774:     }
156775: 
156776:     sqlite3Fts3SegReaderFinish(pCsr);
156777:   }
156778: 
156779:   /* Write the hint values into the %_stat table for the next incr-merger */
156780:   if( bDirtyHint && rc==SQLITE_OK ){
156781:     rc = fts3IncrmergeHintStore(p, &hint);
156782:   }
156783: 
156784:   sqlite3_free(pWriter);
156785:   sqlite3_free(hint.a);
156786:   return rc;
156787: }
156788: 
156789: /*
156790: ** Convert the text beginning at *pz into an integer and return
156791: ** its value.  Advance *pz to point to the first character past
156792: ** the integer.
156793: */
156794: static int fts3Getint(const char **pz){
156795:   const char *z = *pz;
156796:   int i = 0;
156797:   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
156798:   *pz = z;
156799:   return i;
156800: }
156801: 
156802: /*
156803: ** Process statements of the form:
156804: **
156805: **    INSERT INTO table(table) VALUES('merge=A,B');
156806: **
156807: ** A and B are integers that decode to be the number of leaf pages
156808: ** written for the merge, and the minimum number of segments on a level
156809: ** before it will be selected for a merge, respectively.
156810: */
156811: static int fts3DoIncrmerge(
156812:   Fts3Table *p,                   /* FTS3 table handle */
156813:   const char *zParam              /* Nul-terminated string containing "A,B" */
156814: ){
156815:   int rc;
156816:   int nMin = (FTS3_MERGE_COUNT / 2);
156817:   int nMerge = 0;
156818:   const char *z = zParam;
156819: 
156820:   /* Read the first integer value */
156821:   nMerge = fts3Getint(&z);
156822: 
156823:   /* If the first integer value is followed by a ',',  read the second
156824:   ** integer value. */
156825:   if( z[0]==',' && z[1]!='\0' ){
156826:     z++;
156827:     nMin = fts3Getint(&z);
156828:   }
156829: 
156830:   if( z[0]!='\0' || nMin<2 ){
156831:     rc = SQLITE_ERROR;
156832:   }else{
156833:     rc = SQLITE_OK;
156834:     if( !p->bHasStat ){
156835:       assert( p->bFts4==0 );
156836:       sqlite3Fts3CreateStatTable(&rc, p);
156837:     }
156838:     if( rc==SQLITE_OK ){
156839:       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
156840:     }
156841:     sqlite3Fts3SegmentsClose(p);
156842:   }
156843:   return rc;
156844: }
156845: 
156846: /*
156847: ** Process statements of the form:
156848: **
156849: **    INSERT INTO table(table) VALUES('automerge=X');
156850: **
156851: ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
156852: ** turn it on.  The setting is persistent.
156853: */
156854: static int fts3DoAutoincrmerge(
156855:   Fts3Table *p,                   /* FTS3 table handle */
156856:   const char *zParam              /* Nul-terminated string containing boolean */
156857: ){
156858:   int rc = SQLITE_OK;
156859:   sqlite3_stmt *pStmt = 0;
156860:   p->nAutoincrmerge = fts3Getint(&zParam);
156861:   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
156862:     p->nAutoincrmerge = 8;
156863:   }
156864:   if( !p->bHasStat ){
156865:     assert( p->bFts4==0 );
156866:     sqlite3Fts3CreateStatTable(&rc, p);
156867:     if( rc ) return rc;
156868:   }
156869:   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
156870:   if( rc ) return rc;
156871:   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
156872:   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
156873:   sqlite3_step(pStmt);
156874:   rc = sqlite3_reset(pStmt);
156875:   return rc;
156876: }
156877: 
156878: /*
156879: ** Return a 64-bit checksum for the FTS index entry specified by the
156880: ** arguments to this function.
156881: */
156882: static u64 fts3ChecksumEntry(
156883:   const char *zTerm,              /* Pointer to buffer containing term */
156884:   int nTerm,                      /* Size of zTerm in bytes */
156885:   int iLangid,                    /* Language id for current row */
156886:   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
156887:   i64 iDocid,                     /* Docid for current row. */
156888:   int iCol,                       /* Column number */
156889:   int iPos                        /* Position */
156890: ){
156891:   int i;
156892:   u64 ret = (u64)iDocid;
156893: 
156894:   ret += (ret<<3) + iLangid;
156895:   ret += (ret<<3) + iIndex;
156896:   ret += (ret<<3) + iCol;
156897:   ret += (ret<<3) + iPos;
156898:   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
156899: 
156900:   return ret;
156901: }
156902: 
156903: /*
156904: ** Return a checksum of all entries in the FTS index that correspond to
156905: ** language id iLangid. The checksum is calculated by XORing the checksums
156906: ** of each individual entry (see fts3ChecksumEntry()) together.
156907: **
156908: ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
156909: ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
156910: ** return value is undefined in this case.
156911: */
156912: static u64 fts3ChecksumIndex(
156913:   Fts3Table *p,                   /* FTS3 table handle */
156914:   int iLangid,                    /* Language id to return cksum for */
156915:   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
156916:   int *pRc                        /* OUT: Return code */
156917: ){
156918:   Fts3SegFilter filter;
156919:   Fts3MultiSegReader csr;
156920:   int rc;
156921:   u64 cksum = 0;
156922: 
156923:   assert( *pRc==SQLITE_OK );
156924: 
156925:   memset(&filter, 0, sizeof(filter));
156926:   memset(&csr, 0, sizeof(csr));
156927:   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
156928:   filter.flags |= FTS3_SEGMENT_SCAN;
156929: 
156930:   rc = sqlite3Fts3SegReaderCursor(
156931:       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
156932:   );
156933:   if( rc==SQLITE_OK ){
156934:     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
156935:   }
156936: 
156937:   if( rc==SQLITE_OK ){
156938:     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
156939:       char *pCsr = csr.aDoclist;
156940:       char *pEnd = &pCsr[csr.nDoclist];
156941: 
156942:       i64 iDocid = 0;
156943:       i64 iCol = 0;
156944:       i64 iPos = 0;
156945: 
156946:       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
156947:       while( pCsr<pEnd ){
156948:         i64 iVal = 0;
156949:         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
156950:         if( pCsr<pEnd ){
156951:           if( iVal==0 || iVal==1 ){
156952:             iCol = 0;
156953:             iPos = 0;
156954:             if( iVal ){
156955:               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
156956:             }else{
156957:               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
156958:               iDocid += iVal;
156959:             }
156960:           }else{
156961:             iPos += (iVal - 2);
156962:             cksum = cksum ^ fts3ChecksumEntry(
156963:                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
156964:                 (int)iCol, (int)iPos
156965:             );
156966:           }
156967:         }
156968:       }
156969:     }
156970:   }
156971:   sqlite3Fts3SegReaderFinish(&csr);
156972: 
156973:   *pRc = rc;
156974:   return cksum;
156975: }
156976: 
156977: /*
156978: ** Check if the contents of the FTS index match the current contents of the
156979: ** content table. If no error occurs and the contents do match, set *pbOk
156980: ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
156981: ** to false before returning.
156982: **
156983: ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
156984: ** code. The final value of *pbOk is undefined in this case.
156985: */
156986: static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
156987:   int rc = SQLITE_OK;             /* Return code */
156988:   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
156989:   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
156990:   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
156991: 
156992:   /* This block calculates the checksum according to the FTS index. */
156993:   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
156994:   if( rc==SQLITE_OK ){
156995:     int rc2;
156996:     sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
156997:     sqlite3_bind_int(pAllLangid, 2, p->nIndex);
156998:     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
156999:       int iLangid = sqlite3_column_int(pAllLangid, 0);
157000:       int i;
157001:       for(i=0; i<p->nIndex; i++){
157002:         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
157003:       }
157004:     }
157005:     rc2 = sqlite3_reset(pAllLangid);
157006:     if( rc==SQLITE_OK ) rc = rc2;
157007:   }
157008: 
157009:   /* This block calculates the checksum according to the %_content table */
157010:   if( rc==SQLITE_OK ){
157011:     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
157012:     sqlite3_stmt *pStmt = 0;
157013:     char *zSql;
157014:    
157015:     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
157016:     if( !zSql ){
157017:       rc = SQLITE_NOMEM;
157018:     }else{
157019:       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
157020:       sqlite3_free(zSql);
157021:     }
157022: 
157023:     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
157024:       i64 iDocid = sqlite3_column_int64(pStmt, 0);
157025:       int iLang = langidFromSelect(p, pStmt);
157026:       int iCol;
157027: 
157028:       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
157029:         if( p->abNotindexed[iCol]==0 ){
157030:           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
157031:           int nText = sqlite3_column_bytes(pStmt, iCol+1);
157032:           sqlite3_tokenizer_cursor *pT = 0;
157033: 
157034:           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
157035:           while( rc==SQLITE_OK ){
157036:             char const *zToken;       /* Buffer containing token */
157037:             int nToken = 0;           /* Number of bytes in token */
157038:             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
157039:             int iPos = 0;             /* Position of token in zText */
157040: 
157041:             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
157042:             if( rc==SQLITE_OK ){
157043:               int i;
157044:               cksum2 = cksum2 ^ fts3ChecksumEntry(
157045:                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
157046:               );
157047:               for(i=1; i<p->nIndex; i++){
157048:                 if( p->aIndex[i].nPrefix<=nToken ){
157049:                   cksum2 = cksum2 ^ fts3ChecksumEntry(
157050:                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
157051:                   );
157052:                 }
157053:               }
157054:             }
157055:           }
157056:           if( pT ) pModule->xClose(pT);
157057:           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157058:         }
157059:       }
157060:     }
157061: 
157062:     sqlite3_finalize(pStmt);
157063:   }
157064: 
157065:   *pbOk = (cksum1==cksum2);
157066:   return rc;
157067: }
157068: 
157069: /*
157070: ** Run the integrity-check. If no error occurs and the current contents of
157071: ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
157072: ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
157073: **
157074: ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
157075: ** error code.
157076: **
157077: ** The integrity-check works as follows. For each token and indexed token
157078: ** prefix in the document set, a 64-bit checksum is calculated (by code
157079: ** in fts3ChecksumEntry()) based on the following:
157080: **
157081: **     + The index number (0 for the main index, 1 for the first prefix
157082: **       index etc.),
157083: **     + The token (or token prefix) text itself, 
157084: **     + The language-id of the row it appears in,
157085: **     + The docid of the row it appears in,
157086: **     + The column it appears in, and
157087: **     + The tokens position within that column.
157088: **
157089: ** The checksums for all entries in the index are XORed together to create
157090: ** a single checksum for the entire index.
157091: **
157092: ** The integrity-check code calculates the same checksum in two ways:
157093: **
157094: **     1. By scanning the contents of the FTS index, and 
157095: **     2. By scanning and tokenizing the content table.
157096: **
157097: ** If the two checksums are identical, the integrity-check is deemed to have
157098: ** passed.
157099: */
157100: static int fts3DoIntegrityCheck(
157101:   Fts3Table *p                    /* FTS3 table handle */
157102: ){
157103:   int rc;
157104:   int bOk = 0;
157105:   rc = fts3IntegrityCheck(p, &bOk);
157106:   if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
157107:   return rc;
157108: }
157109: 
157110: /*
157111: ** Handle a 'special' INSERT of the form:
157112: **
157113: **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
157114: **
157115: ** Argument pVal contains the result of <expr>. Currently the only 
157116: ** meaningful value to insert is the text 'optimize'.
157117: */
157118: static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
157119:   int rc;                         /* Return Code */
157120:   const char *zVal = (const char *)sqlite3_value_text(pVal);
157121:   int nVal = sqlite3_value_bytes(pVal);
157122: 
157123:   if( !zVal ){
157124:     return SQLITE_NOMEM;
157125:   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
157126:     rc = fts3DoOptimize(p, 0);
157127:   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
157128:     rc = fts3DoRebuild(p);
157129:   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
157130:     rc = fts3DoIntegrityCheck(p);
157131:   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
157132:     rc = fts3DoIncrmerge(p, &zVal[6]);
157133:   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
157134:     rc = fts3DoAutoincrmerge(p, &zVal[10]);
157135: #ifdef SQLITE_TEST
157136:   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
157137:     p->nNodeSize = atoi(&zVal[9]);
157138:     rc = SQLITE_OK;
157139:   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
157140:     p->nMaxPendingData = atoi(&zVal[11]);
157141:     rc = SQLITE_OK;
157142:   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
157143:     p->bNoIncrDoclist = atoi(&zVal[21]);
157144:     rc = SQLITE_OK;
157145: #endif
157146:   }else{
157147:     rc = SQLITE_ERROR;
157148:   }
157149: 
157150:   return rc;
157151: }
157152: 
157153: #ifndef SQLITE_DISABLE_FTS4_DEFERRED
157154: /*
157155: ** Delete all cached deferred doclists. Deferred doclists are cached
157156: ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
157157: */
157158: SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
157159:   Fts3DeferredToken *pDef;
157160:   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
157161:     fts3PendingListDelete(pDef->pList);
157162:     pDef->pList = 0;
157163:   }
157164: }
157165: 
157166: /*
157167: ** Free all entries in the pCsr->pDeffered list. Entries are added to 
157168: ** this list using sqlite3Fts3DeferToken().
157169: */
157170: SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
157171:   Fts3DeferredToken *pDef;
157172:   Fts3DeferredToken *pNext;
157173:   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
157174:     pNext = pDef->pNext;
157175:     fts3PendingListDelete(pDef->pList);
157176:     sqlite3_free(pDef);
157177:   }
157178:   pCsr->pDeferred = 0;
157179: }
157180: 
157181: /*
157182: ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
157183: ** based on the row that pCsr currently points to.
157184: **
157185: ** A deferred-doclist is like any other doclist with position information
157186: ** included, except that it only contains entries for a single row of the
157187: ** table, not for all rows.
157188: */
157189: SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
157190:   int rc = SQLITE_OK;             /* Return code */
157191:   if( pCsr->pDeferred ){
157192:     int i;                        /* Used to iterate through table columns */
157193:     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
157194:     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
157195:   
157196:     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
157197:     sqlite3_tokenizer *pT = p->pTokenizer;
157198:     sqlite3_tokenizer_module const *pModule = pT->pModule;
157199:    
157200:     assert( pCsr->isRequireSeek==0 );
157201:     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
157202:   
157203:     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
157204:       if( p->abNotindexed[i]==0 ){
157205:         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
157206:         sqlite3_tokenizer_cursor *pTC = 0;
157207: 
157208:         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
157209:         while( rc==SQLITE_OK ){
157210:           char const *zToken;       /* Buffer containing token */
157211:           int nToken = 0;           /* Number of bytes in token */
157212:           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
157213:           int iPos = 0;             /* Position of token in zText */
157214: 
157215:           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
157216:           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
157217:             Fts3PhraseToken *pPT = pDef->pToken;
157218:             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
157219:                 && (pPT->bFirst==0 || iPos==0)
157220:                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
157221:                 && (0==memcmp(zToken, pPT->z, pPT->n))
157222:               ){
157223:               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
157224:             }
157225:           }
157226:         }
157227:         if( pTC ) pModule->xClose(pTC);
157228:         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
157229:       }
157230:     }
157231: 
157232:     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
157233:       if( pDef->pList ){
157234:         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
157235:       }
157236:     }
157237:   }
157238: 
157239:   return rc;
157240: }
157241: 
157242: SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
157243:   Fts3DeferredToken *p, 
157244:   char **ppData, 
157245:   int *pnData
157246: ){
157247:   char *pRet;
157248:   int nSkip;
157249:   sqlite3_int64 dummy;
157250: 
157251:   *ppData = 0;
157252:   *pnData = 0;
157253: 
157254:   if( p->pList==0 ){
157255:     return SQLITE_OK;
157256:   }
157257: 
157258:   pRet = (char *)sqlite3_malloc(p->pList->nData);
157259:   if( !pRet ) return SQLITE_NOMEM;
157260: 
157261:   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
157262:   *pnData = p->pList->nData - nSkip;
157263:   *ppData = pRet;
157264:   
157265:   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
157266:   return SQLITE_OK;
157267: }
157268: 
157269: /*
157270: ** Add an entry for token pToken to the pCsr->pDeferred list.
157271: */
157272: SQLITE_PRIVATE int sqlite3Fts3DeferToken(
157273:   Fts3Cursor *pCsr,               /* Fts3 table cursor */
157274:   Fts3PhraseToken *pToken,        /* Token to defer */
157275:   int iCol                        /* Column that token must appear in (or -1) */
157276: ){
157277:   Fts3DeferredToken *pDeferred;
157278:   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
157279:   if( !pDeferred ){
157280:     return SQLITE_NOMEM;
157281:   }
157282:   memset(pDeferred, 0, sizeof(*pDeferred));
157283:   pDeferred->pToken = pToken;
157284:   pDeferred->pNext = pCsr->pDeferred; 
157285:   pDeferred->iCol = iCol;
157286:   pCsr->pDeferred = pDeferred;
157287: 
157288:   assert( pToken->pDeferred==0 );
157289:   pToken->pDeferred = pDeferred;
157290: 
157291:   return SQLITE_OK;
157292: }
157293: #endif
157294: 
157295: /*
157296: ** SQLite value pRowid contains the rowid of a row that may or may not be
157297: ** present in the FTS3 table. If it is, delete it and adjust the contents
157298: ** of subsiduary data structures accordingly.
157299: */
157300: static int fts3DeleteByRowid(
157301:   Fts3Table *p, 
157302:   sqlite3_value *pRowid, 
157303:   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
157304:   u32 *aSzDel
157305: ){
157306:   int rc = SQLITE_OK;             /* Return code */
157307:   int bFound = 0;                 /* True if *pRowid really is in the table */
157308: 
157309:   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
157310:   if( bFound && rc==SQLITE_OK ){
157311:     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
157312:     rc = fts3IsEmpty(p, pRowid, &isEmpty);
157313:     if( rc==SQLITE_OK ){
157314:       if( isEmpty ){
157315:         /* Deleting this row means the whole table is empty. In this case
157316:         ** delete the contents of all three tables and throw away any
157317:         ** data in the pendingTerms hash table.  */
157318:         rc = fts3DeleteAll(p, 1);
157319:         *pnChng = 0;
157320:         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
157321:       }else{
157322:         *pnChng = *pnChng - 1;
157323:         if( p->zContentTbl==0 ){
157324:           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
157325:         }
157326:         if( p->bHasDocsize ){
157327:           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
157328:         }
157329:       }
157330:     }
157331:   }
157332: 
157333:   return rc;
157334: }
157335: 
157336: /*
157337: ** This function does the work for the xUpdate method of FTS3 virtual
157338: ** tables. The schema of the virtual table being:
157339: **
157340: **     CREATE TABLE <table name>( 
157341: **       <user columns>,
157342: **       <table name> HIDDEN, 
157343: **       docid HIDDEN, 
157344: **       <langid> HIDDEN
157345: **     );
157346: **
157347: ** 
157348: */
157349: SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
157350:   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
157351:   int nArg,                       /* Size of argument array */
157352:   sqlite3_value **apVal,          /* Array of arguments */
157353:   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
157354: ){
157355:   Fts3Table *p = (Fts3Table *)pVtab;
157356:   int rc = SQLITE_OK;             /* Return Code */
157357:   int isRemove = 0;               /* True for an UPDATE or DELETE */
157358:   u32 *aSzIns = 0;                /* Sizes of inserted documents */
157359:   u32 *aSzDel = 0;                /* Sizes of deleted documents */
157360:   int nChng = 0;                  /* Net change in number of documents */
157361:   int bInsertDone = 0;
157362: 
157363:   /* At this point it must be known if the %_stat table exists or not.
157364:   ** So bHasStat may not be 2.  */
157365:   assert( p->bHasStat==0 || p->bHasStat==1 );
157366: 
157367:   assert( p->pSegments==0 );
157368:   assert( 
157369:       nArg==1                     /* DELETE operations */
157370:    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
157371:   );
157372: 
157373:   /* Check for a "special" INSERT operation. One of the form:
157374:   **
157375:   **   INSERT INTO xyz(xyz) VALUES('command');
157376:   */
157377:   if( nArg>1 
157378:    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
157379:    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
157380:   ){
157381:     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
157382:     goto update_out;
157383:   }
157384: 
157385:   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
157386:     rc = SQLITE_CONSTRAINT;
157387:     goto update_out;
157388:   }
157389: 
157390:   /* Allocate space to hold the change in document sizes */
157391:   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
157392:   if( aSzDel==0 ){
157393:     rc = SQLITE_NOMEM;
157394:     goto update_out;
157395:   }
157396:   aSzIns = &aSzDel[p->nColumn+1];
157397:   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
157398: 
157399:   rc = fts3Writelock(p);
157400:   if( rc!=SQLITE_OK ) goto update_out;
157401: 
157402:   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
157403:   ** value, then this operation requires constraint handling.
157404:   **
157405:   ** If the on-conflict mode is REPLACE, this means that the existing row
157406:   ** should be deleted from the database before inserting the new row. Or,
157407:   ** if the on-conflict mode is other than REPLACE, then this method must
157408:   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
157409:   ** modify the database file.
157410:   */
157411:   if( nArg>1 && p->zContentTbl==0 ){
157412:     /* Find the value object that holds the new rowid value. */
157413:     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
157414:     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
157415:       pNewRowid = apVal[1];
157416:     }
157417: 
157418:     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
157419:         sqlite3_value_type(apVal[0])==SQLITE_NULL
157420:      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
157421:     )){
157422:       /* The new rowid is not NULL (in this case the rowid will be
157423:       ** automatically assigned and there is no chance of a conflict), and 
157424:       ** the statement is either an INSERT or an UPDATE that modifies the
157425:       ** rowid column. So if the conflict mode is REPLACE, then delete any
157426:       ** existing row with rowid=pNewRowid. 
157427:       **
157428:       ** Or, if the conflict mode is not REPLACE, insert the new record into 
157429:       ** the %_content table. If we hit the duplicate rowid constraint (or any
157430:       ** other error) while doing so, return immediately.
157431:       **
157432:       ** This branch may also run if pNewRowid contains a value that cannot
157433:       ** be losslessly converted to an integer. In this case, the eventual 
157434:       ** call to fts3InsertData() (either just below or further on in this
157435:       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
157436:       ** invoked, it will delete zero rows (since no row will have
157437:       ** docid=$pNewRowid if $pNewRowid is not an integer value).
157438:       */
157439:       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
157440:         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
157441:       }else{
157442:         rc = fts3InsertData(p, apVal, pRowid);
157443:         bInsertDone = 1;
157444:       }
157445:     }
157446:   }
157447:   if( rc!=SQLITE_OK ){
157448:     goto update_out;
157449:   }
157450: 
157451:   /* If this is a DELETE or UPDATE operation, remove the old record. */
157452:   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
157453:     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
157454:     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
157455:     isRemove = 1;
157456:   }
157457:   
157458:   /* If this is an INSERT or UPDATE operation, insert the new record. */
157459:   if( nArg>1 && rc==SQLITE_OK ){
157460:     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
157461:     if( bInsertDone==0 ){
157462:       rc = fts3InsertData(p, apVal, pRowid);
157463:       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
157464:         rc = FTS_CORRUPT_VTAB;
157465:       }
157466:     }
157467:     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
157468:       rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
157469:     }
157470:     if( rc==SQLITE_OK ){
157471:       assert( p->iPrevDocid==*pRowid );
157472:       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
157473:     }
157474:     if( p->bHasDocsize ){
157475:       fts3InsertDocsize(&rc, p, aSzIns);
157476:     }
157477:     nChng++;
157478:   }
157479: 
157480:   if( p->bFts4 ){
157481:     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
157482:   }
157483: 
157484:  update_out:
157485:   sqlite3_free(aSzDel);
157486:   sqlite3Fts3SegmentsClose(p);
157487:   return rc;
157488: }
157489: 
157490: /* 
157491: ** Flush any data in the pending-terms hash table to disk. If successful,
157492: ** merge all segments in the database (including the new segment, if 
157493: ** there was any data to flush) into a single segment. 
157494: */
157495: SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
157496:   int rc;
157497:   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
157498:   if( rc==SQLITE_OK ){
157499:     rc = fts3DoOptimize(p, 1);
157500:     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
157501:       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
157502:       if( rc2!=SQLITE_OK ) rc = rc2;
157503:     }else{
157504:       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
157505:       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
157506:     }
157507:   }
157508:   sqlite3Fts3SegmentsClose(p);
157509:   return rc;
157510: }
157511: 
157512: #endif
157513: 
157514: /************** End of fts3_write.c ******************************************/
157515: /************** Begin file fts3_snippet.c ************************************/
157516: /*
157517: ** 2009 Oct 23
157518: **
157519: ** The author disclaims copyright to this source code.  In place of
157520: ** a legal notice, here is a blessing:
157521: **
157522: **    May you do good and not evil.
157523: **    May you find forgiveness for yourself and forgive others.
157524: **    May you share freely, never taking more than you give.
157525: **
157526: ******************************************************************************
157527: */
157528: 
157529: /* #include "fts3Int.h" */
157530: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
157531: 
157532: /* #include <string.h> */
157533: /* #include <assert.h> */
157534: 
157535: /*
157536: ** Characters that may appear in the second argument to matchinfo().
157537: */
157538: #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
157539: #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
157540: #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
157541: #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
157542: #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
157543: #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
157544: #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
157545: #define FTS3_MATCHINFO_LHITS     'y'        /* nCol*nPhrase values */
157546: #define FTS3_MATCHINFO_LHITS_BM  'b'        /* nCol*nPhrase values */
157547: 
157548: /*
157549: ** The default value for the second argument to matchinfo(). 
157550: */
157551: #define FTS3_MATCHINFO_DEFAULT   "pcx"
157552: 
157553: 
157554: /*
157555: ** Used as an fts3ExprIterate() context when loading phrase doclists to
157556: ** Fts3Expr.aDoclist[]/nDoclist.
157557: */
157558: typedef struct LoadDoclistCtx LoadDoclistCtx;
157559: struct LoadDoclistCtx {
157560:   Fts3Cursor *pCsr;               /* FTS3 Cursor */
157561:   int nPhrase;                    /* Number of phrases seen so far */
157562:   int nToken;                     /* Number of tokens seen so far */
157563: };
157564: 
157565: /*
157566: ** The following types are used as part of the implementation of the 
157567: ** fts3BestSnippet() routine.
157568: */
157569: typedef struct SnippetIter SnippetIter;
157570: typedef struct SnippetPhrase SnippetPhrase;
157571: typedef struct SnippetFragment SnippetFragment;
157572: 
157573: struct SnippetIter {
157574:   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
157575:   int iCol;                       /* Extract snippet from this column */
157576:   int nSnippet;                   /* Requested snippet length (in tokens) */
157577:   int nPhrase;                    /* Number of phrases in query */
157578:   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
157579:   int iCurrent;                   /* First token of current snippet */
157580: };
157581: 
157582: struct SnippetPhrase {
157583:   int nToken;                     /* Number of tokens in phrase */
157584:   char *pList;                    /* Pointer to start of phrase position list */
157585:   int iHead;                      /* Next value in position list */
157586:   char *pHead;                    /* Position list data following iHead */
157587:   int iTail;                      /* Next value in trailing position list */
157588:   char *pTail;                    /* Position list data following iTail */
157589: };
157590: 
157591: struct SnippetFragment {
157592:   int iCol;                       /* Column snippet is extracted from */
157593:   int iPos;                       /* Index of first token in snippet */
157594:   u64 covered;                    /* Mask of query phrases covered */
157595:   u64 hlmask;                     /* Mask of snippet terms to highlight */
157596: };
157597: 
157598: /*
157599: ** This type is used as an fts3ExprIterate() context object while 
157600: ** accumulating the data returned by the matchinfo() function.
157601: */
157602: typedef struct MatchInfo MatchInfo;
157603: struct MatchInfo {
157604:   Fts3Cursor *pCursor;            /* FTS3 Cursor */
157605:   int nCol;                       /* Number of columns in table */
157606:   int nPhrase;                    /* Number of matchable phrases in query */
157607:   sqlite3_int64 nDoc;             /* Number of docs in database */
157608:   char flag;
157609:   u32 *aMatchinfo;                /* Pre-allocated buffer */
157610: };
157611: 
157612: /*
157613: ** An instance of this structure is used to manage a pair of buffers, each
157614: ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
157615: ** for details.
157616: */
157617: struct MatchinfoBuffer {
157618:   u8 aRef[3];
157619:   int nElem;
157620:   int bGlobal;                    /* Set if global data is loaded */
157621:   char *zMatchinfo;
157622:   u32 aMatchinfo[1];
157623: };
157624: 
157625: 
157626: /*
157627: ** The snippet() and offsets() functions both return text values. An instance
157628: ** of the following structure is used to accumulate those values while the
157629: ** functions are running. See fts3StringAppend() for details.
157630: */
157631: typedef struct StrBuffer StrBuffer;
157632: struct StrBuffer {
157633:   char *z;                        /* Pointer to buffer containing string */
157634:   int n;                          /* Length of z in bytes (excl. nul-term) */
157635:   int nAlloc;                     /* Allocated size of buffer z in bytes */
157636: };
157637: 
157638: 
157639: /*************************************************************************
157640: ** Start of MatchinfoBuffer code.
157641: */
157642: 
157643: /*
157644: ** Allocate a two-slot MatchinfoBuffer object.
157645: */
157646: static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
157647:   MatchinfoBuffer *pRet;
157648:   int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
157649:   int nStr = (int)strlen(zMatchinfo);
157650: 
157651:   pRet = sqlite3_malloc(nByte + nStr+1);
157652:   if( pRet ){
157653:     memset(pRet, 0, nByte);
157654:     pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
157655:     pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
157656:     pRet->nElem = nElem;
157657:     pRet->zMatchinfo = ((char*)pRet) + nByte;
157658:     memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
157659:     pRet->aRef[0] = 1;
157660:   }
157661: 
157662:   return pRet;
157663: }
157664: 
157665: static void fts3MIBufferFree(void *p){
157666:   MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
157667: 
157668:   assert( (u32*)p==&pBuf->aMatchinfo[1] 
157669:        || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2] 
157670:   );
157671:   if( (u32*)p==&pBuf->aMatchinfo[1] ){
157672:     pBuf->aRef[1] = 0;
157673:   }else{
157674:     pBuf->aRef[2] = 0;
157675:   }
157676: 
157677:   if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
157678:     sqlite3_free(pBuf);
157679:   }
157680: }
157681: 
157682: static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
157683:   void (*xRet)(void*) = 0;
157684:   u32 *aOut = 0;
157685: 
157686:   if( p->aRef[1]==0 ){
157687:     p->aRef[1] = 1;
157688:     aOut = &p->aMatchinfo[1];
157689:     xRet = fts3MIBufferFree;
157690:   }
157691:   else if( p->aRef[2]==0 ){
157692:     p->aRef[2] = 1;
157693:     aOut = &p->aMatchinfo[p->nElem+2];
157694:     xRet = fts3MIBufferFree;
157695:   }else{
157696:     aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
157697:     if( aOut ){
157698:       xRet = sqlite3_free;
157699:       if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
157700:     }
157701:   }
157702: 
157703:   *paOut = aOut;
157704:   return xRet;
157705: }
157706: 
157707: static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
157708:   p->bGlobal = 1;
157709:   memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
157710: }
157711: 
157712: /*
157713: ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
157714: */
157715: SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
157716:   if( p ){
157717:     assert( p->aRef[0]==1 );
157718:     p->aRef[0] = 0;
157719:     if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
157720:       sqlite3_free(p);
157721:     }
157722:   }
157723: }
157724: 
157725: /* 
157726: ** End of MatchinfoBuffer code.
157727: *************************************************************************/
157728: 
157729: 
157730: /*
157731: ** This function is used to help iterate through a position-list. A position
157732: ** list is a list of unique integers, sorted from smallest to largest. Each
157733: ** element of the list is represented by an FTS3 varint that takes the value
157734: ** of the difference between the current element and the previous one plus
157735: ** two. For example, to store the position-list:
157736: **
157737: **     4 9 113
157738: **
157739: ** the three varints:
157740: **
157741: **     6 7 106
157742: **
157743: ** are encoded.
157744: **
157745: ** When this function is called, *pp points to the start of an element of
157746: ** the list. *piPos contains the value of the previous entry in the list.
157747: ** After it returns, *piPos contains the value of the next element of the
157748: ** list and *pp is advanced to the following varint.
157749: */
157750: static void fts3GetDeltaPosition(char **pp, int *piPos){
157751:   int iVal;
157752:   *pp += fts3GetVarint32(*pp, &iVal);
157753:   *piPos += (iVal-2);
157754: }
157755: 
157756: /*
157757: ** Helper function for fts3ExprIterate() (see below).
157758: */
157759: static int fts3ExprIterate2(
157760:   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
157761:   int *piPhrase,                  /* Pointer to phrase counter */
157762:   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
157763:   void *pCtx                      /* Second argument to pass to callback */
157764: ){
157765:   int rc;                         /* Return code */
157766:   int eType = pExpr->eType;     /* Type of expression node pExpr */
157767: 
157768:   if( eType!=FTSQUERY_PHRASE ){
157769:     assert( pExpr->pLeft && pExpr->pRight );
157770:     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
157771:     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
157772:       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
157773:     }
157774:   }else{
157775:     rc = x(pExpr, *piPhrase, pCtx);
157776:     (*piPhrase)++;
157777:   }
157778:   return rc;
157779: }
157780: 
157781: /*
157782: ** Iterate through all phrase nodes in an FTS3 query, except those that
157783: ** are part of a sub-tree that is the right-hand-side of a NOT operator.
157784: ** For each phrase node found, the supplied callback function is invoked.
157785: **
157786: ** If the callback function returns anything other than SQLITE_OK, 
157787: ** the iteration is abandoned and the error code returned immediately.
157788: ** Otherwise, SQLITE_OK is returned after a callback has been made for
157789: ** all eligible phrase nodes.
157790: */
157791: static int fts3ExprIterate(
157792:   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
157793:   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
157794:   void *pCtx                      /* Second argument to pass to callback */
157795: ){
157796:   int iPhrase = 0;                /* Variable used as the phrase counter */
157797:   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
157798: }
157799: 
157800: 
157801: /*
157802: ** This is an fts3ExprIterate() callback used while loading the doclists
157803: ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
157804: ** fts3ExprLoadDoclists().
157805: */
157806: static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
157807:   int rc = SQLITE_OK;
157808:   Fts3Phrase *pPhrase = pExpr->pPhrase;
157809:   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
157810: 
157811:   UNUSED_PARAMETER(iPhrase);
157812: 
157813:   p->nPhrase++;
157814:   p->nToken += pPhrase->nToken;
157815: 
157816:   return rc;
157817: }
157818: 
157819: /*
157820: ** Load the doclists for each phrase in the query associated with FTS3 cursor
157821: ** pCsr. 
157822: **
157823: ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
157824: ** phrases in the expression (all phrases except those directly or 
157825: ** indirectly descended from the right-hand-side of a NOT operator). If 
157826: ** pnToken is not NULL, then it is set to the number of tokens in all
157827: ** matchable phrases of the expression.
157828: */
157829: static int fts3ExprLoadDoclists(
157830:   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
157831:   int *pnPhrase,                  /* OUT: Number of phrases in query */
157832:   int *pnToken                    /* OUT: Number of tokens in query */
157833: ){
157834:   int rc;                         /* Return Code */
157835:   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
157836:   sCtx.pCsr = pCsr;
157837:   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
157838:   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
157839:   if( pnToken ) *pnToken = sCtx.nToken;
157840:   return rc;
157841: }
157842: 
157843: static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
157844:   (*(int *)ctx)++;
157845:   pExpr->iPhrase = iPhrase;
157846:   return SQLITE_OK;
157847: }
157848: static int fts3ExprPhraseCount(Fts3Expr *pExpr){
157849:   int nPhrase = 0;
157850:   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
157851:   return nPhrase;
157852: }
157853: 
157854: /*
157855: ** Advance the position list iterator specified by the first two 
157856: ** arguments so that it points to the first element with a value greater
157857: ** than or equal to parameter iNext.
157858: */
157859: static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
157860:   char *pIter = *ppIter;
157861:   if( pIter ){
157862:     int iIter = *piIter;
157863: 
157864:     while( iIter<iNext ){
157865:       if( 0==(*pIter & 0xFE) ){
157866:         iIter = -1;
157867:         pIter = 0;
157868:         break;
157869:       }
157870:       fts3GetDeltaPosition(&pIter, &iIter);
157871:     }
157872: 
157873:     *piIter = iIter;
157874:     *ppIter = pIter;
157875:   }
157876: }
157877: 
157878: /*
157879: ** Advance the snippet iterator to the next candidate snippet.
157880: */
157881: static int fts3SnippetNextCandidate(SnippetIter *pIter){
157882:   int i;                          /* Loop counter */
157883: 
157884:   if( pIter->iCurrent<0 ){
157885:     /* The SnippetIter object has just been initialized. The first snippet
157886:     ** candidate always starts at offset 0 (even if this candidate has a
157887:     ** score of 0.0).
157888:     */
157889:     pIter->iCurrent = 0;
157890: 
157891:     /* Advance the 'head' iterator of each phrase to the first offset that
157892:     ** is greater than or equal to (iNext+nSnippet).
157893:     */
157894:     for(i=0; i<pIter->nPhrase; i++){
157895:       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157896:       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
157897:     }
157898:   }else{
157899:     int iStart;
157900:     int iEnd = 0x7FFFFFFF;
157901: 
157902:     for(i=0; i<pIter->nPhrase; i++){
157903:       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157904:       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
157905:         iEnd = pPhrase->iHead;
157906:       }
157907:     }
157908:     if( iEnd==0x7FFFFFFF ){
157909:       return 1;
157910:     }
157911: 
157912:     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
157913:     for(i=0; i<pIter->nPhrase; i++){
157914:       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157915:       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
157916:       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
157917:     }
157918:   }
157919: 
157920:   return 0;
157921: }
157922: 
157923: /*
157924: ** Retrieve information about the current candidate snippet of snippet 
157925: ** iterator pIter.
157926: */
157927: static void fts3SnippetDetails(
157928:   SnippetIter *pIter,             /* Snippet iterator */
157929:   u64 mCovered,                   /* Bitmask of phrases already covered */
157930:   int *piToken,                   /* OUT: First token of proposed snippet */
157931:   int *piScore,                   /* OUT: "Score" for this snippet */
157932:   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
157933:   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
157934: ){
157935:   int iStart = pIter->iCurrent;   /* First token of snippet */
157936:   int iScore = 0;                 /* Score of this snippet */
157937:   int i;                          /* Loop counter */
157938:   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
157939:   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
157940: 
157941:   for(i=0; i<pIter->nPhrase; i++){
157942:     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
157943:     if( pPhrase->pTail ){
157944:       char *pCsr = pPhrase->pTail;
157945:       int iCsr = pPhrase->iTail;
157946: 
157947:       while( iCsr<(iStart+pIter->nSnippet) ){
157948:         int j;
157949:         u64 mPhrase = (u64)1 << i;
157950:         u64 mPos = (u64)1 << (iCsr - iStart);
157951:         assert( iCsr>=iStart );
157952:         if( (mCover|mCovered)&mPhrase ){
157953:           iScore++;
157954:         }else{
157955:           iScore += 1000;
157956:         }
157957:         mCover |= mPhrase;
157958: 
157959:         for(j=0; j<pPhrase->nToken; j++){
157960:           mHighlight |= (mPos>>j);
157961:         }
157962: 
157963:         if( 0==(*pCsr & 0x0FE) ) break;
157964:         fts3GetDeltaPosition(&pCsr, &iCsr);
157965:       }
157966:     }
157967:   }
157968: 
157969:   /* Set the output variables before returning. */
157970:   *piToken = iStart;
157971:   *piScore = iScore;
157972:   *pmCover = mCover;
157973:   *pmHighlight = mHighlight;
157974: }
157975: 
157976: /*
157977: ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
157978: ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
157979: */
157980: static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
157981:   SnippetIter *p = (SnippetIter *)ctx;
157982:   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
157983:   char *pCsr;
157984:   int rc;
157985: 
157986:   pPhrase->nToken = pExpr->pPhrase->nToken;
157987:   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
157988:   assert( rc==SQLITE_OK || pCsr==0 );
157989:   if( pCsr ){
157990:     int iFirst = 0;
157991:     pPhrase->pList = pCsr;
157992:     fts3GetDeltaPosition(&pCsr, &iFirst);
157993:     assert( iFirst>=0 );
157994:     pPhrase->pHead = pCsr;
157995:     pPhrase->pTail = pCsr;
157996:     pPhrase->iHead = iFirst;
157997:     pPhrase->iTail = iFirst;
157998:   }else{
157999:     assert( rc!=SQLITE_OK || (
158000:        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
158001:     ));
158002:   }
158003: 
158004:   return rc;
158005: }
158006: 
158007: /*
158008: ** Select the fragment of text consisting of nFragment contiguous tokens 
158009: ** from column iCol that represent the "best" snippet. The best snippet
158010: ** is the snippet with the highest score, where scores are calculated
158011: ** by adding:
158012: **
158013: **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
158014: **
158015: **   (b) +1000 points for the first occurrence of each matchable phrase in 
158016: **       the snippet for which the corresponding mCovered bit is not set.
158017: **
158018: ** The selected snippet parameters are stored in structure *pFragment before
158019: ** returning. The score of the selected snippet is stored in *piScore
158020: ** before returning.
158021: */
158022: static int fts3BestSnippet(
158023:   int nSnippet,                   /* Desired snippet length */
158024:   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
158025:   int iCol,                       /* Index of column to create snippet from */
158026:   u64 mCovered,                   /* Mask of phrases already covered */
158027:   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
158028:   SnippetFragment *pFragment,     /* OUT: Best snippet found */
158029:   int *piScore                    /* OUT: Score of snippet pFragment */
158030: ){
158031:   int rc;                         /* Return Code */
158032:   int nList;                      /* Number of phrases in expression */
158033:   SnippetIter sIter;              /* Iterates through snippet candidates */
158034:   int nByte;                      /* Number of bytes of space to allocate */
158035:   int iBestScore = -1;            /* Best snippet score found so far */
158036:   int i;                          /* Loop counter */
158037: 
158038:   memset(&sIter, 0, sizeof(sIter));
158039: 
158040:   /* Iterate through the phrases in the expression to count them. The same
158041:   ** callback makes sure the doclists are loaded for each phrase.
158042:   */
158043:   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
158044:   if( rc!=SQLITE_OK ){
158045:     return rc;
158046:   }
158047: 
158048:   /* Now that it is known how many phrases there are, allocate and zero
158049:   ** the required space using malloc().
158050:   */
158051:   nByte = sizeof(SnippetPhrase) * nList;
158052:   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
158053:   if( !sIter.aPhrase ){
158054:     return SQLITE_NOMEM;
158055:   }
158056:   memset(sIter.aPhrase, 0, nByte);
158057: 
158058:   /* Initialize the contents of the SnippetIter object. Then iterate through
158059:   ** the set of phrases in the expression to populate the aPhrase[] array.
158060:   */
158061:   sIter.pCsr = pCsr;
158062:   sIter.iCol = iCol;
158063:   sIter.nSnippet = nSnippet;
158064:   sIter.nPhrase = nList;
158065:   sIter.iCurrent = -1;
158066:   rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
158067:   if( rc==SQLITE_OK ){
158068: 
158069:     /* Set the *pmSeen output variable. */
158070:     for(i=0; i<nList; i++){
158071:       if( sIter.aPhrase[i].pHead ){
158072:         *pmSeen |= (u64)1 << i;
158073:       }
158074:     }
158075: 
158076:     /* Loop through all candidate snippets. Store the best snippet in 
158077:      ** *pFragment. Store its associated 'score' in iBestScore.
158078:      */
158079:     pFragment->iCol = iCol;
158080:     while( !fts3SnippetNextCandidate(&sIter) ){
158081:       int iPos;
158082:       int iScore;
158083:       u64 mCover;
158084:       u64 mHighlite;
158085:       fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
158086:       assert( iScore>=0 );
158087:       if( iScore>iBestScore ){
158088:         pFragment->iPos = iPos;
158089:         pFragment->hlmask = mHighlite;
158090:         pFragment->covered = mCover;
158091:         iBestScore = iScore;
158092:       }
158093:     }
158094: 
158095:     *piScore = iBestScore;
158096:   }
158097:   sqlite3_free(sIter.aPhrase);
158098:   return rc;
158099: }
158100: 
158101: 
158102: /*
158103: ** Append a string to the string-buffer passed as the first argument.
158104: **
158105: ** If nAppend is negative, then the length of the string zAppend is
158106: ** determined using strlen().
158107: */
158108: static int fts3StringAppend(
158109:   StrBuffer *pStr,                /* Buffer to append to */
158110:   const char *zAppend,            /* Pointer to data to append to buffer */
158111:   int nAppend                     /* Size of zAppend in bytes (or -1) */
158112: ){
158113:   if( nAppend<0 ){
158114:     nAppend = (int)strlen(zAppend);
158115:   }
158116: 
158117:   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
158118:   ** to grow the buffer until so that it is big enough to accomadate the
158119:   ** appended data.
158120:   */
158121:   if( pStr->n+nAppend+1>=pStr->nAlloc ){
158122:     int nAlloc = pStr->nAlloc+nAppend+100;
158123:     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
158124:     if( !zNew ){
158125:       return SQLITE_NOMEM;
158126:     }
158127:     pStr->z = zNew;
158128:     pStr->nAlloc = nAlloc;
158129:   }
158130:   assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
158131: 
158132:   /* Append the data to the string buffer. */
158133:   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
158134:   pStr->n += nAppend;
158135:   pStr->z[pStr->n] = '\0';
158136: 
158137:   return SQLITE_OK;
158138: }
158139: 
158140: /*
158141: ** The fts3BestSnippet() function often selects snippets that end with a
158142: ** query term. That is, the final term of the snippet is always a term
158143: ** that requires highlighting. For example, if 'X' is a highlighted term
158144: ** and '.' is a non-highlighted term, BestSnippet() may select:
158145: **
158146: **     ........X.....X
158147: **
158148: ** This function "shifts" the beginning of the snippet forward in the 
158149: ** document so that there are approximately the same number of 
158150: ** non-highlighted terms to the right of the final highlighted term as there
158151: ** are to the left of the first highlighted term. For example, to this:
158152: **
158153: **     ....X.....X....
158154: **
158155: ** This is done as part of extracting the snippet text, not when selecting
158156: ** the snippet. Snippet selection is done based on doclists only, so there
158157: ** is no way for fts3BestSnippet() to know whether or not the document 
158158: ** actually contains terms that follow the final highlighted term. 
158159: */
158160: static int fts3SnippetShift(
158161:   Fts3Table *pTab,                /* FTS3 table snippet comes from */
158162:   int iLangid,                    /* Language id to use in tokenizing */
158163:   int nSnippet,                   /* Number of tokens desired for snippet */
158164:   const char *zDoc,               /* Document text to extract snippet from */
158165:   int nDoc,                       /* Size of buffer zDoc in bytes */
158166:   int *piPos,                     /* IN/OUT: First token of snippet */
158167:   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
158168: ){
158169:   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
158170: 
158171:   if( hlmask ){
158172:     int nLeft;                    /* Tokens to the left of first highlight */
158173:     int nRight;                   /* Tokens to the right of last highlight */
158174:     int nDesired;                 /* Ideal number of tokens to shift forward */
158175: 
158176:     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
158177:     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
158178:     nDesired = (nLeft-nRight)/2;
158179: 
158180:     /* Ideally, the start of the snippet should be pushed forward in the
158181:     ** document nDesired tokens. This block checks if there are actually
158182:     ** nDesired tokens to the right of the snippet. If so, *piPos and
158183:     ** *pHlMask are updated to shift the snippet nDesired tokens to the
158184:     ** right. Otherwise, the snippet is shifted by the number of tokens
158185:     ** available.
158186:     */
158187:     if( nDesired>0 ){
158188:       int nShift;                 /* Number of tokens to shift snippet by */
158189:       int iCurrent = 0;           /* Token counter */
158190:       int rc;                     /* Return Code */
158191:       sqlite3_tokenizer_module *pMod;
158192:       sqlite3_tokenizer_cursor *pC;
158193:       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
158194: 
158195:       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
158196:       ** or more tokens in zDoc/nDoc.
158197:       */
158198:       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
158199:       if( rc!=SQLITE_OK ){
158200:         return rc;
158201:       }
158202:       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
158203:         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
158204:         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
158205:       }
158206:       pMod->xClose(pC);
158207:       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
158208: 
158209:       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
158210:       assert( nShift<=nDesired );
158211:       if( nShift>0 ){
158212:         *piPos += nShift;
158213:         *pHlmask = hlmask >> nShift;
158214:       }
158215:     }
158216:   }
158217:   return SQLITE_OK;
158218: }
158219: 
158220: /*
158221: ** Extract the snippet text for fragment pFragment from cursor pCsr and
158222: ** append it to string buffer pOut.
158223: */
158224: static int fts3SnippetText(
158225:   Fts3Cursor *pCsr,               /* FTS3 Cursor */
158226:   SnippetFragment *pFragment,     /* Snippet to extract */
158227:   int iFragment,                  /* Fragment number */
158228:   int isLast,                     /* True for final fragment in snippet */
158229:   int nSnippet,                   /* Number of tokens in extracted snippet */
158230:   const char *zOpen,              /* String inserted before highlighted term */
158231:   const char *zClose,             /* String inserted after highlighted term */
158232:   const char *zEllipsis,          /* String inserted between snippets */
158233:   StrBuffer *pOut                 /* Write output here */
158234: ){
158235:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158236:   int rc;                         /* Return code */
158237:   const char *zDoc;               /* Document text to extract snippet from */
158238:   int nDoc;                       /* Size of zDoc in bytes */
158239:   int iCurrent = 0;               /* Current token number of document */
158240:   int iEnd = 0;                   /* Byte offset of end of current token */
158241:   int isShiftDone = 0;            /* True after snippet is shifted */
158242:   int iPos = pFragment->iPos;     /* First token of snippet */
158243:   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
158244:   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
158245:   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
158246:   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
158247:   
158248:   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
158249:   if( zDoc==0 ){
158250:     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
158251:       return SQLITE_NOMEM;
158252:     }
158253:     return SQLITE_OK;
158254:   }
158255:   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
158256: 
158257:   /* Open a token cursor on the document. */
158258:   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
158259:   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
158260:   if( rc!=SQLITE_OK ){
158261:     return rc;
158262:   }
158263: 
158264:   while( rc==SQLITE_OK ){
158265:     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
158266:     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
158267:     int iBegin = 0;               /* Offset in zDoc of start of token */
158268:     int iFin = 0;                 /* Offset in zDoc of end of token */
158269:     int isHighlight = 0;          /* True for highlighted terms */
158270: 
158271:     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
158272:     ** in the FTS code the variable that the third argument to xNext points to
158273:     ** is initialized to zero before the first (*but not necessarily
158274:     ** subsequent*) call to xNext(). This is done for a particular application
158275:     ** that needs to know whether or not the tokenizer is being used for
158276:     ** snippet generation or for some other purpose.
158277:     **
158278:     ** Extreme care is required when writing code to depend on this
158279:     ** initialization. It is not a documented part of the tokenizer interface.
158280:     ** If a tokenizer is used directly by any code outside of FTS, this
158281:     ** convention might not be respected.  */
158282:     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
158283:     if( rc!=SQLITE_OK ){
158284:       if( rc==SQLITE_DONE ){
158285:         /* Special case - the last token of the snippet is also the last token
158286:         ** of the column. Append any punctuation that occurred between the end
158287:         ** of the previous token and the end of the document to the output. 
158288:         ** Then break out of the loop. */
158289:         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
158290:       }
158291:       break;
158292:     }
158293:     if( iCurrent<iPos ){ continue; }
158294: 
158295:     if( !isShiftDone ){
158296:       int n = nDoc - iBegin;
158297:       rc = fts3SnippetShift(
158298:           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
158299:       );
158300:       isShiftDone = 1;
158301: 
158302:       /* Now that the shift has been done, check if the initial "..." are
158303:       ** required. They are required if (a) this is not the first fragment,
158304:       ** or (b) this fragment does not begin at position 0 of its column. 
158305:       */
158306:       if( rc==SQLITE_OK ){
158307:         if( iPos>0 || iFragment>0 ){
158308:           rc = fts3StringAppend(pOut, zEllipsis, -1);
158309:         }else if( iBegin ){
158310:           rc = fts3StringAppend(pOut, zDoc, iBegin);
158311:         }
158312:       }
158313:       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
158314:     }
158315: 
158316:     if( iCurrent>=(iPos+nSnippet) ){
158317:       if( isLast ){
158318:         rc = fts3StringAppend(pOut, zEllipsis, -1);
158319:       }
158320:       break;
158321:     }
158322: 
158323:     /* Set isHighlight to true if this term should be highlighted. */
158324:     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
158325: 
158326:     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
158327:     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
158328:     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
158329:     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
158330: 
158331:     iEnd = iFin;
158332:   }
158333: 
158334:   pMod->xClose(pC);
158335:   return rc;
158336: }
158337: 
158338: 
158339: /*
158340: ** This function is used to count the entries in a column-list (a 
158341: ** delta-encoded list of term offsets within a single column of a single 
158342: ** row). When this function is called, *ppCollist should point to the
158343: ** beginning of the first varint in the column-list (the varint that
158344: ** contains the position of the first matching term in the column data).
158345: ** Before returning, *ppCollist is set to point to the first byte after
158346: ** the last varint in the column-list (either the 0x00 signifying the end
158347: ** of the position-list, or the 0x01 that precedes the column number of
158348: ** the next column in the position-list).
158349: **
158350: ** The number of elements in the column-list is returned.
158351: */
158352: static int fts3ColumnlistCount(char **ppCollist){
158353:   char *pEnd = *ppCollist;
158354:   char c = 0;
158355:   int nEntry = 0;
158356: 
158357:   /* A column-list is terminated by either a 0x01 or 0x00. */
158358:   while( 0xFE & (*pEnd | c) ){
158359:     c = *pEnd++ & 0x80;
158360:     if( !c ) nEntry++;
158361:   }
158362: 
158363:   *ppCollist = pEnd;
158364:   return nEntry;
158365: }
158366: 
158367: /*
158368: ** This function gathers 'y' or 'b' data for a single phrase.
158369: */
158370: static void fts3ExprLHits(
158371:   Fts3Expr *pExpr,                /* Phrase expression node */
158372:   MatchInfo *p                    /* Matchinfo context */
158373: ){
158374:   Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
158375:   int iStart;
158376:   Fts3Phrase *pPhrase = pExpr->pPhrase;
158377:   char *pIter = pPhrase->doclist.pList;
158378:   int iCol = 0;
158379: 
158380:   assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
158381:   if( p->flag==FTS3_MATCHINFO_LHITS ){
158382:     iStart = pExpr->iPhrase * p->nCol;
158383:   }else{
158384:     iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
158385:   }
158386: 
158387:   while( 1 ){
158388:     int nHit = fts3ColumnlistCount(&pIter);
158389:     if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
158390:       if( p->flag==FTS3_MATCHINFO_LHITS ){
158391:         p->aMatchinfo[iStart + iCol] = (u32)nHit;
158392:       }else if( nHit ){
158393:         p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
158394:       }
158395:     }
158396:     assert( *pIter==0x00 || *pIter==0x01 );
158397:     if( *pIter!=0x01 ) break;
158398:     pIter++;
158399:     pIter += fts3GetVarint32(pIter, &iCol);
158400:   }
158401: }
158402: 
158403: /*
158404: ** Gather the results for matchinfo directives 'y' and 'b'.
158405: */
158406: static void fts3ExprLHitGather(
158407:   Fts3Expr *pExpr,
158408:   MatchInfo *p
158409: ){
158410:   assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
158411:   if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
158412:     if( pExpr->pLeft ){
158413:       fts3ExprLHitGather(pExpr->pLeft, p);
158414:       fts3ExprLHitGather(pExpr->pRight, p);
158415:     }else{
158416:       fts3ExprLHits(pExpr, p);
158417:     }
158418:   }
158419: }
158420: 
158421: /*
158422: ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
158423: ** for a single query. 
158424: **
158425: ** fts3ExprIterate() callback to load the 'global' elements of a
158426: ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
158427: ** of the matchinfo array that are constant for all rows returned by the 
158428: ** current query.
158429: **
158430: ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
158431: ** function populates Matchinfo.aMatchinfo[] as follows:
158432: **
158433: **   for(iCol=0; iCol<nCol; iCol++){
158434: **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
158435: **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
158436: **   }
158437: **
158438: ** where X is the number of matches for phrase iPhrase is column iCol of all
158439: ** rows of the table. Y is the number of rows for which column iCol contains
158440: ** at least one instance of phrase iPhrase.
158441: **
158442: ** If the phrase pExpr consists entirely of deferred tokens, then all X and
158443: ** Y values are set to nDoc, where nDoc is the number of documents in the 
158444: ** file system. This is done because the full-text index doclist is required
158445: ** to calculate these values properly, and the full-text index doclist is
158446: ** not available for deferred tokens.
158447: */
158448: static int fts3ExprGlobalHitsCb(
158449:   Fts3Expr *pExpr,                /* Phrase expression node */
158450:   int iPhrase,                    /* Phrase number (numbered from zero) */
158451:   void *pCtx                      /* Pointer to MatchInfo structure */
158452: ){
158453:   MatchInfo *p = (MatchInfo *)pCtx;
158454:   return sqlite3Fts3EvalPhraseStats(
158455:       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
158456:   );
158457: }
158458: 
158459: /*
158460: ** fts3ExprIterate() callback used to collect the "local" part of the
158461: ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
158462: ** array that are different for each row returned by the query.
158463: */
158464: static int fts3ExprLocalHitsCb(
158465:   Fts3Expr *pExpr,                /* Phrase expression node */
158466:   int iPhrase,                    /* Phrase number */
158467:   void *pCtx                      /* Pointer to MatchInfo structure */
158468: ){
158469:   int rc = SQLITE_OK;
158470:   MatchInfo *p = (MatchInfo *)pCtx;
158471:   int iStart = iPhrase * p->nCol * 3;
158472:   int i;
158473: 
158474:   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
158475:     char *pCsr;
158476:     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
158477:     if( pCsr ){
158478:       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
158479:     }else{
158480:       p->aMatchinfo[iStart+i*3] = 0;
158481:     }
158482:   }
158483: 
158484:   return rc;
158485: }
158486: 
158487: static int fts3MatchinfoCheck(
158488:   Fts3Table *pTab, 
158489:   char cArg,
158490:   char **pzErr
158491: ){
158492:   if( (cArg==FTS3_MATCHINFO_NPHRASE)
158493:    || (cArg==FTS3_MATCHINFO_NCOL)
158494:    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
158495:    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
158496:    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
158497:    || (cArg==FTS3_MATCHINFO_LCS)
158498:    || (cArg==FTS3_MATCHINFO_HITS)
158499:    || (cArg==FTS3_MATCHINFO_LHITS)
158500:    || (cArg==FTS3_MATCHINFO_LHITS_BM)
158501:   ){
158502:     return SQLITE_OK;
158503:   }
158504:   sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
158505:   return SQLITE_ERROR;
158506: }
158507: 
158508: static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
158509:   int nVal;                       /* Number of integers output by cArg */
158510: 
158511:   switch( cArg ){
158512:     case FTS3_MATCHINFO_NDOC:
158513:     case FTS3_MATCHINFO_NPHRASE: 
158514:     case FTS3_MATCHINFO_NCOL: 
158515:       nVal = 1;
158516:       break;
158517: 
158518:     case FTS3_MATCHINFO_AVGLENGTH:
158519:     case FTS3_MATCHINFO_LENGTH:
158520:     case FTS3_MATCHINFO_LCS:
158521:       nVal = pInfo->nCol;
158522:       break;
158523: 
158524:     case FTS3_MATCHINFO_LHITS:
158525:       nVal = pInfo->nCol * pInfo->nPhrase;
158526:       break;
158527: 
158528:     case FTS3_MATCHINFO_LHITS_BM:
158529:       nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
158530:       break;
158531: 
158532:     default:
158533:       assert( cArg==FTS3_MATCHINFO_HITS );
158534:       nVal = pInfo->nCol * pInfo->nPhrase * 3;
158535:       break;
158536:   }
158537: 
158538:   return nVal;
158539: }
158540: 
158541: static int fts3MatchinfoSelectDoctotal(
158542:   Fts3Table *pTab,
158543:   sqlite3_stmt **ppStmt,
158544:   sqlite3_int64 *pnDoc,
158545:   const char **paLen
158546: ){
158547:   sqlite3_stmt *pStmt;
158548:   const char *a;
158549:   sqlite3_int64 nDoc;
158550: 
158551:   if( !*ppStmt ){
158552:     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
158553:     if( rc!=SQLITE_OK ) return rc;
158554:   }
158555:   pStmt = *ppStmt;
158556:   assert( sqlite3_data_count(pStmt)==1 );
158557: 
158558:   a = sqlite3_column_blob(pStmt, 0);
158559:   a += sqlite3Fts3GetVarint(a, &nDoc);
158560:   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
158561:   *pnDoc = (u32)nDoc;
158562: 
158563:   if( paLen ) *paLen = a;
158564:   return SQLITE_OK;
158565: }
158566: 
158567: /*
158568: ** An instance of the following structure is used to store state while 
158569: ** iterating through a multi-column position-list corresponding to the
158570: ** hits for a single phrase on a single row in order to calculate the
158571: ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
158572: */
158573: typedef struct LcsIterator LcsIterator;
158574: struct LcsIterator {
158575:   Fts3Expr *pExpr;                /* Pointer to phrase expression */
158576:   int iPosOffset;                 /* Tokens count up to end of this phrase */
158577:   char *pRead;                    /* Cursor used to iterate through aDoclist */
158578:   int iPos;                       /* Current position */
158579: };
158580: 
158581: /* 
158582: ** If LcsIterator.iCol is set to the following value, the iterator has
158583: ** finished iterating through all offsets for all columns.
158584: */
158585: #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
158586: 
158587: static int fts3MatchinfoLcsCb(
158588:   Fts3Expr *pExpr,                /* Phrase expression node */
158589:   int iPhrase,                    /* Phrase number (numbered from zero) */
158590:   void *pCtx                      /* Pointer to MatchInfo structure */
158591: ){
158592:   LcsIterator *aIter = (LcsIterator *)pCtx;
158593:   aIter[iPhrase].pExpr = pExpr;
158594:   return SQLITE_OK;
158595: }
158596: 
158597: /*
158598: ** Advance the iterator passed as an argument to the next position. Return
158599: ** 1 if the iterator is at EOF or if it now points to the start of the
158600: ** position list for the next column.
158601: */
158602: static int fts3LcsIteratorAdvance(LcsIterator *pIter){
158603:   char *pRead = pIter->pRead;
158604:   sqlite3_int64 iRead;
158605:   int rc = 0;
158606: 
158607:   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
158608:   if( iRead==0 || iRead==1 ){
158609:     pRead = 0;
158610:     rc = 1;
158611:   }else{
158612:     pIter->iPos += (int)(iRead-2);
158613:   }
158614: 
158615:   pIter->pRead = pRead;
158616:   return rc;
158617: }
158618:   
158619: /*
158620: ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
158621: **
158622: ** If the call is successful, the longest-common-substring lengths for each
158623: ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
158624: ** array before returning. SQLITE_OK is returned in this case.
158625: **
158626: ** Otherwise, if an error occurs, an SQLite error code is returned and the
158627: ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
158628: ** undefined.
158629: */
158630: static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
158631:   LcsIterator *aIter;
158632:   int i;
158633:   int iCol;
158634:   int nToken = 0;
158635: 
158636:   /* Allocate and populate the array of LcsIterator objects. The array
158637:   ** contains one element for each matchable phrase in the query.
158638:   **/
158639:   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
158640:   if( !aIter ) return SQLITE_NOMEM;
158641:   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
158642:   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
158643: 
158644:   for(i=0; i<pInfo->nPhrase; i++){
158645:     LcsIterator *pIter = &aIter[i];
158646:     nToken -= pIter->pExpr->pPhrase->nToken;
158647:     pIter->iPosOffset = nToken;
158648:   }
158649: 
158650:   for(iCol=0; iCol<pInfo->nCol; iCol++){
158651:     int nLcs = 0;                 /* LCS value for this column */
158652:     int nLive = 0;                /* Number of iterators in aIter not at EOF */
158653: 
158654:     for(i=0; i<pInfo->nPhrase; i++){
158655:       int rc;
158656:       LcsIterator *pIt = &aIter[i];
158657:       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
158658:       if( rc!=SQLITE_OK ) return rc;
158659:       if( pIt->pRead ){
158660:         pIt->iPos = pIt->iPosOffset;
158661:         fts3LcsIteratorAdvance(&aIter[i]);
158662:         nLive++;
158663:       }
158664:     }
158665: 
158666:     while( nLive>0 ){
158667:       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
158668:       int nThisLcs = 0;           /* LCS for the current iterator positions */
158669: 
158670:       for(i=0; i<pInfo->nPhrase; i++){
158671:         LcsIterator *pIter = &aIter[i];
158672:         if( pIter->pRead==0 ){
158673:           /* This iterator is already at EOF for this column. */
158674:           nThisLcs = 0;
158675:         }else{
158676:           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
158677:             pAdv = pIter;
158678:           }
158679:           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
158680:             nThisLcs++;
158681:           }else{
158682:             nThisLcs = 1;
158683:           }
158684:           if( nThisLcs>nLcs ) nLcs = nThisLcs;
158685:         }
158686:       }
158687:       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
158688:     }
158689: 
158690:     pInfo->aMatchinfo[iCol] = nLcs;
158691:   }
158692: 
158693:   sqlite3_free(aIter);
158694:   return SQLITE_OK;
158695: }
158696: 
158697: /*
158698: ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
158699: ** be returned by the matchinfo() function. Argument zArg contains the 
158700: ** format string passed as the second argument to matchinfo (or the
158701: ** default value "pcx" if no second argument was specified). The format
158702: ** string has already been validated and the pInfo->aMatchinfo[] array
158703: ** is guaranteed to be large enough for the output.
158704: **
158705: ** If bGlobal is true, then populate all fields of the matchinfo() output.
158706: ** If it is false, then assume that those fields that do not change between
158707: ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
158708: ** have already been populated.
158709: **
158710: ** Return SQLITE_OK if successful, or an SQLite error code if an error 
158711: ** occurs. If a value other than SQLITE_OK is returned, the state the
158712: ** pInfo->aMatchinfo[] buffer is left in is undefined.
158713: */
158714: static int fts3MatchinfoValues(
158715:   Fts3Cursor *pCsr,               /* FTS3 cursor object */
158716:   int bGlobal,                    /* True to grab the global stats */
158717:   MatchInfo *pInfo,               /* Matchinfo context object */
158718:   const char *zArg                /* Matchinfo format string */
158719: ){
158720:   int rc = SQLITE_OK;
158721:   int i;
158722:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158723:   sqlite3_stmt *pSelect = 0;
158724: 
158725:   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
158726:     pInfo->flag = zArg[i];
158727:     switch( zArg[i] ){
158728:       case FTS3_MATCHINFO_NPHRASE:
158729:         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
158730:         break;
158731: 
158732:       case FTS3_MATCHINFO_NCOL:
158733:         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
158734:         break;
158735:         
158736:       case FTS3_MATCHINFO_NDOC:
158737:         if( bGlobal ){
158738:           sqlite3_int64 nDoc = 0;
158739:           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
158740:           pInfo->aMatchinfo[0] = (u32)nDoc;
158741:         }
158742:         break;
158743: 
158744:       case FTS3_MATCHINFO_AVGLENGTH: 
158745:         if( bGlobal ){
158746:           sqlite3_int64 nDoc;     /* Number of rows in table */
158747:           const char *a;          /* Aggregate column length array */
158748: 
158749:           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
158750:           if( rc==SQLITE_OK ){
158751:             int iCol;
158752:             for(iCol=0; iCol<pInfo->nCol; iCol++){
158753:               u32 iVal;
158754:               sqlite3_int64 nToken;
158755:               a += sqlite3Fts3GetVarint(a, &nToken);
158756:               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
158757:               pInfo->aMatchinfo[iCol] = iVal;
158758:             }
158759:           }
158760:         }
158761:         break;
158762: 
158763:       case FTS3_MATCHINFO_LENGTH: {
158764:         sqlite3_stmt *pSelectDocsize = 0;
158765:         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
158766:         if( rc==SQLITE_OK ){
158767:           int iCol;
158768:           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
158769:           for(iCol=0; iCol<pInfo->nCol; iCol++){
158770:             sqlite3_int64 nToken;
158771:             a += sqlite3Fts3GetVarint(a, &nToken);
158772:             pInfo->aMatchinfo[iCol] = (u32)nToken;
158773:           }
158774:         }
158775:         sqlite3_reset(pSelectDocsize);
158776:         break;
158777:       }
158778: 
158779:       case FTS3_MATCHINFO_LCS:
158780:         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
158781:         if( rc==SQLITE_OK ){
158782:           rc = fts3MatchinfoLcs(pCsr, pInfo);
158783:         }
158784:         break;
158785: 
158786:       case FTS3_MATCHINFO_LHITS_BM:
158787:       case FTS3_MATCHINFO_LHITS: {
158788:         int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
158789:         memset(pInfo->aMatchinfo, 0, nZero);
158790:         fts3ExprLHitGather(pCsr->pExpr, pInfo);
158791:         break;
158792:       }
158793: 
158794:       default: {
158795:         Fts3Expr *pExpr;
158796:         assert( zArg[i]==FTS3_MATCHINFO_HITS );
158797:         pExpr = pCsr->pExpr;
158798:         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
158799:         if( rc!=SQLITE_OK ) break;
158800:         if( bGlobal ){
158801:           if( pCsr->pDeferred ){
158802:             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
158803:             if( rc!=SQLITE_OK ) break;
158804:           }
158805:           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
158806:           sqlite3Fts3EvalTestDeferred(pCsr, &rc);
158807:           if( rc!=SQLITE_OK ) break;
158808:         }
158809:         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
158810:         break;
158811:       }
158812:     }
158813: 
158814:     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
158815:   }
158816: 
158817:   sqlite3_reset(pSelect);
158818:   return rc;
158819: }
158820: 
158821: 
158822: /*
158823: ** Populate pCsr->aMatchinfo[] with data for the current row. The 
158824: ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
158825: */
158826: static void fts3GetMatchinfo(
158827:   sqlite3_context *pCtx,        /* Return results here */
158828:   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
158829:   const char *zArg                /* Second argument to matchinfo() function */
158830: ){
158831:   MatchInfo sInfo;
158832:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158833:   int rc = SQLITE_OK;
158834:   int bGlobal = 0;                /* Collect 'global' stats as well as local */
158835: 
158836:   u32 *aOut = 0;
158837:   void (*xDestroyOut)(void*) = 0;
158838: 
158839:   memset(&sInfo, 0, sizeof(MatchInfo));
158840:   sInfo.pCursor = pCsr;
158841:   sInfo.nCol = pTab->nColumn;
158842: 
158843:   /* If there is cached matchinfo() data, but the format string for the 
158844:   ** cache does not match the format string for this request, discard 
158845:   ** the cached data. */
158846:   if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
158847:     sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
158848:     pCsr->pMIBuffer = 0;
158849:   }
158850: 
158851:   /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
158852:   ** matchinfo function has been called for this query. In this case 
158853:   ** allocate the array used to accumulate the matchinfo data and
158854:   ** initialize those elements that are constant for every row.
158855:   */
158856:   if( pCsr->pMIBuffer==0 ){
158857:     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
158858:     int i;                        /* Used to iterate through zArg */
158859: 
158860:     /* Determine the number of phrases in the query */
158861:     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
158862:     sInfo.nPhrase = pCsr->nPhrase;
158863: 
158864:     /* Determine the number of integers in the buffer returned by this call. */
158865:     for(i=0; zArg[i]; i++){
158866:       char *zErr = 0;
158867:       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
158868:         sqlite3_result_error(pCtx, zErr, -1);
158869:         sqlite3_free(zErr);
158870:         return;
158871:       }
158872:       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
158873:     }
158874: 
158875:     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
158876:     pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
158877:     if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
158878: 
158879:     pCsr->isMatchinfoNeeded = 1;
158880:     bGlobal = 1;
158881:   }
158882: 
158883:   if( rc==SQLITE_OK ){
158884:     xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
158885:     if( xDestroyOut==0 ){
158886:       rc = SQLITE_NOMEM;
158887:     }
158888:   }
158889: 
158890:   if( rc==SQLITE_OK ){
158891:     sInfo.aMatchinfo = aOut;
158892:     sInfo.nPhrase = pCsr->nPhrase;
158893:     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
158894:     if( bGlobal ){
158895:       fts3MIBufferSetGlobal(pCsr->pMIBuffer);
158896:     }
158897:   }
158898: 
158899:   if( rc!=SQLITE_OK ){
158900:     sqlite3_result_error_code(pCtx, rc);
158901:     if( xDestroyOut ) xDestroyOut(aOut);
158902:   }else{
158903:     int n = pCsr->pMIBuffer->nElem * sizeof(u32);
158904:     sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
158905:   }
158906: }
158907: 
158908: /*
158909: ** Implementation of snippet() function.
158910: */
158911: SQLITE_PRIVATE void sqlite3Fts3Snippet(
158912:   sqlite3_context *pCtx,          /* SQLite function call context */
158913:   Fts3Cursor *pCsr,               /* Cursor object */
158914:   const char *zStart,             /* Snippet start text - "<b>" */
158915:   const char *zEnd,               /* Snippet end text - "</b>" */
158916:   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
158917:   int iCol,                       /* Extract snippet from this column */
158918:   int nToken                      /* Approximate number of tokens in snippet */
158919: ){
158920:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158921:   int rc = SQLITE_OK;
158922:   int i;
158923:   StrBuffer res = {0, 0, 0};
158924: 
158925:   /* The returned text includes up to four fragments of text extracted from
158926:   ** the data in the current row. The first iteration of the for(...) loop
158927:   ** below attempts to locate a single fragment of text nToken tokens in 
158928:   ** size that contains at least one instance of all phrases in the query
158929:   ** expression that appear in the current row. If such a fragment of text
158930:   ** cannot be found, the second iteration of the loop attempts to locate
158931:   ** a pair of fragments, and so on.
158932:   */
158933:   int nSnippet = 0;               /* Number of fragments in this snippet */
158934:   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
158935:   int nFToken = -1;               /* Number of tokens in each fragment */
158936: 
158937:   if( !pCsr->pExpr ){
158938:     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
158939:     return;
158940:   }
158941: 
158942:   for(nSnippet=1; 1; nSnippet++){
158943: 
158944:     int iSnip;                    /* Loop counter 0..nSnippet-1 */
158945:     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
158946:     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
158947: 
158948:     if( nToken>=0 ){
158949:       nFToken = (nToken+nSnippet-1) / nSnippet;
158950:     }else{
158951:       nFToken = -1 * nToken;
158952:     }
158953: 
158954:     for(iSnip=0; iSnip<nSnippet; iSnip++){
158955:       int iBestScore = -1;        /* Best score of columns checked so far */
158956:       int iRead;                  /* Used to iterate through columns */
158957:       SnippetFragment *pFragment = &aSnippet[iSnip];
158958: 
158959:       memset(pFragment, 0, sizeof(*pFragment));
158960: 
158961:       /* Loop through all columns of the table being considered for snippets.
158962:       ** If the iCol argument to this function was negative, this means all
158963:       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
158964:       */
158965:       for(iRead=0; iRead<pTab->nColumn; iRead++){
158966:         SnippetFragment sF = {0, 0, 0, 0};
158967:         int iS = 0;
158968:         if( iCol>=0 && iRead!=iCol ) continue;
158969: 
158970:         /* Find the best snippet of nFToken tokens in column iRead. */
158971:         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
158972:         if( rc!=SQLITE_OK ){
158973:           goto snippet_out;
158974:         }
158975:         if( iS>iBestScore ){
158976:           *pFragment = sF;
158977:           iBestScore = iS;
158978:         }
158979:       }
158980: 
158981:       mCovered |= pFragment->covered;
158982:     }
158983: 
158984:     /* If all query phrases seen by fts3BestSnippet() are present in at least
158985:     ** one of the nSnippet snippet fragments, break out of the loop.
158986:     */
158987:     assert( (mCovered&mSeen)==mCovered );
158988:     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
158989:   }
158990: 
158991:   assert( nFToken>0 );
158992: 
158993:   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
158994:     rc = fts3SnippetText(pCsr, &aSnippet[i], 
158995:         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
158996:     );
158997:   }
158998: 
158999:  snippet_out:
159000:   sqlite3Fts3SegmentsClose(pTab);
159001:   if( rc!=SQLITE_OK ){
159002:     sqlite3_result_error_code(pCtx, rc);
159003:     sqlite3_free(res.z);
159004:   }else{
159005:     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
159006:   }
159007: }
159008: 
159009: 
159010: typedef struct TermOffset TermOffset;
159011: typedef struct TermOffsetCtx TermOffsetCtx;
159012: 
159013: struct TermOffset {
159014:   char *pList;                    /* Position-list */
159015:   int iPos;                       /* Position just read from pList */
159016:   int iOff;                       /* Offset of this term from read positions */
159017: };
159018: 
159019: struct TermOffsetCtx {
159020:   Fts3Cursor *pCsr;
159021:   int iCol;                       /* Column of table to populate aTerm for */
159022:   int iTerm;
159023:   sqlite3_int64 iDocid;
159024:   TermOffset *aTerm;
159025: };
159026: 
159027: /*
159028: ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
159029: */
159030: static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
159031:   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
159032:   int nTerm;                      /* Number of tokens in phrase */
159033:   int iTerm;                      /* For looping through nTerm phrase terms */
159034:   char *pList;                    /* Pointer to position list for phrase */
159035:   int iPos = 0;                   /* First position in position-list */
159036:   int rc;
159037: 
159038:   UNUSED_PARAMETER(iPhrase);
159039:   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
159040:   nTerm = pExpr->pPhrase->nToken;
159041:   if( pList ){
159042:     fts3GetDeltaPosition(&pList, &iPos);
159043:     assert( iPos>=0 );
159044:   }
159045: 
159046:   for(iTerm=0; iTerm<nTerm; iTerm++){
159047:     TermOffset *pT = &p->aTerm[p->iTerm++];
159048:     pT->iOff = nTerm-iTerm-1;
159049:     pT->pList = pList;
159050:     pT->iPos = iPos;
159051:   }
159052: 
159053:   return rc;
159054: }
159055: 
159056: /*
159057: ** Implementation of offsets() function.
159058: */
159059: SQLITE_PRIVATE void sqlite3Fts3Offsets(
159060:   sqlite3_context *pCtx,          /* SQLite function call context */
159061:   Fts3Cursor *pCsr                /* Cursor object */
159062: ){
159063:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159064:   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
159065:   int rc;                         /* Return Code */
159066:   int nToken;                     /* Number of tokens in query */
159067:   int iCol;                       /* Column currently being processed */
159068:   StrBuffer res = {0, 0, 0};      /* Result string */
159069:   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
159070: 
159071:   if( !pCsr->pExpr ){
159072:     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
159073:     return;
159074:   }
159075: 
159076:   memset(&sCtx, 0, sizeof(sCtx));
159077:   assert( pCsr->isRequireSeek==0 );
159078: 
159079:   /* Count the number of terms in the query */
159080:   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
159081:   if( rc!=SQLITE_OK ) goto offsets_out;
159082: 
159083:   /* Allocate the array of TermOffset iterators. */
159084:   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
159085:   if( 0==sCtx.aTerm ){
159086:     rc = SQLITE_NOMEM;
159087:     goto offsets_out;
159088:   }
159089:   sCtx.iDocid = pCsr->iPrevId;
159090:   sCtx.pCsr = pCsr;
159091: 
159092:   /* Loop through the table columns, appending offset information to 
159093:   ** string-buffer res for each column.
159094:   */
159095:   for(iCol=0; iCol<pTab->nColumn; iCol++){
159096:     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
159097:     const char *ZDUMMY;           /* Dummy argument used with xNext() */
159098:     int NDUMMY = 0;               /* Dummy argument used with xNext() */
159099:     int iStart = 0;
159100:     int iEnd = 0;
159101:     int iCurrent = 0;
159102:     const char *zDoc;
159103:     int nDoc;
159104: 
159105:     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
159106:     ** no way that this operation can fail, so the return code from
159107:     ** fts3ExprIterate() can be discarded.
159108:     */
159109:     sCtx.iCol = iCol;
159110:     sCtx.iTerm = 0;
159111:     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
159112: 
159113:     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
159114:     ** in column iCol, jump immediately to the next iteration of the loop.
159115:     ** If an OOM occurs while retrieving the data (this can happen if SQLite
159116:     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
159117:     ** to the caller. 
159118:     */
159119:     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
159120:     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
159121:     if( zDoc==0 ){
159122:       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
159123:         continue;
159124:       }
159125:       rc = SQLITE_NOMEM;
159126:       goto offsets_out;
159127:     }
159128: 
159129:     /* Initialize a tokenizer iterator to iterate through column iCol. */
159130:     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
159131:         zDoc, nDoc, &pC
159132:     );
159133:     if( rc!=SQLITE_OK ) goto offsets_out;
159134: 
159135:     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
159136:     while( rc==SQLITE_OK ){
159137:       int i;                      /* Used to loop through terms */
159138:       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
159139:       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
159140: 
159141:       for(i=0; i<nToken; i++){
159142:         TermOffset *pT = &sCtx.aTerm[i];
159143:         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
159144:           iMinPos = pT->iPos-pT->iOff;
159145:           pTerm = pT;
159146:         }
159147:       }
159148: 
159149:       if( !pTerm ){
159150:         /* All offsets for this column have been gathered. */
159151:         rc = SQLITE_DONE;
159152:       }else{
159153:         assert( iCurrent<=iMinPos );
159154:         if( 0==(0xFE&*pTerm->pList) ){
159155:           pTerm->pList = 0;
159156:         }else{
159157:           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
159158:         }
159159:         while( rc==SQLITE_OK && iCurrent<iMinPos ){
159160:           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
159161:         }
159162:         if( rc==SQLITE_OK ){
159163:           char aBuffer[64];
159164:           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
159165:               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
159166:           );
159167:           rc = fts3StringAppend(&res, aBuffer, -1);
159168:         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
159169:           rc = FTS_CORRUPT_VTAB;
159170:         }
159171:       }
159172:     }
159173:     if( rc==SQLITE_DONE ){
159174:       rc = SQLITE_OK;
159175:     }
159176: 
159177:     pMod->xClose(pC);
159178:     if( rc!=SQLITE_OK ) goto offsets_out;
159179:   }
159180: 
159181:  offsets_out:
159182:   sqlite3_free(sCtx.aTerm);
159183:   assert( rc!=SQLITE_DONE );
159184:   sqlite3Fts3SegmentsClose(pTab);
159185:   if( rc!=SQLITE_OK ){
159186:     sqlite3_result_error_code(pCtx,  rc);
159187:     sqlite3_free(res.z);
159188:   }else{
159189:     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
159190:   }
159191:   return;
159192: }
159193: 
159194: /*
159195: ** Implementation of matchinfo() function.
159196: */
159197: SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
159198:   sqlite3_context *pContext,      /* Function call context */
159199:   Fts3Cursor *pCsr,               /* FTS3 table cursor */
159200:   const char *zArg                /* Second arg to matchinfo() function */
159201: ){
159202:   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
159203:   const char *zFormat;
159204: 
159205:   if( zArg ){
159206:     zFormat = zArg;
159207:   }else{
159208:     zFormat = FTS3_MATCHINFO_DEFAULT;
159209:   }
159210: 
159211:   if( !pCsr->pExpr ){
159212:     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
159213:     return;
159214:   }else{
159215:     /* Retrieve matchinfo() data. */
159216:     fts3GetMatchinfo(pContext, pCsr, zFormat);
159217:     sqlite3Fts3SegmentsClose(pTab);
159218:   }
159219: }
159220: 
159221: #endif
159222: 
159223: /************** End of fts3_snippet.c ****************************************/
159224: /************** Begin file fts3_unicode.c ************************************/
159225: /*
159226: ** 2012 May 24
159227: **
159228: ** The author disclaims copyright to this source code.  In place of
159229: ** a legal notice, here is a blessing:
159230: **
159231: **    May you do good and not evil.
159232: **    May you find forgiveness for yourself and forgive others.
159233: **    May you share freely, never taking more than you give.
159234: **
159235: ******************************************************************************
159236: **
159237: ** Implementation of the "unicode" full-text-search tokenizer.
159238: */
159239: 
159240: #ifndef SQLITE_DISABLE_FTS3_UNICODE
159241: 
159242: /* #include "fts3Int.h" */
159243: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
159244: 
159245: /* #include <assert.h> */
159246: /* #include <stdlib.h> */
159247: /* #include <stdio.h> */
159248: /* #include <string.h> */
159249: 
159250: /* #include "fts3_tokenizer.h" */
159251: 
159252: /*
159253: ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
159254: ** from the sqlite3 source file utf.c. If this file is compiled as part
159255: ** of the amalgamation, they are not required.
159256: */
159257: #ifndef SQLITE_AMALGAMATION
159258: 
159259: static const unsigned char sqlite3Utf8Trans1[] = {
159260:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159261:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
159262:   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
159263:   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
159264:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159265:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
159266:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
159267:   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
159268: };
159269: 
159270: #define READ_UTF8(zIn, zTerm, c)                           \
159271:   c = *(zIn++);                                            \
159272:   if( c>=0xc0 ){                                           \
159273:     c = sqlite3Utf8Trans1[c-0xc0];                         \
159274:     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
159275:       c = (c<<6) + (0x3f & *(zIn++));                      \
159276:     }                                                      \
159277:     if( c<0x80                                             \
159278:         || (c&0xFFFFF800)==0xD800                          \
159279:         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
159280:   }
159281: 
159282: #define WRITE_UTF8(zOut, c) {                          \
159283:   if( c<0x00080 ){                                     \
159284:     *zOut++ = (u8)(c&0xFF);                            \
159285:   }                                                    \
159286:   else if( c<0x00800 ){                                \
159287:     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
159288:     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159289:   }                                                    \
159290:   else if( c<0x10000 ){                                \
159291:     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
159292:     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
159293:     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159294:   }else{                                               \
159295:     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
159296:     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
159297:     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
159298:     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
159299:   }                                                    \
159300: }
159301: 
159302: #endif /* ifndef SQLITE_AMALGAMATION */
159303: 
159304: typedef struct unicode_tokenizer unicode_tokenizer;
159305: typedef struct unicode_cursor unicode_cursor;
159306: 
159307: struct unicode_tokenizer {
159308:   sqlite3_tokenizer base;
159309:   int bRemoveDiacritic;
159310:   int nException;
159311:   int *aiException;
159312: };
159313: 
159314: struct unicode_cursor {
159315:   sqlite3_tokenizer_cursor base;
159316:   const unsigned char *aInput;    /* Input text being tokenized */
159317:   int nInput;                     /* Size of aInput[] in bytes */
159318:   int iOff;                       /* Current offset within aInput[] */
159319:   int iToken;                     /* Index of next token to be returned */
159320:   char *zToken;                   /* storage for current token */
159321:   int nAlloc;                     /* space allocated at zToken */
159322: };
159323: 
159324: 
159325: /*
159326: ** Destroy a tokenizer allocated by unicodeCreate().
159327: */
159328: static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
159329:   if( pTokenizer ){
159330:     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
159331:     sqlite3_free(p->aiException);
159332:     sqlite3_free(p);
159333:   }
159334:   return SQLITE_OK;
159335: }
159336: 
159337: /*
159338: ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
159339: ** statement has specified that the tokenizer for this table shall consider
159340: ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
159341: ** token characters (if bAlnum==1).
159342: **
159343: ** For each codepoint in the zIn/nIn string, this function checks if the
159344: ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
159345: ** If so, no action is taken. Otherwise, the codepoint is added to the 
159346: ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
159347: ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
159348: ** codepoints in the aiException[] array.
159349: **
159350: ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
159351: ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
159352: ** It is not possible to change the behavior of the tokenizer with respect
159353: ** to these codepoints.
159354: */
159355: static int unicodeAddExceptions(
159356:   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
159357:   int bAlnum,                     /* Replace Isalnum() return value with this */
159358:   const char *zIn,                /* Array of characters to make exceptions */
159359:   int nIn                         /* Length of z in bytes */
159360: ){
159361:   const unsigned char *z = (const unsigned char *)zIn;
159362:   const unsigned char *zTerm = &z[nIn];
159363:   int iCode;
159364:   int nEntry = 0;
159365: 
159366:   assert( bAlnum==0 || bAlnum==1 );
159367: 
159368:   while( z<zTerm ){
159369:     READ_UTF8(z, zTerm, iCode);
159370:     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
159371:     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
159372:      && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
159373:     ){
159374:       nEntry++;
159375:     }
159376:   }
159377: 
159378:   if( nEntry ){
159379:     int *aNew;                    /* New aiException[] array */
159380:     int nNew;                     /* Number of valid entries in array aNew[] */
159381: 
159382:     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
159383:     if( aNew==0 ) return SQLITE_NOMEM;
159384:     nNew = p->nException;
159385: 
159386:     z = (const unsigned char *)zIn;
159387:     while( z<zTerm ){
159388:       READ_UTF8(z, zTerm, iCode);
159389:       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
159390:        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
159391:       ){
159392:         int i, j;
159393:         for(i=0; i<nNew && aNew[i]<iCode; i++);
159394:         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
159395:         aNew[i] = iCode;
159396:         nNew++;
159397:       }
159398:     }
159399:     p->aiException = aNew;
159400:     p->nException = nNew;
159401:   }
159402: 
159403:   return SQLITE_OK;
159404: }
159405: 
159406: /*
159407: ** Return true if the p->aiException[] array contains the value iCode.
159408: */
159409: static int unicodeIsException(unicode_tokenizer *p, int iCode){
159410:   if( p->nException>0 ){
159411:     int *a = p->aiException;
159412:     int iLo = 0;
159413:     int iHi = p->nException-1;
159414: 
159415:     while( iHi>=iLo ){
159416:       int iTest = (iHi + iLo) / 2;
159417:       if( iCode==a[iTest] ){
159418:         return 1;
159419:       }else if( iCode>a[iTest] ){
159420:         iLo = iTest+1;
159421:       }else{
159422:         iHi = iTest-1;
159423:       }
159424:     }
159425:   }
159426: 
159427:   return 0;
159428: }
159429: 
159430: /*
159431: ** Return true if, for the purposes of tokenization, codepoint iCode is
159432: ** considered a token character (not a separator).
159433: */
159434: static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
159435:   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
159436:   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
159437: }
159438: 
159439: /*
159440: ** Create a new tokenizer instance.
159441: */
159442: static int unicodeCreate(
159443:   int nArg,                       /* Size of array argv[] */
159444:   const char * const *azArg,      /* Tokenizer creation arguments */
159445:   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
159446: ){
159447:   unicode_tokenizer *pNew;        /* New tokenizer object */
159448:   int i;
159449:   int rc = SQLITE_OK;
159450: 
159451:   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
159452:   if( pNew==NULL ) return SQLITE_NOMEM;
159453:   memset(pNew, 0, sizeof(unicode_tokenizer));
159454:   pNew->bRemoveDiacritic = 1;
159455: 
159456:   for(i=0; rc==SQLITE_OK && i<nArg; i++){
159457:     const char *z = azArg[i];
159458:     int n = (int)strlen(z);
159459: 
159460:     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
159461:       pNew->bRemoveDiacritic = 1;
159462:     }
159463:     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
159464:       pNew->bRemoveDiacritic = 0;
159465:     }
159466:     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
159467:       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
159468:     }
159469:     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
159470:       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
159471:     }
159472:     else{
159473:       /* Unrecognized argument */
159474:       rc  = SQLITE_ERROR;
159475:     }
159476:   }
159477: 
159478:   if( rc!=SQLITE_OK ){
159479:     unicodeDestroy((sqlite3_tokenizer *)pNew);
159480:     pNew = 0;
159481:   }
159482:   *pp = (sqlite3_tokenizer *)pNew;
159483:   return rc;
159484: }
159485: 
159486: /*
159487: ** Prepare to begin tokenizing a particular string.  The input
159488: ** string to be tokenized is pInput[0..nBytes-1].  A cursor
159489: ** used to incrementally tokenize this string is returned in 
159490: ** *ppCursor.
159491: */
159492: static int unicodeOpen(
159493:   sqlite3_tokenizer *p,           /* The tokenizer */
159494:   const char *aInput,             /* Input string */
159495:   int nInput,                     /* Size of string aInput in bytes */
159496:   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
159497: ){
159498:   unicode_cursor *pCsr;
159499: 
159500:   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
159501:   if( pCsr==0 ){
159502:     return SQLITE_NOMEM;
159503:   }
159504:   memset(pCsr, 0, sizeof(unicode_cursor));
159505: 
159506:   pCsr->aInput = (const unsigned char *)aInput;
159507:   if( aInput==0 ){
159508:     pCsr->nInput = 0;
159509:   }else if( nInput<0 ){
159510:     pCsr->nInput = (int)strlen(aInput);
159511:   }else{
159512:     pCsr->nInput = nInput;
159513:   }
159514: 
159515:   *pp = &pCsr->base;
159516:   UNUSED_PARAMETER(p);
159517:   return SQLITE_OK;
159518: }
159519: 
159520: /*
159521: ** Close a tokenization cursor previously opened by a call to
159522: ** simpleOpen() above.
159523: */
159524: static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
159525:   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
159526:   sqlite3_free(pCsr->zToken);
159527:   sqlite3_free(pCsr);
159528:   return SQLITE_OK;
159529: }
159530: 
159531: /*
159532: ** Extract the next token from a tokenization cursor.  The cursor must
159533: ** have been opened by a prior call to simpleOpen().
159534: */
159535: static int unicodeNext(
159536:   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
159537:   const char **paToken,           /* OUT: Token text */
159538:   int *pnToken,                   /* OUT: Number of bytes at *paToken */
159539:   int *piStart,                   /* OUT: Starting offset of token */
159540:   int *piEnd,                     /* OUT: Ending offset of token */
159541:   int *piPos                      /* OUT: Position integer of token */
159542: ){
159543:   unicode_cursor *pCsr = (unicode_cursor *)pC;
159544:   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
159545:   int iCode = 0;
159546:   char *zOut;
159547:   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
159548:   const unsigned char *zStart = z;
159549:   const unsigned char *zEnd;
159550:   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
159551: 
159552:   /* Scan past any delimiter characters before the start of the next token.
159553:   ** Return SQLITE_DONE early if this takes us all the way to the end of 
159554:   ** the input.  */
159555:   while( z<zTerm ){
159556:     READ_UTF8(z, zTerm, iCode);
159557:     if( unicodeIsAlnum(p, iCode) ) break;
159558:     zStart = z;
159559:   }
159560:   if( zStart>=zTerm ) return SQLITE_DONE;
159561: 
159562:   zOut = pCsr->zToken;
159563:   do {
159564:     int iOut;
159565: 
159566:     /* Grow the output buffer if required. */
159567:     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
159568:       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
159569:       if( !zNew ) return SQLITE_NOMEM;
159570:       zOut = &zNew[zOut - pCsr->zToken];
159571:       pCsr->zToken = zNew;
159572:       pCsr->nAlloc += 64;
159573:     }
159574: 
159575:     /* Write the folded case of the last character read to the output */
159576:     zEnd = z;
159577:     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
159578:     if( iOut ){
159579:       WRITE_UTF8(zOut, iOut);
159580:     }
159581: 
159582:     /* If the cursor is not at EOF, read the next character */
159583:     if( z>=zTerm ) break;
159584:     READ_UTF8(z, zTerm, iCode);
159585:   }while( unicodeIsAlnum(p, iCode) 
159586:        || sqlite3FtsUnicodeIsdiacritic(iCode)
159587:   );
159588: 
159589:   /* Set the output variables and return. */
159590:   pCsr->iOff = (int)(z - pCsr->aInput);
159591:   *paToken = pCsr->zToken;
159592:   *pnToken = (int)(zOut - pCsr->zToken);
159593:   *piStart = (int)(zStart - pCsr->aInput);
159594:   *piEnd = (int)(zEnd - pCsr->aInput);
159595:   *piPos = pCsr->iToken++;
159596:   return SQLITE_OK;
159597: }
159598: 
159599: /*
159600: ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
159601: ** structure for the unicode tokenizer.
159602: */
159603: SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
159604:   static const sqlite3_tokenizer_module module = {
159605:     0,
159606:     unicodeCreate,
159607:     unicodeDestroy,
159608:     unicodeOpen,
159609:     unicodeClose,
159610:     unicodeNext,
159611:     0,
159612:   };
159613:   *ppModule = &module;
159614: }
159615: 
159616: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
159617: #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
159618: 
159619: /************** End of fts3_unicode.c ****************************************/
159620: /************** Begin file fts3_unicode2.c ***********************************/
159621: /*
159622: ** 2012 May 25
159623: **
159624: ** The author disclaims copyright to this source code.  In place of
159625: ** a legal notice, here is a blessing:
159626: **
159627: **    May you do good and not evil.
159628: **    May you find forgiveness for yourself and forgive others.
159629: **    May you share freely, never taking more than you give.
159630: **
159631: ******************************************************************************
159632: */
159633: 
159634: /*
159635: ** DO NOT EDIT THIS MACHINE GENERATED FILE.
159636: */
159637: 
159638: #ifndef SQLITE_DISABLE_FTS3_UNICODE
159639: #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
159640: 
159641: /* #include <assert.h> */
159642: 
159643: /*
159644: ** Return true if the argument corresponds to a unicode codepoint
159645: ** classified as either a letter or a number. Otherwise false.
159646: **
159647: ** The results are undefined if the value passed to this function
159648: ** is less than zero.
159649: */
159650: SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
159651:   /* Each unsigned integer in the following array corresponds to a contiguous
159652:   ** range of unicode codepoints that are not either letters or numbers (i.e.
159653:   ** codepoints for which this function should return 0).
159654:   **
159655:   ** The most significant 22 bits in each 32-bit value contain the first 
159656:   ** codepoint in the range. The least significant 10 bits are used to store
159657:   ** the size of the range (always at least 1). In other words, the value 
159658:   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
159659:   ** C. It is not possible to represent a range larger than 1023 codepoints 
159660:   ** using this format.
159661:   */
159662:   static const unsigned int aEntry[] = {
159663:     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
159664:     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
159665:     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
159666:     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
159667:     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
159668:     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
159669:     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
159670:     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
159671:     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
159672:     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
159673:     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
159674:     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
159675:     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
159676:     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
159677:     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
159678:     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
159679:     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
159680:     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
159681:     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
159682:     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
159683:     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
159684:     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
159685:     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
159686:     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
159687:     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
159688:     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
159689:     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
159690:     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
159691:     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
159692:     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
159693:     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
159694:     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
159695:     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
159696:     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
159697:     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
159698:     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
159699:     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
159700:     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
159701:     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
159702:     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
159703:     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
159704:     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
159705:     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
159706:     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
159707:     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
159708:     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
159709:     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
159710:     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
159711:     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
159712:     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
159713:     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
159714:     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
159715:     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
159716:     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
159717:     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
159718:     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
159719:     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
159720:     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
159721:     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
159722:     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
159723:     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
159724:     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
159725:     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
159726:     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
159727:     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
159728:     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
159729:     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
159730:     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
159731:     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
159732:     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
159733:     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
159734:     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
159735:     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
159736:     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
159737:     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
159738:     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
159739:     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
159740:     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
159741:     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
159742:     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
159743:     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
159744:     0x380400F0,
159745:   };
159746:   static const unsigned int aAscii[4] = {
159747:     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
159748:   };
159749: 
159750:   if( c<128 ){
159751:     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
159752:   }else if( c<(1<<22) ){
159753:     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
159754:     int iRes = 0;
159755:     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
159756:     int iLo = 0;
159757:     while( iHi>=iLo ){
159758:       int iTest = (iHi + iLo) / 2;
159759:       if( key >= aEntry[iTest] ){
159760:         iRes = iTest;
159761:         iLo = iTest+1;
159762:       }else{
159763:         iHi = iTest-1;
159764:       }
159765:     }
159766:     assert( aEntry[0]<key );
159767:     assert( key>=aEntry[iRes] );
159768:     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
159769:   }
159770:   return 1;
159771: }
159772: 
159773: 
159774: /*
159775: ** If the argument is a codepoint corresponding to a lowercase letter
159776: ** in the ASCII range with a diacritic added, return the codepoint
159777: ** of the ASCII letter only. For example, if passed 235 - "LATIN
159778: ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
159779: ** E"). The resuls of passing a codepoint that corresponds to an
159780: ** uppercase letter are undefined.
159781: */
159782: static int remove_diacritic(int c){
159783:   unsigned short aDia[] = {
159784:         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
159785:      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
159786:      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
159787:      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
159788:      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
159789:      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
159790:      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
159791:      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
159792:     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
159793:     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
159794:     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
159795:     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
159796:     62924, 63050, 63082, 63274, 63390, 
159797:   };
159798:   char aChar[] = {
159799:     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
159800:     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
159801:     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
159802:     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
159803:     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
159804:     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
159805:     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
159806:     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
159807:     'e',  'i',  'o',  'u',  'y',  
159808:   };
159809: 
159810:   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
159811:   int iRes = 0;
159812:   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
159813:   int iLo = 0;
159814:   while( iHi>=iLo ){
159815:     int iTest = (iHi + iLo) / 2;
159816:     if( key >= aDia[iTest] ){
159817:       iRes = iTest;
159818:       iLo = iTest+1;
159819:     }else{
159820:       iHi = iTest-1;
159821:     }
159822:   }
159823:   assert( key>=aDia[iRes] );
159824:   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
159825: }
159826: 
159827: 
159828: /*
159829: ** Return true if the argument interpreted as a unicode codepoint
159830: ** is a diacritical modifier character.
159831: */
159832: SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
159833:   unsigned int mask0 = 0x08029FDF;
159834:   unsigned int mask1 = 0x000361F8;
159835:   if( c<768 || c>817 ) return 0;
159836:   return (c < 768+32) ?
159837:       (mask0 & (1 << (c-768))) :
159838:       (mask1 & (1 << (c-768-32)));
159839: }
159840: 
159841: 
159842: /*
159843: ** Interpret the argument as a unicode codepoint. If the codepoint
159844: ** is an upper case character that has a lower case equivalent,
159845: ** return the codepoint corresponding to the lower case version.
159846: ** Otherwise, return a copy of the argument.
159847: **
159848: ** The results are undefined if the value passed to this function
159849: ** is less than zero.
159850: */
159851: SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
159852:   /* Each entry in the following array defines a rule for folding a range
159853:   ** of codepoints to lower case. The rule applies to a range of nRange
159854:   ** codepoints starting at codepoint iCode.
159855:   **
159856:   ** If the least significant bit in flags is clear, then the rule applies
159857:   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
159858:   ** need to be folded). Or, if it is set, then the rule only applies to
159859:   ** every second codepoint in the range, starting with codepoint C.
159860:   **
159861:   ** The 7 most significant bits in flags are an index into the aiOff[]
159862:   ** array. If a specific codepoint C does require folding, then its lower
159863:   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
159864:   **
159865:   ** The contents of this array are generated by parsing the CaseFolding.txt
159866:   ** file distributed as part of the "Unicode Character Database". See
159867:   ** http://www.unicode.org for details.
159868:   */
159869:   static const struct TableEntry {
159870:     unsigned short iCode;
159871:     unsigned char flags;
159872:     unsigned char nRange;
159873:   } aEntry[] = {
159874:     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
159875:     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
159876:     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
159877:     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
159878:     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
159879:     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
159880:     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
159881:     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
159882:     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
159883:     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
159884:     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
159885:     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
159886:     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
159887:     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
159888:     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
159889:     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
159890:     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
159891:     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
159892:     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
159893:     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
159894:     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
159895:     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
159896:     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
159897:     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
159898:     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
159899:     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
159900:     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
159901:     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
159902:     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
159903:     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
159904:     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
159905:     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
159906:     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
159907:     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
159908:     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
159909:     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
159910:     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
159911:     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
159912:     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
159913:     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
159914:     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
159915:     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
159916:     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
159917:     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
159918:     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
159919:     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
159920:     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
159921:     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
159922:     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
159923:     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
159924:     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
159925:     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
159926:     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
159927:     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
159928:     {65313, 14, 26},       
159929:   };
159930:   static const unsigned short aiOff[] = {
159931:    1,     2,     8,     15,    16,    26,    28,    32,    
159932:    37,    38,    40,    48,    63,    64,    69,    71,    
159933:    79,    80,    116,   202,   203,   205,   206,   207,   
159934:    209,   210,   211,   213,   214,   217,   218,   219,   
159935:    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
159936:    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
159937:    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
159938:    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
159939:    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
159940:    65514, 65521, 65527, 65528, 65529, 
159941:   };
159942: 
159943:   int ret = c;
159944: 
159945:   assert( c>=0 );
159946:   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
159947: 
159948:   if( c<128 ){
159949:     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
159950:   }else if( c<65536 ){
159951:     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
159952:     int iLo = 0;
159953:     int iRes = -1;
159954: 
159955:     while( iHi>=iLo ){
159956:       int iTest = (iHi + iLo) / 2;
159957:       int cmp = (c - aEntry[iTest].iCode);
159958:       if( cmp>=0 ){
159959:         iRes = iTest;
159960:         iLo = iTest+1;
159961:       }else{
159962:         iHi = iTest-1;
159963:       }
159964:     }
159965:     assert( iRes<0 || c>=aEntry[iRes].iCode );
159966: 
159967:     if( iRes>=0 ){
159968:       const struct TableEntry *p = &aEntry[iRes];
159969:       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
159970:         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
159971:         assert( ret>0 );
159972:       }
159973:     }
159974: 
159975:     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
159976:   }
159977:   
159978:   else if( c>=66560 && c<66600 ){
159979:     ret = c + 40;
159980:   }
159981: 
159982:   return ret;
159983: }
159984: #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
159985: #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
159986: 
159987: /************** End of fts3_unicode2.c ***************************************/
159988: /************** Begin file rtree.c *******************************************/
159989: /*
159990: ** 2001 September 15
159991: **
159992: ** The author disclaims copyright to this source code.  In place of
159993: ** a legal notice, here is a blessing:
159994: **
159995: **    May you do good and not evil.
159996: **    May you find forgiveness for yourself and forgive others.
159997: **    May you share freely, never taking more than you give.
159998: **
159999: *************************************************************************
160000: ** This file contains code for implementations of the r-tree and r*-tree
160001: ** algorithms packaged as an SQLite virtual table module.
160002: */
160003: 
160004: /*
160005: ** Database Format of R-Tree Tables
160006: ** --------------------------------
160007: **
160008: ** The data structure for a single virtual r-tree table is stored in three 
160009: ** native SQLite tables declared as follows. In each case, the '%' character
160010: ** in the table name is replaced with the user-supplied name of the r-tree
160011: ** table.
160012: **
160013: **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
160014: **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
160015: **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
160016: **
160017: ** The data for each node of the r-tree structure is stored in the %_node
160018: ** table. For each node that is not the root node of the r-tree, there is
160019: ** an entry in the %_parent table associating the node with its parent.
160020: ** And for each row of data in the table, there is an entry in the %_rowid
160021: ** table that maps from the entries rowid to the id of the node that it
160022: ** is stored on.
160023: **
160024: ** The root node of an r-tree always exists, even if the r-tree table is
160025: ** empty. The nodeno of the root node is always 1. All other nodes in the
160026: ** table must be the same size as the root node. The content of each node
160027: ** is formatted as follows:
160028: **
160029: **   1. If the node is the root node (node 1), then the first 2 bytes
160030: **      of the node contain the tree depth as a big-endian integer.
160031: **      For non-root nodes, the first 2 bytes are left unused.
160032: **
160033: **   2. The next 2 bytes contain the number of entries currently 
160034: **      stored in the node.
160035: **
160036: **   3. The remainder of the node contains the node entries. Each entry
160037: **      consists of a single 8-byte integer followed by an even number
160038: **      of 4-byte coordinates. For leaf nodes the integer is the rowid
160039: **      of a record. For internal nodes it is the node number of a
160040: **      child page.
160041: */
160042: 
160043: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
160044: 
160045: #ifndef SQLITE_CORE
160046: /*   #include "sqlite3ext.h" */
160047:   SQLITE_EXTENSION_INIT1
160048: #else
160049: /*   #include "sqlite3.h" */
160050: #endif
160051: 
160052: /* #include <string.h> */
160053: /* #include <assert.h> */
160054: /* #include <stdio.h> */
160055: 
160056: #ifndef SQLITE_AMALGAMATION
160057: #include "sqlite3rtree.h"
160058: typedef sqlite3_int64 i64;
160059: typedef unsigned char u8;
160060: typedef unsigned short u16;
160061: typedef unsigned int u32;
160062: #endif
160063: 
160064: /*  The following macro is used to suppress compiler warnings.
160065: */
160066: #ifndef UNUSED_PARAMETER
160067: # define UNUSED_PARAMETER(x) (void)(x)
160068: #endif
160069: 
160070: typedef struct Rtree Rtree;
160071: typedef struct RtreeCursor RtreeCursor;
160072: typedef struct RtreeNode RtreeNode;
160073: typedef struct RtreeCell RtreeCell;
160074: typedef struct RtreeConstraint RtreeConstraint;
160075: typedef struct RtreeMatchArg RtreeMatchArg;
160076: typedef struct RtreeGeomCallback RtreeGeomCallback;
160077: typedef union RtreeCoord RtreeCoord;
160078: typedef struct RtreeSearchPoint RtreeSearchPoint;
160079: 
160080: /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
160081: #define RTREE_MAX_DIMENSIONS 5
160082: 
160083: /* Size of hash table Rtree.aHash. This hash table is not expected to
160084: ** ever contain very many entries, so a fixed number of buckets is 
160085: ** used.
160086: */
160087: #define HASHSIZE 97
160088: 
160089: /* The xBestIndex method of this virtual table requires an estimate of
160090: ** the number of rows in the virtual table to calculate the costs of
160091: ** various strategies. If possible, this estimate is loaded from the
160092: ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
160093: ** Otherwise, if no sqlite_stat1 entry is available, use 
160094: ** RTREE_DEFAULT_ROWEST.
160095: */
160096: #define RTREE_DEFAULT_ROWEST 1048576
160097: #define RTREE_MIN_ROWEST         100
160098: 
160099: /* 
160100: ** An rtree virtual-table object.
160101: */
160102: struct Rtree {
160103:   sqlite3_vtab base;          /* Base class.  Must be first */
160104:   sqlite3 *db;                /* Host database connection */
160105:   int iNodeSize;              /* Size in bytes of each node in the node table */
160106:   u8 nDim;                    /* Number of dimensions */
160107:   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
160108:   u8 nBytesPerCell;           /* Bytes consumed per cell */
160109:   int iDepth;                 /* Current depth of the r-tree structure */
160110:   char *zDb;                  /* Name of database containing r-tree table */
160111:   char *zName;                /* Name of r-tree table */ 
160112:   int nBusy;                  /* Current number of users of this structure */
160113:   i64 nRowEst;                /* Estimated number of rows in this table */
160114: 
160115:   /* List of nodes removed during a CondenseTree operation. List is
160116:   ** linked together via the pointer normally used for hash chains -
160117:   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
160118:   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
160119:   */
160120:   RtreeNode *pDeleted;
160121:   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
160122: 
160123:   /* Statements to read/write/delete a record from xxx_node */
160124:   sqlite3_stmt *pReadNode;
160125:   sqlite3_stmt *pWriteNode;
160126:   sqlite3_stmt *pDeleteNode;
160127: 
160128:   /* Statements to read/write/delete a record from xxx_rowid */
160129:   sqlite3_stmt *pReadRowid;
160130:   sqlite3_stmt *pWriteRowid;
160131:   sqlite3_stmt *pDeleteRowid;
160132: 
160133:   /* Statements to read/write/delete a record from xxx_parent */
160134:   sqlite3_stmt *pReadParent;
160135:   sqlite3_stmt *pWriteParent;
160136:   sqlite3_stmt *pDeleteParent;
160137: 
160138:   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
160139: };
160140: 
160141: /* Possible values for Rtree.eCoordType: */
160142: #define RTREE_COORD_REAL32 0
160143: #define RTREE_COORD_INT32  1
160144: 
160145: /*
160146: ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
160147: ** only deal with integer coordinates.  No floating point operations
160148: ** will be done.
160149: */
160150: #ifdef SQLITE_RTREE_INT_ONLY
160151:   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
160152:   typedef int RtreeValue;                  /* Low accuracy coordinate */
160153: # define RTREE_ZERO 0
160154: #else
160155:   typedef double RtreeDValue;              /* High accuracy coordinate */
160156:   typedef float RtreeValue;                /* Low accuracy coordinate */
160157: # define RTREE_ZERO 0.0
160158: #endif
160159: 
160160: /*
160161: ** When doing a search of an r-tree, instances of the following structure
160162: ** record intermediate results from the tree walk.
160163: **
160164: ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
160165: ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
160166: ** the id is of the parent node and the cell that RtreeSearchPoint
160167: ** represents is the iCell-th entry in the parent node.
160168: */
160169: struct RtreeSearchPoint {
160170:   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
160171:   sqlite3_int64 id;      /* Node ID */
160172:   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
160173:   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
160174:   u8 iCell;              /* Cell index within the node */
160175: };
160176: 
160177: /*
160178: ** The minimum number of cells allowed for a node is a third of the 
160179: ** maximum. In Gutman's notation:
160180: **
160181: **     m = M/3
160182: **
160183: ** If an R*-tree "Reinsert" operation is required, the same number of
160184: ** cells are removed from the overfull node and reinserted into the tree.
160185: */
160186: #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
160187: #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
160188: #define RTREE_MAXCELLS 51
160189: 
160190: /*
160191: ** The smallest possible node-size is (512-64)==448 bytes. And the largest
160192: ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
160193: ** Therefore all non-root nodes must contain at least 3 entries. Since 
160194: ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
160195: ** 40 or less.
160196: */
160197: #define RTREE_MAX_DEPTH 40
160198: 
160199: 
160200: /*
160201: ** Number of entries in the cursor RtreeNode cache.  The first entry is
160202: ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
160203: ** entries cache the RtreeNode for the first elements of the priority queue.
160204: */
160205: #define RTREE_CACHE_SZ  5
160206: 
160207: /* 
160208: ** An rtree cursor object.
160209: */
160210: struct RtreeCursor {
160211:   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
160212:   u8 atEOF;                         /* True if at end of search */
160213:   u8 bPoint;                        /* True if sPoint is valid */
160214:   int iStrategy;                    /* Copy of idxNum search parameter */
160215:   int nConstraint;                  /* Number of entries in aConstraint */
160216:   RtreeConstraint *aConstraint;     /* Search constraints. */
160217:   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
160218:   int nPoint;                       /* Number of slots used in aPoint[] */
160219:   int mxLevel;                      /* iLevel value for root of the tree */
160220:   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
160221:   RtreeSearchPoint sPoint;          /* Cached next search point */
160222:   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
160223:   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
160224: };
160225: 
160226: /* Return the Rtree of a RtreeCursor */
160227: #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
160228: 
160229: /*
160230: ** A coordinate can be either a floating point number or a integer.  All
160231: ** coordinates within a single R-Tree are always of the same time.
160232: */
160233: union RtreeCoord {
160234:   RtreeValue f;      /* Floating point value */
160235:   int i;             /* Integer value */
160236:   u32 u;             /* Unsigned for byte-order conversions */
160237: };
160238: 
160239: /*
160240: ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
160241: ** formatted as a RtreeDValue (double or int64). This macro assumes that local
160242: ** variable pRtree points to the Rtree structure associated with the
160243: ** RtreeCoord.
160244: */
160245: #ifdef SQLITE_RTREE_INT_ONLY
160246: # define DCOORD(coord) ((RtreeDValue)coord.i)
160247: #else
160248: # define DCOORD(coord) (                           \
160249:     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
160250:       ((double)coord.f) :                           \
160251:       ((double)coord.i)                             \
160252:   )
160253: #endif
160254: 
160255: /*
160256: ** A search constraint.
160257: */
160258: struct RtreeConstraint {
160259:   int iCoord;                     /* Index of constrained coordinate */
160260:   int op;                         /* Constraining operation */
160261:   union {
160262:     RtreeDValue rValue;             /* Constraint value. */
160263:     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
160264:     int (*xQueryFunc)(sqlite3_rtree_query_info*);
160265:   } u;
160266:   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
160267: };
160268: 
160269: /* Possible values for RtreeConstraint.op */
160270: #define RTREE_EQ    0x41  /* A */
160271: #define RTREE_LE    0x42  /* B */
160272: #define RTREE_LT    0x43  /* C */
160273: #define RTREE_GE    0x44  /* D */
160274: #define RTREE_GT    0x45  /* E */
160275: #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
160276: #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
160277: 
160278: 
160279: /* 
160280: ** An rtree structure node.
160281: */
160282: struct RtreeNode {
160283:   RtreeNode *pParent;         /* Parent node */
160284:   i64 iNode;                  /* The node number */
160285:   int nRef;                   /* Number of references to this node */
160286:   int isDirty;                /* True if the node needs to be written to disk */
160287:   u8 *zData;                  /* Content of the node, as should be on disk */
160288:   RtreeNode *pNext;           /* Next node in this hash collision chain */
160289: };
160290: 
160291: /* Return the number of cells in a node  */
160292: #define NCELL(pNode) readInt16(&(pNode)->zData[2])
160293: 
160294: /* 
160295: ** A single cell from a node, deserialized
160296: */
160297: struct RtreeCell {
160298:   i64 iRowid;                                 /* Node or entry ID */
160299:   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
160300: };
160301: 
160302: 
160303: /*
160304: ** This object becomes the sqlite3_user_data() for the SQL functions
160305: ** that are created by sqlite3_rtree_geometry_callback() and
160306: ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
160307: ** operators in order to constrain a search.
160308: **
160309: ** xGeom and xQueryFunc are the callback functions.  Exactly one of 
160310: ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
160311: ** SQL function was created using sqlite3_rtree_geometry_callback() or
160312: ** sqlite3_rtree_query_callback().
160313: ** 
160314: ** This object is deleted automatically by the destructor mechanism in
160315: ** sqlite3_create_function_v2().
160316: */
160317: struct RtreeGeomCallback {
160318:   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
160319:   int (*xQueryFunc)(sqlite3_rtree_query_info*);
160320:   void (*xDestructor)(void*);
160321:   void *pContext;
160322: };
160323: 
160324: 
160325: /*
160326: ** Value for the first field of every RtreeMatchArg object. The MATCH
160327: ** operator tests that the first field of a blob operand matches this
160328: ** value to avoid operating on invalid blobs (which could cause a segfault).
160329: */
160330: #define RTREE_GEOMETRY_MAGIC 0x891245AB
160331: 
160332: /*
160333: ** An instance of this structure (in the form of a BLOB) is returned by
160334: ** the SQL functions that sqlite3_rtree_geometry_callback() and
160335: ** sqlite3_rtree_query_callback() create, and is read as the right-hand
160336: ** operand to the MATCH operator of an R-Tree.
160337: */
160338: struct RtreeMatchArg {
160339:   u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
160340:   RtreeGeomCallback cb;       /* Info about the callback functions */
160341:   int nParam;                 /* Number of parameters to the SQL function */
160342:   sqlite3_value **apSqlParam; /* Original SQL parameter values */
160343:   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
160344: };
160345: 
160346: #ifndef MAX
160347: # define MAX(x,y) ((x) < (y) ? (y) : (x))
160348: #endif
160349: #ifndef MIN
160350: # define MIN(x,y) ((x) > (y) ? (y) : (x))
160351: #endif
160352: 
160353: /*
160354: ** Functions to deserialize a 16 bit integer, 32 bit real number and
160355: ** 64 bit integer. The deserialized value is returned.
160356: */
160357: static int readInt16(u8 *p){
160358:   return (p[0]<<8) + p[1];
160359: }
160360: static void readCoord(u8 *p, RtreeCoord *pCoord){
160361:   pCoord->u = (
160362:     (((u32)p[0]) << 24) + 
160363:     (((u32)p[1]) << 16) + 
160364:     (((u32)p[2]) <<  8) + 
160365:     (((u32)p[3]) <<  0)
160366:   );
160367: }
160368: static i64 readInt64(u8 *p){
160369:   return (
160370:     (((i64)p[0]) << 56) + 
160371:     (((i64)p[1]) << 48) + 
160372:     (((i64)p[2]) << 40) + 
160373:     (((i64)p[3]) << 32) + 
160374:     (((i64)p[4]) << 24) + 
160375:     (((i64)p[5]) << 16) + 
160376:     (((i64)p[6]) <<  8) + 
160377:     (((i64)p[7]) <<  0)
160378:   );
160379: }
160380: 
160381: /*
160382: ** Functions to serialize a 16 bit integer, 32 bit real number and
160383: ** 64 bit integer. The value returned is the number of bytes written
160384: ** to the argument buffer (always 2, 4 and 8 respectively).
160385: */
160386: static int writeInt16(u8 *p, int i){
160387:   p[0] = (i>> 8)&0xFF;
160388:   p[1] = (i>> 0)&0xFF;
160389:   return 2;
160390: }
160391: static int writeCoord(u8 *p, RtreeCoord *pCoord){
160392:   u32 i;
160393:   assert( sizeof(RtreeCoord)==4 );
160394:   assert( sizeof(u32)==4 );
160395:   i = pCoord->u;
160396:   p[0] = (i>>24)&0xFF;
160397:   p[1] = (i>>16)&0xFF;
160398:   p[2] = (i>> 8)&0xFF;
160399:   p[3] = (i>> 0)&0xFF;
160400:   return 4;
160401: }
160402: static int writeInt64(u8 *p, i64 i){
160403:   p[0] = (i>>56)&0xFF;
160404:   p[1] = (i>>48)&0xFF;
160405:   p[2] = (i>>40)&0xFF;
160406:   p[3] = (i>>32)&0xFF;
160407:   p[4] = (i>>24)&0xFF;
160408:   p[5] = (i>>16)&0xFF;
160409:   p[6] = (i>> 8)&0xFF;
160410:   p[7] = (i>> 0)&0xFF;
160411:   return 8;
160412: }
160413: 
160414: /*
160415: ** Increment the reference count of node p.
160416: */
160417: static void nodeReference(RtreeNode *p){
160418:   if( p ){
160419:     p->nRef++;
160420:   }
160421: }
160422: 
160423: /*
160424: ** Clear the content of node p (set all bytes to 0x00).
160425: */
160426: static void nodeZero(Rtree *pRtree, RtreeNode *p){
160427:   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
160428:   p->isDirty = 1;
160429: }
160430: 
160431: /*
160432: ** Given a node number iNode, return the corresponding key to use
160433: ** in the Rtree.aHash table.
160434: */
160435: static int nodeHash(i64 iNode){
160436:   return iNode % HASHSIZE;
160437: }
160438: 
160439: /*
160440: ** Search the node hash table for node iNode. If found, return a pointer
160441: ** to it. Otherwise, return 0.
160442: */
160443: static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
160444:   RtreeNode *p;
160445:   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
160446:   return p;
160447: }
160448: 
160449: /*
160450: ** Add node pNode to the node hash table.
160451: */
160452: static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
160453:   int iHash;
160454:   assert( pNode->pNext==0 );
160455:   iHash = nodeHash(pNode->iNode);
160456:   pNode->pNext = pRtree->aHash[iHash];
160457:   pRtree->aHash[iHash] = pNode;
160458: }
160459: 
160460: /*
160461: ** Remove node pNode from the node hash table.
160462: */
160463: static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
160464:   RtreeNode **pp;
160465:   if( pNode->iNode!=0 ){
160466:     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
160467:     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
160468:     *pp = pNode->pNext;
160469:     pNode->pNext = 0;
160470:   }
160471: }
160472: 
160473: /*
160474: ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
160475: ** indicating that node has not yet been assigned a node number. It is
160476: ** assigned a node number when nodeWrite() is called to write the
160477: ** node contents out to the database.
160478: */
160479: static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
160480:   RtreeNode *pNode;
160481:   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
160482:   if( pNode ){
160483:     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
160484:     pNode->zData = (u8 *)&pNode[1];
160485:     pNode->nRef = 1;
160486:     pNode->pParent = pParent;
160487:     pNode->isDirty = 1;
160488:     nodeReference(pParent);
160489:   }
160490:   return pNode;
160491: }
160492: 
160493: /*
160494: ** Obtain a reference to an r-tree node.
160495: */
160496: static int nodeAcquire(
160497:   Rtree *pRtree,             /* R-tree structure */
160498:   i64 iNode,                 /* Node number to load */
160499:   RtreeNode *pParent,        /* Either the parent node or NULL */
160500:   RtreeNode **ppNode         /* OUT: Acquired node */
160501: ){
160502:   int rc;
160503:   int rc2 = SQLITE_OK;
160504:   RtreeNode *pNode;
160505: 
160506:   /* Check if the requested node is already in the hash table. If so,
160507:   ** increase its reference count and return it.
160508:   */
160509:   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
160510:     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
160511:     if( pParent && !pNode->pParent ){
160512:       nodeReference(pParent);
160513:       pNode->pParent = pParent;
160514:     }
160515:     pNode->nRef++;
160516:     *ppNode = pNode;
160517:     return SQLITE_OK;
160518:   }
160519: 
160520:   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
160521:   rc = sqlite3_step(pRtree->pReadNode);
160522:   if( rc==SQLITE_ROW ){
160523:     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
160524:     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
160525:       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
160526:       if( !pNode ){
160527:         rc2 = SQLITE_NOMEM;
160528:       }else{
160529:         pNode->pParent = pParent;
160530:         pNode->zData = (u8 *)&pNode[1];
160531:         pNode->nRef = 1;
160532:         pNode->iNode = iNode;
160533:         pNode->isDirty = 0;
160534:         pNode->pNext = 0;
160535:         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
160536:         nodeReference(pParent);
160537:       }
160538:     }
160539:   }
160540:   rc = sqlite3_reset(pRtree->pReadNode);
160541:   if( rc==SQLITE_OK ) rc = rc2;
160542: 
160543:   /* If the root node was just loaded, set pRtree->iDepth to the height
160544:   ** of the r-tree structure. A height of zero means all data is stored on
160545:   ** the root node. A height of one means the children of the root node
160546:   ** are the leaves, and so on. If the depth as specified on the root node
160547:   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
160548:   */
160549:   if( pNode && iNode==1 ){
160550:     pRtree->iDepth = readInt16(pNode->zData);
160551:     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
160552:       rc = SQLITE_CORRUPT_VTAB;
160553:     }
160554:   }
160555: 
160556:   /* If no error has occurred so far, check if the "number of entries"
160557:   ** field on the node is too large. If so, set the return code to 
160558:   ** SQLITE_CORRUPT_VTAB.
160559:   */
160560:   if( pNode && rc==SQLITE_OK ){
160561:     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
160562:       rc = SQLITE_CORRUPT_VTAB;
160563:     }
160564:   }
160565: 
160566:   if( rc==SQLITE_OK ){
160567:     if( pNode!=0 ){
160568:       nodeHashInsert(pRtree, pNode);
160569:     }else{
160570:       rc = SQLITE_CORRUPT_VTAB;
160571:     }
160572:     *ppNode = pNode;
160573:   }else{
160574:     sqlite3_free(pNode);
160575:     *ppNode = 0;
160576:   }
160577: 
160578:   return rc;
160579: }
160580: 
160581: /*
160582: ** Overwrite cell iCell of node pNode with the contents of pCell.
160583: */
160584: static void nodeOverwriteCell(
160585:   Rtree *pRtree,             /* The overall R-Tree */
160586:   RtreeNode *pNode,          /* The node into which the cell is to be written */
160587:   RtreeCell *pCell,          /* The cell to write */
160588:   int iCell                  /* Index into pNode into which pCell is written */
160589: ){
160590:   int ii;
160591:   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
160592:   p += writeInt64(p, pCell->iRowid);
160593:   for(ii=0; ii<(pRtree->nDim*2); ii++){
160594:     p += writeCoord(p, &pCell->aCoord[ii]);
160595:   }
160596:   pNode->isDirty = 1;
160597: }
160598: 
160599: /*
160600: ** Remove the cell with index iCell from node pNode.
160601: */
160602: static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
160603:   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
160604:   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
160605:   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
160606:   memmove(pDst, pSrc, nByte);
160607:   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
160608:   pNode->isDirty = 1;
160609: }
160610: 
160611: /*
160612: ** Insert the contents of cell pCell into node pNode. If the insert
160613: ** is successful, return SQLITE_OK.
160614: **
160615: ** If there is not enough free space in pNode, return SQLITE_FULL.
160616: */
160617: static int nodeInsertCell(
160618:   Rtree *pRtree,                /* The overall R-Tree */
160619:   RtreeNode *pNode,             /* Write new cell into this node */
160620:   RtreeCell *pCell              /* The cell to be inserted */
160621: ){
160622:   int nCell;                    /* Current number of cells in pNode */
160623:   int nMaxCell;                 /* Maximum number of cells for pNode */
160624: 
160625:   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
160626:   nCell = NCELL(pNode);
160627: 
160628:   assert( nCell<=nMaxCell );
160629:   if( nCell<nMaxCell ){
160630:     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
160631:     writeInt16(&pNode->zData[2], nCell+1);
160632:     pNode->isDirty = 1;
160633:   }
160634: 
160635:   return (nCell==nMaxCell);
160636: }
160637: 
160638: /*
160639: ** If the node is dirty, write it out to the database.
160640: */
160641: static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
160642:   int rc = SQLITE_OK;
160643:   if( pNode->isDirty ){
160644:     sqlite3_stmt *p = pRtree->pWriteNode;
160645:     if( pNode->iNode ){
160646:       sqlite3_bind_int64(p, 1, pNode->iNode);
160647:     }else{
160648:       sqlite3_bind_null(p, 1);
160649:     }
160650:     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
160651:     sqlite3_step(p);
160652:     pNode->isDirty = 0;
160653:     rc = sqlite3_reset(p);
160654:     if( pNode->iNode==0 && rc==SQLITE_OK ){
160655:       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
160656:       nodeHashInsert(pRtree, pNode);
160657:     }
160658:   }
160659:   return rc;
160660: }
160661: 
160662: /*
160663: ** Release a reference to a node. If the node is dirty and the reference
160664: ** count drops to zero, the node data is written to the database.
160665: */
160666: static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
160667:   int rc = SQLITE_OK;
160668:   if( pNode ){
160669:     assert( pNode->nRef>0 );
160670:     pNode->nRef--;
160671:     if( pNode->nRef==0 ){
160672:       if( pNode->iNode==1 ){
160673:         pRtree->iDepth = -1;
160674:       }
160675:       if( pNode->pParent ){
160676:         rc = nodeRelease(pRtree, pNode->pParent);
160677:       }
160678:       if( rc==SQLITE_OK ){
160679:         rc = nodeWrite(pRtree, pNode);
160680:       }
160681:       nodeHashDelete(pRtree, pNode);
160682:       sqlite3_free(pNode);
160683:     }
160684:   }
160685:   return rc;
160686: }
160687: 
160688: /*
160689: ** Return the 64-bit integer value associated with cell iCell of
160690: ** node pNode. If pNode is a leaf node, this is a rowid. If it is
160691: ** an internal node, then the 64-bit integer is a child page number.
160692: */
160693: static i64 nodeGetRowid(
160694:   Rtree *pRtree,       /* The overall R-Tree */
160695:   RtreeNode *pNode,    /* The node from which to extract the ID */
160696:   int iCell            /* The cell index from which to extract the ID */
160697: ){
160698:   assert( iCell<NCELL(pNode) );
160699:   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
160700: }
160701: 
160702: /*
160703: ** Return coordinate iCoord from cell iCell in node pNode.
160704: */
160705: static void nodeGetCoord(
160706:   Rtree *pRtree,               /* The overall R-Tree */
160707:   RtreeNode *pNode,            /* The node from which to extract a coordinate */
160708:   int iCell,                   /* The index of the cell within the node */
160709:   int iCoord,                  /* Which coordinate to extract */
160710:   RtreeCoord *pCoord           /* OUT: Space to write result to */
160711: ){
160712:   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
160713: }
160714: 
160715: /*
160716: ** Deserialize cell iCell of node pNode. Populate the structure pointed
160717: ** to by pCell with the results.
160718: */
160719: static void nodeGetCell(
160720:   Rtree *pRtree,               /* The overall R-Tree */
160721:   RtreeNode *pNode,            /* The node containing the cell to be read */
160722:   int iCell,                   /* Index of the cell within the node */
160723:   RtreeCell *pCell             /* OUT: Write the cell contents here */
160724: ){
160725:   u8 *pData;
160726:   RtreeCoord *pCoord;
160727:   int ii;
160728:   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
160729:   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
160730:   pCoord = pCell->aCoord;
160731:   for(ii=0; ii<pRtree->nDim*2; ii++){
160732:     readCoord(&pData[ii*4], &pCoord[ii]);
160733:   }
160734: }
160735: 
160736: 
160737: /* Forward declaration for the function that does the work of
160738: ** the virtual table module xCreate() and xConnect() methods.
160739: */
160740: static int rtreeInit(
160741:   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
160742: );
160743: 
160744: /* 
160745: ** Rtree virtual table module xCreate method.
160746: */
160747: static int rtreeCreate(
160748:   sqlite3 *db,
160749:   void *pAux,
160750:   int argc, const char *const*argv,
160751:   sqlite3_vtab **ppVtab,
160752:   char **pzErr
160753: ){
160754:   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
160755: }
160756: 
160757: /* 
160758: ** Rtree virtual table module xConnect method.
160759: */
160760: static int rtreeConnect(
160761:   sqlite3 *db,
160762:   void *pAux,
160763:   int argc, const char *const*argv,
160764:   sqlite3_vtab **ppVtab,
160765:   char **pzErr
160766: ){
160767:   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
160768: }
160769: 
160770: /*
160771: ** Increment the r-tree reference count.
160772: */
160773: static void rtreeReference(Rtree *pRtree){
160774:   pRtree->nBusy++;
160775: }
160776: 
160777: /*
160778: ** Decrement the r-tree reference count. When the reference count reaches
160779: ** zero the structure is deleted.
160780: */
160781: static void rtreeRelease(Rtree *pRtree){
160782:   pRtree->nBusy--;
160783:   if( pRtree->nBusy==0 ){
160784:     sqlite3_finalize(pRtree->pReadNode);
160785:     sqlite3_finalize(pRtree->pWriteNode);
160786:     sqlite3_finalize(pRtree->pDeleteNode);
160787:     sqlite3_finalize(pRtree->pReadRowid);
160788:     sqlite3_finalize(pRtree->pWriteRowid);
160789:     sqlite3_finalize(pRtree->pDeleteRowid);
160790:     sqlite3_finalize(pRtree->pReadParent);
160791:     sqlite3_finalize(pRtree->pWriteParent);
160792:     sqlite3_finalize(pRtree->pDeleteParent);
160793:     sqlite3_free(pRtree);
160794:   }
160795: }
160796: 
160797: /* 
160798: ** Rtree virtual table module xDisconnect method.
160799: */
160800: static int rtreeDisconnect(sqlite3_vtab *pVtab){
160801:   rtreeRelease((Rtree *)pVtab);
160802:   return SQLITE_OK;
160803: }
160804: 
160805: /* 
160806: ** Rtree virtual table module xDestroy method.
160807: */
160808: static int rtreeDestroy(sqlite3_vtab *pVtab){
160809:   Rtree *pRtree = (Rtree *)pVtab;
160810:   int rc;
160811:   char *zCreate = sqlite3_mprintf(
160812:     "DROP TABLE '%q'.'%q_node';"
160813:     "DROP TABLE '%q'.'%q_rowid';"
160814:     "DROP TABLE '%q'.'%q_parent';",
160815:     pRtree->zDb, pRtree->zName, 
160816:     pRtree->zDb, pRtree->zName,
160817:     pRtree->zDb, pRtree->zName
160818:   );
160819:   if( !zCreate ){
160820:     rc = SQLITE_NOMEM;
160821:   }else{
160822:     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
160823:     sqlite3_free(zCreate);
160824:   }
160825:   if( rc==SQLITE_OK ){
160826:     rtreeRelease(pRtree);
160827:   }
160828: 
160829:   return rc;
160830: }
160831: 
160832: /* 
160833: ** Rtree virtual table module xOpen method.
160834: */
160835: static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
160836:   int rc = SQLITE_NOMEM;
160837:   RtreeCursor *pCsr;
160838: 
160839:   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
160840:   if( pCsr ){
160841:     memset(pCsr, 0, sizeof(RtreeCursor));
160842:     pCsr->base.pVtab = pVTab;
160843:     rc = SQLITE_OK;
160844:   }
160845:   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
160846: 
160847:   return rc;
160848: }
160849: 
160850: 
160851: /*
160852: ** Free the RtreeCursor.aConstraint[] array and its contents.
160853: */
160854: static void freeCursorConstraints(RtreeCursor *pCsr){
160855:   if( pCsr->aConstraint ){
160856:     int i;                        /* Used to iterate through constraint array */
160857:     for(i=0; i<pCsr->nConstraint; i++){
160858:       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
160859:       if( pInfo ){
160860:         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
160861:         sqlite3_free(pInfo);
160862:       }
160863:     }
160864:     sqlite3_free(pCsr->aConstraint);
160865:     pCsr->aConstraint = 0;
160866:   }
160867: }
160868: 
160869: /* 
160870: ** Rtree virtual table module xClose method.
160871: */
160872: static int rtreeClose(sqlite3_vtab_cursor *cur){
160873:   Rtree *pRtree = (Rtree *)(cur->pVtab);
160874:   int ii;
160875:   RtreeCursor *pCsr = (RtreeCursor *)cur;
160876:   freeCursorConstraints(pCsr);
160877:   sqlite3_free(pCsr->aPoint);
160878:   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
160879:   sqlite3_free(pCsr);
160880:   return SQLITE_OK;
160881: }
160882: 
160883: /*
160884: ** Rtree virtual table module xEof method.
160885: **
160886: ** Return non-zero if the cursor does not currently point to a valid 
160887: ** record (i.e if the scan has finished), or zero otherwise.
160888: */
160889: static int rtreeEof(sqlite3_vtab_cursor *cur){
160890:   RtreeCursor *pCsr = (RtreeCursor *)cur;
160891:   return pCsr->atEOF;
160892: }
160893: 
160894: /*
160895: ** Convert raw bits from the on-disk RTree record into a coordinate value.
160896: ** The on-disk format is big-endian and needs to be converted for little-
160897: ** endian platforms.  The on-disk record stores integer coordinates if
160898: ** eInt is true and it stores 32-bit floating point records if eInt is
160899: ** false.  a[] is the four bytes of the on-disk record to be decoded.
160900: ** Store the results in "r".
160901: **
160902: ** There are three versions of this macro, one each for little-endian and
160903: ** big-endian processors and a third generic implementation.  The endian-
160904: ** specific implementations are much faster and are preferred if the
160905: ** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
160906: ** macro is part of sqliteInt.h and hence the endian-specific
160907: ** implementation will only be used if this module is compiled as part
160908: ** of the amalgamation.
160909: */
160910: #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
160911: #define RTREE_DECODE_COORD(eInt, a, r) {                        \
160912:     RtreeCoord c;    /* Coordinate decoded */                   \
160913:     memcpy(&c.u,a,4);                                           \
160914:     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
160915:           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
160916:     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160917: }
160918: #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
160919: #define RTREE_DECODE_COORD(eInt, a, r) {                        \
160920:     RtreeCoord c;    /* Coordinate decoded */                   \
160921:     memcpy(&c.u,a,4);                                           \
160922:     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160923: }
160924: #else
160925: #define RTREE_DECODE_COORD(eInt, a, r) {                        \
160926:     RtreeCoord c;    /* Coordinate decoded */                   \
160927:     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
160928:            +((u32)a[2]<<8) + a[3];                              \
160929:     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
160930: }
160931: #endif
160932: 
160933: /*
160934: ** Check the RTree node or entry given by pCellData and p against the MATCH
160935: ** constraint pConstraint.  
160936: */
160937: static int rtreeCallbackConstraint(
160938:   RtreeConstraint *pConstraint,  /* The constraint to test */
160939:   int eInt,                      /* True if RTree holding integer coordinates */
160940:   u8 *pCellData,                 /* Raw cell content */
160941:   RtreeSearchPoint *pSearch,     /* Container of this cell */
160942:   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
160943:   int *peWithin                  /* OUT: visibility of the cell */
160944: ){
160945:   int i;                                                /* Loop counter */
160946:   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
160947:   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
160948:   int rc;                                             /* Callback return code */
160949:   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
160950: 
160951:   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
160952:   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
160953: 
160954:   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
160955:     pInfo->iRowid = readInt64(pCellData);
160956:   }
160957:   pCellData += 8;
160958:   for(i=0; i<nCoord; i++, pCellData += 4){
160959:     RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
160960:   }
160961:   if( pConstraint->op==RTREE_MATCH ){
160962:     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
160963:                               nCoord, aCoord, &i);
160964:     if( i==0 ) *peWithin = NOT_WITHIN;
160965:     *prScore = RTREE_ZERO;
160966:   }else{
160967:     pInfo->aCoord = aCoord;
160968:     pInfo->iLevel = pSearch->iLevel - 1;
160969:     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
160970:     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
160971:     rc = pConstraint->u.xQueryFunc(pInfo);
160972:     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
160973:     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
160974:       *prScore = pInfo->rScore;
160975:     }
160976:   }
160977:   return rc;
160978: }
160979: 
160980: /* 
160981: ** Check the internal RTree node given by pCellData against constraint p.
160982: ** If this constraint cannot be satisfied by any child within the node,
160983: ** set *peWithin to NOT_WITHIN.
160984: */
160985: static void rtreeNonleafConstraint(
160986:   RtreeConstraint *p,        /* The constraint to test */
160987:   int eInt,                  /* True if RTree holds integer coordinates */
160988:   u8 *pCellData,             /* Raw cell content as appears on disk */
160989:   int *peWithin              /* Adjust downward, as appropriate */
160990: ){
160991:   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
160992: 
160993:   /* p->iCoord might point to either a lower or upper bound coordinate
160994:   ** in a coordinate pair.  But make pCellData point to the lower bound.
160995:   */
160996:   pCellData += 8 + 4*(p->iCoord&0xfe);
160997: 
160998:   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
160999:       || p->op==RTREE_GT || p->op==RTREE_EQ );
161000:   switch( p->op ){
161001:     case RTREE_LE:
161002:     case RTREE_LT:
161003:     case RTREE_EQ:
161004:       RTREE_DECODE_COORD(eInt, pCellData, val);
161005:       /* val now holds the lower bound of the coordinate pair */
161006:       if( p->u.rValue>=val ) return;
161007:       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
161008:       /* Fall through for the RTREE_EQ case */
161009: 
161010:     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
161011:       pCellData += 4;
161012:       RTREE_DECODE_COORD(eInt, pCellData, val);
161013:       /* val now holds the upper bound of the coordinate pair */
161014:       if( p->u.rValue<=val ) return;
161015:   }
161016:   *peWithin = NOT_WITHIN;
161017: }
161018: 
161019: /*
161020: ** Check the leaf RTree cell given by pCellData against constraint p.
161021: ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
161022: ** If the constraint is satisfied, leave *peWithin unchanged.
161023: **
161024: ** The constraint is of the form:  xN op $val
161025: **
161026: ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
161027: ** pCellData.  $val is given by p->u.rValue.
161028: */
161029: static void rtreeLeafConstraint(
161030:   RtreeConstraint *p,        /* The constraint to test */
161031:   int eInt,                  /* True if RTree holds integer coordinates */
161032:   u8 *pCellData,             /* Raw cell content as appears on disk */
161033:   int *peWithin              /* Adjust downward, as appropriate */
161034: ){
161035:   RtreeDValue xN;      /* Coordinate value converted to a double */
161036: 
161037:   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
161038:       || p->op==RTREE_GT || p->op==RTREE_EQ );
161039:   pCellData += 8 + p->iCoord*4;
161040:   RTREE_DECODE_COORD(eInt, pCellData, xN);
161041:   switch( p->op ){
161042:     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
161043:     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
161044:     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
161045:     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
161046:     default:       if( xN == p->u.rValue ) return;  break;
161047:   }
161048:   *peWithin = NOT_WITHIN;
161049: }
161050: 
161051: /*
161052: ** One of the cells in node pNode is guaranteed to have a 64-bit 
161053: ** integer value equal to iRowid. Return the index of this cell.
161054: */
161055: static int nodeRowidIndex(
161056:   Rtree *pRtree, 
161057:   RtreeNode *pNode, 
161058:   i64 iRowid,
161059:   int *piIndex
161060: ){
161061:   int ii;
161062:   int nCell = NCELL(pNode);
161063:   assert( nCell<200 );
161064:   for(ii=0; ii<nCell; ii++){
161065:     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
161066:       *piIndex = ii;
161067:       return SQLITE_OK;
161068:     }
161069:   }
161070:   return SQLITE_CORRUPT_VTAB;
161071: }
161072: 
161073: /*
161074: ** Return the index of the cell containing a pointer to node pNode
161075: ** in its parent. If pNode is the root node, return -1.
161076: */
161077: static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
161078:   RtreeNode *pParent = pNode->pParent;
161079:   if( pParent ){
161080:     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
161081:   }
161082:   *piIndex = -1;
161083:   return SQLITE_OK;
161084: }
161085: 
161086: /*
161087: ** Compare two search points.  Return negative, zero, or positive if the first
161088: ** is less than, equal to, or greater than the second.
161089: **
161090: ** The rScore is the primary key.  Smaller rScore values come first.
161091: ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
161092: ** iLevel values coming first.  In this way, if rScore is the same for all
161093: ** SearchPoints, then iLevel becomes the deciding factor and the result
161094: ** is a depth-first search, which is the desired default behavior.
161095: */
161096: static int rtreeSearchPointCompare(
161097:   const RtreeSearchPoint *pA,
161098:   const RtreeSearchPoint *pB
161099: ){
161100:   if( pA->rScore<pB->rScore ) return -1;
161101:   if( pA->rScore>pB->rScore ) return +1;
161102:   if( pA->iLevel<pB->iLevel ) return -1;
161103:   if( pA->iLevel>pB->iLevel ) return +1;
161104:   return 0;
161105: }
161106: 
161107: /*
161108: ** Interchange to search points in a cursor.
161109: */
161110: static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
161111:   RtreeSearchPoint t = p->aPoint[i];
161112:   assert( i<j );
161113:   p->aPoint[i] = p->aPoint[j];
161114:   p->aPoint[j] = t;
161115:   i++; j++;
161116:   if( i<RTREE_CACHE_SZ ){
161117:     if( j>=RTREE_CACHE_SZ ){
161118:       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
161119:       p->aNode[i] = 0;
161120:     }else{
161121:       RtreeNode *pTemp = p->aNode[i];
161122:       p->aNode[i] = p->aNode[j];
161123:       p->aNode[j] = pTemp;
161124:     }
161125:   }
161126: }
161127: 
161128: /*
161129: ** Return the search point with the lowest current score.
161130: */
161131: static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
161132:   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
161133: }
161134: 
161135: /*
161136: ** Get the RtreeNode for the search point with the lowest score.
161137: */
161138: static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
161139:   sqlite3_int64 id;
161140:   int ii = 1 - pCur->bPoint;
161141:   assert( ii==0 || ii==1 );
161142:   assert( pCur->bPoint || pCur->nPoint );
161143:   if( pCur->aNode[ii]==0 ){
161144:     assert( pRC!=0 );
161145:     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
161146:     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
161147:   }
161148:   return pCur->aNode[ii];
161149: }
161150: 
161151: /*
161152: ** Push a new element onto the priority queue
161153: */
161154: static RtreeSearchPoint *rtreeEnqueue(
161155:   RtreeCursor *pCur,    /* The cursor */
161156:   RtreeDValue rScore,   /* Score for the new search point */
161157:   u8 iLevel             /* Level for the new search point */
161158: ){
161159:   int i, j;
161160:   RtreeSearchPoint *pNew;
161161:   if( pCur->nPoint>=pCur->nPointAlloc ){
161162:     int nNew = pCur->nPointAlloc*2 + 8;
161163:     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
161164:     if( pNew==0 ) return 0;
161165:     pCur->aPoint = pNew;
161166:     pCur->nPointAlloc = nNew;
161167:   }
161168:   i = pCur->nPoint++;
161169:   pNew = pCur->aPoint + i;
161170:   pNew->rScore = rScore;
161171:   pNew->iLevel = iLevel;
161172:   assert( iLevel<=RTREE_MAX_DEPTH );
161173:   while( i>0 ){
161174:     RtreeSearchPoint *pParent;
161175:     j = (i-1)/2;
161176:     pParent = pCur->aPoint + j;
161177:     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
161178:     rtreeSearchPointSwap(pCur, j, i);
161179:     i = j;
161180:     pNew = pParent;
161181:   }
161182:   return pNew;
161183: }
161184: 
161185: /*
161186: ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
161187: ** NULL if malloc fails.
161188: */
161189: static RtreeSearchPoint *rtreeSearchPointNew(
161190:   RtreeCursor *pCur,    /* The cursor */
161191:   RtreeDValue rScore,   /* Score for the new search point */
161192:   u8 iLevel             /* Level for the new search point */
161193: ){
161194:   RtreeSearchPoint *pNew, *pFirst;
161195:   pFirst = rtreeSearchPointFirst(pCur);
161196:   pCur->anQueue[iLevel]++;
161197:   if( pFirst==0
161198:    || pFirst->rScore>rScore 
161199:    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
161200:   ){
161201:     if( pCur->bPoint ){
161202:       int ii;
161203:       pNew = rtreeEnqueue(pCur, rScore, iLevel);
161204:       if( pNew==0 ) return 0;
161205:       ii = (int)(pNew - pCur->aPoint) + 1;
161206:       if( ii<RTREE_CACHE_SZ ){
161207:         assert( pCur->aNode[ii]==0 );
161208:         pCur->aNode[ii] = pCur->aNode[0];
161209:        }else{
161210:         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
161211:       }
161212:       pCur->aNode[0] = 0;
161213:       *pNew = pCur->sPoint;
161214:     }
161215:     pCur->sPoint.rScore = rScore;
161216:     pCur->sPoint.iLevel = iLevel;
161217:     pCur->bPoint = 1;
161218:     return &pCur->sPoint;
161219:   }else{
161220:     return rtreeEnqueue(pCur, rScore, iLevel);
161221:   }
161222: }
161223: 
161224: #if 0
161225: /* Tracing routines for the RtreeSearchPoint queue */
161226: static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
161227:   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
161228:   printf(" %d.%05lld.%02d %g %d",
161229:     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
161230:   );
161231:   idx++;
161232:   if( idx<RTREE_CACHE_SZ ){
161233:     printf(" %p\n", pCur->aNode[idx]);
161234:   }else{
161235:     printf("\n");
161236:   }
161237: }
161238: static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
161239:   int ii;
161240:   printf("=== %9s ", zPrefix);
161241:   if( pCur->bPoint ){
161242:     tracePoint(&pCur->sPoint, -1, pCur);
161243:   }
161244:   for(ii=0; ii<pCur->nPoint; ii++){
161245:     if( ii>0 || pCur->bPoint ) printf("              ");
161246:     tracePoint(&pCur->aPoint[ii], ii, pCur);
161247:   }
161248: }
161249: # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
161250: #else
161251: # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
161252: #endif
161253: 
161254: /* Remove the search point with the lowest current score.
161255: */
161256: static void rtreeSearchPointPop(RtreeCursor *p){
161257:   int i, j, k, n;
161258:   i = 1 - p->bPoint;
161259:   assert( i==0 || i==1 );
161260:   if( p->aNode[i] ){
161261:     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
161262:     p->aNode[i] = 0;
161263:   }
161264:   if( p->bPoint ){
161265:     p->anQueue[p->sPoint.iLevel]--;
161266:     p->bPoint = 0;
161267:   }else if( p->nPoint ){
161268:     p->anQueue[p->aPoint[0].iLevel]--;
161269:     n = --p->nPoint;
161270:     p->aPoint[0] = p->aPoint[n];
161271:     if( n<RTREE_CACHE_SZ-1 ){
161272:       p->aNode[1] = p->aNode[n+1];
161273:       p->aNode[n+1] = 0;
161274:     }
161275:     i = 0;
161276:     while( (j = i*2+1)<n ){
161277:       k = j+1;
161278:       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
161279:         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
161280:           rtreeSearchPointSwap(p, i, k);
161281:           i = k;
161282:         }else{
161283:           break;
161284:         }
161285:       }else{
161286:         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
161287:           rtreeSearchPointSwap(p, i, j);
161288:           i = j;
161289:         }else{
161290:           break;
161291:         }
161292:       }
161293:     }
161294:   }
161295: }
161296: 
161297: 
161298: /*
161299: ** Continue the search on cursor pCur until the front of the queue
161300: ** contains an entry suitable for returning as a result-set row,
161301: ** or until the RtreeSearchPoint queue is empty, indicating that the
161302: ** query has completed.
161303: */
161304: static int rtreeStepToLeaf(RtreeCursor *pCur){
161305:   RtreeSearchPoint *p;
161306:   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
161307:   RtreeNode *pNode;
161308:   int eWithin;
161309:   int rc = SQLITE_OK;
161310:   int nCell;
161311:   int nConstraint = pCur->nConstraint;
161312:   int ii;
161313:   int eInt;
161314:   RtreeSearchPoint x;
161315: 
161316:   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
161317:   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
161318:     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
161319:     if( rc ) return rc;
161320:     nCell = NCELL(pNode);
161321:     assert( nCell<200 );
161322:     while( p->iCell<nCell ){
161323:       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
161324:       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
161325:       eWithin = FULLY_WITHIN;
161326:       for(ii=0; ii<nConstraint; ii++){
161327:         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
161328:         if( pConstraint->op>=RTREE_MATCH ){
161329:           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
161330:                                        &rScore, &eWithin);
161331:           if( rc ) return rc;
161332:         }else if( p->iLevel==1 ){
161333:           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
161334:         }else{
161335:           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
161336:         }
161337:         if( eWithin==NOT_WITHIN ) break;
161338:       }
161339:       p->iCell++;
161340:       if( eWithin==NOT_WITHIN ) continue;
161341:       x.iLevel = p->iLevel - 1;
161342:       if( x.iLevel ){
161343:         x.id = readInt64(pCellData);
161344:         x.iCell = 0;
161345:       }else{
161346:         x.id = p->id;
161347:         x.iCell = p->iCell - 1;
161348:       }
161349:       if( p->iCell>=nCell ){
161350:         RTREE_QUEUE_TRACE(pCur, "POP-S:");
161351:         rtreeSearchPointPop(pCur);
161352:       }
161353:       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
161354:       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
161355:       if( p==0 ) return SQLITE_NOMEM;
161356:       p->eWithin = eWithin;
161357:       p->id = x.id;
161358:       p->iCell = x.iCell;
161359:       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
161360:       break;
161361:     }
161362:     if( p->iCell>=nCell ){
161363:       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
161364:       rtreeSearchPointPop(pCur);
161365:     }
161366:   }
161367:   pCur->atEOF = p==0;
161368:   return SQLITE_OK;
161369: }
161370: 
161371: /* 
161372: ** Rtree virtual table module xNext method.
161373: */
161374: static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
161375:   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161376:   int rc = SQLITE_OK;
161377: 
161378:   /* Move to the next entry that matches the configured constraints. */
161379:   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
161380:   rtreeSearchPointPop(pCsr);
161381:   rc = rtreeStepToLeaf(pCsr);
161382:   return rc;
161383: }
161384: 
161385: /* 
161386: ** Rtree virtual table module xRowid method.
161387: */
161388: static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
161389:   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161390:   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
161391:   int rc = SQLITE_OK;
161392:   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
161393:   if( rc==SQLITE_OK && p ){
161394:     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
161395:   }
161396:   return rc;
161397: }
161398: 
161399: /* 
161400: ** Rtree virtual table module xColumn method.
161401: */
161402: static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
161403:   Rtree *pRtree = (Rtree *)cur->pVtab;
161404:   RtreeCursor *pCsr = (RtreeCursor *)cur;
161405:   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
161406:   RtreeCoord c;
161407:   int rc = SQLITE_OK;
161408:   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
161409: 
161410:   if( rc ) return rc;
161411:   if( p==0 ) return SQLITE_OK;
161412:   if( i==0 ){
161413:     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
161414:   }else{
161415:     if( rc ) return rc;
161416:     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
161417: #ifndef SQLITE_RTREE_INT_ONLY
161418:     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
161419:       sqlite3_result_double(ctx, c.f);
161420:     }else
161421: #endif
161422:     {
161423:       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
161424:       sqlite3_result_int(ctx, c.i);
161425:     }
161426:   }
161427:   return SQLITE_OK;
161428: }
161429: 
161430: /* 
161431: ** Use nodeAcquire() to obtain the leaf node containing the record with 
161432: ** rowid iRowid. If successful, set *ppLeaf to point to the node and
161433: ** return SQLITE_OK. If there is no such record in the table, set
161434: ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
161435: ** to zero and return an SQLite error code.
161436: */
161437: static int findLeafNode(
161438:   Rtree *pRtree,              /* RTree to search */
161439:   i64 iRowid,                 /* The rowid searching for */
161440:   RtreeNode **ppLeaf,         /* Write the node here */
161441:   sqlite3_int64 *piNode       /* Write the node-id here */
161442: ){
161443:   int rc;
161444:   *ppLeaf = 0;
161445:   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
161446:   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
161447:     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
161448:     if( piNode ) *piNode = iNode;
161449:     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
161450:     sqlite3_reset(pRtree->pReadRowid);
161451:   }else{
161452:     rc = sqlite3_reset(pRtree->pReadRowid);
161453:   }
161454:   return rc;
161455: }
161456: 
161457: /*
161458: ** This function is called to configure the RtreeConstraint object passed
161459: ** as the second argument for a MATCH constraint. The value passed as the
161460: ** first argument to this function is the right-hand operand to the MATCH
161461: ** operator.
161462: */
161463: static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
161464:   RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
161465:   sqlite3_rtree_query_info *pInfo;   /* Callback information */
161466:   int nBlob;                         /* Size of the geometry function blob */
161467:   int nExpected;                     /* Expected size of the BLOB */
161468: 
161469:   /* Check that value is actually a blob. */
161470:   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
161471: 
161472:   /* Check that the blob is roughly the right size. */
161473:   nBlob = sqlite3_value_bytes(pValue);
161474:   if( nBlob<(int)sizeof(RtreeMatchArg) ){
161475:     return SQLITE_ERROR;
161476:   }
161477: 
161478:   pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
161479:   if( !pInfo ) return SQLITE_NOMEM;
161480:   memset(pInfo, 0, sizeof(*pInfo));
161481:   pBlob = (RtreeMatchArg*)&pInfo[1];
161482: 
161483:   memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
161484:   nExpected = (int)(sizeof(RtreeMatchArg) +
161485:                     pBlob->nParam*sizeof(sqlite3_value*) +
161486:                     (pBlob->nParam-1)*sizeof(RtreeDValue));
161487:   if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
161488:     sqlite3_free(pInfo);
161489:     return SQLITE_ERROR;
161490:   }
161491:   pInfo->pContext = pBlob->cb.pContext;
161492:   pInfo->nParam = pBlob->nParam;
161493:   pInfo->aParam = pBlob->aParam;
161494:   pInfo->apSqlParam = pBlob->apSqlParam;
161495: 
161496:   if( pBlob->cb.xGeom ){
161497:     pCons->u.xGeom = pBlob->cb.xGeom;
161498:   }else{
161499:     pCons->op = RTREE_QUERY;
161500:     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
161501:   }
161502:   pCons->pInfo = pInfo;
161503:   return SQLITE_OK;
161504: }
161505: 
161506: /* 
161507: ** Rtree virtual table module xFilter method.
161508: */
161509: static int rtreeFilter(
161510:   sqlite3_vtab_cursor *pVtabCursor, 
161511:   int idxNum, const char *idxStr,
161512:   int argc, sqlite3_value **argv
161513: ){
161514:   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
161515:   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
161516:   RtreeNode *pRoot = 0;
161517:   int ii;
161518:   int rc = SQLITE_OK;
161519:   int iCell = 0;
161520: 
161521:   rtreeReference(pRtree);
161522: 
161523:   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
161524:   freeCursorConstraints(pCsr);
161525:   sqlite3_free(pCsr->aPoint);
161526:   memset(pCsr, 0, sizeof(RtreeCursor));
161527:   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
161528: 
161529:   pCsr->iStrategy = idxNum;
161530:   if( idxNum==1 ){
161531:     /* Special case - lookup by rowid. */
161532:     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
161533:     RtreeSearchPoint *p;     /* Search point for the the leaf */
161534:     i64 iRowid = sqlite3_value_int64(argv[0]);
161535:     i64 iNode = 0;
161536:     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
161537:     if( rc==SQLITE_OK && pLeaf!=0 ){
161538:       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
161539:       assert( p!=0 );  /* Always returns pCsr->sPoint */
161540:       pCsr->aNode[0] = pLeaf;
161541:       p->id = iNode;
161542:       p->eWithin = PARTLY_WITHIN;
161543:       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
161544:       p->iCell = iCell;
161545:       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
161546:     }else{
161547:       pCsr->atEOF = 1;
161548:     }
161549:   }else{
161550:     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
161551:     ** with the configured constraints. 
161552:     */
161553:     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
161554:     if( rc==SQLITE_OK && argc>0 ){
161555:       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
161556:       pCsr->nConstraint = argc;
161557:       if( !pCsr->aConstraint ){
161558:         rc = SQLITE_NOMEM;
161559:       }else{
161560:         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
161561:         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
161562:         assert( (idxStr==0 && argc==0)
161563:                 || (idxStr && (int)strlen(idxStr)==argc*2) );
161564:         for(ii=0; ii<argc; ii++){
161565:           RtreeConstraint *p = &pCsr->aConstraint[ii];
161566:           p->op = idxStr[ii*2];
161567:           p->iCoord = idxStr[ii*2+1]-'0';
161568:           if( p->op>=RTREE_MATCH ){
161569:             /* A MATCH operator. The right-hand-side must be a blob that
161570:             ** can be cast into an RtreeMatchArg object. One created using
161571:             ** an sqlite3_rtree_geometry_callback() SQL user function.
161572:             */
161573:             rc = deserializeGeometry(argv[ii], p);
161574:             if( rc!=SQLITE_OK ){
161575:               break;
161576:             }
161577:             p->pInfo->nCoord = pRtree->nDim*2;
161578:             p->pInfo->anQueue = pCsr->anQueue;
161579:             p->pInfo->mxLevel = pRtree->iDepth + 1;
161580:           }else{
161581: #ifdef SQLITE_RTREE_INT_ONLY
161582:             p->u.rValue = sqlite3_value_int64(argv[ii]);
161583: #else
161584:             p->u.rValue = sqlite3_value_double(argv[ii]);
161585: #endif
161586:           }
161587:         }
161588:       }
161589:     }
161590:     if( rc==SQLITE_OK ){
161591:       RtreeSearchPoint *pNew;
161592:       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
161593:       if( pNew==0 ) return SQLITE_NOMEM;
161594:       pNew->id = 1;
161595:       pNew->iCell = 0;
161596:       pNew->eWithin = PARTLY_WITHIN;
161597:       assert( pCsr->bPoint==1 );
161598:       pCsr->aNode[0] = pRoot;
161599:       pRoot = 0;
161600:       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
161601:       rc = rtreeStepToLeaf(pCsr);
161602:     }
161603:   }
161604: 
161605:   nodeRelease(pRtree, pRoot);
161606:   rtreeRelease(pRtree);
161607:   return rc;
161608: }
161609: 
161610: /*
161611: ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
161612: ** extension is currently being used by a version of SQLite too old to
161613: ** support estimatedRows. In that case this function is a no-op.
161614: */
161615: static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
161616: #if SQLITE_VERSION_NUMBER>=3008002
161617:   if( sqlite3_libversion_number()>=3008002 ){
161618:     pIdxInfo->estimatedRows = nRow;
161619:   }
161620: #endif
161621: }
161622: 
161623: /*
161624: ** Rtree virtual table module xBestIndex method. There are three
161625: ** table scan strategies to choose from (in order from most to 
161626: ** least desirable):
161627: **
161628: **   idxNum     idxStr        Strategy
161629: **   ------------------------------------------------
161630: **     1        Unused        Direct lookup by rowid.
161631: **     2        See below     R-tree query or full-table scan.
161632: **   ------------------------------------------------
161633: **
161634: ** If strategy 1 is used, then idxStr is not meaningful. If strategy
161635: ** 2 is used, idxStr is formatted to contain 2 bytes for each 
161636: ** constraint used. The first two bytes of idxStr correspond to 
161637: ** the constraint in sqlite3_index_info.aConstraintUsage[] with
161638: ** (argvIndex==1) etc.
161639: **
161640: ** The first of each pair of bytes in idxStr identifies the constraint
161641: ** operator as follows:
161642: **
161643: **   Operator    Byte Value
161644: **   ----------------------
161645: **      =        0x41 ('A')
161646: **     <=        0x42 ('B')
161647: **      <        0x43 ('C')
161648: **     >=        0x44 ('D')
161649: **      >        0x45 ('E')
161650: **   MATCH       0x46 ('F')
161651: **   ----------------------
161652: **
161653: ** The second of each pair of bytes identifies the coordinate column
161654: ** to which the constraint applies. The leftmost coordinate column
161655: ** is 'a', the second from the left 'b' etc.
161656: */
161657: static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
161658:   Rtree *pRtree = (Rtree*)tab;
161659:   int rc = SQLITE_OK;
161660:   int ii;
161661:   int bMatch = 0;                 /* True if there exists a MATCH constraint */
161662:   i64 nRow;                       /* Estimated rows returned by this scan */
161663: 
161664:   int iIdx = 0;
161665:   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
161666:   memset(zIdxStr, 0, sizeof(zIdxStr));
161667: 
161668:   /* Check if there exists a MATCH constraint - even an unusable one. If there
161669:   ** is, do not consider the lookup-by-rowid plan as using such a plan would
161670:   ** require the VDBE to evaluate the MATCH constraint, which is not currently
161671:   ** possible. */
161672:   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
161673:     if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
161674:       bMatch = 1;
161675:     }
161676:   }
161677: 
161678:   assert( pIdxInfo->idxStr==0 );
161679:   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
161680:     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
161681: 
161682:     if( bMatch==0 && p->usable 
161683:      && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ 
161684:     ){
161685:       /* We have an equality constraint on the rowid. Use strategy 1. */
161686:       int jj;
161687:       for(jj=0; jj<ii; jj++){
161688:         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
161689:         pIdxInfo->aConstraintUsage[jj].omit = 0;
161690:       }
161691:       pIdxInfo->idxNum = 1;
161692:       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
161693:       pIdxInfo->aConstraintUsage[jj].omit = 1;
161694: 
161695:       /* This strategy involves a two rowid lookups on an B-Tree structures
161696:       ** and then a linear search of an R-Tree node. This should be 
161697:       ** considered almost as quick as a direct rowid lookup (for which 
161698:       ** sqlite uses an internal cost of 0.0). It is expected to return
161699:       ** a single row.
161700:       */ 
161701:       pIdxInfo->estimatedCost = 30.0;
161702:       setEstimatedRows(pIdxInfo, 1);
161703:       return SQLITE_OK;
161704:     }
161705: 
161706:     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
161707:       u8 op;
161708:       switch( p->op ){
161709:         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
161710:         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
161711:         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
161712:         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
161713:         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
161714:         default:
161715:           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
161716:           op = RTREE_MATCH; 
161717:           break;
161718:       }
161719:       zIdxStr[iIdx++] = op;
161720:       zIdxStr[iIdx++] = p->iColumn - 1 + '0';
161721:       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
161722:       pIdxInfo->aConstraintUsage[ii].omit = 1;
161723:     }
161724:   }
161725: 
161726:   pIdxInfo->idxNum = 2;
161727:   pIdxInfo->needToFreeIdxStr = 1;
161728:   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
161729:     return SQLITE_NOMEM;
161730:   }
161731: 
161732:   nRow = pRtree->nRowEst >> (iIdx/2);
161733:   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
161734:   setEstimatedRows(pIdxInfo, nRow);
161735: 
161736:   return rc;
161737: }
161738: 
161739: /*
161740: ** Return the N-dimensional volumn of the cell stored in *p.
161741: */
161742: static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
161743:   RtreeDValue area = (RtreeDValue)1;
161744:   int ii;
161745:   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161746:     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
161747:   }
161748:   return area;
161749: }
161750: 
161751: /*
161752: ** Return the margin length of cell p. The margin length is the sum
161753: ** of the objects size in each dimension.
161754: */
161755: static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
161756:   RtreeDValue margin = (RtreeDValue)0;
161757:   int ii;
161758:   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161759:     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
161760:   }
161761:   return margin;
161762: }
161763: 
161764: /*
161765: ** Store the union of cells p1 and p2 in p1.
161766: */
161767: static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
161768:   int ii;
161769:   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
161770:     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161771:       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
161772:       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
161773:     }
161774:   }else{
161775:     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161776:       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
161777:       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
161778:     }
161779:   }
161780: }
161781: 
161782: /*
161783: ** Return true if the area covered by p2 is a subset of the area covered
161784: ** by p1. False otherwise.
161785: */
161786: static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
161787:   int ii;
161788:   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
161789:   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
161790:     RtreeCoord *a1 = &p1->aCoord[ii];
161791:     RtreeCoord *a2 = &p2->aCoord[ii];
161792:     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
161793:      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
161794:     ){
161795:       return 0;
161796:     }
161797:   }
161798:   return 1;
161799: }
161800: 
161801: /*
161802: ** Return the amount cell p would grow by if it were unioned with pCell.
161803: */
161804: static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
161805:   RtreeDValue area;
161806:   RtreeCell cell;
161807:   memcpy(&cell, p, sizeof(RtreeCell));
161808:   area = cellArea(pRtree, &cell);
161809:   cellUnion(pRtree, &cell, pCell);
161810:   return (cellArea(pRtree, &cell)-area);
161811: }
161812: 
161813: static RtreeDValue cellOverlap(
161814:   Rtree *pRtree, 
161815:   RtreeCell *p, 
161816:   RtreeCell *aCell, 
161817:   int nCell
161818: ){
161819:   int ii;
161820:   RtreeDValue overlap = RTREE_ZERO;
161821:   for(ii=0; ii<nCell; ii++){
161822:     int jj;
161823:     RtreeDValue o = (RtreeDValue)1;
161824:     for(jj=0; jj<(pRtree->nDim*2); jj+=2){
161825:       RtreeDValue x1, x2;
161826:       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
161827:       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
161828:       if( x2<x1 ){
161829:         o = (RtreeDValue)0;
161830:         break;
161831:       }else{
161832:         o = o * (x2-x1);
161833:       }
161834:     }
161835:     overlap += o;
161836:   }
161837:   return overlap;
161838: }
161839: 
161840: 
161841: /*
161842: ** This function implements the ChooseLeaf algorithm from Gutman[84].
161843: ** ChooseSubTree in r*tree terminology.
161844: */
161845: static int ChooseLeaf(
161846:   Rtree *pRtree,               /* Rtree table */
161847:   RtreeCell *pCell,            /* Cell to insert into rtree */
161848:   int iHeight,                 /* Height of sub-tree rooted at pCell */
161849:   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
161850: ){
161851:   int rc;
161852:   int ii;
161853:   RtreeNode *pNode;
161854:   rc = nodeAcquire(pRtree, 1, 0, &pNode);
161855: 
161856:   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
161857:     int iCell;
161858:     sqlite3_int64 iBest = 0;
161859: 
161860:     RtreeDValue fMinGrowth = RTREE_ZERO;
161861:     RtreeDValue fMinArea = RTREE_ZERO;
161862: 
161863:     int nCell = NCELL(pNode);
161864:     RtreeCell cell;
161865:     RtreeNode *pChild;
161866: 
161867:     RtreeCell *aCell = 0;
161868: 
161869:     /* Select the child node which will be enlarged the least if pCell
161870:     ** is inserted into it. Resolve ties by choosing the entry with
161871:     ** the smallest area.
161872:     */
161873:     for(iCell=0; iCell<nCell; iCell++){
161874:       int bBest = 0;
161875:       RtreeDValue growth;
161876:       RtreeDValue area;
161877:       nodeGetCell(pRtree, pNode, iCell, &cell);
161878:       growth = cellGrowth(pRtree, &cell, pCell);
161879:       area = cellArea(pRtree, &cell);
161880:       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
161881:         bBest = 1;
161882:       }
161883:       if( bBest ){
161884:         fMinGrowth = growth;
161885:         fMinArea = area;
161886:         iBest = cell.iRowid;
161887:       }
161888:     }
161889: 
161890:     sqlite3_free(aCell);
161891:     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
161892:     nodeRelease(pRtree, pNode);
161893:     pNode = pChild;
161894:   }
161895: 
161896:   *ppLeaf = pNode;
161897:   return rc;
161898: }
161899: 
161900: /*
161901: ** A cell with the same content as pCell has just been inserted into
161902: ** the node pNode. This function updates the bounding box cells in
161903: ** all ancestor elements.
161904: */
161905: static int AdjustTree(
161906:   Rtree *pRtree,                    /* Rtree table */
161907:   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
161908:   RtreeCell *pCell                  /* This cell was just inserted */
161909: ){
161910:   RtreeNode *p = pNode;
161911:   while( p->pParent ){
161912:     RtreeNode *pParent = p->pParent;
161913:     RtreeCell cell;
161914:     int iCell;
161915: 
161916:     if( nodeParentIndex(pRtree, p, &iCell) ){
161917:       return SQLITE_CORRUPT_VTAB;
161918:     }
161919: 
161920:     nodeGetCell(pRtree, pParent, iCell, &cell);
161921:     if( !cellContains(pRtree, &cell, pCell) ){
161922:       cellUnion(pRtree, &cell, pCell);
161923:       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
161924:     }
161925:  
161926:     p = pParent;
161927:   }
161928:   return SQLITE_OK;
161929: }
161930: 
161931: /*
161932: ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
161933: */
161934: static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
161935:   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
161936:   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
161937:   sqlite3_step(pRtree->pWriteRowid);
161938:   return sqlite3_reset(pRtree->pWriteRowid);
161939: }
161940: 
161941: /*
161942: ** Write mapping (iNode->iPar) to the <rtree>_parent table.
161943: */
161944: static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
161945:   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
161946:   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
161947:   sqlite3_step(pRtree->pWriteParent);
161948:   return sqlite3_reset(pRtree->pWriteParent);
161949: }
161950: 
161951: static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
161952: 
161953: 
161954: /*
161955: ** Arguments aIdx, aDistance and aSpare all point to arrays of size
161956: ** nIdx. The aIdx array contains the set of integers from 0 to 
161957: ** (nIdx-1) in no particular order. This function sorts the values
161958: ** in aIdx according to the indexed values in aDistance. For
161959: ** example, assuming the inputs:
161960: **
161961: **   aIdx      = { 0,   1,   2,   3 }
161962: **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
161963: **
161964: ** this function sets the aIdx array to contain:
161965: **
161966: **   aIdx      = { 0,   1,   2,   3 }
161967: **
161968: ** The aSpare array is used as temporary working space by the
161969: ** sorting algorithm.
161970: */
161971: static void SortByDistance(
161972:   int *aIdx, 
161973:   int nIdx, 
161974:   RtreeDValue *aDistance, 
161975:   int *aSpare
161976: ){
161977:   if( nIdx>1 ){
161978:     int iLeft = 0;
161979:     int iRight = 0;
161980: 
161981:     int nLeft = nIdx/2;
161982:     int nRight = nIdx-nLeft;
161983:     int *aLeft = aIdx;
161984:     int *aRight = &aIdx[nLeft];
161985: 
161986:     SortByDistance(aLeft, nLeft, aDistance, aSpare);
161987:     SortByDistance(aRight, nRight, aDistance, aSpare);
161988: 
161989:     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
161990:     aLeft = aSpare;
161991: 
161992:     while( iLeft<nLeft || iRight<nRight ){
161993:       if( iLeft==nLeft ){
161994:         aIdx[iLeft+iRight] = aRight[iRight];
161995:         iRight++;
161996:       }else if( iRight==nRight ){
161997:         aIdx[iLeft+iRight] = aLeft[iLeft];
161998:         iLeft++;
161999:       }else{
162000:         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
162001:         RtreeDValue fRight = aDistance[aRight[iRight]];
162002:         if( fLeft<fRight ){
162003:           aIdx[iLeft+iRight] = aLeft[iLeft];
162004:           iLeft++;
162005:         }else{
162006:           aIdx[iLeft+iRight] = aRight[iRight];
162007:           iRight++;
162008:         }
162009:       }
162010:     }
162011: 
162012: #if 0
162013:     /* Check that the sort worked */
162014:     {
162015:       int jj;
162016:       for(jj=1; jj<nIdx; jj++){
162017:         RtreeDValue left = aDistance[aIdx[jj-1]];
162018:         RtreeDValue right = aDistance[aIdx[jj]];
162019:         assert( left<=right );
162020:       }
162021:     }
162022: #endif
162023:   }
162024: }
162025: 
162026: /*
162027: ** Arguments aIdx, aCell and aSpare all point to arrays of size
162028: ** nIdx. The aIdx array contains the set of integers from 0 to 
162029: ** (nIdx-1) in no particular order. This function sorts the values
162030: ** in aIdx according to dimension iDim of the cells in aCell. The
162031: ** minimum value of dimension iDim is considered first, the
162032: ** maximum used to break ties.
162033: **
162034: ** The aSpare array is used as temporary working space by the
162035: ** sorting algorithm.
162036: */
162037: static void SortByDimension(
162038:   Rtree *pRtree,
162039:   int *aIdx, 
162040:   int nIdx, 
162041:   int iDim, 
162042:   RtreeCell *aCell, 
162043:   int *aSpare
162044: ){
162045:   if( nIdx>1 ){
162046: 
162047:     int iLeft = 0;
162048:     int iRight = 0;
162049: 
162050:     int nLeft = nIdx/2;
162051:     int nRight = nIdx-nLeft;
162052:     int *aLeft = aIdx;
162053:     int *aRight = &aIdx[nLeft];
162054: 
162055:     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
162056:     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
162057: 
162058:     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
162059:     aLeft = aSpare;
162060:     while( iLeft<nLeft || iRight<nRight ){
162061:       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
162062:       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
162063:       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
162064:       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
162065:       if( (iLeft!=nLeft) && ((iRight==nRight)
162066:        || (xleft1<xright1)
162067:        || (xleft1==xright1 && xleft2<xright2)
162068:       )){
162069:         aIdx[iLeft+iRight] = aLeft[iLeft];
162070:         iLeft++;
162071:       }else{
162072:         aIdx[iLeft+iRight] = aRight[iRight];
162073:         iRight++;
162074:       }
162075:     }
162076: 
162077: #if 0
162078:     /* Check that the sort worked */
162079:     {
162080:       int jj;
162081:       for(jj=1; jj<nIdx; jj++){
162082:         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
162083:         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
162084:         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
162085:         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
162086:         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
162087:       }
162088:     }
162089: #endif
162090:   }
162091: }
162092: 
162093: /*
162094: ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
162095: */
162096: static int splitNodeStartree(
162097:   Rtree *pRtree,
162098:   RtreeCell *aCell,
162099:   int nCell,
162100:   RtreeNode *pLeft,
162101:   RtreeNode *pRight,
162102:   RtreeCell *pBboxLeft,
162103:   RtreeCell *pBboxRight
162104: ){
162105:   int **aaSorted;
162106:   int *aSpare;
162107:   int ii;
162108: 
162109:   int iBestDim = 0;
162110:   int iBestSplit = 0;
162111:   RtreeDValue fBestMargin = RTREE_ZERO;
162112: 
162113:   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
162114: 
162115:   aaSorted = (int **)sqlite3_malloc(nByte);
162116:   if( !aaSorted ){
162117:     return SQLITE_NOMEM;
162118:   }
162119: 
162120:   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
162121:   memset(aaSorted, 0, nByte);
162122:   for(ii=0; ii<pRtree->nDim; ii++){
162123:     int jj;
162124:     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
162125:     for(jj=0; jj<nCell; jj++){
162126:       aaSorted[ii][jj] = jj;
162127:     }
162128:     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
162129:   }
162130: 
162131:   for(ii=0; ii<pRtree->nDim; ii++){
162132:     RtreeDValue margin = RTREE_ZERO;
162133:     RtreeDValue fBestOverlap = RTREE_ZERO;
162134:     RtreeDValue fBestArea = RTREE_ZERO;
162135:     int iBestLeft = 0;
162136:     int nLeft;
162137: 
162138:     for(
162139:       nLeft=RTREE_MINCELLS(pRtree); 
162140:       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
162141:       nLeft++
162142:     ){
162143:       RtreeCell left;
162144:       RtreeCell right;
162145:       int kk;
162146:       RtreeDValue overlap;
162147:       RtreeDValue area;
162148: 
162149:       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
162150:       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
162151:       for(kk=1; kk<(nCell-1); kk++){
162152:         if( kk<nLeft ){
162153:           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
162154:         }else{
162155:           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
162156:         }
162157:       }
162158:       margin += cellMargin(pRtree, &left);
162159:       margin += cellMargin(pRtree, &right);
162160:       overlap = cellOverlap(pRtree, &left, &right, 1);
162161:       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
162162:       if( (nLeft==RTREE_MINCELLS(pRtree))
162163:        || (overlap<fBestOverlap)
162164:        || (overlap==fBestOverlap && area<fBestArea)
162165:       ){
162166:         iBestLeft = nLeft;
162167:         fBestOverlap = overlap;
162168:         fBestArea = area;
162169:       }
162170:     }
162171: 
162172:     if( ii==0 || margin<fBestMargin ){
162173:       iBestDim = ii;
162174:       fBestMargin = margin;
162175:       iBestSplit = iBestLeft;
162176:     }
162177:   }
162178: 
162179:   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
162180:   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
162181:   for(ii=0; ii<nCell; ii++){
162182:     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
162183:     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
162184:     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
162185:     nodeInsertCell(pRtree, pTarget, pCell);
162186:     cellUnion(pRtree, pBbox, pCell);
162187:   }
162188: 
162189:   sqlite3_free(aaSorted);
162190:   return SQLITE_OK;
162191: }
162192: 
162193: 
162194: static int updateMapping(
162195:   Rtree *pRtree, 
162196:   i64 iRowid, 
162197:   RtreeNode *pNode, 
162198:   int iHeight
162199: ){
162200:   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
162201:   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
162202:   if( iHeight>0 ){
162203:     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
162204:     if( pChild ){
162205:       nodeRelease(pRtree, pChild->pParent);
162206:       nodeReference(pNode);
162207:       pChild->pParent = pNode;
162208:     }
162209:   }
162210:   return xSetMapping(pRtree, iRowid, pNode->iNode);
162211: }
162212: 
162213: static int SplitNode(
162214:   Rtree *pRtree,
162215:   RtreeNode *pNode,
162216:   RtreeCell *pCell,
162217:   int iHeight
162218: ){
162219:   int i;
162220:   int newCellIsRight = 0;
162221: 
162222:   int rc = SQLITE_OK;
162223:   int nCell = NCELL(pNode);
162224:   RtreeCell *aCell;
162225:   int *aiUsed;
162226: 
162227:   RtreeNode *pLeft = 0;
162228:   RtreeNode *pRight = 0;
162229: 
162230:   RtreeCell leftbbox;
162231:   RtreeCell rightbbox;
162232: 
162233:   /* Allocate an array and populate it with a copy of pCell and 
162234:   ** all cells from node pLeft. Then zero the original node.
162235:   */
162236:   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
162237:   if( !aCell ){
162238:     rc = SQLITE_NOMEM;
162239:     goto splitnode_out;
162240:   }
162241:   aiUsed = (int *)&aCell[nCell+1];
162242:   memset(aiUsed, 0, sizeof(int)*(nCell+1));
162243:   for(i=0; i<nCell; i++){
162244:     nodeGetCell(pRtree, pNode, i, &aCell[i]);
162245:   }
162246:   nodeZero(pRtree, pNode);
162247:   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
162248:   nCell++;
162249: 
162250:   if( pNode->iNode==1 ){
162251:     pRight = nodeNew(pRtree, pNode);
162252:     pLeft = nodeNew(pRtree, pNode);
162253:     pRtree->iDepth++;
162254:     pNode->isDirty = 1;
162255:     writeInt16(pNode->zData, pRtree->iDepth);
162256:   }else{
162257:     pLeft = pNode;
162258:     pRight = nodeNew(pRtree, pLeft->pParent);
162259:     nodeReference(pLeft);
162260:   }
162261: 
162262:   if( !pLeft || !pRight ){
162263:     rc = SQLITE_NOMEM;
162264:     goto splitnode_out;
162265:   }
162266: 
162267:   memset(pLeft->zData, 0, pRtree->iNodeSize);
162268:   memset(pRight->zData, 0, pRtree->iNodeSize);
162269: 
162270:   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
162271:                          &leftbbox, &rightbbox);
162272:   if( rc!=SQLITE_OK ){
162273:     goto splitnode_out;
162274:   }
162275: 
162276:   /* Ensure both child nodes have node numbers assigned to them by calling
162277:   ** nodeWrite(). Node pRight always needs a node number, as it was created
162278:   ** by nodeNew() above. But node pLeft sometimes already has a node number.
162279:   ** In this case avoid the all to nodeWrite().
162280:   */
162281:   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
162282:    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
162283:   ){
162284:     goto splitnode_out;
162285:   }
162286: 
162287:   rightbbox.iRowid = pRight->iNode;
162288:   leftbbox.iRowid = pLeft->iNode;
162289: 
162290:   if( pNode->iNode==1 ){
162291:     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
162292:     if( rc!=SQLITE_OK ){
162293:       goto splitnode_out;
162294:     }
162295:   }else{
162296:     RtreeNode *pParent = pLeft->pParent;
162297:     int iCell;
162298:     rc = nodeParentIndex(pRtree, pLeft, &iCell);
162299:     if( rc==SQLITE_OK ){
162300:       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
162301:       rc = AdjustTree(pRtree, pParent, &leftbbox);
162302:     }
162303:     if( rc!=SQLITE_OK ){
162304:       goto splitnode_out;
162305:     }
162306:   }
162307:   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
162308:     goto splitnode_out;
162309:   }
162310: 
162311:   for(i=0; i<NCELL(pRight); i++){
162312:     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
162313:     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
162314:     if( iRowid==pCell->iRowid ){
162315:       newCellIsRight = 1;
162316:     }
162317:     if( rc!=SQLITE_OK ){
162318:       goto splitnode_out;
162319:     }
162320:   }
162321:   if( pNode->iNode==1 ){
162322:     for(i=0; i<NCELL(pLeft); i++){
162323:       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
162324:       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
162325:       if( rc!=SQLITE_OK ){
162326:         goto splitnode_out;
162327:       }
162328:     }
162329:   }else if( newCellIsRight==0 ){
162330:     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
162331:   }
162332: 
162333:   if( rc==SQLITE_OK ){
162334:     rc = nodeRelease(pRtree, pRight);
162335:     pRight = 0;
162336:   }
162337:   if( rc==SQLITE_OK ){
162338:     rc = nodeRelease(pRtree, pLeft);
162339:     pLeft = 0;
162340:   }
162341: 
162342: splitnode_out:
162343:   nodeRelease(pRtree, pRight);
162344:   nodeRelease(pRtree, pLeft);
162345:   sqlite3_free(aCell);
162346:   return rc;
162347: }
162348: 
162349: /*
162350: ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
162351: ** still NULL, load all ancestor nodes of pLeaf into memory and populate
162352: ** the pLeaf->pParent chain all the way up to the root node.
162353: **
162354: ** This operation is required when a row is deleted (or updated - an update
162355: ** is implemented as a delete followed by an insert). SQLite provides the
162356: ** rowid of the row to delete, which can be used to find the leaf on which
162357: ** the entry resides (argument pLeaf). Once the leaf is located, this 
162358: ** function is called to determine its ancestry.
162359: */
162360: static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
162361:   int rc = SQLITE_OK;
162362:   RtreeNode *pChild = pLeaf;
162363:   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
162364:     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
162365:     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
162366:     rc = sqlite3_step(pRtree->pReadParent);
162367:     if( rc==SQLITE_ROW ){
162368:       RtreeNode *pTest;           /* Used to test for reference loops */
162369:       i64 iNode;                  /* Node number of parent node */
162370: 
162371:       /* Before setting pChild->pParent, test that we are not creating a
162372:       ** loop of references (as we would if, say, pChild==pParent). We don't
162373:       ** want to do this as it leads to a memory leak when trying to delete
162374:       ** the referenced counted node structures.
162375:       */
162376:       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
162377:       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
162378:       if( !pTest ){
162379:         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
162380:       }
162381:     }
162382:     rc = sqlite3_reset(pRtree->pReadParent);
162383:     if( rc==SQLITE_OK ) rc = rc2;
162384:     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
162385:     pChild = pChild->pParent;
162386:   }
162387:   return rc;
162388: }
162389: 
162390: static int deleteCell(Rtree *, RtreeNode *, int, int);
162391: 
162392: static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
162393:   int rc;
162394:   int rc2;
162395:   RtreeNode *pParent = 0;
162396:   int iCell;
162397: 
162398:   assert( pNode->nRef==1 );
162399: 
162400:   /* Remove the entry in the parent cell. */
162401:   rc = nodeParentIndex(pRtree, pNode, &iCell);
162402:   if( rc==SQLITE_OK ){
162403:     pParent = pNode->pParent;
162404:     pNode->pParent = 0;
162405:     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
162406:   }
162407:   rc2 = nodeRelease(pRtree, pParent);
162408:   if( rc==SQLITE_OK ){
162409:     rc = rc2;
162410:   }
162411:   if( rc!=SQLITE_OK ){
162412:     return rc;
162413:   }
162414: 
162415:   /* Remove the xxx_node entry. */
162416:   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
162417:   sqlite3_step(pRtree->pDeleteNode);
162418:   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
162419:     return rc;
162420:   }
162421: 
162422:   /* Remove the xxx_parent entry. */
162423:   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
162424:   sqlite3_step(pRtree->pDeleteParent);
162425:   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
162426:     return rc;
162427:   }
162428:   
162429:   /* Remove the node from the in-memory hash table and link it into
162430:   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
162431:   */
162432:   nodeHashDelete(pRtree, pNode);
162433:   pNode->iNode = iHeight;
162434:   pNode->pNext = pRtree->pDeleted;
162435:   pNode->nRef++;
162436:   pRtree->pDeleted = pNode;
162437: 
162438:   return SQLITE_OK;
162439: }
162440: 
162441: static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
162442:   RtreeNode *pParent = pNode->pParent;
162443:   int rc = SQLITE_OK; 
162444:   if( pParent ){
162445:     int ii; 
162446:     int nCell = NCELL(pNode);
162447:     RtreeCell box;                            /* Bounding box for pNode */
162448:     nodeGetCell(pRtree, pNode, 0, &box);
162449:     for(ii=1; ii<nCell; ii++){
162450:       RtreeCell cell;
162451:       nodeGetCell(pRtree, pNode, ii, &cell);
162452:       cellUnion(pRtree, &box, &cell);
162453:     }
162454:     box.iRowid = pNode->iNode;
162455:     rc = nodeParentIndex(pRtree, pNode, &ii);
162456:     if( rc==SQLITE_OK ){
162457:       nodeOverwriteCell(pRtree, pParent, &box, ii);
162458:       rc = fixBoundingBox(pRtree, pParent);
162459:     }
162460:   }
162461:   return rc;
162462: }
162463: 
162464: /*
162465: ** Delete the cell at index iCell of node pNode. After removing the
162466: ** cell, adjust the r-tree data structure if required.
162467: */
162468: static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
162469:   RtreeNode *pParent;
162470:   int rc;
162471: 
162472:   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
162473:     return rc;
162474:   }
162475: 
162476:   /* Remove the cell from the node. This call just moves bytes around
162477:   ** the in-memory node image, so it cannot fail.
162478:   */
162479:   nodeDeleteCell(pRtree, pNode, iCell);
162480: 
162481:   /* If the node is not the tree root and now has less than the minimum
162482:   ** number of cells, remove it from the tree. Otherwise, update the
162483:   ** cell in the parent node so that it tightly contains the updated
162484:   ** node.
162485:   */
162486:   pParent = pNode->pParent;
162487:   assert( pParent || pNode->iNode==1 );
162488:   if( pParent ){
162489:     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
162490:       rc = removeNode(pRtree, pNode, iHeight);
162491:     }else{
162492:       rc = fixBoundingBox(pRtree, pNode);
162493:     }
162494:   }
162495: 
162496:   return rc;
162497: }
162498: 
162499: static int Reinsert(
162500:   Rtree *pRtree, 
162501:   RtreeNode *pNode, 
162502:   RtreeCell *pCell, 
162503:   int iHeight
162504: ){
162505:   int *aOrder;
162506:   int *aSpare;
162507:   RtreeCell *aCell;
162508:   RtreeDValue *aDistance;
162509:   int nCell;
162510:   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
162511:   int iDim;
162512:   int ii;
162513:   int rc = SQLITE_OK;
162514:   int n;
162515: 
162516:   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
162517: 
162518:   nCell = NCELL(pNode)+1;
162519:   n = (nCell+1)&(~1);
162520: 
162521:   /* Allocate the buffers used by this operation. The allocation is
162522:   ** relinquished before this function returns.
162523:   */
162524:   aCell = (RtreeCell *)sqlite3_malloc(n * (
162525:     sizeof(RtreeCell)     +         /* aCell array */
162526:     sizeof(int)           +         /* aOrder array */
162527:     sizeof(int)           +         /* aSpare array */
162528:     sizeof(RtreeDValue)             /* aDistance array */
162529:   ));
162530:   if( !aCell ){
162531:     return SQLITE_NOMEM;
162532:   }
162533:   aOrder    = (int *)&aCell[n];
162534:   aSpare    = (int *)&aOrder[n];
162535:   aDistance = (RtreeDValue *)&aSpare[n];
162536: 
162537:   for(ii=0; ii<nCell; ii++){
162538:     if( ii==(nCell-1) ){
162539:       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
162540:     }else{
162541:       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
162542:     }
162543:     aOrder[ii] = ii;
162544:     for(iDim=0; iDim<pRtree->nDim; iDim++){
162545:       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
162546:       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
162547:     }
162548:   }
162549:   for(iDim=0; iDim<pRtree->nDim; iDim++){
162550:     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
162551:   }
162552: 
162553:   for(ii=0; ii<nCell; ii++){
162554:     aDistance[ii] = RTREE_ZERO;
162555:     for(iDim=0; iDim<pRtree->nDim; iDim++){
162556:       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
162557:                                DCOORD(aCell[ii].aCoord[iDim*2]));
162558:       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
162559:     }
162560:   }
162561: 
162562:   SortByDistance(aOrder, nCell, aDistance, aSpare);
162563:   nodeZero(pRtree, pNode);
162564: 
162565:   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
162566:     RtreeCell *p = &aCell[aOrder[ii]];
162567:     nodeInsertCell(pRtree, pNode, p);
162568:     if( p->iRowid==pCell->iRowid ){
162569:       if( iHeight==0 ){
162570:         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
162571:       }else{
162572:         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
162573:       }
162574:     }
162575:   }
162576:   if( rc==SQLITE_OK ){
162577:     rc = fixBoundingBox(pRtree, pNode);
162578:   }
162579:   for(; rc==SQLITE_OK && ii<nCell; ii++){
162580:     /* Find a node to store this cell in. pNode->iNode currently contains
162581:     ** the height of the sub-tree headed by the cell.
162582:     */
162583:     RtreeNode *pInsert;
162584:     RtreeCell *p = &aCell[aOrder[ii]];
162585:     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
162586:     if( rc==SQLITE_OK ){
162587:       int rc2;
162588:       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
162589:       rc2 = nodeRelease(pRtree, pInsert);
162590:       if( rc==SQLITE_OK ){
162591:         rc = rc2;
162592:       }
162593:     }
162594:   }
162595: 
162596:   sqlite3_free(aCell);
162597:   return rc;
162598: }
162599: 
162600: /*
162601: ** Insert cell pCell into node pNode. Node pNode is the head of a 
162602: ** subtree iHeight high (leaf nodes have iHeight==0).
162603: */
162604: static int rtreeInsertCell(
162605:   Rtree *pRtree,
162606:   RtreeNode *pNode,
162607:   RtreeCell *pCell,
162608:   int iHeight
162609: ){
162610:   int rc = SQLITE_OK;
162611:   if( iHeight>0 ){
162612:     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
162613:     if( pChild ){
162614:       nodeRelease(pRtree, pChild->pParent);
162615:       nodeReference(pNode);
162616:       pChild->pParent = pNode;
162617:     }
162618:   }
162619:   if( nodeInsertCell(pRtree, pNode, pCell) ){
162620:     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
162621:       rc = SplitNode(pRtree, pNode, pCell, iHeight);
162622:     }else{
162623:       pRtree->iReinsertHeight = iHeight;
162624:       rc = Reinsert(pRtree, pNode, pCell, iHeight);
162625:     }
162626:   }else{
162627:     rc = AdjustTree(pRtree, pNode, pCell);
162628:     if( rc==SQLITE_OK ){
162629:       if( iHeight==0 ){
162630:         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
162631:       }else{
162632:         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
162633:       }
162634:     }
162635:   }
162636:   return rc;
162637: }
162638: 
162639: static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
162640:   int ii;
162641:   int rc = SQLITE_OK;
162642:   int nCell = NCELL(pNode);
162643: 
162644:   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
162645:     RtreeNode *pInsert;
162646:     RtreeCell cell;
162647:     nodeGetCell(pRtree, pNode, ii, &cell);
162648: 
162649:     /* Find a node to store this cell in. pNode->iNode currently contains
162650:     ** the height of the sub-tree headed by the cell.
162651:     */
162652:     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
162653:     if( rc==SQLITE_OK ){
162654:       int rc2;
162655:       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
162656:       rc2 = nodeRelease(pRtree, pInsert);
162657:       if( rc==SQLITE_OK ){
162658:         rc = rc2;
162659:       }
162660:     }
162661:   }
162662:   return rc;
162663: }
162664: 
162665: /*
162666: ** Select a currently unused rowid for a new r-tree record.
162667: */
162668: static int newRowid(Rtree *pRtree, i64 *piRowid){
162669:   int rc;
162670:   sqlite3_bind_null(pRtree->pWriteRowid, 1);
162671:   sqlite3_bind_null(pRtree->pWriteRowid, 2);
162672:   sqlite3_step(pRtree->pWriteRowid);
162673:   rc = sqlite3_reset(pRtree->pWriteRowid);
162674:   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
162675:   return rc;
162676: }
162677: 
162678: /*
162679: ** Remove the entry with rowid=iDelete from the r-tree structure.
162680: */
162681: static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
162682:   int rc;                         /* Return code */
162683:   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
162684:   int iCell;                      /* Index of iDelete cell in pLeaf */
162685:   RtreeNode *pRoot;               /* Root node of rtree structure */
162686: 
162687: 
162688:   /* Obtain a reference to the root node to initialize Rtree.iDepth */
162689:   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
162690: 
162691:   /* Obtain a reference to the leaf node that contains the entry 
162692:   ** about to be deleted. 
162693:   */
162694:   if( rc==SQLITE_OK ){
162695:     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
162696:   }
162697: 
162698:   /* Delete the cell in question from the leaf node. */
162699:   if( rc==SQLITE_OK ){
162700:     int rc2;
162701:     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
162702:     if( rc==SQLITE_OK ){
162703:       rc = deleteCell(pRtree, pLeaf, iCell, 0);
162704:     }
162705:     rc2 = nodeRelease(pRtree, pLeaf);
162706:     if( rc==SQLITE_OK ){
162707:       rc = rc2;
162708:     }
162709:   }
162710: 
162711:   /* Delete the corresponding entry in the <rtree>_rowid table. */
162712:   if( rc==SQLITE_OK ){
162713:     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
162714:     sqlite3_step(pRtree->pDeleteRowid);
162715:     rc = sqlite3_reset(pRtree->pDeleteRowid);
162716:   }
162717: 
162718:   /* Check if the root node now has exactly one child. If so, remove
162719:   ** it, schedule the contents of the child for reinsertion and 
162720:   ** reduce the tree height by one.
162721:   **
162722:   ** This is equivalent to copying the contents of the child into
162723:   ** the root node (the operation that Gutman's paper says to perform 
162724:   ** in this scenario).
162725:   */
162726:   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
162727:     int rc2;
162728:     RtreeNode *pChild;
162729:     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
162730:     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
162731:     if( rc==SQLITE_OK ){
162732:       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
162733:     }
162734:     rc2 = nodeRelease(pRtree, pChild);
162735:     if( rc==SQLITE_OK ) rc = rc2;
162736:     if( rc==SQLITE_OK ){
162737:       pRtree->iDepth--;
162738:       writeInt16(pRoot->zData, pRtree->iDepth);
162739:       pRoot->isDirty = 1;
162740:     }
162741:   }
162742: 
162743:   /* Re-insert the contents of any underfull nodes removed from the tree. */
162744:   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
162745:     if( rc==SQLITE_OK ){
162746:       rc = reinsertNodeContent(pRtree, pLeaf);
162747:     }
162748:     pRtree->pDeleted = pLeaf->pNext;
162749:     sqlite3_free(pLeaf);
162750:   }
162751: 
162752:   /* Release the reference to the root node. */
162753:   if( rc==SQLITE_OK ){
162754:     rc = nodeRelease(pRtree, pRoot);
162755:   }else{
162756:     nodeRelease(pRtree, pRoot);
162757:   }
162758: 
162759:   return rc;
162760: }
162761: 
162762: /*
162763: ** Rounding constants for float->double conversion.
162764: */
162765: #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
162766: #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
162767: 
162768: #if !defined(SQLITE_RTREE_INT_ONLY)
162769: /*
162770: ** Convert an sqlite3_value into an RtreeValue (presumably a float)
162771: ** while taking care to round toward negative or positive, respectively.
162772: */
162773: static RtreeValue rtreeValueDown(sqlite3_value *v){
162774:   double d = sqlite3_value_double(v);
162775:   float f = (float)d;
162776:   if( f>d ){
162777:     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
162778:   }
162779:   return f;
162780: }
162781: static RtreeValue rtreeValueUp(sqlite3_value *v){
162782:   double d = sqlite3_value_double(v);
162783:   float f = (float)d;
162784:   if( f<d ){
162785:     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
162786:   }
162787:   return f;
162788: }
162789: #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
162790: 
162791: /*
162792: ** A constraint has failed while inserting a row into an rtree table. 
162793: ** Assuming no OOM error occurs, this function sets the error message 
162794: ** (at pRtree->base.zErrMsg) to an appropriate value and returns
162795: ** SQLITE_CONSTRAINT.
162796: **
162797: ** Parameter iCol is the index of the leftmost column involved in the
162798: ** constraint failure. If it is 0, then the constraint that failed is
162799: ** the unique constraint on the id column. Otherwise, it is the rtree
162800: ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
162801: **
162802: ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
162803: */
162804: static int rtreeConstraintError(Rtree *pRtree, int iCol){
162805:   sqlite3_stmt *pStmt = 0;
162806:   char *zSql; 
162807:   int rc;
162808: 
162809:   assert( iCol==0 || iCol%2 );
162810:   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
162811:   if( zSql ){
162812:     rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
162813:   }else{
162814:     rc = SQLITE_NOMEM;
162815:   }
162816:   sqlite3_free(zSql);
162817: 
162818:   if( rc==SQLITE_OK ){
162819:     if( iCol==0 ){
162820:       const char *zCol = sqlite3_column_name(pStmt, 0);
162821:       pRtree->base.zErrMsg = sqlite3_mprintf(
162822:           "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
162823:       );
162824:     }else{
162825:       const char *zCol1 = sqlite3_column_name(pStmt, iCol);
162826:       const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
162827:       pRtree->base.zErrMsg = sqlite3_mprintf(
162828:           "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
162829:       );
162830:     }
162831:   }
162832: 
162833:   sqlite3_finalize(pStmt);
162834:   return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
162835: }
162836: 
162837: 
162838: 
162839: /*
162840: ** The xUpdate method for rtree module virtual tables.
162841: */
162842: static int rtreeUpdate(
162843:   sqlite3_vtab *pVtab, 
162844:   int nData, 
162845:   sqlite3_value **azData, 
162846:   sqlite_int64 *pRowid
162847: ){
162848:   Rtree *pRtree = (Rtree *)pVtab;
162849:   int rc = SQLITE_OK;
162850:   RtreeCell cell;                 /* New cell to insert if nData>1 */
162851:   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
162852: 
162853:   rtreeReference(pRtree);
162854:   assert(nData>=1);
162855: 
162856:   cell.iRowid = 0;  /* Used only to suppress a compiler warning */
162857: 
162858:   /* Constraint handling. A write operation on an r-tree table may return
162859:   ** SQLITE_CONSTRAINT for two reasons:
162860:   **
162861:   **   1. A duplicate rowid value, or
162862:   **   2. The supplied data violates the "x2>=x1" constraint.
162863:   **
162864:   ** In the first case, if the conflict-handling mode is REPLACE, then
162865:   ** the conflicting row can be removed before proceeding. In the second
162866:   ** case, SQLITE_CONSTRAINT must be returned regardless of the
162867:   ** conflict-handling mode specified by the user.
162868:   */
162869:   if( nData>1 ){
162870:     int ii;
162871: 
162872:     /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
162873:     **
162874:     ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
162875:     ** with "column" that are interpreted as table constraints.
162876:     ** Example:  CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
162877:     ** This problem was discovered after years of use, so we silently ignore
162878:     ** these kinds of misdeclared tables to avoid breaking any legacy.
162879:     */
162880:     assert( nData<=(pRtree->nDim*2 + 3) );
162881: 
162882: #ifndef SQLITE_RTREE_INT_ONLY
162883:     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
162884:       for(ii=0; ii<nData-4; ii+=2){
162885:         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
162886:         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
162887:         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
162888:           rc = rtreeConstraintError(pRtree, ii+1);
162889:           goto constraint;
162890:         }
162891:       }
162892:     }else
162893: #endif
162894:     {
162895:       for(ii=0; ii<nData-4; ii+=2){
162896:         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
162897:         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
162898:         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
162899:           rc = rtreeConstraintError(pRtree, ii+1);
162900:           goto constraint;
162901:         }
162902:       }
162903:     }
162904: 
162905:     /* If a rowid value was supplied, check if it is already present in 
162906:     ** the table. If so, the constraint has failed. */
162907:     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
162908:       cell.iRowid = sqlite3_value_int64(azData[2]);
162909:       if( sqlite3_value_type(azData[0])==SQLITE_NULL
162910:        || sqlite3_value_int64(azData[0])!=cell.iRowid
162911:       ){
162912:         int steprc;
162913:         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
162914:         steprc = sqlite3_step(pRtree->pReadRowid);
162915:         rc = sqlite3_reset(pRtree->pReadRowid);
162916:         if( SQLITE_ROW==steprc ){
162917:           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
162918:             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
162919:           }else{
162920:             rc = rtreeConstraintError(pRtree, 0);
162921:             goto constraint;
162922:           }
162923:         }
162924:       }
162925:       bHaveRowid = 1;
162926:     }
162927:   }
162928: 
162929:   /* If azData[0] is not an SQL NULL value, it is the rowid of a
162930:   ** record to delete from the r-tree table. The following block does
162931:   ** just that.
162932:   */
162933:   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
162934:     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
162935:   }
162936: 
162937:   /* If the azData[] array contains more than one element, elements
162938:   ** (azData[2]..azData[argc-1]) contain a new record to insert into
162939:   ** the r-tree structure.
162940:   */
162941:   if( rc==SQLITE_OK && nData>1 ){
162942:     /* Insert the new record into the r-tree */
162943:     RtreeNode *pLeaf = 0;
162944: 
162945:     /* Figure out the rowid of the new row. */
162946:     if( bHaveRowid==0 ){
162947:       rc = newRowid(pRtree, &cell.iRowid);
162948:     }
162949:     *pRowid = cell.iRowid;
162950: 
162951:     if( rc==SQLITE_OK ){
162952:       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
162953:     }
162954:     if( rc==SQLITE_OK ){
162955:       int rc2;
162956:       pRtree->iReinsertHeight = -1;
162957:       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
162958:       rc2 = nodeRelease(pRtree, pLeaf);
162959:       if( rc==SQLITE_OK ){
162960:         rc = rc2;
162961:       }
162962:     }
162963:   }
162964: 
162965: constraint:
162966:   rtreeRelease(pRtree);
162967:   return rc;
162968: }
162969: 
162970: /*
162971: ** The xRename method for rtree module virtual tables.
162972: */
162973: static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
162974:   Rtree *pRtree = (Rtree *)pVtab;
162975:   int rc = SQLITE_NOMEM;
162976:   char *zSql = sqlite3_mprintf(
162977:     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
162978:     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
162979:     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
162980:     , pRtree->zDb, pRtree->zName, zNewName 
162981:     , pRtree->zDb, pRtree->zName, zNewName 
162982:     , pRtree->zDb, pRtree->zName, zNewName
162983:   );
162984:   if( zSql ){
162985:     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
162986:     sqlite3_free(zSql);
162987:   }
162988:   return rc;
162989: }
162990: 
162991: /*
162992: ** This function populates the pRtree->nRowEst variable with an estimate
162993: ** of the number of rows in the virtual table. If possible, this is based
162994: ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
162995: */
162996: static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
162997:   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
162998:   char *zSql;
162999:   sqlite3_stmt *p;
163000:   int rc;
163001:   i64 nRow = 0;
163002: 
163003:   if( sqlite3_table_column_metadata(db,pRtree->zDb,"sqlite_stat1",
163004:           0,0,0,0,0,0)==SQLITE_ERROR ){
163005:     pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
163006:     return SQLITE_OK;
163007:   }
163008:   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
163009:   if( zSql==0 ){
163010:     rc = SQLITE_NOMEM;
163011:   }else{
163012:     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
163013:     if( rc==SQLITE_OK ){
163014:       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
163015:       rc = sqlite3_finalize(p);
163016:     }else if( rc!=SQLITE_NOMEM ){
163017:       rc = SQLITE_OK;
163018:     }
163019: 
163020:     if( rc==SQLITE_OK ){
163021:       if( nRow==0 ){
163022:         pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
163023:       }else{
163024:         pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
163025:       }
163026:     }
163027:     sqlite3_free(zSql);
163028:   }
163029: 
163030:   return rc;
163031: }
163032: 
163033: static sqlite3_module rtreeModule = {
163034:   0,                          /* iVersion */
163035:   rtreeCreate,                /* xCreate - create a table */
163036:   rtreeConnect,               /* xConnect - connect to an existing table */
163037:   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
163038:   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
163039:   rtreeDestroy,               /* xDestroy - Drop a table */
163040:   rtreeOpen,                  /* xOpen - open a cursor */
163041:   rtreeClose,                 /* xClose - close a cursor */
163042:   rtreeFilter,                /* xFilter - configure scan constraints */
163043:   rtreeNext,                  /* xNext - advance a cursor */
163044:   rtreeEof,                   /* xEof */
163045:   rtreeColumn,                /* xColumn - read data */
163046:   rtreeRowid,                 /* xRowid - read data */
163047:   rtreeUpdate,                /* xUpdate - write data */
163048:   0,                          /* xBegin - begin transaction */
163049:   0,                          /* xSync - sync transaction */
163050:   0,                          /* xCommit - commit transaction */
163051:   0,                          /* xRollback - rollback transaction */
163052:   0,                          /* xFindFunction - function overloading */
163053:   rtreeRename,                /* xRename - rename the table */
163054:   0,                          /* xSavepoint */
163055:   0,                          /* xRelease */
163056:   0                           /* xRollbackTo */
163057: };
163058: 
163059: static int rtreeSqlInit(
163060:   Rtree *pRtree, 
163061:   sqlite3 *db, 
163062:   const char *zDb, 
163063:   const char *zPrefix, 
163064:   int isCreate
163065: ){
163066:   int rc = SQLITE_OK;
163067: 
163068:   #define N_STATEMENT 9
163069:   static const char *azSql[N_STATEMENT] = {
163070:     /* Read and write the xxx_node table */
163071:     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
163072:     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
163073:     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
163074: 
163075:     /* Read and write the xxx_rowid table */
163076:     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
163077:     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
163078:     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
163079: 
163080:     /* Read and write the xxx_parent table */
163081:     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
163082:     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
163083:     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
163084:   };
163085:   sqlite3_stmt **appStmt[N_STATEMENT];
163086:   int i;
163087: 
163088:   pRtree->db = db;
163089: 
163090:   if( isCreate ){
163091:     char *zCreate = sqlite3_mprintf(
163092: "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
163093: "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
163094: "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
163095:                                   " parentnode INTEGER);"
163096: "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
163097:       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
163098:     );
163099:     if( !zCreate ){
163100:       return SQLITE_NOMEM;
163101:     }
163102:     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
163103:     sqlite3_free(zCreate);
163104:     if( rc!=SQLITE_OK ){
163105:       return rc;
163106:     }
163107:   }
163108: 
163109:   appStmt[0] = &pRtree->pReadNode;
163110:   appStmt[1] = &pRtree->pWriteNode;
163111:   appStmt[2] = &pRtree->pDeleteNode;
163112:   appStmt[3] = &pRtree->pReadRowid;
163113:   appStmt[4] = &pRtree->pWriteRowid;
163114:   appStmt[5] = &pRtree->pDeleteRowid;
163115:   appStmt[6] = &pRtree->pReadParent;
163116:   appStmt[7] = &pRtree->pWriteParent;
163117:   appStmt[8] = &pRtree->pDeleteParent;
163118: 
163119:   rc = rtreeQueryStat1(db, pRtree);
163120:   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
163121:     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
163122:     if( zSql ){
163123:       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
163124:     }else{
163125:       rc = SQLITE_NOMEM;
163126:     }
163127:     sqlite3_free(zSql);
163128:   }
163129: 
163130:   return rc;
163131: }
163132: 
163133: /*
163134: ** The second argument to this function contains the text of an SQL statement
163135: ** that returns a single integer value. The statement is compiled and executed
163136: ** using database connection db. If successful, the integer value returned
163137: ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
163138: ** code is returned and the value of *piVal after returning is not defined.
163139: */
163140: static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
163141:   int rc = SQLITE_NOMEM;
163142:   if( zSql ){
163143:     sqlite3_stmt *pStmt = 0;
163144:     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
163145:     if( rc==SQLITE_OK ){
163146:       if( SQLITE_ROW==sqlite3_step(pStmt) ){
163147:         *piVal = sqlite3_column_int(pStmt, 0);
163148:       }
163149:       rc = sqlite3_finalize(pStmt);
163150:     }
163151:   }
163152:   return rc;
163153: }
163154: 
163155: /*
163156: ** This function is called from within the xConnect() or xCreate() method to
163157: ** determine the node-size used by the rtree table being created or connected
163158: ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
163159: ** Otherwise, an SQLite error code is returned.
163160: **
163161: ** If this function is being called as part of an xConnect(), then the rtree
163162: ** table already exists. In this case the node-size is determined by inspecting
163163: ** the root node of the tree.
163164: **
163165: ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
163166: ** This ensures that each node is stored on a single database page. If the 
163167: ** database page-size is so large that more than RTREE_MAXCELLS entries 
163168: ** would fit in a single node, use a smaller node-size.
163169: */
163170: static int getNodeSize(
163171:   sqlite3 *db,                    /* Database handle */
163172:   Rtree *pRtree,                  /* Rtree handle */
163173:   int isCreate,                   /* True for xCreate, false for xConnect */
163174:   char **pzErr                    /* OUT: Error message, if any */
163175: ){
163176:   int rc;
163177:   char *zSql;
163178:   if( isCreate ){
163179:     int iPageSize = 0;
163180:     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
163181:     rc = getIntFromStmt(db, zSql, &iPageSize);
163182:     if( rc==SQLITE_OK ){
163183:       pRtree->iNodeSize = iPageSize-64;
163184:       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
163185:         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
163186:       }
163187:     }else{
163188:       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163189:     }
163190:   }else{
163191:     zSql = sqlite3_mprintf(
163192:         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
163193:         pRtree->zDb, pRtree->zName
163194:     );
163195:     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
163196:     if( rc!=SQLITE_OK ){
163197:       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163198:     }
163199:   }
163200: 
163201:   sqlite3_free(zSql);
163202:   return rc;
163203: }
163204: 
163205: /* 
163206: ** This function is the implementation of both the xConnect and xCreate
163207: ** methods of the r-tree virtual table.
163208: **
163209: **   argv[0]   -> module name
163210: **   argv[1]   -> database name
163211: **   argv[2]   -> table name
163212: **   argv[...] -> column names...
163213: */
163214: static int rtreeInit(
163215:   sqlite3 *db,                        /* Database connection */
163216:   void *pAux,                         /* One of the RTREE_COORD_* constants */
163217:   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
163218:   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
163219:   char **pzErr,                       /* OUT: Error message, if any */
163220:   int isCreate                        /* True for xCreate, false for xConnect */
163221: ){
163222:   int rc = SQLITE_OK;
163223:   Rtree *pRtree;
163224:   int nDb;              /* Length of string argv[1] */
163225:   int nName;            /* Length of string argv[2] */
163226:   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
163227: 
163228:   const char *aErrMsg[] = {
163229:     0,                                                    /* 0 */
163230:     "Wrong number of columns for an rtree table",         /* 1 */
163231:     "Too few columns for an rtree table",                 /* 2 */
163232:     "Too many columns for an rtree table"                 /* 3 */
163233:   };
163234: 
163235:   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
163236:   if( aErrMsg[iErr] ){
163237:     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
163238:     return SQLITE_ERROR;
163239:   }
163240: 
163241:   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
163242: 
163243:   /* Allocate the sqlite3_vtab structure */
163244:   nDb = (int)strlen(argv[1]);
163245:   nName = (int)strlen(argv[2]);
163246:   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
163247:   if( !pRtree ){
163248:     return SQLITE_NOMEM;
163249:   }
163250:   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
163251:   pRtree->nBusy = 1;
163252:   pRtree->base.pModule = &rtreeModule;
163253:   pRtree->zDb = (char *)&pRtree[1];
163254:   pRtree->zName = &pRtree->zDb[nDb+1];
163255:   pRtree->nDim = (argc-4)/2;
163256:   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
163257:   pRtree->eCoordType = eCoordType;
163258:   memcpy(pRtree->zDb, argv[1], nDb);
163259:   memcpy(pRtree->zName, argv[2], nName);
163260: 
163261:   /* Figure out the node size to use. */
163262:   rc = getNodeSize(db, pRtree, isCreate, pzErr);
163263: 
163264:   /* Create/Connect to the underlying relational database schema. If
163265:   ** that is successful, call sqlite3_declare_vtab() to configure
163266:   ** the r-tree table schema.
163267:   */
163268:   if( rc==SQLITE_OK ){
163269:     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
163270:       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163271:     }else{
163272:       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
163273:       char *zTmp;
163274:       int ii;
163275:       for(ii=4; zSql && ii<argc; ii++){
163276:         zTmp = zSql;
163277:         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
163278:         sqlite3_free(zTmp);
163279:       }
163280:       if( zSql ){
163281:         zTmp = zSql;
163282:         zSql = sqlite3_mprintf("%s);", zTmp);
163283:         sqlite3_free(zTmp);
163284:       }
163285:       if( !zSql ){
163286:         rc = SQLITE_NOMEM;
163287:       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
163288:         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
163289:       }
163290:       sqlite3_free(zSql);
163291:     }
163292:   }
163293: 
163294:   if( rc==SQLITE_OK ){
163295:     *ppVtab = (sqlite3_vtab *)pRtree;
163296:   }else{
163297:     assert( *ppVtab==0 );
163298:     assert( pRtree->nBusy==1 );
163299:     rtreeRelease(pRtree);
163300:   }
163301:   return rc;
163302: }
163303: 
163304: 
163305: /*
163306: ** Implementation of a scalar function that decodes r-tree nodes to
163307: ** human readable strings. This can be used for debugging and analysis.
163308: **
163309: ** The scalar function takes two arguments: (1) the number of dimensions
163310: ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
163311: ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
163312: ** deserialize all nodes, a statement like:
163313: **
163314: **   SELECT rtreenode(2, data) FROM rt_node;
163315: **
163316: ** The human readable string takes the form of a Tcl list with one
163317: ** entry for each cell in the r-tree node. Each entry is itself a
163318: ** list, containing the 8-byte rowid/pageno followed by the 
163319: ** <num-dimension>*2 coordinates.
163320: */
163321: static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
163322:   char *zText = 0;
163323:   RtreeNode node;
163324:   Rtree tree;
163325:   int ii;
163326: 
163327:   UNUSED_PARAMETER(nArg);
163328:   memset(&node, 0, sizeof(RtreeNode));
163329:   memset(&tree, 0, sizeof(Rtree));
163330:   tree.nDim = sqlite3_value_int(apArg[0]);
163331:   tree.nBytesPerCell = 8 + 8 * tree.nDim;
163332:   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
163333: 
163334:   for(ii=0; ii<NCELL(&node); ii++){
163335:     char zCell[512];
163336:     int nCell = 0;
163337:     RtreeCell cell;
163338:     int jj;
163339: 
163340:     nodeGetCell(&tree, &node, ii, &cell);
163341:     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
163342:     nCell = (int)strlen(zCell);
163343:     for(jj=0; jj<tree.nDim*2; jj++){
163344: #ifndef SQLITE_RTREE_INT_ONLY
163345:       sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
163346:                        (double)cell.aCoord[jj].f);
163347: #else
163348:       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
163349:                        cell.aCoord[jj].i);
163350: #endif
163351:       nCell = (int)strlen(zCell);
163352:     }
163353: 
163354:     if( zText ){
163355:       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
163356:       sqlite3_free(zText);
163357:       zText = zTextNew;
163358:     }else{
163359:       zText = sqlite3_mprintf("{%s}", zCell);
163360:     }
163361:   }
163362:   
163363:   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
163364: }
163365: 
163366: /* This routine implements an SQL function that returns the "depth" parameter
163367: ** from the front of a blob that is an r-tree node.  For example:
163368: **
163369: **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
163370: **
163371: ** The depth value is 0 for all nodes other than the root node, and the root
163372: ** node always has nodeno=1, so the example above is the primary use for this
163373: ** routine.  This routine is intended for testing and analysis only.
163374: */
163375: static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
163376:   UNUSED_PARAMETER(nArg);
163377:   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
163378:    || sqlite3_value_bytes(apArg[0])<2
163379:   ){
163380:     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
163381:   }else{
163382:     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
163383:     sqlite3_result_int(ctx, readInt16(zBlob));
163384:   }
163385: }
163386: 
163387: /*
163388: ** Register the r-tree module with database handle db. This creates the
163389: ** virtual table module "rtree" and the debugging/analysis scalar 
163390: ** function "rtreenode".
163391: */
163392: SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
163393:   const int utf8 = SQLITE_UTF8;
163394:   int rc;
163395: 
163396:   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
163397:   if( rc==SQLITE_OK ){
163398:     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
163399:   }
163400:   if( rc==SQLITE_OK ){
163401: #ifdef SQLITE_RTREE_INT_ONLY
163402:     void *c = (void *)RTREE_COORD_INT32;
163403: #else
163404:     void *c = (void *)RTREE_COORD_REAL32;
163405: #endif
163406:     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
163407:   }
163408:   if( rc==SQLITE_OK ){
163409:     void *c = (void *)RTREE_COORD_INT32;
163410:     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
163411:   }
163412: 
163413:   return rc;
163414: }
163415: 
163416: /*
163417: ** This routine deletes the RtreeGeomCallback object that was attached
163418: ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
163419: ** or sqlite3_rtree_query_callback().  In other words, this routine is the
163420: ** destructor for an RtreeGeomCallback objecct.  This routine is called when
163421: ** the corresponding SQL function is deleted.
163422: */
163423: static void rtreeFreeCallback(void *p){
163424:   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
163425:   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
163426:   sqlite3_free(p);
163427: }
163428: 
163429: /*
163430: ** This routine frees the BLOB that is returned by geomCallback().
163431: */
163432: static void rtreeMatchArgFree(void *pArg){
163433:   int i;
163434:   RtreeMatchArg *p = (RtreeMatchArg*)pArg;
163435:   for(i=0; i<p->nParam; i++){
163436:     sqlite3_value_free(p->apSqlParam[i]);
163437:   }
163438:   sqlite3_free(p);
163439: }
163440: 
163441: /*
163442: ** Each call to sqlite3_rtree_geometry_callback() or
163443: ** sqlite3_rtree_query_callback() creates an ordinary SQLite
163444: ** scalar function that is implemented by this routine.
163445: **
163446: ** All this function does is construct an RtreeMatchArg object that
163447: ** contains the geometry-checking callback routines and a list of
163448: ** parameters to this function, then return that RtreeMatchArg object
163449: ** as a BLOB.
163450: **
163451: ** The R-Tree MATCH operator will read the returned BLOB, deserialize
163452: ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
163453: ** out which elements of the R-Tree should be returned by the query.
163454: */
163455: static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
163456:   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
163457:   RtreeMatchArg *pBlob;
163458:   int nBlob;
163459:   int memErr = 0;
163460: 
163461:   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
163462:            + nArg*sizeof(sqlite3_value*);
163463:   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
163464:   if( !pBlob ){
163465:     sqlite3_result_error_nomem(ctx);
163466:   }else{
163467:     int i;
163468:     pBlob->magic = RTREE_GEOMETRY_MAGIC;
163469:     pBlob->cb = pGeomCtx[0];
163470:     pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
163471:     pBlob->nParam = nArg;
163472:     for(i=0; i<nArg; i++){
163473:       pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
163474:       if( pBlob->apSqlParam[i]==0 ) memErr = 1;
163475: #ifdef SQLITE_RTREE_INT_ONLY
163476:       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
163477: #else
163478:       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
163479: #endif
163480:     }
163481:     if( memErr ){
163482:       sqlite3_result_error_nomem(ctx);
163483:       rtreeMatchArgFree(pBlob);
163484:     }else{
163485:       sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
163486:     }
163487:   }
163488: }
163489: 
163490: /*
163491: ** Register a new geometry function for use with the r-tree MATCH operator.
163492: */
163493: SQLITE_API int sqlite3_rtree_geometry_callback(
163494:   sqlite3 *db,                  /* Register SQL function on this connection */
163495:   const char *zGeom,            /* Name of the new SQL function */
163496:   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
163497:   void *pContext                /* Extra data associated with the callback */
163498: ){
163499:   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
163500: 
163501:   /* Allocate and populate the context object. */
163502:   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
163503:   if( !pGeomCtx ) return SQLITE_NOMEM;
163504:   pGeomCtx->xGeom = xGeom;
163505:   pGeomCtx->xQueryFunc = 0;
163506:   pGeomCtx->xDestructor = 0;
163507:   pGeomCtx->pContext = pContext;
163508:   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
163509:       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
163510:   );
163511: }
163512: 
163513: /*
163514: ** Register a new 2nd-generation geometry function for use with the
163515: ** r-tree MATCH operator.
163516: */
163517: SQLITE_API int sqlite3_rtree_query_callback(
163518:   sqlite3 *db,                 /* Register SQL function on this connection */
163519:   const char *zQueryFunc,      /* Name of new SQL function */
163520:   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
163521:   void *pContext,              /* Extra data passed into the callback */
163522:   void (*xDestructor)(void*)   /* Destructor for the extra data */
163523: ){
163524:   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
163525: 
163526:   /* Allocate and populate the context object. */
163527:   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
163528:   if( !pGeomCtx ) return SQLITE_NOMEM;
163529:   pGeomCtx->xGeom = 0;
163530:   pGeomCtx->xQueryFunc = xQueryFunc;
163531:   pGeomCtx->xDestructor = xDestructor;
163532:   pGeomCtx->pContext = pContext;
163533:   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, 
163534:       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
163535:   );
163536: }
163537: 
163538: #if !SQLITE_CORE
163539: #ifdef _WIN32
163540: __declspec(dllexport)
163541: #endif
163542: SQLITE_API int sqlite3_rtree_init(
163543:   sqlite3 *db,
163544:   char **pzErrMsg,
163545:   const sqlite3_api_routines *pApi
163546: ){
163547:   SQLITE_EXTENSION_INIT2(pApi)
163548:   return sqlite3RtreeInit(db);
163549: }
163550: #endif
163551: 
163552: #endif
163553: 
163554: /************** End of rtree.c ***********************************************/
163555: /************** Begin file icu.c *********************************************/
163556: /*
163557: ** 2007 May 6
163558: **
163559: ** The author disclaims copyright to this source code.  In place of
163560: ** a legal notice, here is a blessing:
163561: **
163562: **    May you do good and not evil.
163563: **    May you find forgiveness for yourself and forgive others.
163564: **    May you share freely, never taking more than you give.
163565: **
163566: *************************************************************************
163567: ** $Id: sqlite3.c,v 1.6 2017/02/13 16:52:48 misho Exp $
163568: **
163569: ** This file implements an integration between the ICU library 
163570: ** ("International Components for Unicode", an open-source library 
163571: ** for handling unicode data) and SQLite. The integration uses 
163572: ** ICU to provide the following to SQLite:
163573: **
163574: **   * An implementation of the SQL regexp() function (and hence REGEXP
163575: **     operator) using the ICU uregex_XX() APIs.
163576: **
163577: **   * Implementations of the SQL scalar upper() and lower() functions
163578: **     for case mapping.
163579: **
163580: **   * Integration of ICU and SQLite collation sequences.
163581: **
163582: **   * An implementation of the LIKE operator that uses ICU to 
163583: **     provide case-independent matching.
163584: */
163585: 
163586: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
163587: 
163588: /* Include ICU headers */
163589: #include <unicode/utypes.h>
163590: #include <unicode/uregex.h>
163591: #include <unicode/ustring.h>
163592: #include <unicode/ucol.h>
163593: 
163594: /* #include <assert.h> */
163595: 
163596: #ifndef SQLITE_CORE
163597: /*   #include "sqlite3ext.h" */
163598:   SQLITE_EXTENSION_INIT1
163599: #else
163600: /*   #include "sqlite3.h" */
163601: #endif
163602: 
163603: /*
163604: ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
163605: ** operator.
163606: */
163607: #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
163608: # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
163609: #endif
163610: 
163611: /*
163612: ** Version of sqlite3_free() that is always a function, never a macro.
163613: */
163614: static void xFree(void *p){
163615:   sqlite3_free(p);
163616: }
163617: 
163618: /*
163619: ** This lookup table is used to help decode the first byte of
163620: ** a multi-byte UTF8 character. It is copied here from SQLite source
163621: ** code file utf8.c.
163622: */
163623: static const unsigned char icuUtf8Trans1[] = {
163624:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163625:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
163626:   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
163627:   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
163628:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163629:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
163630:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
163631:   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
163632: };
163633: 
163634: #define SQLITE_ICU_READ_UTF8(zIn, c)                       \
163635:   c = *(zIn++);                                            \
163636:   if( c>=0xc0 ){                                           \
163637:     c = icuUtf8Trans1[c-0xc0];                             \
163638:     while( (*zIn & 0xc0)==0x80 ){                          \
163639:       c = (c<<6) + (0x3f & *(zIn++));                      \
163640:     }                                                      \
163641:   }
163642: 
163643: #define SQLITE_ICU_SKIP_UTF8(zIn)                          \
163644:   assert( *zIn );                                          \
163645:   if( *(zIn++)>=0xc0 ){                                    \
163646:     while( (*zIn & 0xc0)==0x80 ){zIn++;}                   \
163647:   }
163648: 
163649: 
163650: /*
163651: ** Compare two UTF-8 strings for equality where the first string is
163652: ** a "LIKE" expression. Return true (1) if they are the same and 
163653: ** false (0) if they are different.
163654: */
163655: static int icuLikeCompare(
163656:   const uint8_t *zPattern,   /* LIKE pattern */
163657:   const uint8_t *zString,    /* The UTF-8 string to compare against */
163658:   const UChar32 uEsc         /* The escape character */
163659: ){
163660:   static const int MATCH_ONE = (UChar32)'_';
163661:   static const int MATCH_ALL = (UChar32)'%';
163662: 
163663:   int prevEscape = 0;     /* True if the previous character was uEsc */
163664: 
163665:   while( 1 ){
163666: 
163667:     /* Read (and consume) the next character from the input pattern. */
163668:     UChar32 uPattern;
163669:     SQLITE_ICU_READ_UTF8(zPattern, uPattern);
163670:     if( uPattern==0 ) break;
163671: 
163672:     /* There are now 4 possibilities:
163673:     **
163674:     **     1. uPattern is an unescaped match-all character "%",
163675:     **     2. uPattern is an unescaped match-one character "_",
163676:     **     3. uPattern is an unescaped escape character, or
163677:     **     4. uPattern is to be handled as an ordinary character
163678:     */
163679:     if( !prevEscape && uPattern==MATCH_ALL ){
163680:       /* Case 1. */
163681:       uint8_t c;
163682: 
163683:       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
163684:       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
163685:       ** test string.
163686:       */
163687:       while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
163688:         if( c==MATCH_ONE ){
163689:           if( *zString==0 ) return 0;
163690:           SQLITE_ICU_SKIP_UTF8(zString);
163691:         }
163692:         zPattern++;
163693:       }
163694: 
163695:       if( *zPattern==0 ) return 1;
163696: 
163697:       while( *zString ){
163698:         if( icuLikeCompare(zPattern, zString, uEsc) ){
163699:           return 1;
163700:         }
163701:         SQLITE_ICU_SKIP_UTF8(zString);
163702:       }
163703:       return 0;
163704: 
163705:     }else if( !prevEscape && uPattern==MATCH_ONE ){
163706:       /* Case 2. */
163707:       if( *zString==0 ) return 0;
163708:       SQLITE_ICU_SKIP_UTF8(zString);
163709: 
163710:     }else if( !prevEscape && uPattern==uEsc){
163711:       /* Case 3. */
163712:       prevEscape = 1;
163713: 
163714:     }else{
163715:       /* Case 4. */
163716:       UChar32 uString;
163717:       SQLITE_ICU_READ_UTF8(zString, uString);
163718:       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
163719:       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
163720:       if( uString!=uPattern ){
163721:         return 0;
163722:       }
163723:       prevEscape = 0;
163724:     }
163725:   }
163726: 
163727:   return *zString==0;
163728: }
163729: 
163730: /*
163731: ** Implementation of the like() SQL function.  This function implements
163732: ** the build-in LIKE operator.  The first argument to the function is the
163733: ** pattern and the second argument is the string.  So, the SQL statements:
163734: **
163735: **       A LIKE B
163736: **
163737: ** is implemented as like(B, A). If there is an escape character E, 
163738: **
163739: **       A LIKE B ESCAPE E
163740: **
163741: ** is mapped to like(B, A, E).
163742: */
163743: static void icuLikeFunc(
163744:   sqlite3_context *context, 
163745:   int argc, 
163746:   sqlite3_value **argv
163747: ){
163748:   const unsigned char *zA = sqlite3_value_text(argv[0]);
163749:   const unsigned char *zB = sqlite3_value_text(argv[1]);
163750:   UChar32 uEsc = 0;
163751: 
163752:   /* Limit the length of the LIKE or GLOB pattern to avoid problems
163753:   ** of deep recursion and N*N behavior in patternCompare().
163754:   */
163755:   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
163756:     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
163757:     return;
163758:   }
163759: 
163760: 
163761:   if( argc==3 ){
163762:     /* The escape character string must consist of a single UTF-8 character.
163763:     ** Otherwise, return an error.
163764:     */
163765:     int nE= sqlite3_value_bytes(argv[2]);
163766:     const unsigned char *zE = sqlite3_value_text(argv[2]);
163767:     int i = 0;
163768:     if( zE==0 ) return;
163769:     U8_NEXT(zE, i, nE, uEsc);
163770:     if( i!=nE){
163771:       sqlite3_result_error(context, 
163772:           "ESCAPE expression must be a single character", -1);
163773:       return;
163774:     }
163775:   }
163776: 
163777:   if( zA && zB ){
163778:     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
163779:   }
163780: }
163781: 
163782: /*
163783: ** This function is called when an ICU function called from within
163784: ** the implementation of an SQL scalar function returns an error.
163785: **
163786: ** The scalar function context passed as the first argument is 
163787: ** loaded with an error message based on the following two args.
163788: */
163789: static void icuFunctionError(
163790:   sqlite3_context *pCtx,       /* SQLite scalar function context */
163791:   const char *zName,           /* Name of ICU function that failed */
163792:   UErrorCode e                 /* Error code returned by ICU function */
163793: ){
163794:   char zBuf[128];
163795:   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
163796:   zBuf[127] = '\0';
163797:   sqlite3_result_error(pCtx, zBuf, -1);
163798: }
163799: 
163800: /*
163801: ** Function to delete compiled regexp objects. Registered as
163802: ** a destructor function with sqlite3_set_auxdata().
163803: */
163804: static void icuRegexpDelete(void *p){
163805:   URegularExpression *pExpr = (URegularExpression *)p;
163806:   uregex_close(pExpr);
163807: }
163808: 
163809: /*
163810: ** Implementation of SQLite REGEXP operator. This scalar function takes
163811: ** two arguments. The first is a regular expression pattern to compile
163812: ** the second is a string to match against that pattern. If either 
163813: ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
163814: ** is 1 if the string matches the pattern, or 0 otherwise.
163815: **
163816: ** SQLite maps the regexp() function to the regexp() operator such
163817: ** that the following two are equivalent:
163818: **
163819: **     zString REGEXP zPattern
163820: **     regexp(zPattern, zString)
163821: **
163822: ** Uses the following ICU regexp APIs:
163823: **
163824: **     uregex_open()
163825: **     uregex_matches()
163826: **     uregex_close()
163827: */
163828: static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
163829:   UErrorCode status = U_ZERO_ERROR;
163830:   URegularExpression *pExpr;
163831:   UBool res;
163832:   const UChar *zString = sqlite3_value_text16(apArg[1]);
163833: 
163834:   (void)nArg;  /* Unused parameter */
163835: 
163836:   /* If the left hand side of the regexp operator is NULL, 
163837:   ** then the result is also NULL. 
163838:   */
163839:   if( !zString ){
163840:     return;
163841:   }
163842: 
163843:   pExpr = sqlite3_get_auxdata(p, 0);
163844:   if( !pExpr ){
163845:     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
163846:     if( !zPattern ){
163847:       return;
163848:     }
163849:     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
163850: 
163851:     if( U_SUCCESS(status) ){
163852:       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
163853:     }else{
163854:       assert(!pExpr);
163855:       icuFunctionError(p, "uregex_open", status);
163856:       return;
163857:     }
163858:   }
163859: 
163860:   /* Configure the text that the regular expression operates on. */
163861:   uregex_setText(pExpr, zString, -1, &status);
163862:   if( !U_SUCCESS(status) ){
163863:     icuFunctionError(p, "uregex_setText", status);
163864:     return;
163865:   }
163866: 
163867:   /* Attempt the match */
163868:   res = uregex_matches(pExpr, 0, &status);
163869:   if( !U_SUCCESS(status) ){
163870:     icuFunctionError(p, "uregex_matches", status);
163871:     return;
163872:   }
163873: 
163874:   /* Set the text that the regular expression operates on to a NULL
163875:   ** pointer. This is not really necessary, but it is tidier than 
163876:   ** leaving the regular expression object configured with an invalid
163877:   ** pointer after this function returns.
163878:   */
163879:   uregex_setText(pExpr, 0, 0, &status);
163880: 
163881:   /* Return 1 or 0. */
163882:   sqlite3_result_int(p, res ? 1 : 0);
163883: }
163884: 
163885: /*
163886: ** Implementations of scalar functions for case mapping - upper() and 
163887: ** lower(). Function upper() converts its input to upper-case (ABC).
163888: ** Function lower() converts to lower-case (abc).
163889: **
163890: ** ICU provides two types of case mapping, "general" case mapping and
163891: ** "language specific". Refer to ICU documentation for the differences
163892: ** between the two.
163893: **
163894: ** To utilise "general" case mapping, the upper() or lower() scalar 
163895: ** functions are invoked with one argument:
163896: **
163897: **     upper('ABC') -> 'abc'
163898: **     lower('abc') -> 'ABC'
163899: **
163900: ** To access ICU "language specific" case mapping, upper() or lower()
163901: ** should be invoked with two arguments. The second argument is the name
163902: ** of the locale to use. Passing an empty string ("") or SQL NULL value
163903: ** as the second argument is the same as invoking the 1 argument version
163904: ** of upper() or lower().
163905: **
163906: **     lower('I', 'en_us') -> 'i'
163907: **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
163908: **
163909: ** http://www.icu-project.org/userguide/posix.html#case_mappings
163910: */
163911: static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
163912:   const UChar *zInput;            /* Pointer to input string */
163913:   UChar *zOutput = 0;             /* Pointer to output buffer */
163914:   int nInput;                     /* Size of utf-16 input string in bytes */
163915:   int nOut;                       /* Size of output buffer in bytes */
163916:   int cnt;
163917:   int bToUpper;                   /* True for toupper(), false for tolower() */
163918:   UErrorCode status;
163919:   const char *zLocale = 0;
163920: 
163921:   assert(nArg==1 || nArg==2);
163922:   bToUpper = (sqlite3_user_data(p)!=0);
163923:   if( nArg==2 ){
163924:     zLocale = (const char *)sqlite3_value_text(apArg[1]);
163925:   }
163926: 
163927:   zInput = sqlite3_value_text16(apArg[0]);
163928:   if( !zInput ){
163929:     return;
163930:   }
163931:   nOut = nInput = sqlite3_value_bytes16(apArg[0]);
163932:   if( nOut==0 ){
163933:     sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
163934:     return;
163935:   }
163936: 
163937:   for(cnt=0; cnt<2; cnt++){
163938:     UChar *zNew = sqlite3_realloc(zOutput, nOut);
163939:     if( zNew==0 ){
163940:       sqlite3_free(zOutput);
163941:       sqlite3_result_error_nomem(p);
163942:       return;
163943:     }
163944:     zOutput = zNew;
163945:     status = U_ZERO_ERROR;
163946:     if( bToUpper ){
163947:       nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
163948:     }else{
163949:       nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
163950:     }
163951: 
163952:     if( U_SUCCESS(status) ){
163953:       sqlite3_result_text16(p, zOutput, nOut, xFree);
163954:     }else if( status==U_BUFFER_OVERFLOW_ERROR ){
163955:       assert( cnt==0 );
163956:       continue;
163957:     }else{
163958:       icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
163959:     }
163960:     return;
163961:   }
163962:   assert( 0 );     /* Unreachable */
163963: }
163964: 
163965: /*
163966: ** Collation sequence destructor function. The pCtx argument points to
163967: ** a UCollator structure previously allocated using ucol_open().
163968: */
163969: static void icuCollationDel(void *pCtx){
163970:   UCollator *p = (UCollator *)pCtx;
163971:   ucol_close(p);
163972: }
163973: 
163974: /*
163975: ** Collation sequence comparison function. The pCtx argument points to
163976: ** a UCollator structure previously allocated using ucol_open().
163977: */
163978: static int icuCollationColl(
163979:   void *pCtx,
163980:   int nLeft,
163981:   const void *zLeft,
163982:   int nRight,
163983:   const void *zRight
163984: ){
163985:   UCollationResult res;
163986:   UCollator *p = (UCollator *)pCtx;
163987:   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
163988:   switch( res ){
163989:     case UCOL_LESS:    return -1;
163990:     case UCOL_GREATER: return +1;
163991:     case UCOL_EQUAL:   return 0;
163992:   }
163993:   assert(!"Unexpected return value from ucol_strcoll()");
163994:   return 0;
163995: }
163996: 
163997: /*
163998: ** Implementation of the scalar function icu_load_collation().
163999: **
164000: ** This scalar function is used to add ICU collation based collation 
164001: ** types to an SQLite database connection. It is intended to be called
164002: ** as follows:
164003: **
164004: **     SELECT icu_load_collation(<locale>, <collation-name>);
164005: **
164006: ** Where <locale> is a string containing an ICU locale identifier (i.e.
164007: ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
164008: ** collation sequence to create.
164009: */
164010: static void icuLoadCollation(
164011:   sqlite3_context *p, 
164012:   int nArg, 
164013:   sqlite3_value **apArg
164014: ){
164015:   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
164016:   UErrorCode status = U_ZERO_ERROR;
164017:   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
164018:   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
164019:   UCollator *pUCollator;    /* ICU library collation object */
164020:   int rc;                   /* Return code from sqlite3_create_collation_x() */
164021: 
164022:   assert(nArg==2);
164023:   (void)nArg; /* Unused parameter */
164024:   zLocale = (const char *)sqlite3_value_text(apArg[0]);
164025:   zName = (const char *)sqlite3_value_text(apArg[1]);
164026: 
164027:   if( !zLocale || !zName ){
164028:     return;
164029:   }
164030: 
164031:   pUCollator = ucol_open(zLocale, &status);
164032:   if( !U_SUCCESS(status) ){
164033:     icuFunctionError(p, "ucol_open", status);
164034:     return;
164035:   }
164036:   assert(p);
164037: 
164038:   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
164039:       icuCollationColl, icuCollationDel
164040:   );
164041:   if( rc!=SQLITE_OK ){
164042:     ucol_close(pUCollator);
164043:     sqlite3_result_error(p, "Error registering collation function", -1);
164044:   }
164045: }
164046: 
164047: /*
164048: ** Register the ICU extension functions with database db.
164049: */
164050: SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
164051:   struct IcuScalar {
164052:     const char *zName;                        /* Function name */
164053:     int nArg;                                 /* Number of arguments */
164054:     int enc;                                  /* Optimal text encoding */
164055:     void *pContext;                           /* sqlite3_user_data() context */
164056:     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
164057:   } scalars[] = {
164058:     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
164059: 
164060:     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
164061:     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
164062:     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
164063:     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
164064: 
164065:     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
164066:     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
164067:     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
164068:     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
164069: 
164070:     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
164071:     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
164072: 
164073:     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
164074:   };
164075: 
164076:   int rc = SQLITE_OK;
164077:   int i;
164078: 
164079:   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
164080:     struct IcuScalar *p = &scalars[i];
164081:     rc = sqlite3_create_function(
164082:         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
164083:     );
164084:   }
164085: 
164086:   return rc;
164087: }
164088: 
164089: #if !SQLITE_CORE
164090: #ifdef _WIN32
164091: __declspec(dllexport)
164092: #endif
164093: SQLITE_API int sqlite3_icu_init(
164094:   sqlite3 *db, 
164095:   char **pzErrMsg,
164096:   const sqlite3_api_routines *pApi
164097: ){
164098:   SQLITE_EXTENSION_INIT2(pApi)
164099:   return sqlite3IcuInit(db);
164100: }
164101: #endif
164102: 
164103: #endif
164104: 
164105: /************** End of icu.c *************************************************/
164106: /************** Begin file fts3_icu.c ****************************************/
164107: /*
164108: ** 2007 June 22
164109: **
164110: ** The author disclaims copyright to this source code.  In place of
164111: ** a legal notice, here is a blessing:
164112: **
164113: **    May you do good and not evil.
164114: **    May you find forgiveness for yourself and forgive others.
164115: **    May you share freely, never taking more than you give.
164116: **
164117: *************************************************************************
164118: ** This file implements a tokenizer for fts3 based on the ICU library.
164119: */
164120: /* #include "fts3Int.h" */
164121: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
164122: #ifdef SQLITE_ENABLE_ICU
164123: 
164124: /* #include <assert.h> */
164125: /* #include <string.h> */
164126: /* #include "fts3_tokenizer.h" */
164127: 
164128: #include <unicode/ubrk.h>
164129: /* #include <unicode/ucol.h> */
164130: /* #include <unicode/ustring.h> */
164131: #include <unicode/utf16.h>
164132: 
164133: typedef struct IcuTokenizer IcuTokenizer;
164134: typedef struct IcuCursor IcuCursor;
164135: 
164136: struct IcuTokenizer {
164137:   sqlite3_tokenizer base;
164138:   char *zLocale;
164139: };
164140: 
164141: struct IcuCursor {
164142:   sqlite3_tokenizer_cursor base;
164143: 
164144:   UBreakIterator *pIter;      /* ICU break-iterator object */
164145:   int nChar;                  /* Number of UChar elements in pInput */
164146:   UChar *aChar;               /* Copy of input using utf-16 encoding */
164147:   int *aOffset;               /* Offsets of each character in utf-8 input */
164148: 
164149:   int nBuffer;
164150:   char *zBuffer;
164151: 
164152:   int iToken;
164153: };
164154: 
164155: /*
164156: ** Create a new tokenizer instance.
164157: */
164158: static int icuCreate(
164159:   int argc,                            /* Number of entries in argv[] */
164160:   const char * const *argv,            /* Tokenizer creation arguments */
164161:   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
164162: ){
164163:   IcuTokenizer *p;
164164:   int n = 0;
164165: 
164166:   if( argc>0 ){
164167:     n = strlen(argv[0])+1;
164168:   }
164169:   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
164170:   if( !p ){
164171:     return SQLITE_NOMEM;
164172:   }
164173:   memset(p, 0, sizeof(IcuTokenizer));
164174: 
164175:   if( n ){
164176:     p->zLocale = (char *)&p[1];
164177:     memcpy(p->zLocale, argv[0], n);
164178:   }
164179: 
164180:   *ppTokenizer = (sqlite3_tokenizer *)p;
164181: 
164182:   return SQLITE_OK;
164183: }
164184: 
164185: /*
164186: ** Destroy a tokenizer
164187: */
164188: static int icuDestroy(sqlite3_tokenizer *pTokenizer){
164189:   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
164190:   sqlite3_free(p);
164191:   return SQLITE_OK;
164192: }
164193: 
164194: /*
164195: ** Prepare to begin tokenizing a particular string.  The input
164196: ** string to be tokenized is pInput[0..nBytes-1].  A cursor
164197: ** used to incrementally tokenize this string is returned in 
164198: ** *ppCursor.
164199: */
164200: static int icuOpen(
164201:   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
164202:   const char *zInput,                    /* Input string */
164203:   int nInput,                            /* Length of zInput in bytes */
164204:   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
164205: ){
164206:   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
164207:   IcuCursor *pCsr;
164208: 
164209:   const int32_t opt = U_FOLD_CASE_DEFAULT;
164210:   UErrorCode status = U_ZERO_ERROR;
164211:   int nChar;
164212: 
164213:   UChar32 c;
164214:   int iInput = 0;
164215:   int iOut = 0;
164216: 
164217:   *ppCursor = 0;
164218: 
164219:   if( zInput==0 ){
164220:     nInput = 0;
164221:     zInput = "";
164222:   }else if( nInput<0 ){
164223:     nInput = strlen(zInput);
164224:   }
164225:   nChar = nInput+1;
164226:   pCsr = (IcuCursor *)sqlite3_malloc(
164227:       sizeof(IcuCursor) +                /* IcuCursor */
164228:       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
164229:       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
164230:   );
164231:   if( !pCsr ){
164232:     return SQLITE_NOMEM;
164233:   }
164234:   memset(pCsr, 0, sizeof(IcuCursor));
164235:   pCsr->aChar = (UChar *)&pCsr[1];
164236:   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
164237: 
164238:   pCsr->aOffset[iOut] = iInput;
164239:   U8_NEXT(zInput, iInput, nInput, c); 
164240:   while( c>0 ){
164241:     int isError = 0;
164242:     c = u_foldCase(c, opt);
164243:     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
164244:     if( isError ){
164245:       sqlite3_free(pCsr);
164246:       return SQLITE_ERROR;
164247:     }
164248:     pCsr->aOffset[iOut] = iInput;
164249: 
164250:     if( iInput<nInput ){
164251:       U8_NEXT(zInput, iInput, nInput, c);
164252:     }else{
164253:       c = 0;
164254:     }
164255:   }
164256: 
164257:   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
164258:   if( !U_SUCCESS(status) ){
164259:     sqlite3_free(pCsr);
164260:     return SQLITE_ERROR;
164261:   }
164262:   pCsr->nChar = iOut;
164263: 
164264:   ubrk_first(pCsr->pIter);
164265:   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
164266:   return SQLITE_OK;
164267: }
164268: 
164269: /*
164270: ** Close a tokenization cursor previously opened by a call to icuOpen().
164271: */
164272: static int icuClose(sqlite3_tokenizer_cursor *pCursor){
164273:   IcuCursor *pCsr = (IcuCursor *)pCursor;
164274:   ubrk_close(pCsr->pIter);
164275:   sqlite3_free(pCsr->zBuffer);
164276:   sqlite3_free(pCsr);
164277:   return SQLITE_OK;
164278: }
164279: 
164280: /*
164281: ** Extract the next token from a tokenization cursor.
164282: */
164283: static int icuNext(
164284:   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
164285:   const char **ppToken,               /* OUT: *ppToken is the token text */
164286:   int *pnBytes,                       /* OUT: Number of bytes in token */
164287:   int *piStartOffset,                 /* OUT: Starting offset of token */
164288:   int *piEndOffset,                   /* OUT: Ending offset of token */
164289:   int *piPosition                     /* OUT: Position integer of token */
164290: ){
164291:   IcuCursor *pCsr = (IcuCursor *)pCursor;
164292: 
164293:   int iStart = 0;
164294:   int iEnd = 0;
164295:   int nByte = 0;
164296: 
164297:   while( iStart==iEnd ){
164298:     UChar32 c;
164299: 
164300:     iStart = ubrk_current(pCsr->pIter);
164301:     iEnd = ubrk_next(pCsr->pIter);
164302:     if( iEnd==UBRK_DONE ){
164303:       return SQLITE_DONE;
164304:     }
164305: 
164306:     while( iStart<iEnd ){
164307:       int iWhite = iStart;
164308:       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
164309:       if( u_isspace(c) ){
164310:         iStart = iWhite;
164311:       }else{
164312:         break;
164313:       }
164314:     }
164315:     assert(iStart<=iEnd);
164316:   }
164317: 
164318:   do {
164319:     UErrorCode status = U_ZERO_ERROR;
164320:     if( nByte ){
164321:       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
164322:       if( !zNew ){
164323:         return SQLITE_NOMEM;
164324:       }
164325:       pCsr->zBuffer = zNew;
164326:       pCsr->nBuffer = nByte;
164327:     }
164328: 
164329:     u_strToUTF8(
164330:         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
164331:         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
164332:         &status                                  /* Output success/failure */
164333:     );
164334:   } while( nByte>pCsr->nBuffer );
164335: 
164336:   *ppToken = pCsr->zBuffer;
164337:   *pnBytes = nByte;
164338:   *piStartOffset = pCsr->aOffset[iStart];
164339:   *piEndOffset = pCsr->aOffset[iEnd];
164340:   *piPosition = pCsr->iToken++;
164341: 
164342:   return SQLITE_OK;
164343: }
164344: 
164345: /*
164346: ** The set of routines that implement the simple tokenizer
164347: */
164348: static const sqlite3_tokenizer_module icuTokenizerModule = {
164349:   0,                           /* iVersion    */
164350:   icuCreate,                   /* xCreate     */
164351:   icuDestroy,                  /* xCreate     */
164352:   icuOpen,                     /* xOpen       */
164353:   icuClose,                    /* xClose      */
164354:   icuNext,                     /* xNext       */
164355:   0,                           /* xLanguageid */
164356: };
164357: 
164358: /*
164359: ** Set *ppModule to point at the implementation of the ICU tokenizer.
164360: */
164361: SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
164362:   sqlite3_tokenizer_module const**ppModule
164363: ){
164364:   *ppModule = &icuTokenizerModule;
164365: }
164366: 
164367: #endif /* defined(SQLITE_ENABLE_ICU) */
164368: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
164369: 
164370: /************** End of fts3_icu.c ********************************************/
164371: /************** Begin file sqlite3rbu.c **************************************/
164372: /*
164373: ** 2014 August 30
164374: **
164375: ** The author disclaims copyright to this source code.  In place of
164376: ** a legal notice, here is a blessing:
164377: **
164378: **    May you do good and not evil.
164379: **    May you find forgiveness for yourself and forgive others.
164380: **    May you share freely, never taking more than you give.
164381: **
164382: *************************************************************************
164383: **
164384: **
164385: ** OVERVIEW 
164386: **
164387: **  The RBU extension requires that the RBU update be packaged as an
164388: **  SQLite database. The tables it expects to find are described in
164389: **  sqlite3rbu.h.  Essentially, for each table xyz in the target database
164390: **  that the user wishes to write to, a corresponding data_xyz table is
164391: **  created in the RBU database and populated with one row for each row to
164392: **  update, insert or delete from the target table.
164393: ** 
164394: **  The update proceeds in three stages:
164395: ** 
164396: **  1) The database is updated. The modified database pages are written
164397: **     to a *-oal file. A *-oal file is just like a *-wal file, except
164398: **     that it is named "<database>-oal" instead of "<database>-wal".
164399: **     Because regular SQLite clients do not look for file named
164400: **     "<database>-oal", they go on using the original database in
164401: **     rollback mode while the *-oal file is being generated.
164402: ** 
164403: **     During this stage RBU does not update the database by writing
164404: **     directly to the target tables. Instead it creates "imposter"
164405: **     tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
164406: **     to update each b-tree individually. All updates required by each
164407: **     b-tree are completed before moving on to the next, and all
164408: **     updates are done in sorted key order.
164409: ** 
164410: **  2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
164411: **     location using a call to rename(2). Before doing this the RBU
164412: **     module takes an EXCLUSIVE lock on the database file, ensuring
164413: **     that there are no other active readers.
164414: ** 
164415: **     Once the EXCLUSIVE lock is released, any other database readers
164416: **     detect the new *-wal file and read the database in wal mode. At
164417: **     this point they see the new version of the database - including
164418: **     the updates made as part of the RBU update.
164419: ** 
164420: **  3) The new *-wal file is checkpointed. This proceeds in the same way 
164421: **     as a regular database checkpoint, except that a single frame is
164422: **     checkpointed each time sqlite3rbu_step() is called. If the RBU
164423: **     handle is closed before the entire *-wal file is checkpointed,
164424: **     the checkpoint progress is saved in the RBU database and the
164425: **     checkpoint can be resumed by another RBU client at some point in
164426: **     the future.
164427: **
164428: ** POTENTIAL PROBLEMS
164429: ** 
164430: **  The rename() call might not be portable. And RBU is not currently
164431: **  syncing the directory after renaming the file.
164432: **
164433: **  When state is saved, any commit to the *-oal file and the commit to
164434: **  the RBU update database are not atomic. So if the power fails at the
164435: **  wrong moment they might get out of sync. As the main database will be
164436: **  committed before the RBU update database this will likely either just
164437: **  pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
164438: **  constraint violations).
164439: **
164440: **  If some client does modify the target database mid RBU update, or some
164441: **  other error occurs, the RBU extension will keep throwing errors. It's
164442: **  not really clear how to get out of this state. The system could just
164443: **  by delete the RBU update database and *-oal file and have the device
164444: **  download the update again and start over.
164445: **
164446: **  At present, for an UPDATE, both the new.* and old.* records are
164447: **  collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
164448: **  fields are collected.  This means we're probably writing a lot more
164449: **  data to disk when saving the state of an ongoing update to the RBU
164450: **  update database than is strictly necessary.
164451: ** 
164452: */
164453: 
164454: /* #include <assert.h> */
164455: /* #include <string.h> */
164456: /* #include <stdio.h> */
164457: 
164458: /* #include "sqlite3.h" */
164459: 
164460: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
164461: /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
164462: /************** Begin file sqlite3rbu.h **************************************/
164463: /*
164464: ** 2014 August 30
164465: **
164466: ** The author disclaims copyright to this source code.  In place of
164467: ** a legal notice, here is a blessing:
164468: **
164469: **    May you do good and not evil.
164470: **    May you find forgiveness for yourself and forgive others.
164471: **    May you share freely, never taking more than you give.
164472: **
164473: *************************************************************************
164474: **
164475: ** This file contains the public interface for the RBU extension. 
164476: */
164477: 
164478: /*
164479: ** SUMMARY
164480: **
164481: ** Writing a transaction containing a large number of operations on 
164482: ** b-tree indexes that are collectively larger than the available cache
164483: ** memory can be very inefficient. 
164484: **
164485: ** The problem is that in order to update a b-tree, the leaf page (at least)
164486: ** containing the entry being inserted or deleted must be modified. If the
164487: ** working set of leaves is larger than the available cache memory, then a 
164488: ** single leaf that is modified more than once as part of the transaction 
164489: ** may be loaded from or written to the persistent media multiple times.
164490: ** Additionally, because the index updates are likely to be applied in
164491: ** random order, access to pages within the database is also likely to be in 
164492: ** random order, which is itself quite inefficient.
164493: **
164494: ** One way to improve the situation is to sort the operations on each index
164495: ** by index key before applying them to the b-tree. This leads to an IO
164496: ** pattern that resembles a single linear scan through the index b-tree,
164497: ** and all but guarantees each modified leaf page is loaded and stored 
164498: ** exactly once. SQLite uses this trick to improve the performance of
164499: ** CREATE INDEX commands. This extension allows it to be used to improve
164500: ** the performance of large transactions on existing databases.
164501: **
164502: ** Additionally, this extension allows the work involved in writing the 
164503: ** large transaction to be broken down into sub-transactions performed 
164504: ** sequentially by separate processes. This is useful if the system cannot 
164505: ** guarantee that a single update process will run for long enough to apply 
164506: ** the entire update, for example because the update is being applied on a 
164507: ** mobile device that is frequently rebooted. Even after the writer process 
164508: ** has committed one or more sub-transactions, other database clients continue
164509: ** to read from the original database snapshot. In other words, partially 
164510: ** applied transactions are not visible to other clients. 
164511: **
164512: ** "RBU" stands for "Resumable Bulk Update". As in a large database update
164513: ** transmitted via a wireless network to a mobile device. A transaction
164514: ** applied using this extension is hence refered to as an "RBU update".
164515: **
164516: **
164517: ** LIMITATIONS
164518: **
164519: ** An "RBU update" transaction is subject to the following limitations:
164520: **
164521: **   * The transaction must consist of INSERT, UPDATE and DELETE operations
164522: **     only.
164523: **
164524: **   * INSERT statements may not use any default values.
164525: **
164526: **   * UPDATE and DELETE statements must identify their target rows by 
164527: **     non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
164528: **     KEY fields may not be updated or deleted. If the table being written 
164529: **     has no PRIMARY KEY, affected rows must be identified by rowid.
164530: **
164531: **   * UPDATE statements may not modify PRIMARY KEY columns.
164532: **
164533: **   * No triggers will be fired.
164534: **
164535: **   * No foreign key violations are detected or reported.
164536: **
164537: **   * CHECK constraints are not enforced.
164538: **
164539: **   * No constraint handling mode except for "OR ROLLBACK" is supported.
164540: **
164541: **
164542: ** PREPARATION
164543: **
164544: ** An "RBU update" is stored as a separate SQLite database. A database
164545: ** containing an RBU update is an "RBU database". For each table in the 
164546: ** target database to be updated, the RBU database should contain a table
164547: ** named "data_<target name>" containing the same set of columns as the
164548: ** target table, and one more - "rbu_control". The data_% table should 
164549: ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
164550: ** the same type as the corresponding column in the target database.
164551: ** The "rbu_control" column should have no type at all. For example, if
164552: ** the target database contains:
164553: **
164554: **   CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
164555: **
164556: ** Then the RBU database should contain:
164557: **
164558: **   CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
164559: **
164560: ** The order of the columns in the data_% table does not matter.
164561: **
164562: ** Instead of a regular table, the RBU database may also contain virtual
164563: ** tables or view named using the data_<target> naming scheme. 
164564: **
164565: ** Instead of the plain data_<target> naming scheme, RBU database tables 
164566: ** may also be named data<integer>_<target>, where <integer> is any sequence
164567: ** of zero or more numeric characters (0-9). This can be significant because
164568: ** tables within the RBU database are always processed in order sorted by 
164569: ** name. By judicious selection of the the <integer> portion of the names
164570: ** of the RBU tables the user can therefore control the order in which they
164571: ** are processed. This can be useful, for example, to ensure that "external
164572: ** content" FTS4 tables are updated before their underlying content tables.
164573: **
164574: ** If the target database table is a virtual table or a table that has no
164575: ** PRIMARY KEY declaration, the data_% table must also contain a column 
164576: ** named "rbu_rowid". This column is mapped to the tables implicit primary 
164577: ** key column - "rowid". Virtual tables for which the "rowid" column does 
164578: ** not function like a primary key value cannot be updated using RBU. For 
164579: ** example, if the target db contains either of the following:
164580: **
164581: **   CREATE VIRTUAL TABLE x1 USING fts3(a, b);
164582: **   CREATE TABLE x1(a, b)
164583: **
164584: ** then the RBU database should contain:
164585: **
164586: **   CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
164587: **
164588: ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
164589: ** target table must be present in the input table. For virtual tables,
164590: ** hidden columns are optional - they are updated by RBU if present in
164591: ** the input table, or not otherwise. For example, to write to an fts4
164592: ** table with a hidden languageid column such as:
164593: **
164594: **   CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
164595: **
164596: ** Either of the following input table schemas may be used:
164597: **
164598: **   CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
164599: **   CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
164600: **
164601: ** For each row to INSERT into the target database as part of the RBU 
164602: ** update, the corresponding data_% table should contain a single record
164603: ** with the "rbu_control" column set to contain integer value 0. The
164604: ** other columns should be set to the values that make up the new record 
164605: ** to insert. 
164606: **
164607: ** If the target database table has an INTEGER PRIMARY KEY, it is not 
164608: ** possible to insert a NULL value into the IPK column. Attempting to 
164609: ** do so results in an SQLITE_MISMATCH error.
164610: **
164611: ** For each row to DELETE from the target database as part of the RBU 
164612: ** update, the corresponding data_% table should contain a single record
164613: ** with the "rbu_control" column set to contain integer value 1. The
164614: ** real primary key values of the row to delete should be stored in the
164615: ** corresponding columns of the data_% table. The values stored in the
164616: ** other columns are not used.
164617: **
164618: ** For each row to UPDATE from the target database as part of the RBU 
164619: ** update, the corresponding data_% table should contain a single record
164620: ** with the "rbu_control" column set to contain a value of type text.
164621: ** The real primary key values identifying the row to update should be 
164622: ** stored in the corresponding columns of the data_% table row, as should
164623: ** the new values of all columns being update. The text value in the 
164624: ** "rbu_control" column must contain the same number of characters as
164625: ** there are columns in the target database table, and must consist entirely
164626: ** of 'x' and '.' characters (or in some special cases 'd' - see below). For 
164627: ** each column that is being updated, the corresponding character is set to
164628: ** 'x'. For those that remain as they are, the corresponding character of the
164629: ** rbu_control value should be set to '.'. For example, given the tables 
164630: ** above, the update statement:
164631: **
164632: **   UPDATE t1 SET c = 'usa' WHERE a = 4;
164633: **
164634: ** is represented by the data_t1 row created by:
164635: **
164636: **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
164637: **
164638: ** Instead of an 'x' character, characters of the rbu_control value specified
164639: ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
164640: ** target table with the value stored in the corresponding data_% column, the
164641: ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
164642: ** the target table column. rbu_delta() is invoked with two arguments - the
164643: ** original value currently stored in the target table column and the 
164644: ** value specified in the data_xxx table.
164645: **
164646: ** For example, this row:
164647: **
164648: **   INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
164649: **
164650: ** is similar to an UPDATE statement such as: 
164651: **
164652: **   UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
164653: **
164654: ** Finally, if an 'f' character appears in place of a 'd' or 's' in an 
164655: ** ota_control string, the contents of the data_xxx table column is assumed
164656: ** to be a "fossil delta" - a patch to be applied to a blob value in the
164657: ** format used by the fossil source-code management system. In this case
164658: ** the existing value within the target database table must be of type BLOB. 
164659: ** It is replaced by the result of applying the specified fossil delta to
164660: ** itself.
164661: **
164662: ** If the target database table is a virtual table or a table with no PRIMARY
164663: ** KEY, the rbu_control value should not include a character corresponding 
164664: ** to the rbu_rowid value. For example, this:
164665: **
164666: **   INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) 
164667: **       VALUES(NULL, 'usa', 12, '.x');
164668: **
164669: ** causes a result similar to:
164670: **
164671: **   UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
164672: **
164673: ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
164674: ** However, RBU is more efficient if reading the rows in from each data_xxx
164675: ** table in "rowid" order is roughly the same as reading them sorted by
164676: ** the PRIMARY KEY of the corresponding target database table. In other 
164677: ** words, rows should be sorted using the destination table PRIMARY KEY 
164678: ** fields before they are inserted into the data_xxx tables.
164679: **
164680: ** USAGE
164681: **
164682: ** The API declared below allows an application to apply an RBU update 
164683: ** stored on disk to an existing target database. Essentially, the 
164684: ** application:
164685: **
164686: **     1) Opens an RBU handle using the sqlite3rbu_open() function.
164687: **
164688: **     2) Registers any required virtual table modules with the database
164689: **        handle returned by sqlite3rbu_db(). Also, if required, register
164690: **        the rbu_delta() implementation.
164691: **
164692: **     3) Calls the sqlite3rbu_step() function one or more times on
164693: **        the new handle. Each call to sqlite3rbu_step() performs a single
164694: **        b-tree operation, so thousands of calls may be required to apply 
164695: **        a complete update.
164696: **
164697: **     4) Calls sqlite3rbu_close() to close the RBU update handle. If
164698: **        sqlite3rbu_step() has been called enough times to completely
164699: **        apply the update to the target database, then the RBU database
164700: **        is marked as fully applied. Otherwise, the state of the RBU 
164701: **        update application is saved in the RBU database for later 
164702: **        resumption.
164703: **
164704: ** See comments below for more detail on APIs.
164705: **
164706: ** If an update is only partially applied to the target database by the
164707: ** time sqlite3rbu_close() is called, various state information is saved 
164708: ** within the RBU database. This allows subsequent processes to automatically
164709: ** resume the RBU update from where it left off.
164710: **
164711: ** To remove all RBU extension state information, returning an RBU database 
164712: ** to its original contents, it is sufficient to drop all tables that begin
164713: ** with the prefix "rbu_"
164714: **
164715: ** DATABASE LOCKING
164716: **
164717: ** An RBU update may not be applied to a database in WAL mode. Attempting
164718: ** to do so is an error (SQLITE_ERROR).
164719: **
164720: ** While an RBU handle is open, a SHARED lock may be held on the target
164721: ** database file. This means it is possible for other clients to read the
164722: ** database, but not to write it.
164723: **
164724: ** If an RBU update is started and then suspended before it is completed,
164725: ** then an external client writes to the database, then attempting to resume
164726: ** the suspended RBU update is also an error (SQLITE_BUSY).
164727: */
164728: 
164729: #ifndef _SQLITE3RBU_H
164730: #define _SQLITE3RBU_H
164731: 
164732: /* #include "sqlite3.h"              ** Required for error code definitions ** */
164733: 
164734: #if 0
164735: extern "C" {
164736: #endif
164737: 
164738: typedef struct sqlite3rbu sqlite3rbu;
164739: 
164740: /*
164741: ** Open an RBU handle.
164742: **
164743: ** Argument zTarget is the path to the target database. Argument zRbu is
164744: ** the path to the RBU database. Each call to this function must be matched
164745: ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
164746: ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
164747: ** or zRbu begin with "file:", it will be interpreted as an SQLite 
164748: ** database URI, not a regular file name.
164749: **
164750: ** If the zState argument is passed a NULL value, the RBU extension stores 
164751: ** the current state of the update (how many rows have been updated, which 
164752: ** indexes are yet to be updated etc.) within the RBU database itself. This
164753: ** can be convenient, as it means that the RBU application does not need to
164754: ** organize removing a separate state file after the update is concluded. 
164755: ** Or, if zState is non-NULL, it must be a path to a database file in which 
164756: ** the RBU extension can store the state of the update.
164757: **
164758: ** When resuming an RBU update, the zState argument must be passed the same
164759: ** value as when the RBU update was started.
164760: **
164761: ** Once the RBU update is finished, the RBU extension does not 
164762: ** automatically remove any zState database file, even if it created it.
164763: **
164764: ** By default, RBU uses the default VFS to access the files on disk. To
164765: ** use a VFS other than the default, an SQLite "file:" URI containing a
164766: ** "vfs=..." option may be passed as the zTarget option.
164767: **
164768: ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
164769: ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
164770: ** not work out of the box with zipvfs. Refer to the comment describing
164771: ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
164772: */
164773: SQLITE_API sqlite3rbu *sqlite3rbu_open(
164774:   const char *zTarget, 
164775:   const char *zRbu,
164776:   const char *zState
164777: );
164778: 
164779: /*
164780: ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
164781: ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
164782: ** that it can be suspended and resumed like an RBU update.
164783: **
164784: ** The second argument to this function, which may not be NULL, identifies 
164785: ** a database in which to store the state of the RBU vacuum operation if
164786: ** it is suspended. The first time sqlite3rbu_vacuum() is called, to start
164787: ** an RBU vacuum operation, the state database should either not exist or
164788: ** be empty (contain no tables). If an RBU vacuum is suspended by calling
164789: ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
164790: ** returned SQLITE_DONE, the vacuum state is stored in the state database. 
164791: ** The vacuum can be resumed by calling this function to open a new RBU
164792: ** handle specifying the same target and state databases.
164793: **
164794: ** This function does not delete the state database after an RBU vacuum
164795: ** is completed, even if it created it. However, if the call to
164796: ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
164797: ** of the state tables within the state database are zeroed. This way,
164798: ** the next call to sqlite3rbu_vacuum() opens a handle that starts a 
164799: ** new RBU vacuum operation.
164800: **
164801: ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
164802: ** describing the sqlite3rbu_create_vfs() API function below for 
164803: ** a description of the complications associated with using RBU with 
164804: ** zipvfs databases.
164805: */
164806: SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
164807:   const char *zTarget, 
164808:   const char *zState
164809: );
164810: 
164811: /*
164812: ** Internally, each RBU connection uses a separate SQLite database 
164813: ** connection to access the target and rbu update databases. This
164814: ** API allows the application direct access to these database handles.
164815: **
164816: ** The first argument passed to this function must be a valid, open, RBU
164817: ** handle. The second argument should be passed zero to access the target
164818: ** database handle, or non-zero to access the rbu update database handle.
164819: ** Accessing the underlying database handles may be useful in the
164820: ** following scenarios:
164821: **
164822: **   * If any target tables are virtual tables, it may be necessary to
164823: **     call sqlite3_create_module() on the target database handle to 
164824: **     register the required virtual table implementations.
164825: **
164826: **   * If the data_xxx tables in the RBU source database are virtual 
164827: **     tables, the application may need to call sqlite3_create_module() on
164828: **     the rbu update db handle to any required virtual table
164829: **     implementations.
164830: **
164831: **   * If the application uses the "rbu_delta()" feature described above,
164832: **     it must use sqlite3_create_function() or similar to register the
164833: **     rbu_delta() implementation with the target database handle.
164834: **
164835: ** If an error has occurred, either while opening or stepping the RBU object,
164836: ** this function may return NULL. The error code and message may be collected
164837: ** when sqlite3rbu_close() is called.
164838: **
164839: ** Database handles returned by this function remain valid until the next
164840: ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
164841: */
164842: SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
164843: 
164844: /*
164845: ** Do some work towards applying the RBU update to the target db. 
164846: **
164847: ** Return SQLITE_DONE if the update has been completely applied, or 
164848: ** SQLITE_OK if no error occurs but there remains work to do to apply
164849: ** the RBU update. If an error does occur, some other error code is 
164850: ** returned. 
164851: **
164852: ** Once a call to sqlite3rbu_step() has returned a value other than
164853: ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
164854: ** that immediately return the same value.
164855: */
164856: SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
164857: 
164858: /*
164859: ** Force RBU to save its state to disk.
164860: **
164861: ** If a power failure or application crash occurs during an update, following
164862: ** system recovery RBU may resume the update from the point at which the state
164863: ** was last saved. In other words, from the most recent successful call to 
164864: ** sqlite3rbu_close() or this function.
164865: **
164866: ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
164867: */
164868: SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
164869: 
164870: /*
164871: ** Close an RBU handle. 
164872: **
164873: ** If the RBU update has been completely applied, mark the RBU database
164874: ** as fully applied. Otherwise, assuming no error has occurred, save the
164875: ** current state of the RBU update appliation to the RBU database.
164876: **
164877: ** If an error has already occurred as part of an sqlite3rbu_step()
164878: ** or sqlite3rbu_open() call, or if one occurs within this function, an
164879: ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
164880: ** point to a buffer containing a utf-8 formatted English language error
164881: ** message. It is the responsibility of the caller to eventually free any 
164882: ** such buffer using sqlite3_free().
164883: **
164884: ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
164885: ** update has been partially applied, or SQLITE_DONE if it has been 
164886: ** completely applied.
164887: */
164888: SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
164889: 
164890: /*
164891: ** Return the total number of key-value operations (inserts, deletes or 
164892: ** updates) that have been performed on the target database since the
164893: ** current RBU update was started.
164894: */
164895: SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
164896: 
164897: /*
164898: ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100) 
164899: ** progress indications for the two stages of an RBU update. This API may
164900: ** be useful for driving GUI progress indicators and similar.
164901: **
164902: ** An RBU update is divided into two stages:
164903: **
164904: **   * Stage 1, in which changes are accumulated in an oal/wal file, and
164905: **   * Stage 2, in which the contents of the wal file are copied into the
164906: **     main database.
164907: **
164908: ** The update is visible to non-RBU clients during stage 2. During stage 1
164909: ** non-RBU reader clients may see the original database.
164910: **
164911: ** If this API is called during stage 2 of the update, output variable 
164912: ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
164913: ** to a value between 0 and 10000 to indicate the permyriadage progress of
164914: ** stage 2. A value of 5000 indicates that stage 2 is half finished, 
164915: ** 9000 indicates that it is 90% finished, and so on.
164916: **
164917: ** If this API is called during stage 1 of the update, output variable 
164918: ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
164919: ** value to which (*pnOne) is set depends on whether or not the RBU 
164920: ** database contains an "rbu_count" table. The rbu_count table, if it 
164921: ** exists, must contain the same columns as the following:
164922: **
164923: **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
164924: **
164925: ** There must be one row in the table for each source (data_xxx) table within
164926: ** the RBU database. The 'tbl' column should contain the name of the source
164927: ** table. The 'cnt' column should contain the number of rows within the
164928: ** source table.
164929: **
164930: ** If the rbu_count table is present and populated correctly and this
164931: ** API is called during stage 1, the *pnOne output variable is set to the
164932: ** permyriadage progress of the same stage. If the rbu_count table does
164933: ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
164934: ** table exists but is not correctly populated, the value of the *pnOne
164935: ** output variable during stage 1 is undefined.
164936: */
164937: SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
164938: 
164939: /*
164940: ** Obtain an indication as to the current stage of an RBU update or vacuum.
164941: ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
164942: ** defined in this file. Return values should be interpreted as follows:
164943: **
164944: ** SQLITE_RBU_STATE_OAL:
164945: **   RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
164946: **   may either add further data to the *-oal file, or compute data that will
164947: **   be added by a subsequent call.
164948: **
164949: ** SQLITE_RBU_STATE_MOVE:
164950: **   RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
164951: **   will move the *-oal file to the equivalent *-wal path. If the current
164952: **   operation is an RBU update, then the updated version of the database
164953: **   file will become visible to ordinary SQLite clients following the next
164954: **   call to sqlite3rbu_step().
164955: **
164956: ** SQLITE_RBU_STATE_CHECKPOINT:
164957: **   RBU is currently performing an incremental checkpoint. The next call to
164958: **   sqlite3rbu_step() will copy a page of data from the *-wal file into
164959: **   the target database file.
164960: **
164961: ** SQLITE_RBU_STATE_DONE:
164962: **   The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
164963: **   will immediately return SQLITE_DONE.
164964: **
164965: ** SQLITE_RBU_STATE_ERROR:
164966: **   An error has occurred. Any subsequent calls to sqlite3rbu_step() will
164967: **   immediately return the SQLite error code associated with the error.
164968: */
164969: #define SQLITE_RBU_STATE_OAL        1
164970: #define SQLITE_RBU_STATE_MOVE       2
164971: #define SQLITE_RBU_STATE_CHECKPOINT 3
164972: #define SQLITE_RBU_STATE_DONE       4
164973: #define SQLITE_RBU_STATE_ERROR      5
164974: 
164975: SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
164976: 
164977: /*
164978: ** Create an RBU VFS named zName that accesses the underlying file-system
164979: ** via existing VFS zParent. Or, if the zParent parameter is passed NULL, 
164980: ** then the new RBU VFS uses the default system VFS to access the file-system.
164981: ** The new object is registered as a non-default VFS with SQLite before 
164982: ** returning.
164983: **
164984: ** Part of the RBU implementation uses a custom VFS object. Usually, this
164985: ** object is created and deleted automatically by RBU. 
164986: **
164987: ** The exception is for applications that also use zipvfs. In this case,
164988: ** the custom VFS must be explicitly created by the user before the RBU
164989: ** handle is opened. The RBU VFS should be installed so that the zipvfs
164990: ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use 
164991: ** (for example multiplexor) to access the file-system. For example,
164992: ** to assemble an RBU enabled VFS stack that uses both zipvfs and 
164993: ** multiplexor (error checking omitted):
164994: **
164995: **     // Create a VFS named "multiplex" (not the default).
164996: **     sqlite3_multiplex_initialize(0, 0);
164997: **
164998: **     // Create an rbu VFS named "rbu" that uses multiplexor. If the
164999: **     // second argument were replaced with NULL, the "rbu" VFS would
165000: **     // access the file-system via the system default VFS, bypassing the
165001: **     // multiplexor.
165002: **     sqlite3rbu_create_vfs("rbu", "multiplex");
165003: **
165004: **     // Create a zipvfs VFS named "zipvfs" that uses rbu.
165005: **     zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
165006: **
165007: **     // Make zipvfs the default VFS.
165008: **     sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
165009: **
165010: ** Because the default VFS created above includes a RBU functionality, it
165011: ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
165012: ** that does not include the RBU layer results in an error.
165013: **
165014: ** The overhead of adding the "rbu" VFS to the system is negligible for 
165015: ** non-RBU users. There is no harm in an application accessing the 
165016: ** file-system via "rbu" all the time, even if it only uses RBU functionality 
165017: ** occasionally.
165018: */
165019: SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
165020: 
165021: /*
165022: ** Deregister and destroy an RBU vfs created by an earlier call to
165023: ** sqlite3rbu_create_vfs().
165024: **
165025: ** VFS objects are not reference counted. If a VFS object is destroyed
165026: ** before all database handles that use it have been closed, the results
165027: ** are undefined.
165028: */
165029: SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
165030: 
165031: #if 0
165032: }  /* end of the 'extern "C"' block */
165033: #endif
165034: 
165035: #endif /* _SQLITE3RBU_H */
165036: 
165037: /************** End of sqlite3rbu.h ******************************************/
165038: /************** Continuing where we left off in sqlite3rbu.c *****************/
165039: 
165040: #if defined(_WIN32_WCE)
165041: /* #include "windows.h" */
165042: #endif
165043: 
165044: /* Maximum number of prepared UPDATE statements held by this module */
165045: #define SQLITE_RBU_UPDATE_CACHESIZE 16
165046: 
165047: /*
165048: ** Swap two objects of type TYPE.
165049: */
165050: #if !defined(SQLITE_AMALGAMATION)
165051: # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
165052: #endif
165053: 
165054: /*
165055: ** The rbu_state table is used to save the state of a partially applied
165056: ** update so that it can be resumed later. The table consists of integer
165057: ** keys mapped to values as follows:
165058: **
165059: ** RBU_STATE_STAGE:
165060: **   May be set to integer values 1, 2, 4 or 5. As follows:
165061: **       1: the *-rbu file is currently under construction.
165062: **       2: the *-rbu file has been constructed, but not yet moved 
165063: **          to the *-wal path.
165064: **       4: the checkpoint is underway.
165065: **       5: the rbu update has been checkpointed.
165066: **
165067: ** RBU_STATE_TBL:
165068: **   Only valid if STAGE==1. The target database name of the table 
165069: **   currently being written.
165070: **
165071: ** RBU_STATE_IDX:
165072: **   Only valid if STAGE==1. The target database name of the index 
165073: **   currently being written, or NULL if the main table is currently being
165074: **   updated.
165075: **
165076: ** RBU_STATE_ROW:
165077: **   Only valid if STAGE==1. Number of rows already processed for the current
165078: **   table/index.
165079: **
165080: ** RBU_STATE_PROGRESS:
165081: **   Trbul number of sqlite3rbu_step() calls made so far as part of this
165082: **   rbu update.
165083: **
165084: ** RBU_STATE_CKPT:
165085: **   Valid if STAGE==4. The 64-bit checksum associated with the wal-index
165086: **   header created by recovering the *-wal file. This is used to detect
165087: **   cases when another client appends frames to the *-wal file in the
165088: **   middle of an incremental checkpoint (an incremental checkpoint cannot
165089: **   be continued if this happens).
165090: **
165091: ** RBU_STATE_COOKIE:
165092: **   Valid if STAGE==1. The current change-counter cookie value in the 
165093: **   target db file.
165094: **
165095: ** RBU_STATE_OALSZ:
165096: **   Valid if STAGE==1. The size in bytes of the *-oal file.
165097: */
165098: #define RBU_STATE_STAGE        1
165099: #define RBU_STATE_TBL          2
165100: #define RBU_STATE_IDX          3
165101: #define RBU_STATE_ROW          4
165102: #define RBU_STATE_PROGRESS     5
165103: #define RBU_STATE_CKPT         6
165104: #define RBU_STATE_COOKIE       7
165105: #define RBU_STATE_OALSZ        8
165106: #define RBU_STATE_PHASEONESTEP 9
165107: 
165108: #define RBU_STAGE_OAL         1
165109: #define RBU_STAGE_MOVE        2
165110: #define RBU_STAGE_CAPTURE     3
165111: #define RBU_STAGE_CKPT        4
165112: #define RBU_STAGE_DONE        5
165113: 
165114: 
165115: #define RBU_CREATE_STATE \
165116:   "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
165117: 
165118: typedef struct RbuFrame RbuFrame;
165119: typedef struct RbuObjIter RbuObjIter;
165120: typedef struct RbuState RbuState;
165121: typedef struct rbu_vfs rbu_vfs;
165122: typedef struct rbu_file rbu_file;
165123: typedef struct RbuUpdateStmt RbuUpdateStmt;
165124: 
165125: #if !defined(SQLITE_AMALGAMATION)
165126: typedef unsigned int u32;
165127: typedef unsigned short u16;
165128: typedef unsigned char u8;
165129: typedef sqlite3_int64 i64;
165130: #endif
165131: 
165132: /*
165133: ** These values must match the values defined in wal.c for the equivalent
165134: ** locks. These are not magic numbers as they are part of the SQLite file
165135: ** format.
165136: */
165137: #define WAL_LOCK_WRITE  0
165138: #define WAL_LOCK_CKPT   1
165139: #define WAL_LOCK_READ0  3
165140: 
165141: #define SQLITE_FCNTL_RBUCNT    5149216
165142: 
165143: /*
165144: ** A structure to store values read from the rbu_state table in memory.
165145: */
165146: struct RbuState {
165147:   int eStage;
165148:   char *zTbl;
165149:   char *zIdx;
165150:   i64 iWalCksum;
165151:   int nRow;
165152:   i64 nProgress;
165153:   u32 iCookie;
165154:   i64 iOalSz;
165155:   i64 nPhaseOneStep;
165156: };
165157: 
165158: struct RbuUpdateStmt {
165159:   char *zMask;                    /* Copy of update mask used with pUpdate */
165160:   sqlite3_stmt *pUpdate;          /* Last update statement (or NULL) */
165161:   RbuUpdateStmt *pNext;
165162: };
165163: 
165164: /*
165165: ** An iterator of this type is used to iterate through all objects in
165166: ** the target database that require updating. For each such table, the
165167: ** iterator visits, in order:
165168: **
165169: **     * the table itself, 
165170: **     * each index of the table (zero or more points to visit), and
165171: **     * a special "cleanup table" state.
165172: **
165173: ** abIndexed:
165174: **   If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
165175: **   it points to an array of flags nTblCol elements in size. The flag is
165176: **   set for each column that is either a part of the PK or a part of an
165177: **   index. Or clear otherwise.
165178: **   
165179: */
165180: struct RbuObjIter {
165181:   sqlite3_stmt *pTblIter;         /* Iterate through tables */
165182:   sqlite3_stmt *pIdxIter;         /* Index iterator */
165183:   int nTblCol;                    /* Size of azTblCol[] array */
165184:   char **azTblCol;                /* Array of unquoted target column names */
165185:   char **azTblType;               /* Array of target column types */
165186:   int *aiSrcOrder;                /* src table col -> target table col */
165187:   u8 *abTblPk;                    /* Array of flags, set on target PK columns */
165188:   u8 *abNotNull;                  /* Array of flags, set on NOT NULL columns */
165189:   u8 *abIndexed;                  /* Array of flags, set on indexed & PK cols */
165190:   int eType;                      /* Table type - an RBU_PK_XXX value */
165191: 
165192:   /* Output variables. zTbl==0 implies EOF. */
165193:   int bCleanup;                   /* True in "cleanup" state */
165194:   const char *zTbl;               /* Name of target db table */
165195:   const char *zDataTbl;           /* Name of rbu db table (or null) */
165196:   const char *zIdx;               /* Name of target db index (or null) */
165197:   int iTnum;                      /* Root page of current object */
165198:   int iPkTnum;                    /* If eType==EXTERNAL, root of PK index */
165199:   int bUnique;                    /* Current index is unique */
165200:   int nIndex;                     /* Number of aux. indexes on table zTbl */
165201: 
165202:   /* Statements created by rbuObjIterPrepareAll() */
165203:   int nCol;                       /* Number of columns in current object */
165204:   sqlite3_stmt *pSelect;          /* Source data */
165205:   sqlite3_stmt *pInsert;          /* Statement for INSERT operations */
165206:   sqlite3_stmt *pDelete;          /* Statement for DELETE ops */
165207:   sqlite3_stmt *pTmpInsert;       /* Insert into rbu_tmp_$zDataTbl */
165208: 
165209:   /* Last UPDATE used (for PK b-tree updates only), or NULL. */
165210:   RbuUpdateStmt *pRbuUpdate;
165211: };
165212: 
165213: /*
165214: ** Values for RbuObjIter.eType
165215: **
165216: **     0: Table does not exist (error)
165217: **     1: Table has an implicit rowid.
165218: **     2: Table has an explicit IPK column.
165219: **     3: Table has an external PK index.
165220: **     4: Table is WITHOUT ROWID.
165221: **     5: Table is a virtual table.
165222: */
165223: #define RBU_PK_NOTABLE        0
165224: #define RBU_PK_NONE           1
165225: #define RBU_PK_IPK            2
165226: #define RBU_PK_EXTERNAL       3
165227: #define RBU_PK_WITHOUT_ROWID  4
165228: #define RBU_PK_VTAB           5
165229: 
165230: 
165231: /*
165232: ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
165233: ** one of the following operations.
165234: */
165235: #define RBU_INSERT     1          /* Insert on a main table b-tree */
165236: #define RBU_DELETE     2          /* Delete a row from a main table b-tree */
165237: #define RBU_REPLACE    3          /* Delete and then insert a row */
165238: #define RBU_IDX_DELETE 4          /* Delete a row from an aux. index b-tree */
165239: #define RBU_IDX_INSERT 5          /* Insert on an aux. index b-tree */
165240: 
165241: #define RBU_UPDATE     6          /* Update a row in a main table b-tree */
165242: 
165243: /*
165244: ** A single step of an incremental checkpoint - frame iWalFrame of the wal
165245: ** file should be copied to page iDbPage of the database file.
165246: */
165247: struct RbuFrame {
165248:   u32 iDbPage;
165249:   u32 iWalFrame;
165250: };
165251: 
165252: /*
165253: ** RBU handle.
165254: **
165255: ** nPhaseOneStep:
165256: **   If the RBU database contains an rbu_count table, this value is set to
165257: **   a running estimate of the number of b-tree operations required to 
165258: **   finish populating the *-oal file. This allows the sqlite3_bp_progress()
165259: **   API to calculate the permyriadage progress of populating the *-oal file
165260: **   using the formula:
165261: **
165262: **     permyriadage = (10000 * nProgress) / nPhaseOneStep
165263: **
165264: **   nPhaseOneStep is initialized to the sum of:
165265: **
165266: **     nRow * (nIndex + 1)
165267: **
165268: **   for all source tables in the RBU database, where nRow is the number
165269: **   of rows in the source table and nIndex the number of indexes on the
165270: **   corresponding target database table.
165271: **
165272: **   This estimate is accurate if the RBU update consists entirely of
165273: **   INSERT operations. However, it is inaccurate if:
165274: **
165275: **     * the RBU update contains any UPDATE operations. If the PK specified
165276: **       for an UPDATE operation does not exist in the target table, then
165277: **       no b-tree operations are required on index b-trees. Or if the 
165278: **       specified PK does exist, then (nIndex*2) such operations are
165279: **       required (one delete and one insert on each index b-tree).
165280: **
165281: **     * the RBU update contains any DELETE operations for which the specified
165282: **       PK does not exist. In this case no operations are required on index
165283: **       b-trees.
165284: **
165285: **     * the RBU update contains REPLACE operations. These are similar to
165286: **       UPDATE operations.
165287: **
165288: **   nPhaseOneStep is updated to account for the conditions above during the
165289: **   first pass of each source table. The updated nPhaseOneStep value is
165290: **   stored in the rbu_state table if the RBU update is suspended.
165291: */
165292: struct sqlite3rbu {
165293:   int eStage;                     /* Value of RBU_STATE_STAGE field */
165294:   sqlite3 *dbMain;                /* target database handle */
165295:   sqlite3 *dbRbu;                 /* rbu database handle */
165296:   char *zTarget;                  /* Path to target db */
165297:   char *zRbu;                     /* Path to rbu db */
165298:   char *zState;                   /* Path to state db (or NULL if zRbu) */
165299:   char zStateDb[5];               /* Db name for state ("stat" or "main") */
165300:   int rc;                         /* Value returned by last rbu_step() call */
165301:   char *zErrmsg;                  /* Error message if rc!=SQLITE_OK */
165302:   int nStep;                      /* Rows processed for current object */
165303:   int nProgress;                  /* Rows processed for all objects */
165304:   RbuObjIter objiter;             /* Iterator for skipping through tbl/idx */
165305:   const char *zVfsName;           /* Name of automatically created rbu vfs */
165306:   rbu_file *pTargetFd;            /* File handle open on target db */
165307:   i64 iOalSz;
165308:   i64 nPhaseOneStep;
165309: 
165310:   /* The following state variables are used as part of the incremental
165311:   ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
165312:   ** function rbuSetupCheckpoint() for details.  */
165313:   u32 iMaxFrame;                  /* Largest iWalFrame value in aFrame[] */
165314:   u32 mLock;
165315:   int nFrame;                     /* Entries in aFrame[] array */
165316:   int nFrameAlloc;                /* Allocated size of aFrame[] array */
165317:   RbuFrame *aFrame;
165318:   int pgsz;
165319:   u8 *aBuf;
165320:   i64 iWalCksum;
165321: 
165322:   /* Used in RBU vacuum mode only */
165323:   int nRbu;                       /* Number of RBU VFS in the stack */
165324:   rbu_file *pRbuFd;               /* Fd for main db of dbRbu */
165325: };
165326: 
165327: /*
165328: ** An rbu VFS is implemented using an instance of this structure.
165329: */
165330: struct rbu_vfs {
165331:   sqlite3_vfs base;               /* rbu VFS shim methods */
165332:   sqlite3_vfs *pRealVfs;          /* Underlying VFS */
165333:   sqlite3_mutex *mutex;           /* Mutex to protect pMain */
165334:   rbu_file *pMain;                /* Linked list of main db files */
165335: };
165336: 
165337: /*
165338: ** Each file opened by an rbu VFS is represented by an instance of
165339: ** the following structure.
165340: */
165341: struct rbu_file {
165342:   sqlite3_file base;              /* sqlite3_file methods */
165343:   sqlite3_file *pReal;            /* Underlying file handle */
165344:   rbu_vfs *pRbuVfs;               /* Pointer to the rbu_vfs object */
165345:   sqlite3rbu *pRbu;               /* Pointer to rbu object (rbu target only) */
165346: 
165347:   int openFlags;                  /* Flags this file was opened with */
165348:   u32 iCookie;                    /* Cookie value for main db files */
165349:   u8 iWriteVer;                   /* "write-version" value for main db files */
165350:   u8 bNolock;                     /* True to fail EXCLUSIVE locks */
165351: 
165352:   int nShm;                       /* Number of entries in apShm[] array */
165353:   char **apShm;                   /* Array of mmap'd *-shm regions */
165354:   char *zDel;                     /* Delete this when closing file */
165355: 
165356:   const char *zWal;               /* Wal filename for this main db file */
165357:   rbu_file *pWalFd;               /* Wal file descriptor for this main db */
165358:   rbu_file *pMainNext;            /* Next MAIN_DB file */
165359: };
165360: 
165361: /*
165362: ** True for an RBU vacuum handle, or false otherwise.
165363: */
165364: #define rbuIsVacuum(p) ((p)->zTarget==0)
165365: 
165366: 
165367: /*************************************************************************
165368: ** The following three functions, found below:
165369: **
165370: **   rbuDeltaGetInt()
165371: **   rbuDeltaChecksum()
165372: **   rbuDeltaApply()
165373: **
165374: ** are lifted from the fossil source code (http://fossil-scm.org). They
165375: ** are used to implement the scalar SQL function rbu_fossil_delta().
165376: */
165377: 
165378: /*
165379: ** Read bytes from *pz and convert them into a positive integer.  When
165380: ** finished, leave *pz pointing to the first character past the end of
165381: ** the integer.  The *pLen parameter holds the length of the string
165382: ** in *pz and is decremented once for each character in the integer.
165383: */
165384: static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
165385:   static const signed char zValue[] = {
165386:     -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165387:     -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165388:     -1, -1, -1, -1, -1, -1, -1, -1,   -1, -1, -1, -1, -1, -1, -1, -1,
165389:      0,  1,  2,  3,  4,  5,  6,  7,    8,  9, -1, -1, -1, -1, -1, -1,
165390:     -1, 10, 11, 12, 13, 14, 15, 16,   17, 18, 19, 20, 21, 22, 23, 24,
165391:     25, 26, 27, 28, 29, 30, 31, 32,   33, 34, 35, -1, -1, -1, -1, 36,
165392:     -1, 37, 38, 39, 40, 41, 42, 43,   44, 45, 46, 47, 48, 49, 50, 51,
165393:     52, 53, 54, 55, 56, 57, 58, 59,   60, 61, 62, -1, -1, -1, 63, -1,
165394:   };
165395:   unsigned int v = 0;
165396:   int c;
165397:   unsigned char *z = (unsigned char*)*pz;
165398:   unsigned char *zStart = z;
165399:   while( (c = zValue[0x7f&*(z++)])>=0 ){
165400:      v = (v<<6) + c;
165401:   }
165402:   z--;
165403:   *pLen -= z - zStart;
165404:   *pz = (char*)z;
165405:   return v;
165406: }
165407: 
165408: /*
165409: ** Compute a 32-bit checksum on the N-byte buffer.  Return the result.
165410: */
165411: static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
165412:   const unsigned char *z = (const unsigned char *)zIn;
165413:   unsigned sum0 = 0;
165414:   unsigned sum1 = 0;
165415:   unsigned sum2 = 0;
165416:   unsigned sum3 = 0;
165417:   while(N >= 16){
165418:     sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
165419:     sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
165420:     sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
165421:     sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
165422:     z += 16;
165423:     N -= 16;
165424:   }
165425:   while(N >= 4){
165426:     sum0 += z[0];
165427:     sum1 += z[1];
165428:     sum2 += z[2];
165429:     sum3 += z[3];
165430:     z += 4;
165431:     N -= 4;
165432:   }
165433:   sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
165434:   switch(N){
165435:     case 3:   sum3 += (z[2] << 8);
165436:     case 2:   sum3 += (z[1] << 16);
165437:     case 1:   sum3 += (z[0] << 24);
165438:     default:  ;
165439:   }
165440:   return sum3;
165441: }
165442: 
165443: /*
165444: ** Apply a delta.
165445: **
165446: ** The output buffer should be big enough to hold the whole output
165447: ** file and a NUL terminator at the end.  The delta_output_size()
165448: ** routine will determine this size for you.
165449: **
165450: ** The delta string should be null-terminated.  But the delta string
165451: ** may contain embedded NUL characters (if the input and output are
165452: ** binary files) so we also have to pass in the length of the delta in
165453: ** the lenDelta parameter.
165454: **
165455: ** This function returns the size of the output file in bytes (excluding
165456: ** the final NUL terminator character).  Except, if the delta string is
165457: ** malformed or intended for use with a source file other than zSrc,
165458: ** then this routine returns -1.
165459: **
165460: ** Refer to the delta_create() documentation above for a description
165461: ** of the delta file format.
165462: */
165463: static int rbuDeltaApply(
165464:   const char *zSrc,      /* The source or pattern file */
165465:   int lenSrc,            /* Length of the source file */
165466:   const char *zDelta,    /* Delta to apply to the pattern */
165467:   int lenDelta,          /* Length of the delta */
165468:   char *zOut             /* Write the output into this preallocated buffer */
165469: ){
165470:   unsigned int limit;
165471:   unsigned int total = 0;
165472: #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
165473:   char *zOrigOut = zOut;
165474: #endif
165475: 
165476:   limit = rbuDeltaGetInt(&zDelta, &lenDelta);
165477:   if( *zDelta!='\n' ){
165478:     /* ERROR: size integer not terminated by "\n" */
165479:     return -1;
165480:   }
165481:   zDelta++; lenDelta--;
165482:   while( *zDelta && lenDelta>0 ){
165483:     unsigned int cnt, ofst;
165484:     cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
165485:     switch( zDelta[0] ){
165486:       case '@': {
165487:         zDelta++; lenDelta--;
165488:         ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
165489:         if( lenDelta>0 && zDelta[0]!=',' ){
165490:           /* ERROR: copy command not terminated by ',' */
165491:           return -1;
165492:         }
165493:         zDelta++; lenDelta--;
165494:         total += cnt;
165495:         if( total>limit ){
165496:           /* ERROR: copy exceeds output file size */
165497:           return -1;
165498:         }
165499:         if( (int)(ofst+cnt) > lenSrc ){
165500:           /* ERROR: copy extends past end of input */
165501:           return -1;
165502:         }
165503:         memcpy(zOut, &zSrc[ofst], cnt);
165504:         zOut += cnt;
165505:         break;
165506:       }
165507:       case ':': {
165508:         zDelta++; lenDelta--;
165509:         total += cnt;
165510:         if( total>limit ){
165511:           /* ERROR:  insert command gives an output larger than predicted */
165512:           return -1;
165513:         }
165514:         if( (int)cnt>lenDelta ){
165515:           /* ERROR: insert count exceeds size of delta */
165516:           return -1;
165517:         }
165518:         memcpy(zOut, zDelta, cnt);
165519:         zOut += cnt;
165520:         zDelta += cnt;
165521:         lenDelta -= cnt;
165522:         break;
165523:       }
165524:       case ';': {
165525:         zDelta++; lenDelta--;
165526:         zOut[0] = 0;
165527: #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
165528:         if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
165529:           /* ERROR:  bad checksum */
165530:           return -1;
165531:         }
165532: #endif
165533:         if( total!=limit ){
165534:           /* ERROR: generated size does not match predicted size */
165535:           return -1;
165536:         }
165537:         return total;
165538:       }
165539:       default: {
165540:         /* ERROR: unknown delta operator */
165541:         return -1;
165542:       }
165543:     }
165544:   }
165545:   /* ERROR: unterminated delta */
165546:   return -1;
165547: }
165548: 
165549: static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
165550:   int size;
165551:   size = rbuDeltaGetInt(&zDelta, &lenDelta);
165552:   if( *zDelta!='\n' ){
165553:     /* ERROR: size integer not terminated by "\n" */
165554:     return -1;
165555:   }
165556:   return size;
165557: }
165558: 
165559: /*
165560: ** End of code taken from fossil.
165561: *************************************************************************/
165562: 
165563: /*
165564: ** Implementation of SQL scalar function rbu_fossil_delta().
165565: **
165566: ** This function applies a fossil delta patch to a blob. Exactly two
165567: ** arguments must be passed to this function. The first is the blob to
165568: ** patch and the second the patch to apply. If no error occurs, this
165569: ** function returns the patched blob.
165570: */
165571: static void rbuFossilDeltaFunc(
165572:   sqlite3_context *context,
165573:   int argc,
165574:   sqlite3_value **argv
165575: ){
165576:   const char *aDelta;
165577:   int nDelta;
165578:   const char *aOrig;
165579:   int nOrig;
165580: 
165581:   int nOut;
165582:   int nOut2;
165583:   char *aOut;
165584: 
165585:   assert( argc==2 );
165586: 
165587:   nOrig = sqlite3_value_bytes(argv[0]);
165588:   aOrig = (const char*)sqlite3_value_blob(argv[0]);
165589:   nDelta = sqlite3_value_bytes(argv[1]);
165590:   aDelta = (const char*)sqlite3_value_blob(argv[1]);
165591: 
165592:   /* Figure out the size of the output */
165593:   nOut = rbuDeltaOutputSize(aDelta, nDelta);
165594:   if( nOut<0 ){
165595:     sqlite3_result_error(context, "corrupt fossil delta", -1);
165596:     return;
165597:   }
165598: 
165599:   aOut = sqlite3_malloc(nOut+1);
165600:   if( aOut==0 ){
165601:     sqlite3_result_error_nomem(context);
165602:   }else{
165603:     nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
165604:     if( nOut2!=nOut ){
165605:       sqlite3_result_error(context, "corrupt fossil delta", -1);
165606:     }else{
165607:       sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
165608:     }
165609:   }
165610: }
165611: 
165612: 
165613: /*
165614: ** Prepare the SQL statement in buffer zSql against database handle db.
165615: ** If successful, set *ppStmt to point to the new statement and return
165616: ** SQLITE_OK. 
165617: **
165618: ** Otherwise, if an error does occur, set *ppStmt to NULL and return
165619: ** an SQLite error code. Additionally, set output variable *pzErrmsg to
165620: ** point to a buffer containing an error message. It is the responsibility
165621: ** of the caller to (eventually) free this buffer using sqlite3_free().
165622: */
165623: static int prepareAndCollectError(
165624:   sqlite3 *db, 
165625:   sqlite3_stmt **ppStmt,
165626:   char **pzErrmsg,
165627:   const char *zSql
165628: ){
165629:   int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
165630:   if( rc!=SQLITE_OK ){
165631:     *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
165632:     *ppStmt = 0;
165633:   }
165634:   return rc;
165635: }
165636: 
165637: /*
165638: ** Reset the SQL statement passed as the first argument. Return a copy
165639: ** of the value returned by sqlite3_reset().
165640: **
165641: ** If an error has occurred, then set *pzErrmsg to point to a buffer
165642: ** containing an error message. It is the responsibility of the caller
165643: ** to eventually free this buffer using sqlite3_free().
165644: */
165645: static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
165646:   int rc = sqlite3_reset(pStmt);
165647:   if( rc!=SQLITE_OK ){
165648:     *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
165649:   }
165650:   return rc;
165651: }
165652: 
165653: /*
165654: ** Unless it is NULL, argument zSql points to a buffer allocated using
165655: ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
165656: ** statement against database db and frees the buffer. If statement 
165657: ** compilation is successful, *ppStmt is set to point to the new statement 
165658: ** handle and SQLITE_OK is returned. 
165659: **
165660: ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
165661: ** returned. In this case, *pzErrmsg may also be set to point to an error
165662: ** message. It is the responsibility of the caller to free this error message
165663: ** buffer using sqlite3_free().
165664: **
165665: ** If argument zSql is NULL, this function assumes that an OOM has occurred.
165666: ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
165667: */
165668: static int prepareFreeAndCollectError(
165669:   sqlite3 *db, 
165670:   sqlite3_stmt **ppStmt,
165671:   char **pzErrmsg,
165672:   char *zSql
165673: ){
165674:   int rc;
165675:   assert( *pzErrmsg==0 );
165676:   if( zSql==0 ){
165677:     rc = SQLITE_NOMEM;
165678:     *ppStmt = 0;
165679:   }else{
165680:     rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
165681:     sqlite3_free(zSql);
165682:   }
165683:   return rc;
165684: }
165685: 
165686: /*
165687: ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
165688: ** by an earlier call to rbuObjIterCacheTableInfo().
165689: */
165690: static void rbuObjIterFreeCols(RbuObjIter *pIter){
165691:   int i;
165692:   for(i=0; i<pIter->nTblCol; i++){
165693:     sqlite3_free(pIter->azTblCol[i]);
165694:     sqlite3_free(pIter->azTblType[i]);
165695:   }
165696:   sqlite3_free(pIter->azTblCol);
165697:   pIter->azTblCol = 0;
165698:   pIter->azTblType = 0;
165699:   pIter->aiSrcOrder = 0;
165700:   pIter->abTblPk = 0;
165701:   pIter->abNotNull = 0;
165702:   pIter->nTblCol = 0;
165703:   pIter->eType = 0;               /* Invalid value */
165704: }
165705: 
165706: /*
165707: ** Finalize all statements and free all allocations that are specific to
165708: ** the current object (table/index pair).
165709: */
165710: static void rbuObjIterClearStatements(RbuObjIter *pIter){
165711:   RbuUpdateStmt *pUp;
165712: 
165713:   sqlite3_finalize(pIter->pSelect);
165714:   sqlite3_finalize(pIter->pInsert);
165715:   sqlite3_finalize(pIter->pDelete);
165716:   sqlite3_finalize(pIter->pTmpInsert);
165717:   pUp = pIter->pRbuUpdate;
165718:   while( pUp ){
165719:     RbuUpdateStmt *pTmp = pUp->pNext;
165720:     sqlite3_finalize(pUp->pUpdate);
165721:     sqlite3_free(pUp);
165722:     pUp = pTmp;
165723:   }
165724:   
165725:   pIter->pSelect = 0;
165726:   pIter->pInsert = 0;
165727:   pIter->pDelete = 0;
165728:   pIter->pRbuUpdate = 0;
165729:   pIter->pTmpInsert = 0;
165730:   pIter->nCol = 0;
165731: }
165732: 
165733: /*
165734: ** Clean up any resources allocated as part of the iterator object passed
165735: ** as the only argument.
165736: */
165737: static void rbuObjIterFinalize(RbuObjIter *pIter){
165738:   rbuObjIterClearStatements(pIter);
165739:   sqlite3_finalize(pIter->pTblIter);
165740:   sqlite3_finalize(pIter->pIdxIter);
165741:   rbuObjIterFreeCols(pIter);
165742:   memset(pIter, 0, sizeof(RbuObjIter));
165743: }
165744: 
165745: /*
165746: ** Advance the iterator to the next position.
165747: **
165748: ** If no error occurs, SQLITE_OK is returned and the iterator is left 
165749: ** pointing to the next entry. Otherwise, an error code and message is 
165750: ** left in the RBU handle passed as the first argument. A copy of the 
165751: ** error code is returned.
165752: */
165753: static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
165754:   int rc = p->rc;
165755:   if( rc==SQLITE_OK ){
165756: 
165757:     /* Free any SQLite statements used while processing the previous object */ 
165758:     rbuObjIterClearStatements(pIter);
165759:     if( pIter->zIdx==0 ){
165760:       rc = sqlite3_exec(p->dbMain,
165761:           "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
165762:           "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
165763:           "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
165764:           "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
165765:           , 0, 0, &p->zErrmsg
165766:       );
165767:     }
165768: 
165769:     if( rc==SQLITE_OK ){
165770:       if( pIter->bCleanup ){
165771:         rbuObjIterFreeCols(pIter);
165772:         pIter->bCleanup = 0;
165773:         rc = sqlite3_step(pIter->pTblIter);
165774:         if( rc!=SQLITE_ROW ){
165775:           rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
165776:           pIter->zTbl = 0;
165777:         }else{
165778:           pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
165779:           pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
165780:           rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
165781:         }
165782:       }else{
165783:         if( pIter->zIdx==0 ){
165784:           sqlite3_stmt *pIdx = pIter->pIdxIter;
165785:           rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
165786:         }
165787:         if( rc==SQLITE_OK ){
165788:           rc = sqlite3_step(pIter->pIdxIter);
165789:           if( rc!=SQLITE_ROW ){
165790:             rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
165791:             pIter->bCleanup = 1;
165792:             pIter->zIdx = 0;
165793:           }else{
165794:             pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
165795:             pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
165796:             pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
165797:             rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
165798:           }
165799:         }
165800:       }
165801:     }
165802:   }
165803: 
165804:   if( rc!=SQLITE_OK ){
165805:     rbuObjIterFinalize(pIter);
165806:     p->rc = rc;
165807:   }
165808:   return rc;
165809: }
165810: 
165811: 
165812: /*
165813: ** The implementation of the rbu_target_name() SQL function. This function
165814: ** accepts one or two arguments. The first argument is the name of a table -
165815: ** the name of a table in the RBU database.  The second, if it is present, is 1
165816: ** for a view or 0 for a table. 
165817: **
165818: ** For a non-vacuum RBU handle, if the table name matches the pattern:
165819: **
165820: **     data[0-9]_<name>
165821: **
165822: ** where <name> is any sequence of 1 or more characters, <name> is returned.
165823: ** Otherwise, if the only argument does not match the above pattern, an SQL
165824: ** NULL is returned.
165825: **
165826: **     "data_t1"     -> "t1"
165827: **     "data0123_t2" -> "t2"
165828: **     "dataAB_t3"   -> NULL
165829: **
165830: ** For an rbu vacuum handle, a copy of the first argument is returned if
165831: ** the second argument is either missing or 0 (not a view).
165832: */
165833: static void rbuTargetNameFunc(
165834:   sqlite3_context *pCtx,
165835:   int argc,
165836:   sqlite3_value **argv
165837: ){
165838:   sqlite3rbu *p = sqlite3_user_data(pCtx);
165839:   const char *zIn;
165840:   assert( argc==1 || argc==2 );
165841: 
165842:   zIn = (const char*)sqlite3_value_text(argv[0]);
165843:   if( zIn ){
165844:     if( rbuIsVacuum(p) ){
165845:       if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
165846:         sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
165847:       }
165848:     }else{
165849:       if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
165850:         int i;
165851:         for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
165852:         if( zIn[i]=='_' && zIn[i+1] ){
165853:           sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
165854:         }
165855:       }
165856:     }
165857:   }
165858: }
165859: 
165860: /*
165861: ** Initialize the iterator structure passed as the second argument.
165862: **
165863: ** If no error occurs, SQLITE_OK is returned and the iterator is left 
165864: ** pointing to the first entry. Otherwise, an error code and message is 
165865: ** left in the RBU handle passed as the first argument. A copy of the 
165866: ** error code is returned.
165867: */
165868: static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
165869:   int rc;
165870:   memset(pIter, 0, sizeof(RbuObjIter));
165871: 
165872:   rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg, 
165873:     sqlite3_mprintf(
165874:       "SELECT rbu_target_name(name, type='view') AS target, name "
165875:       "FROM sqlite_master "
165876:       "WHERE type IN ('table', 'view') AND target IS NOT NULL "
165877:       " %s "
165878:       "ORDER BY name"
165879:   , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
165880: 
165881:   if( rc==SQLITE_OK ){
165882:     rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
165883:         "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
165884:         "  FROM main.sqlite_master "
165885:         "  WHERE type='index' AND tbl_name = ?"
165886:     );
165887:   }
165888: 
165889:   pIter->bCleanup = 1;
165890:   p->rc = rc;
165891:   return rbuObjIterNext(p, pIter);
165892: }
165893: 
165894: /*
165895: ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
165896: ** an error code is stored in the RBU handle passed as the first argument.
165897: **
165898: ** If an error has already occurred (p->rc is already set to something other
165899: ** than SQLITE_OK), then this function returns NULL without modifying the
165900: ** stored error code. In this case it still calls sqlite3_free() on any 
165901: ** printf() parameters associated with %z conversions.
165902: */
165903: static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
165904:   char *zSql = 0;
165905:   va_list ap;
165906:   va_start(ap, zFmt);
165907:   zSql = sqlite3_vmprintf(zFmt, ap);
165908:   if( p->rc==SQLITE_OK ){
165909:     if( zSql==0 ) p->rc = SQLITE_NOMEM;
165910:   }else{
165911:     sqlite3_free(zSql);
165912:     zSql = 0;
165913:   }
165914:   va_end(ap);
165915:   return zSql;
165916: }
165917: 
165918: /*
165919: ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
165920: ** arguments are the usual subsitution values. This function performs
165921: ** the printf() style substitutions and executes the result as an SQL
165922: ** statement on the RBU handles database.
165923: **
165924: ** If an error occurs, an error code and error message is stored in the
165925: ** RBU handle. If an error has already occurred when this function is
165926: ** called, it is a no-op.
165927: */
165928: static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
165929:   va_list ap;
165930:   char *zSql;
165931:   va_start(ap, zFmt);
165932:   zSql = sqlite3_vmprintf(zFmt, ap);
165933:   if( p->rc==SQLITE_OK ){
165934:     if( zSql==0 ){
165935:       p->rc = SQLITE_NOMEM;
165936:     }else{
165937:       p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
165938:     }
165939:   }
165940:   sqlite3_free(zSql);
165941:   va_end(ap);
165942:   return p->rc;
165943: }
165944: 
165945: /*
165946: ** Attempt to allocate and return a pointer to a zeroed block of nByte 
165947: ** bytes. 
165948: **
165949: ** If an error (i.e. an OOM condition) occurs, return NULL and leave an 
165950: ** error code in the rbu handle passed as the first argument. Or, if an 
165951: ** error has already occurred when this function is called, return NULL 
165952: ** immediately without attempting the allocation or modifying the stored
165953: ** error code.
165954: */
165955: static void *rbuMalloc(sqlite3rbu *p, int nByte){
165956:   void *pRet = 0;
165957:   if( p->rc==SQLITE_OK ){
165958:     assert( nByte>0 );
165959:     pRet = sqlite3_malloc64(nByte);
165960:     if( pRet==0 ){
165961:       p->rc = SQLITE_NOMEM;
165962:     }else{
165963:       memset(pRet, 0, nByte);
165964:     }
165965:   }
165966:   return pRet;
165967: }
165968: 
165969: 
165970: /*
165971: ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
165972: ** there is room for at least nCol elements. If an OOM occurs, store an
165973: ** error code in the RBU handle passed as the first argument.
165974: */
165975: static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
165976:   int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
165977:   char **azNew;
165978: 
165979:   azNew = (char**)rbuMalloc(p, nByte);
165980:   if( azNew ){
165981:     pIter->azTblCol = azNew;
165982:     pIter->azTblType = &azNew[nCol];
165983:     pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
165984:     pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
165985:     pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
165986:     pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
165987:   }
165988: }
165989: 
165990: /*
165991: ** The first argument must be a nul-terminated string. This function
165992: ** returns a copy of the string in memory obtained from sqlite3_malloc().
165993: ** It is the responsibility of the caller to eventually free this memory
165994: ** using sqlite3_free().
165995: **
165996: ** If an OOM condition is encountered when attempting to allocate memory,
165997: ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
165998: ** if the allocation succeeds, (*pRc) is left unchanged.
165999: */
166000: static char *rbuStrndup(const char *zStr, int *pRc){
166001:   char *zRet = 0;
166002: 
166003:   assert( *pRc==SQLITE_OK );
166004:   if( zStr ){
166005:     size_t nCopy = strlen(zStr) + 1;
166006:     zRet = (char*)sqlite3_malloc64(nCopy);
166007:     if( zRet ){
166008:       memcpy(zRet, zStr, nCopy);
166009:     }else{
166010:       *pRc = SQLITE_NOMEM;
166011:     }
166012:   }
166013: 
166014:   return zRet;
166015: }
166016: 
166017: /*
166018: ** Finalize the statement passed as the second argument.
166019: **
166020: ** If the sqlite3_finalize() call indicates that an error occurs, and the
166021: ** rbu handle error code is not already set, set the error code and error
166022: ** message accordingly.
166023: */
166024: static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
166025:   sqlite3 *db = sqlite3_db_handle(pStmt);
166026:   int rc = sqlite3_finalize(pStmt);
166027:   if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
166028:     p->rc = rc;
166029:     p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166030:   }
166031: }
166032: 
166033: /* Determine the type of a table.
166034: **
166035: **   peType is of type (int*), a pointer to an output parameter of type
166036: **   (int). This call sets the output parameter as follows, depending
166037: **   on the type of the table specified by parameters dbName and zTbl.
166038: **
166039: **     RBU_PK_NOTABLE:       No such table.
166040: **     RBU_PK_NONE:          Table has an implicit rowid.
166041: **     RBU_PK_IPK:           Table has an explicit IPK column.
166042: **     RBU_PK_EXTERNAL:      Table has an external PK index.
166043: **     RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
166044: **     RBU_PK_VTAB:          Table is a virtual table.
166045: **
166046: **   Argument *piPk is also of type (int*), and also points to an output
166047: **   parameter. Unless the table has an external primary key index 
166048: **   (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
166049: **   if the table does have an external primary key index, then *piPk
166050: **   is set to the root page number of the primary key index before
166051: **   returning.
166052: **
166053: ** ALGORITHM:
166054: **
166055: **   if( no entry exists in sqlite_master ){
166056: **     return RBU_PK_NOTABLE
166057: **   }else if( sql for the entry starts with "CREATE VIRTUAL" ){
166058: **     return RBU_PK_VTAB
166059: **   }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
166060: **     if( the index that is the pk exists in sqlite_master ){
166061: **       *piPK = rootpage of that index.
166062: **       return RBU_PK_EXTERNAL
166063: **     }else{
166064: **       return RBU_PK_WITHOUT_ROWID
166065: **     }
166066: **   }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
166067: **     return RBU_PK_IPK
166068: **   }else{
166069: **     return RBU_PK_NONE
166070: **   }
166071: */
166072: static void rbuTableType(
166073:   sqlite3rbu *p,
166074:   const char *zTab,
166075:   int *peType,
166076:   int *piTnum,
166077:   int *piPk
166078: ){
166079:   /*
166080:   ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
166081:   ** 1) PRAGMA index_list = ?
166082:   ** 2) SELECT count(*) FROM sqlite_master where name=%Q 
166083:   ** 3) PRAGMA table_info = ?
166084:   */
166085:   sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
166086: 
166087:   *peType = RBU_PK_NOTABLE;
166088:   *piPk = 0;
166089: 
166090:   assert( p->rc==SQLITE_OK );
166091:   p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg, 
166092:     sqlite3_mprintf(
166093:           "SELECT (sql LIKE 'create virtual%%'), rootpage"
166094:           "  FROM sqlite_master"
166095:           " WHERE name=%Q", zTab
166096:   ));
166097:   if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
166098:     /* Either an error, or no such table. */
166099:     goto rbuTableType_end;
166100:   }
166101:   if( sqlite3_column_int(aStmt[0], 0) ){
166102:     *peType = RBU_PK_VTAB;                     /* virtual table */
166103:     goto rbuTableType_end;
166104:   }
166105:   *piTnum = sqlite3_column_int(aStmt[0], 1);
166106: 
166107:   p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg, 
166108:     sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
166109:   );
166110:   if( p->rc ) goto rbuTableType_end;
166111:   while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
166112:     const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
166113:     const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
166114:     if( zOrig && zIdx && zOrig[0]=='p' ){
166115:       p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg, 
166116:           sqlite3_mprintf(
166117:             "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
166118:       ));
166119:       if( p->rc==SQLITE_OK ){
166120:         if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
166121:           *piPk = sqlite3_column_int(aStmt[2], 0);
166122:           *peType = RBU_PK_EXTERNAL;
166123:         }else{
166124:           *peType = RBU_PK_WITHOUT_ROWID;
166125:         }
166126:       }
166127:       goto rbuTableType_end;
166128:     }
166129:   }
166130: 
166131:   p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg, 
166132:     sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
166133:   );
166134:   if( p->rc==SQLITE_OK ){
166135:     while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
166136:       if( sqlite3_column_int(aStmt[3],5)>0 ){
166137:         *peType = RBU_PK_IPK;                /* explicit IPK column */
166138:         goto rbuTableType_end;
166139:       }
166140:     }
166141:     *peType = RBU_PK_NONE;
166142:   }
166143: 
166144: rbuTableType_end: {
166145:     unsigned int i;
166146:     for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
166147:       rbuFinalize(p, aStmt[i]);
166148:     }
166149:   }
166150: }
166151: 
166152: /*
166153: ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
166154: ** the pIter->abIndexed[] array.
166155: */
166156: static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
166157:   sqlite3_stmt *pList = 0;
166158:   int bIndex = 0;
166159: 
166160:   if( p->rc==SQLITE_OK ){
166161:     memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
166162:     p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
166163:         sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
166164:     );
166165:   }
166166: 
166167:   pIter->nIndex = 0;
166168:   while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
166169:     const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
166170:     sqlite3_stmt *pXInfo = 0;
166171:     if( zIdx==0 ) break;
166172:     p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166173:         sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166174:     );
166175:     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166176:       int iCid = sqlite3_column_int(pXInfo, 1);
166177:       if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
166178:     }
166179:     rbuFinalize(p, pXInfo);
166180:     bIndex = 1;
166181:     pIter->nIndex++;
166182:   }
166183: 
166184:   if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
166185:     /* "PRAGMA index_list" includes the main PK b-tree */
166186:     pIter->nIndex--;
166187:   }
166188: 
166189:   rbuFinalize(p, pList);
166190:   if( bIndex==0 ) pIter->abIndexed = 0;
166191: }
166192: 
166193: 
166194: /*
166195: ** If they are not already populated, populate the pIter->azTblCol[],
166196: ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
166197: ** the table (not index) that the iterator currently points to.
166198: **
166199: ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
166200: ** an error does occur, an error code and error message are also left in 
166201: ** the RBU handle.
166202: */
166203: static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
166204:   if( pIter->azTblCol==0 ){
166205:     sqlite3_stmt *pStmt = 0;
166206:     int nCol = 0;
166207:     int i;                        /* for() loop iterator variable */
166208:     int bRbuRowid = 0;            /* If input table has column "rbu_rowid" */
166209:     int iOrder = 0;
166210:     int iTnum = 0;
166211: 
166212:     /* Figure out the type of table this step will deal with. */
166213:     assert( pIter->eType==0 );
166214:     rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
166215:     if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
166216:       p->rc = SQLITE_ERROR;
166217:       p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
166218:     }
166219:     if( p->rc ) return p->rc;
166220:     if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
166221: 
166222:     assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK 
166223:          || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
166224:          || pIter->eType==RBU_PK_VTAB
166225:     );
166226: 
166227:     /* Populate the azTblCol[] and nTblCol variables based on the columns
166228:     ** of the input table. Ignore any input table columns that begin with
166229:     ** "rbu_".  */
166230:     p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
166231:         sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
166232:     );
166233:     if( p->rc==SQLITE_OK ){
166234:       nCol = sqlite3_column_count(pStmt);
166235:       rbuAllocateIterArrays(p, pIter, nCol);
166236:     }
166237:     for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
166238:       const char *zName = (const char*)sqlite3_column_name(pStmt, i);
166239:       if( sqlite3_strnicmp("rbu_", zName, 4) ){
166240:         char *zCopy = rbuStrndup(zName, &p->rc);
166241:         pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
166242:         pIter->azTblCol[pIter->nTblCol++] = zCopy;
166243:       }
166244:       else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
166245:         bRbuRowid = 1;
166246:       }
166247:     }
166248:     sqlite3_finalize(pStmt);
166249:     pStmt = 0;
166250: 
166251:     if( p->rc==SQLITE_OK
166252:      && rbuIsVacuum(p)==0
166253:      && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
166254:     ){
166255:       p->rc = SQLITE_ERROR;
166256:       p->zErrmsg = sqlite3_mprintf(
166257:           "table %q %s rbu_rowid column", pIter->zDataTbl,
166258:           (bRbuRowid ? "may not have" : "requires")
166259:       );
166260:     }
166261: 
166262:     /* Check that all non-HIDDEN columns in the destination table are also
166263:     ** present in the input table. Populate the abTblPk[], azTblType[] and
166264:     ** aiTblOrder[] arrays at the same time.  */
166265:     if( p->rc==SQLITE_OK ){
166266:       p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg, 
166267:           sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
166268:       );
166269:     }
166270:     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
166271:       const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
166272:       if( zName==0 ) break;  /* An OOM - finalize() below returns S_NOMEM */
166273:       for(i=iOrder; i<pIter->nTblCol; i++){
166274:         if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
166275:       }
166276:       if( i==pIter->nTblCol ){
166277:         p->rc = SQLITE_ERROR;
166278:         p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
166279:             pIter->zDataTbl, zName
166280:         );
166281:       }else{
166282:         int iPk = sqlite3_column_int(pStmt, 5);
166283:         int bNotNull = sqlite3_column_int(pStmt, 3);
166284:         const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
166285: 
166286:         if( i!=iOrder ){
166287:           SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
166288:           SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
166289:         }
166290: 
166291:         pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
166292:         pIter->abTblPk[iOrder] = (iPk!=0);
166293:         pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
166294:         iOrder++;
166295:       }
166296:     }
166297: 
166298:     rbuFinalize(p, pStmt);
166299:     rbuObjIterCacheIndexedCols(p, pIter);
166300:     assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
166301:     assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
166302:   }
166303: 
166304:   return p->rc;
166305: }
166306: 
166307: /*
166308: ** This function constructs and returns a pointer to a nul-terminated 
166309: ** string containing some SQL clause or list based on one or more of the 
166310: ** column names currently stored in the pIter->azTblCol[] array.
166311: */
166312: static char *rbuObjIterGetCollist(
166313:   sqlite3rbu *p,                  /* RBU object */
166314:   RbuObjIter *pIter               /* Object iterator for column names */
166315: ){
166316:   char *zList = 0;
166317:   const char *zSep = "";
166318:   int i;
166319:   for(i=0; i<pIter->nTblCol; i++){
166320:     const char *z = pIter->azTblCol[i];
166321:     zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
166322:     zSep = ", ";
166323:   }
166324:   return zList;
166325: }
166326: 
166327: /*
166328: ** This function is used to create a SELECT list (the list of SQL 
166329: ** expressions that follows a SELECT keyword) for a SELECT statement 
166330: ** used to read from an data_xxx or rbu_tmp_xxx table while updating the 
166331: ** index object currently indicated by the iterator object passed as the 
166332: ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used 
166333: ** to obtain the required information.
166334: **
166335: ** If the index is of the following form:
166336: **
166337: **   CREATE INDEX i1 ON t1(c, b COLLATE nocase);
166338: **
166339: ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column 
166340: ** "ipk", the returned string is:
166341: **
166342: **   "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
166343: **
166344: ** As well as the returned string, three other malloc'd strings are 
166345: ** returned via output parameters. As follows:
166346: **
166347: **   pzImposterCols: ...
166348: **   pzImposterPk: ...
166349: **   pzWhere: ...
166350: */
166351: static char *rbuObjIterGetIndexCols(
166352:   sqlite3rbu *p,                  /* RBU object */
166353:   RbuObjIter *pIter,              /* Object iterator for column names */
166354:   char **pzImposterCols,          /* OUT: Columns for imposter table */
166355:   char **pzImposterPk,            /* OUT: Imposter PK clause */
166356:   char **pzWhere,                 /* OUT: WHERE clause */
166357:   int *pnBind                     /* OUT: Trbul number of columns */
166358: ){
166359:   int rc = p->rc;                 /* Error code */
166360:   int rc2;                        /* sqlite3_finalize() return code */
166361:   char *zRet = 0;                 /* String to return */
166362:   char *zImpCols = 0;             /* String to return via *pzImposterCols */
166363:   char *zImpPK = 0;               /* String to return via *pzImposterPK */
166364:   char *zWhere = 0;               /* String to return via *pzWhere */
166365:   int nBind = 0;                  /* Value to return via *pnBind */
166366:   const char *zCom = "";          /* Set to ", " later on */
166367:   const char *zAnd = "";          /* Set to " AND " later on */
166368:   sqlite3_stmt *pXInfo = 0;       /* PRAGMA index_xinfo = ? */
166369: 
166370:   if( rc==SQLITE_OK ){
166371:     assert( p->zErrmsg==0 );
166372:     rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166373:         sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
166374:     );
166375:   }
166376: 
166377:   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166378:     int iCid = sqlite3_column_int(pXInfo, 1);
166379:     int bDesc = sqlite3_column_int(pXInfo, 3);
166380:     const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
166381:     const char *zCol;
166382:     const char *zType;
166383: 
166384:     if( iCid<0 ){
166385:       /* An integer primary key. If the table has an explicit IPK, use
166386:       ** its name. Otherwise, use "rbu_rowid".  */
166387:       if( pIter->eType==RBU_PK_IPK ){
166388:         int i;
166389:         for(i=0; pIter->abTblPk[i]==0; i++);
166390:         assert( i<pIter->nTblCol );
166391:         zCol = pIter->azTblCol[i];
166392:       }else if( rbuIsVacuum(p) ){
166393:         zCol = "_rowid_";
166394:       }else{
166395:         zCol = "rbu_rowid";
166396:       }
166397:       zType = "INTEGER";
166398:     }else{
166399:       zCol = pIter->azTblCol[iCid];
166400:       zType = pIter->azTblType[iCid];
166401:     }
166402: 
166403:     zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
166404:     if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
166405:       const char *zOrder = (bDesc ? " DESC" : "");
166406:       zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s", 
166407:           zImpPK, zCom, nBind, zCol, zOrder
166408:       );
166409:     }
166410:     zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q", 
166411:         zImpCols, zCom, nBind, zCol, zType, zCollate
166412:     );
166413:     zWhere = sqlite3_mprintf(
166414:         "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
166415:     );
166416:     if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
166417:     zCom = ", ";
166418:     zAnd = " AND ";
166419:     nBind++;
166420:   }
166421: 
166422:   rc2 = sqlite3_finalize(pXInfo);
166423:   if( rc==SQLITE_OK ) rc = rc2;
166424: 
166425:   if( rc!=SQLITE_OK ){
166426:     sqlite3_free(zRet);
166427:     sqlite3_free(zImpCols);
166428:     sqlite3_free(zImpPK);
166429:     sqlite3_free(zWhere);
166430:     zRet = 0;
166431:     zImpCols = 0;
166432:     zImpPK = 0;
166433:     zWhere = 0;
166434:     p->rc = rc;
166435:   }
166436: 
166437:   *pzImposterCols = zImpCols;
166438:   *pzImposterPk = zImpPK;
166439:   *pzWhere = zWhere;
166440:   *pnBind = nBind;
166441:   return zRet;
166442: }
166443: 
166444: /*
166445: ** Assuming the current table columns are "a", "b" and "c", and the zObj
166446: ** paramter is passed "old", return a string of the form:
166447: **
166448: **     "old.a, old.b, old.b"
166449: **
166450: ** With the column names escaped.
166451: **
166452: ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
166453: ** the text ", old._rowid_" to the returned value.
166454: */
166455: static char *rbuObjIterGetOldlist(
166456:   sqlite3rbu *p, 
166457:   RbuObjIter *pIter,
166458:   const char *zObj
166459: ){
166460:   char *zList = 0;
166461:   if( p->rc==SQLITE_OK && pIter->abIndexed ){
166462:     const char *zS = "";
166463:     int i;
166464:     for(i=0; i<pIter->nTblCol; i++){
166465:       if( pIter->abIndexed[i] ){
166466:         const char *zCol = pIter->azTblCol[i];
166467:         zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
166468:       }else{
166469:         zList = sqlite3_mprintf("%z%sNULL", zList, zS);
166470:       }
166471:       zS = ", ";
166472:       if( zList==0 ){
166473:         p->rc = SQLITE_NOMEM;
166474:         break;
166475:       }
166476:     }
166477: 
166478:     /* For a table with implicit rowids, append "old._rowid_" to the list. */
166479:     if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166480:       zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
166481:     }
166482:   }
166483:   return zList;
166484: }
166485: 
166486: /*
166487: ** Return an expression that can be used in a WHERE clause to match the
166488: ** primary key of the current table. For example, if the table is:
166489: **
166490: **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
166491: **
166492: ** Return the string:
166493: **
166494: **   "b = ?1 AND c = ?2"
166495: */
166496: static char *rbuObjIterGetWhere(
166497:   sqlite3rbu *p, 
166498:   RbuObjIter *pIter
166499: ){
166500:   char *zList = 0;
166501:   if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
166502:     zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
166503:   }else if( pIter->eType==RBU_PK_EXTERNAL ){
166504:     const char *zSep = "";
166505:     int i;
166506:     for(i=0; i<pIter->nTblCol; i++){
166507:       if( pIter->abTblPk[i] ){
166508:         zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
166509:         zSep = " AND ";
166510:       }
166511:     }
166512:     zList = rbuMPrintf(p, 
166513:         "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
166514:     );
166515: 
166516:   }else{
166517:     const char *zSep = "";
166518:     int i;
166519:     for(i=0; i<pIter->nTblCol; i++){
166520:       if( pIter->abTblPk[i] ){
166521:         const char *zCol = pIter->azTblCol[i];
166522:         zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
166523:         zSep = " AND ";
166524:       }
166525:     }
166526:   }
166527:   return zList;
166528: }
166529: 
166530: /*
166531: ** The SELECT statement iterating through the keys for the current object
166532: ** (p->objiter.pSelect) currently points to a valid row. However, there
166533: ** is something wrong with the rbu_control value in the rbu_control value
166534: ** stored in the (p->nCol+1)'th column. Set the error code and error message
166535: ** of the RBU handle to something reflecting this.
166536: */
166537: static void rbuBadControlError(sqlite3rbu *p){
166538:   p->rc = SQLITE_ERROR;
166539:   p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
166540: }
166541: 
166542: 
166543: /*
166544: ** Return a nul-terminated string containing the comma separated list of
166545: ** assignments that should be included following the "SET" keyword of
166546: ** an UPDATE statement used to update the table object that the iterator
166547: ** passed as the second argument currently points to if the rbu_control
166548: ** column of the data_xxx table entry is set to zMask.
166549: **
166550: ** The memory for the returned string is obtained from sqlite3_malloc().
166551: ** It is the responsibility of the caller to eventually free it using
166552: ** sqlite3_free(). 
166553: **
166554: ** If an OOM error is encountered when allocating space for the new
166555: ** string, an error code is left in the rbu handle passed as the first
166556: ** argument and NULL is returned. Or, if an error has already occurred
166557: ** when this function is called, NULL is returned immediately, without
166558: ** attempting the allocation or modifying the stored error code.
166559: */
166560: static char *rbuObjIterGetSetlist(
166561:   sqlite3rbu *p,
166562:   RbuObjIter *pIter,
166563:   const char *zMask
166564: ){
166565:   char *zList = 0;
166566:   if( p->rc==SQLITE_OK ){
166567:     int i;
166568: 
166569:     if( (int)strlen(zMask)!=pIter->nTblCol ){
166570:       rbuBadControlError(p);
166571:     }else{
166572:       const char *zSep = "";
166573:       for(i=0; i<pIter->nTblCol; i++){
166574:         char c = zMask[pIter->aiSrcOrder[i]];
166575:         if( c=='x' ){
166576:           zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", 
166577:               zList, zSep, pIter->azTblCol[i], i+1
166578:           );
166579:           zSep = ", ";
166580:         }
166581:         else if( c=='d' ){
166582:           zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)", 
166583:               zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
166584:           );
166585:           zSep = ", ";
166586:         }
166587:         else if( c=='f' ){
166588:           zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)", 
166589:               zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
166590:           );
166591:           zSep = ", ";
166592:         }
166593:       }
166594:     }
166595:   }
166596:   return zList;
166597: }
166598: 
166599: /*
166600: ** Return a nul-terminated string consisting of nByte comma separated
166601: ** "?" expressions. For example, if nByte is 3, return a pointer to
166602: ** a buffer containing the string "?,?,?".
166603: **
166604: ** The memory for the returned string is obtained from sqlite3_malloc().
166605: ** It is the responsibility of the caller to eventually free it using
166606: ** sqlite3_free(). 
166607: **
166608: ** If an OOM error is encountered when allocating space for the new
166609: ** string, an error code is left in the rbu handle passed as the first
166610: ** argument and NULL is returned. Or, if an error has already occurred
166611: ** when this function is called, NULL is returned immediately, without
166612: ** attempting the allocation or modifying the stored error code.
166613: */
166614: static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
166615:   char *zRet = 0;
166616:   int nByte = nBind*2 + 1;
166617: 
166618:   zRet = (char*)rbuMalloc(p, nByte);
166619:   if( zRet ){
166620:     int i;
166621:     for(i=0; i<nBind; i++){
166622:       zRet[i*2] = '?';
166623:       zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
166624:     }
166625:   }
166626:   return zRet;
166627: }
166628: 
166629: /*
166630: ** The iterator currently points to a table (not index) of type 
166631: ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY 
166632: ** declaration for the corresponding imposter table. For example,
166633: ** if the iterator points to a table created as:
166634: **
166635: **   CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
166636: **
166637: ** this function returns:
166638: **
166639: **   PRIMARY KEY("b", "a" DESC)
166640: */
166641: static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
166642:   char *z = 0;
166643:   assert( pIter->zIdx==0 );
166644:   if( p->rc==SQLITE_OK ){
166645:     const char *zSep = "PRIMARY KEY(";
166646:     sqlite3_stmt *pXList = 0;     /* PRAGMA index_list = (pIter->zTbl) */
166647:     sqlite3_stmt *pXInfo = 0;     /* PRAGMA index_xinfo = <pk-index> */
166648:    
166649:     p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
166650:         sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
166651:     );
166652:     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
166653:       const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
166654:       if( zOrig && strcmp(zOrig, "pk")==0 ){
166655:         const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
166656:         if( zIdx ){
166657:           p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166658:               sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166659:           );
166660:         }
166661:         break;
166662:       }
166663:     }
166664:     rbuFinalize(p, pXList);
166665: 
166666:     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166667:       if( sqlite3_column_int(pXInfo, 5) ){
166668:         /* int iCid = sqlite3_column_int(pXInfo, 0); */
166669:         const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
166670:         const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
166671:         z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
166672:         zSep = ", ";
166673:       }
166674:     }
166675:     z = rbuMPrintf(p, "%z)", z);
166676:     rbuFinalize(p, pXInfo);
166677:   }
166678:   return z;
166679: }
166680: 
166681: /*
166682: ** This function creates the second imposter table used when writing to
166683: ** a table b-tree where the table has an external primary key. If the
166684: ** iterator passed as the second argument does not currently point to
166685: ** a table (not index) with an external primary key, this function is a
166686: ** no-op. 
166687: **
166688: ** Assuming the iterator does point to a table with an external PK, this
166689: ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
166690: ** used to access that PK index. For example, if the target table is
166691: ** declared as follows:
166692: **
166693: **   CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
166694: **
166695: ** then the imposter table schema is:
166696: **
166697: **   CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
166698: **
166699: */
166700: static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
166701:   if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
166702:     int tnum = pIter->iPkTnum;    /* Root page of PK index */
166703:     sqlite3_stmt *pQuery = 0;     /* SELECT name ... WHERE rootpage = $tnum */
166704:     const char *zIdx = 0;         /* Name of PK index */
166705:     sqlite3_stmt *pXInfo = 0;     /* PRAGMA main.index_xinfo = $zIdx */
166706:     const char *zComma = "";
166707:     char *zCols = 0;              /* Used to build up list of table cols */
166708:     char *zPk = 0;                /* Used to build up table PK declaration */
166709: 
166710:     /* Figure out the name of the primary key index for the current table.
166711:     ** This is needed for the argument to "PRAGMA index_xinfo". Set
166712:     ** zIdx to point to a nul-terminated string containing this name. */
166713:     p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg, 
166714:         "SELECT name FROM sqlite_master WHERE rootpage = ?"
166715:     );
166716:     if( p->rc==SQLITE_OK ){
166717:       sqlite3_bind_int(pQuery, 1, tnum);
166718:       if( SQLITE_ROW==sqlite3_step(pQuery) ){
166719:         zIdx = (const char*)sqlite3_column_text(pQuery, 0);
166720:       }
166721:     }
166722:     if( zIdx ){
166723:       p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
166724:           sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
166725:       );
166726:     }
166727:     rbuFinalize(p, pQuery);
166728: 
166729:     while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
166730:       int bKey = sqlite3_column_int(pXInfo, 5);
166731:       if( bKey ){
166732:         int iCid = sqlite3_column_int(pXInfo, 1);
166733:         int bDesc = sqlite3_column_int(pXInfo, 3);
166734:         const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
166735:         zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma, 
166736:             iCid, pIter->azTblType[iCid], zCollate
166737:         );
166738:         zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
166739:         zComma = ", ";
166740:       }
166741:     }
166742:     zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
166743:     rbuFinalize(p, pXInfo);
166744: 
166745:     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
166746:     rbuMPrintfExec(p, p->dbMain,
166747:         "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID", 
166748:         zCols, zPk
166749:     );
166750:     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166751:   }
166752: }
166753: 
166754: /*
166755: ** If an error has already occurred when this function is called, it 
166756: ** immediately returns zero (without doing any work). Or, if an error
166757: ** occurs during the execution of this function, it sets the error code
166758: ** in the sqlite3rbu object indicated by the first argument and returns
166759: ** zero.
166760: **
166761: ** The iterator passed as the second argument is guaranteed to point to
166762: ** a table (not an index) when this function is called. This function
166763: ** attempts to create any imposter table required to write to the main
166764: ** table b-tree of the table before returning. Non-zero is returned if
166765: ** an imposter table are created, or zero otherwise.
166766: **
166767: ** An imposter table is required in all cases except RBU_PK_VTAB. Only
166768: ** virtual tables are written to directly. The imposter table has the 
166769: ** same schema as the actual target table (less any UNIQUE constraints). 
166770: ** More precisely, the "same schema" means the same columns, types, 
166771: ** collation sequences. For tables that do not have an external PRIMARY
166772: ** KEY, it also means the same PRIMARY KEY declaration.
166773: */
166774: static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
166775:   if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
166776:     int tnum = pIter->iTnum;
166777:     const char *zComma = "";
166778:     char *zSql = 0;
166779:     int iCol;
166780:     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
166781: 
166782:     for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
166783:       const char *zPk = "";
166784:       const char *zCol = pIter->azTblCol[iCol];
166785:       const char *zColl = 0;
166786: 
166787:       p->rc = sqlite3_table_column_metadata(
166788:           p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
166789:       );
166790: 
166791:       if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
166792:         /* If the target table column is an "INTEGER PRIMARY KEY", add
166793:         ** "PRIMARY KEY" to the imposter table column declaration. */
166794:         zPk = "PRIMARY KEY ";
166795:       }
166796:       zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s", 
166797:           zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
166798:           (pIter->abNotNull[iCol] ? " NOT NULL" : "")
166799:       );
166800:       zComma = ", ";
166801:     }
166802: 
166803:     if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
166804:       char *zPk = rbuWithoutRowidPK(p, pIter);
166805:       if( zPk ){
166806:         zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
166807:       }
166808:     }
166809: 
166810:     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
166811:     rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s", 
166812:         pIter->zTbl, zSql, 
166813:         (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
166814:     );
166815:     sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166816:   }
166817: }
166818: 
166819: /*
166820: ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
166821: ** Specifically a statement of the form:
166822: **
166823: **     INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
166824: **
166825: ** The number of bound variables is equal to the number of columns in
166826: ** the target table, plus one (for the rbu_control column), plus one more 
166827: ** (for the rbu_rowid column) if the target table is an implicit IPK or 
166828: ** virtual table.
166829: */
166830: static void rbuObjIterPrepareTmpInsert(
166831:   sqlite3rbu *p, 
166832:   RbuObjIter *pIter,
166833:   const char *zCollist,
166834:   const char *zRbuRowid
166835: ){
166836:   int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
166837:   char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
166838:   if( zBind ){
166839:     assert( pIter->pTmpInsert==0 );
166840:     p->rc = prepareFreeAndCollectError(
166841:         p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
166842:           "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)", 
166843:           p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
166844:     ));
166845:   }
166846: }
166847: 
166848: static void rbuTmpInsertFunc(
166849:   sqlite3_context *pCtx, 
166850:   int nVal,
166851:   sqlite3_value **apVal
166852: ){
166853:   sqlite3rbu *p = sqlite3_user_data(pCtx);
166854:   int rc = SQLITE_OK;
166855:   int i;
166856: 
166857:   assert( sqlite3_value_int(apVal[0])!=0
166858:       || p->objiter.eType==RBU_PK_EXTERNAL 
166859:       || p->objiter.eType==RBU_PK_NONE 
166860:   );
166861:   if( sqlite3_value_int(apVal[0])!=0 ){
166862:     p->nPhaseOneStep += p->objiter.nIndex;
166863:   }
166864: 
166865:   for(i=0; rc==SQLITE_OK && i<nVal; i++){
166866:     rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
166867:   }
166868:   if( rc==SQLITE_OK ){
166869:     sqlite3_step(p->objiter.pTmpInsert);
166870:     rc = sqlite3_reset(p->objiter.pTmpInsert);
166871:   }
166872: 
166873:   if( rc!=SQLITE_OK ){
166874:     sqlite3_result_error_code(pCtx, rc);
166875:   }
166876: }
166877: 
166878: /*
166879: ** Ensure that the SQLite statement handles required to update the 
166880: ** target database object currently indicated by the iterator passed 
166881: ** as the second argument are available.
166882: */
166883: static int rbuObjIterPrepareAll(
166884:   sqlite3rbu *p, 
166885:   RbuObjIter *pIter,
166886:   int nOffset                     /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
166887: ){
166888:   assert( pIter->bCleanup==0 );
166889:   if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
166890:     const int tnum = pIter->iTnum;
166891:     char *zCollist = 0;           /* List of indexed columns */
166892:     char **pz = &p->zErrmsg;
166893:     const char *zIdx = pIter->zIdx;
166894:     char *zLimit = 0;
166895: 
166896:     if( nOffset ){
166897:       zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
166898:       if( !zLimit ) p->rc = SQLITE_NOMEM;
166899:     }
166900: 
166901:     if( zIdx ){
166902:       const char *zTbl = pIter->zTbl;
166903:       char *zImposterCols = 0;    /* Columns for imposter table */
166904:       char *zImposterPK = 0;      /* Primary key declaration for imposter */
166905:       char *zWhere = 0;           /* WHERE clause on PK columns */
166906:       char *zBind = 0;
166907:       int nBind = 0;
166908: 
166909:       assert( pIter->eType!=RBU_PK_VTAB );
166910:       zCollist = rbuObjIterGetIndexCols(
166911:           p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
166912:       );
166913:       zBind = rbuObjIterGetBindlist(p, nBind);
166914: 
166915:       /* Create the imposter table used to write to this index. */
166916:       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
166917:       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
166918:       rbuMPrintfExec(p, p->dbMain,
166919:           "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
166920:           zTbl, zImposterCols, zImposterPK
166921:       );
166922:       sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
166923: 
166924:       /* Create the statement to insert index entries */
166925:       pIter->nCol = nBind;
166926:       if( p->rc==SQLITE_OK ){
166927:         p->rc = prepareFreeAndCollectError(
166928:             p->dbMain, &pIter->pInsert, &p->zErrmsg,
166929:           sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
166930:         );
166931:       }
166932: 
166933:       /* And to delete index entries */
166934:       if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
166935:         p->rc = prepareFreeAndCollectError(
166936:             p->dbMain, &pIter->pDelete, &p->zErrmsg,
166937:           sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
166938:         );
166939:       }
166940: 
166941:       /* Create the SELECT statement to read keys in sorted order */
166942:       if( p->rc==SQLITE_OK ){
166943:         char *zSql;
166944:         if( rbuIsVacuum(p) ){
166945:           zSql = sqlite3_mprintf(
166946:               "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
166947:               zCollist, 
166948:               pIter->zDataTbl,
166949:               zCollist, zLimit
166950:           );
166951:         }else
166952: 
166953:         if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166954:           zSql = sqlite3_mprintf(
166955:               "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
166956:               zCollist, p->zStateDb, pIter->zDataTbl,
166957:               zCollist, zLimit
166958:           );
166959:         }else{
166960:           zSql = sqlite3_mprintf(
166961:               "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
166962:               "UNION ALL "
166963:               "SELECT %s, rbu_control FROM '%q' "
166964:               "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
166965:               "ORDER BY %s%s",
166966:               zCollist, p->zStateDb, pIter->zDataTbl, 
166967:               zCollist, pIter->zDataTbl, 
166968:               zCollist, zLimit
166969:           );
166970:         }
166971:         p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
166972:       }
166973: 
166974:       sqlite3_free(zImposterCols);
166975:       sqlite3_free(zImposterPK);
166976:       sqlite3_free(zWhere);
166977:       sqlite3_free(zBind);
166978:     }else{
166979:       int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
166980:                     ||(pIter->eType==RBU_PK_NONE)
166981:                     ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
166982:       const char *zTbl = pIter->zTbl;       /* Table this step applies to */
166983:       const char *zWrite;                   /* Imposter table name */
166984: 
166985:       char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
166986:       char *zWhere = rbuObjIterGetWhere(p, pIter);
166987:       char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
166988:       char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
166989: 
166990:       zCollist = rbuObjIterGetCollist(p, pIter);
166991:       pIter->nCol = pIter->nTblCol;
166992: 
166993:       /* Create the imposter table or tables (if required). */
166994:       rbuCreateImposterTable(p, pIter);
166995:       rbuCreateImposterTable2(p, pIter);
166996:       zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
166997: 
166998:       /* Create the INSERT statement to write to the target PK b-tree */
166999:       if( p->rc==SQLITE_OK ){
167000:         p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
167001:             sqlite3_mprintf(
167002:               "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)", 
167003:               zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
167004:             )
167005:         );
167006:       }
167007: 
167008:       /* Create the DELETE statement to write to the target PK b-tree.
167009:       ** Because it only performs INSERT operations, this is not required for
167010:       ** an rbu vacuum handle.  */
167011:       if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
167012:         p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
167013:             sqlite3_mprintf(
167014:               "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
167015:             )
167016:         );
167017:       }
167018: 
167019:       if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
167020:         const char *zRbuRowid = "";
167021:         if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
167022:           zRbuRowid = ", rbu_rowid";
167023:         }
167024: 
167025:         /* Create the rbu_tmp_xxx table and the triggers to populate it. */
167026:         rbuMPrintfExec(p, p->dbRbu,
167027:             "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
167028:             "SELECT *%s FROM '%q' WHERE 0;"
167029:             , p->zStateDb, pIter->zDataTbl
167030:             , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
167031:             , pIter->zDataTbl
167032:         );
167033: 
167034:         rbuMPrintfExec(p, p->dbMain,
167035:             "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
167036:             "BEGIN "
167037:             "  SELECT rbu_tmp_insert(3, %s);"
167038:             "END;"
167039: 
167040:             "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
167041:             "BEGIN "
167042:             "  SELECT rbu_tmp_insert(3, %s);"
167043:             "END;"
167044: 
167045:             "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
167046:             "BEGIN "
167047:             "  SELECT rbu_tmp_insert(4, %s);"
167048:             "END;",
167049:             zWrite, zTbl, zOldlist,
167050:             zWrite, zTbl, zOldlist,
167051:             zWrite, zTbl, zNewlist
167052:         );
167053: 
167054:         if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
167055:           rbuMPrintfExec(p, p->dbMain,
167056:               "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
167057:               "BEGIN "
167058:               "  SELECT rbu_tmp_insert(0, %s);"
167059:               "END;",
167060:               zWrite, zTbl, zNewlist
167061:           );
167062:         }
167063: 
167064:         rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
167065:       }
167066: 
167067:       /* Create the SELECT statement to read keys from data_xxx */
167068:       if( p->rc==SQLITE_OK ){
167069:         const char *zRbuRowid = "";
167070:         if( bRbuRowid ){
167071:           zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
167072:         }
167073:         p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
167074:             sqlite3_mprintf(
167075:               "SELECT %s,%s rbu_control%s FROM '%q'%s", 
167076:               zCollist, 
167077:               (rbuIsVacuum(p) ? "0 AS " : ""),
167078:               zRbuRowid,
167079:               pIter->zDataTbl, zLimit
167080:             )
167081:         );
167082:       }
167083: 
167084:       sqlite3_free(zWhere);
167085:       sqlite3_free(zOldlist);
167086:       sqlite3_free(zNewlist);
167087:       sqlite3_free(zBindings);
167088:     }
167089:     sqlite3_free(zCollist);
167090:     sqlite3_free(zLimit);
167091:   }
167092:   
167093:   return p->rc;
167094: }
167095: 
167096: /*
167097: ** Set output variable *ppStmt to point to an UPDATE statement that may
167098: ** be used to update the imposter table for the main table b-tree of the
167099: ** table object that pIter currently points to, assuming that the 
167100: ** rbu_control column of the data_xyz table contains zMask.
167101: ** 
167102: ** If the zMask string does not specify any columns to update, then this
167103: ** is not an error. Output variable *ppStmt is set to NULL in this case.
167104: */
167105: static int rbuGetUpdateStmt(
167106:   sqlite3rbu *p,                  /* RBU handle */
167107:   RbuObjIter *pIter,              /* Object iterator */
167108:   const char *zMask,              /* rbu_control value ('x.x.') */
167109:   sqlite3_stmt **ppStmt           /* OUT: UPDATE statement handle */
167110: ){
167111:   RbuUpdateStmt **pp;
167112:   RbuUpdateStmt *pUp = 0;
167113:   int nUp = 0;
167114: 
167115:   /* In case an error occurs */
167116:   *ppStmt = 0;
167117: 
167118:   /* Search for an existing statement. If one is found, shift it to the front
167119:   ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
167120:   ** to the number of statements currently in the cache and pUp to the
167121:   ** last object in the list.  */
167122:   for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
167123:     pUp = *pp;
167124:     if( strcmp(pUp->zMask, zMask)==0 ){
167125:       *pp = pUp->pNext;
167126:       pUp->pNext = pIter->pRbuUpdate;
167127:       pIter->pRbuUpdate = pUp;
167128:       *ppStmt = pUp->pUpdate; 
167129:       return SQLITE_OK;
167130:     }
167131:     nUp++;
167132:   }
167133:   assert( pUp==0 || pUp->pNext==0 );
167134: 
167135:   if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
167136:     for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
167137:     *pp = 0;
167138:     sqlite3_finalize(pUp->pUpdate);
167139:     pUp->pUpdate = 0;
167140:   }else{
167141:     pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
167142:   }
167143: 
167144:   if( pUp ){
167145:     char *zWhere = rbuObjIterGetWhere(p, pIter);
167146:     char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
167147:     char *zUpdate = 0;
167148: 
167149:     pUp->zMask = (char*)&pUp[1];
167150:     memcpy(pUp->zMask, zMask, pIter->nTblCol);
167151:     pUp->pNext = pIter->pRbuUpdate;
167152:     pIter->pRbuUpdate = pUp;
167153: 
167154:     if( zSet ){
167155:       const char *zPrefix = "";
167156: 
167157:       if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
167158:       zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s", 
167159:           zPrefix, pIter->zTbl, zSet, zWhere
167160:       );
167161:       p->rc = prepareFreeAndCollectError(
167162:           p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
167163:       );
167164:       *ppStmt = pUp->pUpdate;
167165:     }
167166:     sqlite3_free(zWhere);
167167:     sqlite3_free(zSet);
167168:   }
167169: 
167170:   return p->rc;
167171: }
167172: 
167173: static sqlite3 *rbuOpenDbhandle(
167174:   sqlite3rbu *p, 
167175:   const char *zName, 
167176:   int bUseVfs
167177: ){
167178:   sqlite3 *db = 0;
167179:   if( p->rc==SQLITE_OK ){
167180:     const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
167181:     p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
167182:     if( p->rc ){
167183:       p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
167184:       sqlite3_close(db);
167185:       db = 0;
167186:     }
167187:   }
167188:   return db;
167189: }
167190: 
167191: /*
167192: ** Free an RbuState object allocated by rbuLoadState().
167193: */
167194: static void rbuFreeState(RbuState *p){
167195:   if( p ){
167196:     sqlite3_free(p->zTbl);
167197:     sqlite3_free(p->zIdx);
167198:     sqlite3_free(p);
167199:   }
167200: }
167201: 
167202: /*
167203: ** Allocate an RbuState object and load the contents of the rbu_state 
167204: ** table into it. Return a pointer to the new object. It is the 
167205: ** responsibility of the caller to eventually free the object using
167206: ** sqlite3_free().
167207: **
167208: ** If an error occurs, leave an error code and message in the rbu handle
167209: ** and return NULL.
167210: */
167211: static RbuState *rbuLoadState(sqlite3rbu *p){
167212:   RbuState *pRet = 0;
167213:   sqlite3_stmt *pStmt = 0;
167214:   int rc;
167215:   int rc2;
167216: 
167217:   pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
167218:   if( pRet==0 ) return 0;
167219: 
167220:   rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg, 
167221:       sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
167222:   );
167223:   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
167224:     switch( sqlite3_column_int(pStmt, 0) ){
167225:       case RBU_STATE_STAGE:
167226:         pRet->eStage = sqlite3_column_int(pStmt, 1);
167227:         if( pRet->eStage!=RBU_STAGE_OAL
167228:          && pRet->eStage!=RBU_STAGE_MOVE
167229:          && pRet->eStage!=RBU_STAGE_CKPT
167230:         ){
167231:           p->rc = SQLITE_CORRUPT;
167232:         }
167233:         break;
167234: 
167235:       case RBU_STATE_TBL:
167236:         pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
167237:         break;
167238: 
167239:       case RBU_STATE_IDX:
167240:         pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
167241:         break;
167242: 
167243:       case RBU_STATE_ROW:
167244:         pRet->nRow = sqlite3_column_int(pStmt, 1);
167245:         break;
167246: 
167247:       case RBU_STATE_PROGRESS:
167248:         pRet->nProgress = sqlite3_column_int64(pStmt, 1);
167249:         break;
167250: 
167251:       case RBU_STATE_CKPT:
167252:         pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
167253:         break;
167254: 
167255:       case RBU_STATE_COOKIE:
167256:         pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
167257:         break;
167258: 
167259:       case RBU_STATE_OALSZ:
167260:         pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
167261:         break;
167262: 
167263:       case RBU_STATE_PHASEONESTEP:
167264:         pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
167265:         break;
167266: 
167267:       default:
167268:         rc = SQLITE_CORRUPT;
167269:         break;
167270:     }
167271:   }
167272:   rc2 = sqlite3_finalize(pStmt);
167273:   if( rc==SQLITE_OK ) rc = rc2;
167274: 
167275:   p->rc = rc;
167276:   return pRet;
167277: }
167278: 
167279: 
167280: /*
167281: ** Open the database handle and attach the RBU database as "rbu". If an
167282: ** error occurs, leave an error code and message in the RBU handle.
167283: */
167284: static void rbuOpenDatabase(sqlite3rbu *p){
167285:   assert( p->rc==SQLITE_OK );
167286:   assert( p->dbMain==0 && p->dbRbu==0 );
167287:   assert( rbuIsVacuum(p) || p->zTarget!=0 );
167288: 
167289:   /* Open the RBU database */
167290:   p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
167291: 
167292:   if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167293:     sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
167294:   }
167295: 
167296:   /* If using separate RBU and state databases, attach the state database to
167297:   ** the RBU db handle now.  */
167298:   if( p->zState ){
167299:     rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
167300:     memcpy(p->zStateDb, "stat", 4);
167301:   }else{
167302:     memcpy(p->zStateDb, "main", 4);
167303:   }
167304: 
167305: #if 0
167306:   if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167307:     p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
167308:   }
167309: #endif
167310: 
167311:   /* If it has not already been created, create the rbu_state table */
167312:   rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
167313: 
167314: #if 0
167315:   if( rbuIsVacuum(p) ){
167316:     if( p->rc==SQLITE_OK ){
167317:       int rc2;
167318:       int bOk = 0;
167319:       sqlite3_stmt *pCnt = 0;
167320:       p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
167321:           "SELECT count(*) FROM stat.sqlite_master"
167322:       );
167323:       if( p->rc==SQLITE_OK 
167324:        && sqlite3_step(pCnt)==SQLITE_ROW
167325:        && 1==sqlite3_column_int(pCnt, 0)
167326:       ){
167327:         bOk = 1;
167328:       }
167329:       rc2 = sqlite3_finalize(pCnt);
167330:       if( p->rc==SQLITE_OK ) p->rc = rc2;
167331: 
167332:       if( p->rc==SQLITE_OK && bOk==0 ){
167333:         p->rc = SQLITE_ERROR;
167334:         p->zErrmsg = sqlite3_mprintf("invalid state database");
167335:       }
167336:     
167337:       if( p->rc==SQLITE_OK ){
167338:         p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
167339:       }
167340:     }
167341:   }
167342: #endif
167343: 
167344:   if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
167345:     int bOpen = 0;
167346:     int rc;
167347:     p->nRbu = 0;
167348:     p->pRbuFd = 0;
167349:     rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
167350:     if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
167351:     if( p->eStage>=RBU_STAGE_MOVE ){
167352:       bOpen = 1;
167353:     }else{
167354:       RbuState *pState = rbuLoadState(p);
167355:       if( pState ){
167356:         bOpen = (pState->eStage>RBU_STAGE_MOVE);
167357:         rbuFreeState(pState);
167358:       }
167359:     }
167360:     if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
167361:   }
167362: 
167363:   p->eStage = 0;
167364:   if( p->rc==SQLITE_OK && p->dbMain==0 ){
167365:     if( !rbuIsVacuum(p) ){
167366:       p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
167367:     }else if( p->pRbuFd->pWalFd ){
167368:       p->rc = SQLITE_ERROR;
167369:       p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
167370:     }else{
167371:       char *zTarget;
167372:       char *zExtra = 0;
167373:       if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
167374:         zExtra = &p->zRbu[5];
167375:         while( *zExtra ){
167376:           if( *zExtra++=='?' ) break;
167377:         }
167378:         if( *zExtra=='\0' ) zExtra = 0;
167379:       }
167380: 
167381:       zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s", 
167382:           sqlite3_db_filename(p->dbRbu, "main"),
167383:           (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
167384:       );
167385: 
167386:       if( zTarget==0 ){
167387:         p->rc = SQLITE_NOMEM;
167388:         return;
167389:       }
167390:       p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
167391:       sqlite3_free(zTarget);
167392:     }
167393:   }
167394: 
167395:   if( p->rc==SQLITE_OK ){
167396:     p->rc = sqlite3_create_function(p->dbMain, 
167397:         "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
167398:     );
167399:   }
167400: 
167401:   if( p->rc==SQLITE_OK ){
167402:     p->rc = sqlite3_create_function(p->dbMain, 
167403:         "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
167404:     );
167405:   }
167406: 
167407:   if( p->rc==SQLITE_OK ){
167408:     p->rc = sqlite3_create_function(p->dbRbu, 
167409:         "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
167410:     );
167411:   }
167412: 
167413:   if( p->rc==SQLITE_OK ){
167414:     p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
167415:   }
167416:   rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
167417: 
167418:   /* Mark the database file just opened as an RBU target database. If 
167419:   ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
167420:   ** This is an error.  */
167421:   if( p->rc==SQLITE_OK ){
167422:     p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
167423:   }
167424: 
167425:   if( p->rc==SQLITE_NOTFOUND ){
167426:     p->rc = SQLITE_ERROR;
167427:     p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
167428:   }
167429: }
167430: 
167431: /*
167432: ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
167433: ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
167434: **
167435: ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
167436: ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
167437: ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
167438: ** three characters, then shorten the suffix on z[] to be the last three
167439: ** characters of the original suffix.
167440: **
167441: ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
167442: ** do the suffix shortening regardless of URI parameter.
167443: **
167444: ** Examples:
167445: **
167446: **     test.db-journal    =>   test.nal
167447: **     test.db-wal        =>   test.wal
167448: **     test.db-shm        =>   test.shm
167449: **     test.db-mj7f3319fa =>   test.9fa
167450: */
167451: static void rbuFileSuffix3(const char *zBase, char *z){
167452: #ifdef SQLITE_ENABLE_8_3_NAMES
167453: #if SQLITE_ENABLE_8_3_NAMES<2
167454:   if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
167455: #endif
167456:   {
167457:     int i, sz;
167458:     sz = (int)strlen(z)&0xffffff;
167459:     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
167460:     if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
167461:   }
167462: #endif
167463: }
167464: 
167465: /*
167466: ** Return the current wal-index header checksum for the target database 
167467: ** as a 64-bit integer.
167468: **
167469: ** The checksum is store in the first page of xShmMap memory as an 8-byte 
167470: ** blob starting at byte offset 40.
167471: */
167472: static i64 rbuShmChecksum(sqlite3rbu *p){
167473:   i64 iRet = 0;
167474:   if( p->rc==SQLITE_OK ){
167475:     sqlite3_file *pDb = p->pTargetFd->pReal;
167476:     u32 volatile *ptr;
167477:     p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
167478:     if( p->rc==SQLITE_OK ){
167479:       iRet = ((i64)ptr[10] << 32) + ptr[11];
167480:     }
167481:   }
167482:   return iRet;
167483: }
167484: 
167485: /*
167486: ** This function is called as part of initializing or reinitializing an
167487: ** incremental checkpoint. 
167488: **
167489: ** It populates the sqlite3rbu.aFrame[] array with the set of 
167490: ** (wal frame -> db page) copy operations required to checkpoint the 
167491: ** current wal file, and obtains the set of shm locks required to safely 
167492: ** perform the copy operations directly on the file-system.
167493: **
167494: ** If argument pState is not NULL, then the incremental checkpoint is
167495: ** being resumed. In this case, if the checksum of the wal-index-header
167496: ** following recovery is not the same as the checksum saved in the RbuState
167497: ** object, then the rbu handle is set to DONE state. This occurs if some
167498: ** other client appends a transaction to the wal file in the middle of
167499: ** an incremental checkpoint.
167500: */
167501: static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
167502: 
167503:   /* If pState is NULL, then the wal file may not have been opened and
167504:   ** recovered. Running a read-statement here to ensure that doing so
167505:   ** does not interfere with the "capture" process below.  */
167506:   if( pState==0 ){
167507:     p->eStage = 0;
167508:     if( p->rc==SQLITE_OK ){
167509:       p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
167510:     }
167511:   }
167512: 
167513:   /* Assuming no error has occurred, run a "restart" checkpoint with the
167514:   ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
167515:   ** special behaviour in the rbu VFS:
167516:   **
167517:   **   * If the exclusive shm WRITER or READ0 lock cannot be obtained,
167518:   **     the checkpoint fails with SQLITE_BUSY (normally SQLite would
167519:   **     proceed with running a passive checkpoint instead of failing).
167520:   **
167521:   **   * Attempts to read from the *-wal file or write to the database file
167522:   **     do not perform any IO. Instead, the frame/page combinations that
167523:   **     would be read/written are recorded in the sqlite3rbu.aFrame[]
167524:   **     array.
167525:   **
167526:   **   * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER, 
167527:   **     READ0 and CHECKPOINT locks taken as part of the checkpoint are
167528:   **     no-ops. These locks will not be released until the connection
167529:   **     is closed.
167530:   **
167531:   **   * Attempting to xSync() the database file causes an SQLITE_INTERNAL 
167532:   **     error.
167533:   **
167534:   ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
167535:   ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
167536:   ** array populated with a set of (frame -> page) mappings. Because the 
167537:   ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy 
167538:   ** data from the wal file into the database file according to the 
167539:   ** contents of aFrame[].
167540:   */
167541:   if( p->rc==SQLITE_OK ){
167542:     int rc2;
167543:     p->eStage = RBU_STAGE_CAPTURE;
167544:     rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
167545:     if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
167546:   }
167547: 
167548:   if( p->rc==SQLITE_OK ){
167549:     p->eStage = RBU_STAGE_CKPT;
167550:     p->nStep = (pState ? pState->nRow : 0);
167551:     p->aBuf = rbuMalloc(p, p->pgsz);
167552:     p->iWalCksum = rbuShmChecksum(p);
167553:   }
167554: 
167555:   if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
167556:     p->rc = SQLITE_DONE;
167557:     p->eStage = RBU_STAGE_DONE;
167558:   }
167559: }
167560: 
167561: /*
167562: ** Called when iAmt bytes are read from offset iOff of the wal file while
167563: ** the rbu object is in capture mode. Record the frame number of the frame
167564: ** being read in the aFrame[] array.
167565: */
167566: static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
167567:   const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
167568:   u32 iFrame;
167569: 
167570:   if( pRbu->mLock!=mReq ){
167571:     pRbu->rc = SQLITE_BUSY;
167572:     return SQLITE_INTERNAL;
167573:   }
167574: 
167575:   pRbu->pgsz = iAmt;
167576:   if( pRbu->nFrame==pRbu->nFrameAlloc ){
167577:     int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
167578:     RbuFrame *aNew;
167579:     aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
167580:     if( aNew==0 ) return SQLITE_NOMEM;
167581:     pRbu->aFrame = aNew;
167582:     pRbu->nFrameAlloc = nNew;
167583:   }
167584: 
167585:   iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
167586:   if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
167587:   pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
167588:   pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
167589:   pRbu->nFrame++;
167590:   return SQLITE_OK;
167591: }
167592: 
167593: /*
167594: ** Called when a page of data is written to offset iOff of the database
167595: ** file while the rbu handle is in capture mode. Record the page number 
167596: ** of the page being written in the aFrame[] array.
167597: */
167598: static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
167599:   pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
167600:   return SQLITE_OK;
167601: }
167602: 
167603: /*
167604: ** This is called as part of an incremental checkpoint operation. Copy
167605: ** a single frame of data from the wal file into the database file, as
167606: ** indicated by the RbuFrame object.
167607: */
167608: static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
167609:   sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
167610:   sqlite3_file *pDb = p->pTargetFd->pReal;
167611:   i64 iOff;
167612: 
167613:   assert( p->rc==SQLITE_OK );
167614:   iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
167615:   p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
167616:   if( p->rc ) return;
167617: 
167618:   iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
167619:   p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
167620: }
167621: 
167622: 
167623: /*
167624: ** Take an EXCLUSIVE lock on the database file.
167625: */
167626: static void rbuLockDatabase(sqlite3rbu *p){
167627:   sqlite3_file *pReal = p->pTargetFd->pReal;
167628:   assert( p->rc==SQLITE_OK );
167629:   p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
167630:   if( p->rc==SQLITE_OK ){
167631:     p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
167632:   }
167633: }
167634: 
167635: #if defined(_WIN32_WCE)
167636: static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
167637:   int nChar;
167638:   LPWSTR zWideFilename;
167639: 
167640:   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
167641:   if( nChar==0 ){
167642:     return 0;
167643:   }
167644:   zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
167645:   if( zWideFilename==0 ){
167646:     return 0;
167647:   }
167648:   memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
167649:   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
167650:                                 nChar);
167651:   if( nChar==0 ){
167652:     sqlite3_free(zWideFilename);
167653:     zWideFilename = 0;
167654:   }
167655:   return zWideFilename;
167656: }
167657: #endif
167658: 
167659: /*
167660: ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
167661: ** on the database file. This proc moves the *-oal file to the *-wal path,
167662: ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
167663: ** If an error occurs, leave an error code and error message in the rbu 
167664: ** handle.
167665: */
167666: static void rbuMoveOalFile(sqlite3rbu *p){
167667:   const char *zBase = sqlite3_db_filename(p->dbMain, "main");
167668:   const char *zMove = zBase;
167669:   char *zOal;
167670:   char *zWal;
167671: 
167672:   if( rbuIsVacuum(p) ){
167673:     zMove = sqlite3_db_filename(p->dbRbu, "main");
167674:   }
167675:   zOal = sqlite3_mprintf("%s-oal", zMove);
167676:   zWal = sqlite3_mprintf("%s-wal", zMove);
167677: 
167678:   assert( p->eStage==RBU_STAGE_MOVE );
167679:   assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
167680:   if( zWal==0 || zOal==0 ){
167681:     p->rc = SQLITE_NOMEM;
167682:   }else{
167683:     /* Move the *-oal file to *-wal. At this point connection p->db is
167684:     ** holding a SHARED lock on the target database file (because it is
167685:     ** in WAL mode). So no other connection may be writing the db. 
167686:     **
167687:     ** In order to ensure that there are no database readers, an EXCLUSIVE
167688:     ** lock is obtained here before the *-oal is moved to *-wal.
167689:     */
167690:     rbuLockDatabase(p);
167691:     if( p->rc==SQLITE_OK ){
167692:       rbuFileSuffix3(zBase, zWal);
167693:       rbuFileSuffix3(zBase, zOal);
167694: 
167695:       /* Re-open the databases. */
167696:       rbuObjIterFinalize(&p->objiter);
167697:       sqlite3_close(p->dbRbu);
167698:       sqlite3_close(p->dbMain);
167699:       p->dbMain = 0;
167700:       p->dbRbu = 0;
167701: 
167702: #if defined(_WIN32_WCE)
167703:       {
167704:         LPWSTR zWideOal;
167705:         LPWSTR zWideWal;
167706: 
167707:         zWideOal = rbuWinUtf8ToUnicode(zOal);
167708:         if( zWideOal ){
167709:           zWideWal = rbuWinUtf8ToUnicode(zWal);
167710:           if( zWideWal ){
167711:             if( MoveFileW(zWideOal, zWideWal) ){
167712:               p->rc = SQLITE_OK;
167713:             }else{
167714:               p->rc = SQLITE_IOERR;
167715:             }
167716:             sqlite3_free(zWideWal);
167717:           }else{
167718:             p->rc = SQLITE_IOERR_NOMEM;
167719:           }
167720:           sqlite3_free(zWideOal);
167721:         }else{
167722:           p->rc = SQLITE_IOERR_NOMEM;
167723:         }
167724:       }
167725: #else
167726:       p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
167727: #endif
167728: 
167729:       if( p->rc==SQLITE_OK ){
167730:         rbuOpenDatabase(p);
167731:         rbuSetupCheckpoint(p, 0);
167732:       }
167733:     }
167734:   }
167735: 
167736:   sqlite3_free(zWal);
167737:   sqlite3_free(zOal);
167738: }
167739: 
167740: /*
167741: ** The SELECT statement iterating through the keys for the current object
167742: ** (p->objiter.pSelect) currently points to a valid row. This function
167743: ** determines the type of operation requested by this row and returns
167744: ** one of the following values to indicate the result:
167745: **
167746: **     * RBU_INSERT
167747: **     * RBU_DELETE
167748: **     * RBU_IDX_DELETE
167749: **     * RBU_UPDATE
167750: **
167751: ** If RBU_UPDATE is returned, then output variable *pzMask is set to
167752: ** point to the text value indicating the columns to update.
167753: **
167754: ** If the rbu_control field contains an invalid value, an error code and
167755: ** message are left in the RBU handle and zero returned.
167756: */
167757: static int rbuStepType(sqlite3rbu *p, const char **pzMask){
167758:   int iCol = p->objiter.nCol;     /* Index of rbu_control column */
167759:   int res = 0;                    /* Return value */
167760: 
167761:   switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
167762:     case SQLITE_INTEGER: {
167763:       int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
167764:       switch( iVal ){
167765:         case 0: res = RBU_INSERT;     break;
167766:         case 1: res = RBU_DELETE;     break;
167767:         case 2: res = RBU_REPLACE;    break;
167768:         case 3: res = RBU_IDX_DELETE; break;
167769:         case 4: res = RBU_IDX_INSERT; break;
167770:       }
167771:       break;
167772:     }
167773: 
167774:     case SQLITE_TEXT: {
167775:       const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
167776:       if( z==0 ){
167777:         p->rc = SQLITE_NOMEM;
167778:       }else{
167779:         *pzMask = (const char*)z;
167780:       }
167781:       res = RBU_UPDATE;
167782: 
167783:       break;
167784:     }
167785: 
167786:     default:
167787:       break;
167788:   }
167789: 
167790:   if( res==0 ){
167791:     rbuBadControlError(p);
167792:   }
167793:   return res;
167794: }
167795: 
167796: #ifdef SQLITE_DEBUG
167797: /*
167798: ** Assert that column iCol of statement pStmt is named zName.
167799: */
167800: static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
167801:   const char *zCol = sqlite3_column_name(pStmt, iCol);
167802:   assert( 0==sqlite3_stricmp(zName, zCol) );
167803: }
167804: #else
167805: # define assertColumnName(x,y,z)
167806: #endif
167807: 
167808: /*
167809: ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
167810: ** RBU_IDX_DELETE. This function performs the work of a single
167811: ** sqlite3rbu_step() call for the type of operation specified by eType.
167812: */
167813: static void rbuStepOneOp(sqlite3rbu *p, int eType){
167814:   RbuObjIter *pIter = &p->objiter;
167815:   sqlite3_value *pVal;
167816:   sqlite3_stmt *pWriter;
167817:   int i;
167818: 
167819:   assert( p->rc==SQLITE_OK );
167820:   assert( eType!=RBU_DELETE || pIter->zIdx==0 );
167821:   assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
167822:        || eType==RBU_INSERT || eType==RBU_IDX_INSERT
167823:   );
167824: 
167825:   /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
167826:   ** statement below does actually delete a row, nPhaseOneStep will be
167827:   ** incremented by the same amount when SQL function rbu_tmp_insert()
167828:   ** is invoked by the trigger.  */
167829:   if( eType==RBU_DELETE ){
167830:     p->nPhaseOneStep -= p->objiter.nIndex;
167831:   }
167832: 
167833:   if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
167834:     pWriter = pIter->pDelete;
167835:   }else{
167836:     pWriter = pIter->pInsert;
167837:   }
167838: 
167839:   for(i=0; i<pIter->nCol; i++){
167840:     /* If this is an INSERT into a table b-tree and the table has an
167841:     ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
167842:     ** to write a NULL into the IPK column. That is not permitted.  */
167843:     if( eType==RBU_INSERT 
167844:      && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i] 
167845:      && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
167846:     ){
167847:       p->rc = SQLITE_MISMATCH;
167848:       p->zErrmsg = sqlite3_mprintf("datatype mismatch");
167849:       return;
167850:     }
167851: 
167852:     if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
167853:       continue;
167854:     }
167855: 
167856:     pVal = sqlite3_column_value(pIter->pSelect, i);
167857:     p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
167858:     if( p->rc ) return;
167859:   }
167860:   if( pIter->zIdx==0 ){
167861:     if( pIter->eType==RBU_PK_VTAB 
167862:      || pIter->eType==RBU_PK_NONE 
167863:      || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p)) 
167864:     ){
167865:       /* For a virtual table, or a table with no primary key, the 
167866:       ** SELECT statement is:
167867:       **
167868:       **   SELECT <cols>, rbu_control, rbu_rowid FROM ....
167869:       **
167870:       ** Hence column_value(pIter->nCol+1).
167871:       */
167872:       assertColumnName(pIter->pSelect, pIter->nCol+1, 
167873:           rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
167874:       );
167875:       pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
167876:       p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
167877:     }
167878:   }
167879:   if( p->rc==SQLITE_OK ){
167880:     sqlite3_step(pWriter);
167881:     p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
167882:   }
167883: }
167884: 
167885: /*
167886: ** This function does the work for an sqlite3rbu_step() call.
167887: **
167888: ** The object-iterator (p->objiter) currently points to a valid object,
167889: ** and the input cursor (p->objiter.pSelect) currently points to a valid
167890: ** input row. Perform whatever processing is required and return.
167891: **
167892: ** If no  error occurs, SQLITE_OK is returned. Otherwise, an error code
167893: ** and message is left in the RBU handle and a copy of the error code
167894: ** returned.
167895: */
167896: static int rbuStep(sqlite3rbu *p){
167897:   RbuObjIter *pIter = &p->objiter;
167898:   const char *zMask = 0;
167899:   int eType = rbuStepType(p, &zMask);
167900: 
167901:   if( eType ){
167902:     assert( eType==RBU_INSERT     || eType==RBU_DELETE
167903:          || eType==RBU_REPLACE    || eType==RBU_IDX_DELETE
167904:          || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
167905:     );
167906:     assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
167907: 
167908:     if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
167909:       rbuBadControlError(p);
167910:     }
167911:     else if( eType==RBU_REPLACE ){
167912:       if( pIter->zIdx==0 ){
167913:         p->nPhaseOneStep += p->objiter.nIndex;
167914:         rbuStepOneOp(p, RBU_DELETE);
167915:       }
167916:       if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
167917:     }
167918:     else if( eType!=RBU_UPDATE ){
167919:       rbuStepOneOp(p, eType);
167920:     }
167921:     else{
167922:       sqlite3_value *pVal;
167923:       sqlite3_stmt *pUpdate = 0;
167924:       assert( eType==RBU_UPDATE );
167925:       p->nPhaseOneStep -= p->objiter.nIndex;
167926:       rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
167927:       if( pUpdate ){
167928:         int i;
167929:         for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
167930:           char c = zMask[pIter->aiSrcOrder[i]];
167931:           pVal = sqlite3_column_value(pIter->pSelect, i);
167932:           if( pIter->abTblPk[i] || c!='.' ){
167933:             p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
167934:           }
167935:         }
167936:         if( p->rc==SQLITE_OK 
167937:          && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE) 
167938:         ){
167939:           /* Bind the rbu_rowid value to column _rowid_ */
167940:           assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
167941:           pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
167942:           p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
167943:         }
167944:         if( p->rc==SQLITE_OK ){
167945:           sqlite3_step(pUpdate);
167946:           p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
167947:         }
167948:       }
167949:     }
167950:   }
167951:   return p->rc;
167952: }
167953: 
167954: /*
167955: ** Increment the schema cookie of the main database opened by p->dbMain.
167956: **
167957: ** Or, if this is an RBU vacuum, set the schema cookie of the main db
167958: ** opened by p->dbMain to one more than the schema cookie of the main
167959: ** db opened by p->dbRbu.
167960: */
167961: static void rbuIncrSchemaCookie(sqlite3rbu *p){
167962:   if( p->rc==SQLITE_OK ){
167963:     sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
167964:     int iCookie = 1000000;
167965:     sqlite3_stmt *pStmt;
167966: 
167967:     p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg, 
167968:         "PRAGMA schema_version"
167969:     );
167970:     if( p->rc==SQLITE_OK ){
167971:       /* Coverage: it may be that this sqlite3_step() cannot fail. There
167972:       ** is already a transaction open, so the prepared statement cannot
167973:       ** throw an SQLITE_SCHEMA exception. The only database page the
167974:       ** statement reads is page 1, which is guaranteed to be in the cache.
167975:       ** And no memory allocations are required.  */
167976:       if( SQLITE_ROW==sqlite3_step(pStmt) ){
167977:         iCookie = sqlite3_column_int(pStmt, 0);
167978:       }
167979:       rbuFinalize(p, pStmt);
167980:     }
167981:     if( p->rc==SQLITE_OK ){
167982:       rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
167983:     }
167984:   }
167985: }
167986: 
167987: /*
167988: ** Update the contents of the rbu_state table within the rbu database. The
167989: ** value stored in the RBU_STATE_STAGE column is eStage. All other values
167990: ** are determined by inspecting the rbu handle passed as the first argument.
167991: */
167992: static void rbuSaveState(sqlite3rbu *p, int eStage){
167993:   if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
167994:     sqlite3_stmt *pInsert = 0;
167995:     rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
167996:     int rc;
167997: 
167998:     assert( p->zErrmsg==0 );
167999:     rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg, 
168000:         sqlite3_mprintf(
168001:           "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
168002:           "(%d, %d), "
168003:           "(%d, %Q), "
168004:           "(%d, %Q), "
168005:           "(%d, %d), "
168006:           "(%d, %d), "
168007:           "(%d, %lld), "
168008:           "(%d, %lld), "
168009:           "(%d, %lld), "
168010:           "(%d, %lld) ",
168011:           p->zStateDb,
168012:           RBU_STATE_STAGE, eStage,
168013:           RBU_STATE_TBL, p->objiter.zTbl, 
168014:           RBU_STATE_IDX, p->objiter.zIdx, 
168015:           RBU_STATE_ROW, p->nStep, 
168016:           RBU_STATE_PROGRESS, p->nProgress,
168017:           RBU_STATE_CKPT, p->iWalCksum,
168018:           RBU_STATE_COOKIE, (i64)pFd->iCookie,
168019:           RBU_STATE_OALSZ, p->iOalSz,
168020:           RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
168021:       )
168022:     );
168023:     assert( pInsert==0 || rc==SQLITE_OK );
168024: 
168025:     if( rc==SQLITE_OK ){
168026:       sqlite3_step(pInsert);
168027:       rc = sqlite3_finalize(pInsert);
168028:     }
168029:     if( rc!=SQLITE_OK ) p->rc = rc;
168030:   }
168031: }
168032: 
168033: 
168034: /*
168035: ** The second argument passed to this function is the name of a PRAGMA 
168036: ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
168037: ** This function executes the following on sqlite3rbu.dbRbu:
168038: **
168039: **   "PRAGMA main.$zPragma"
168040: **
168041: ** where $zPragma is the string passed as the second argument, then
168042: ** on sqlite3rbu.dbMain:
168043: **
168044: **   "PRAGMA main.$zPragma = $val"
168045: **
168046: ** where $val is the value returned by the first PRAGMA invocation.
168047: **
168048: ** In short, it copies the value  of the specified PRAGMA setting from
168049: ** dbRbu to dbMain.
168050: */
168051: static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
168052:   if( p->rc==SQLITE_OK ){
168053:     sqlite3_stmt *pPragma = 0;
168054:     p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg, 
168055:         sqlite3_mprintf("PRAGMA main.%s", zPragma)
168056:     );
168057:     if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
168058:       p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
168059:           zPragma, sqlite3_column_int(pPragma, 0)
168060:       );
168061:     }
168062:     rbuFinalize(p, pPragma);
168063:   }
168064: }
168065: 
168066: /*
168067: ** The RBU handle passed as the only argument has just been opened and 
168068: ** the state database is empty. If this RBU handle was opened for an
168069: ** RBU vacuum operation, create the schema in the target db.
168070: */
168071: static void rbuCreateTargetSchema(sqlite3rbu *p){
168072:   sqlite3_stmt *pSql = 0;
168073:   sqlite3_stmt *pInsert = 0;
168074: 
168075:   assert( rbuIsVacuum(p) );
168076:   p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
168077:   if( p->rc==SQLITE_OK ){
168078:     p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
168079:       "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
168080:       " AND name!='sqlite_sequence' "
168081:       " ORDER BY type DESC"
168082:     );
168083:   }
168084: 
168085:   while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
168086:     const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
168087:     p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
168088:   }
168089:   rbuFinalize(p, pSql);
168090:   if( p->rc!=SQLITE_OK ) return;
168091: 
168092:   if( p->rc==SQLITE_OK ){
168093:     p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg, 
168094:         "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL" 
168095:     );
168096:   }
168097: 
168098:   if( p->rc==SQLITE_OK ){
168099:     p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg, 
168100:         "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
168101:     );
168102:   }
168103: 
168104:   while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
168105:     int i;
168106:     for(i=0; i<5; i++){
168107:       sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
168108:     }
168109:     sqlite3_step(pInsert);
168110:     p->rc = sqlite3_reset(pInsert);
168111:   }
168112:   if( p->rc==SQLITE_OK ){
168113:     p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
168114:   }
168115: 
168116:   rbuFinalize(p, pSql);
168117:   rbuFinalize(p, pInsert);
168118: }
168119: 
168120: /*
168121: ** Step the RBU object.
168122: */
168123: SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
168124:   if( p ){
168125:     switch( p->eStage ){
168126:       case RBU_STAGE_OAL: {
168127:         RbuObjIter *pIter = &p->objiter;
168128: 
168129:         /* If this is an RBU vacuum operation and the state table was empty
168130:         ** when this handle was opened, create the target database schema. */
168131:         if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
168132:           rbuCreateTargetSchema(p);
168133:           rbuCopyPragma(p, "user_version");
168134:           rbuCopyPragma(p, "application_id");
168135:         }
168136: 
168137:         while( p->rc==SQLITE_OK && pIter->zTbl ){
168138: 
168139:           if( pIter->bCleanup ){
168140:             /* Clean up the rbu_tmp_xxx table for the previous table. It 
168141:             ** cannot be dropped as there are currently active SQL statements.
168142:             ** But the contents can be deleted.  */
168143:             if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
168144:               rbuMPrintfExec(p, p->dbRbu, 
168145:                   "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
168146:               );
168147:             }
168148:           }else{
168149:             rbuObjIterPrepareAll(p, pIter, 0);
168150: 
168151:             /* Advance to the next row to process. */
168152:             if( p->rc==SQLITE_OK ){
168153:               int rc = sqlite3_step(pIter->pSelect);
168154:               if( rc==SQLITE_ROW ){
168155:                 p->nProgress++;
168156:                 p->nStep++;
168157:                 return rbuStep(p);
168158:               }
168159:               p->rc = sqlite3_reset(pIter->pSelect);
168160:               p->nStep = 0;
168161:             }
168162:           }
168163: 
168164:           rbuObjIterNext(p, pIter);
168165:         }
168166: 
168167:         if( p->rc==SQLITE_OK ){
168168:           assert( pIter->zTbl==0 );
168169:           rbuSaveState(p, RBU_STAGE_MOVE);
168170:           rbuIncrSchemaCookie(p);
168171:           if( p->rc==SQLITE_OK ){
168172:             p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
168173:           }
168174:           if( p->rc==SQLITE_OK ){
168175:             p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
168176:           }
168177:           p->eStage = RBU_STAGE_MOVE;
168178:         }
168179:         break;
168180:       }
168181: 
168182:       case RBU_STAGE_MOVE: {
168183:         if( p->rc==SQLITE_OK ){
168184:           rbuMoveOalFile(p);
168185:           p->nProgress++;
168186:         }
168187:         break;
168188:       }
168189: 
168190:       case RBU_STAGE_CKPT: {
168191:         if( p->rc==SQLITE_OK ){
168192:           if( p->nStep>=p->nFrame ){
168193:             sqlite3_file *pDb = p->pTargetFd->pReal;
168194:   
168195:             /* Sync the db file */
168196:             p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
168197:   
168198:             /* Update nBackfill */
168199:             if( p->rc==SQLITE_OK ){
168200:               void volatile *ptr;
168201:               p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
168202:               if( p->rc==SQLITE_OK ){
168203:                 ((u32 volatile*)ptr)[24] = p->iMaxFrame;
168204:               }
168205:             }
168206:   
168207:             if( p->rc==SQLITE_OK ){
168208:               p->eStage = RBU_STAGE_DONE;
168209:               p->rc = SQLITE_DONE;
168210:             }
168211:           }else{
168212:             RbuFrame *pFrame = &p->aFrame[p->nStep];
168213:             rbuCheckpointFrame(p, pFrame);
168214:             p->nStep++;
168215:           }
168216:           p->nProgress++;
168217:         }
168218:         break;
168219:       }
168220: 
168221:       default:
168222:         break;
168223:     }
168224:     return p->rc;
168225:   }else{
168226:     return SQLITE_NOMEM;
168227:   }
168228: }
168229: 
168230: /*
168231: ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
168232: ** otherwise. Either or both argument may be NULL. Two NULL values are
168233: ** considered equal, and NULL is considered distinct from all other values.
168234: */
168235: static int rbuStrCompare(const char *z1, const char *z2){
168236:   if( z1==0 && z2==0 ) return 0;
168237:   if( z1==0 || z2==0 ) return 1;
168238:   return (sqlite3_stricmp(z1, z2)!=0);
168239: }
168240: 
168241: /*
168242: ** This function is called as part of sqlite3rbu_open() when initializing
168243: ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
168244: ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
168245: ** things so that the next call to sqlite3rbu_step() continues on from
168246: ** where the previous rbu handle left off.
168247: **
168248: ** If an error occurs, an error code and error message are left in the
168249: ** rbu handle passed as the first argument.
168250: */
168251: static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
168252:   assert( p->rc==SQLITE_OK );
168253:   if( pState->zTbl ){
168254:     RbuObjIter *pIter = &p->objiter;
168255:     int rc = SQLITE_OK;
168256: 
168257:     while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup 
168258:        || rbuStrCompare(pIter->zIdx, pState->zIdx)
168259:        || rbuStrCompare(pIter->zTbl, pState->zTbl) 
168260:     )){
168261:       rc = rbuObjIterNext(p, pIter);
168262:     }
168263: 
168264:     if( rc==SQLITE_OK && !pIter->zTbl ){
168265:       rc = SQLITE_ERROR;
168266:       p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
168267:     }
168268: 
168269:     if( rc==SQLITE_OK ){
168270:       p->nStep = pState->nRow;
168271:       rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
168272:     }
168273: 
168274:     p->rc = rc;
168275:   }
168276: }
168277: 
168278: /*
168279: ** If there is a "*-oal" file in the file-system corresponding to the
168280: ** target database in the file-system, delete it. If an error occurs,
168281: ** leave an error code and error message in the rbu handle.
168282: */
168283: static void rbuDeleteOalFile(sqlite3rbu *p){
168284:   char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
168285:   if( zOal ){
168286:     sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
168287:     assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
168288:     pVfs->xDelete(pVfs, zOal, 0);
168289:     sqlite3_free(zOal);
168290:   }
168291: }
168292: 
168293: /*
168294: ** Allocate a private rbu VFS for the rbu handle passed as the only
168295: ** argument. This VFS will be used unless the call to sqlite3rbu_open()
168296: ** specified a URI with a vfs=? option in place of a target database
168297: ** file name.
168298: */
168299: static void rbuCreateVfs(sqlite3rbu *p){
168300:   int rnd;
168301:   char zRnd[64];
168302: 
168303:   assert( p->rc==SQLITE_OK );
168304:   sqlite3_randomness(sizeof(int), (void*)&rnd);
168305:   sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
168306:   p->rc = sqlite3rbu_create_vfs(zRnd, 0);
168307:   if( p->rc==SQLITE_OK ){
168308:     sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
168309:     assert( pVfs );
168310:     p->zVfsName = pVfs->zName;
168311:   }
168312: }
168313: 
168314: /*
168315: ** Destroy the private VFS created for the rbu handle passed as the only
168316: ** argument by an earlier call to rbuCreateVfs().
168317: */
168318: static void rbuDeleteVfs(sqlite3rbu *p){
168319:   if( p->zVfsName ){
168320:     sqlite3rbu_destroy_vfs(p->zVfsName);
168321:     p->zVfsName = 0;
168322:   }
168323: }
168324: 
168325: /*
168326: ** This user-defined SQL function is invoked with a single argument - the
168327: ** name of a table expected to appear in the target database. It returns
168328: ** the number of auxilliary indexes on the table.
168329: */
168330: static void rbuIndexCntFunc(
168331:   sqlite3_context *pCtx, 
168332:   int nVal,
168333:   sqlite3_value **apVal
168334: ){
168335:   sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
168336:   sqlite3_stmt *pStmt = 0;
168337:   char *zErrmsg = 0;
168338:   int rc;
168339: 
168340:   assert( nVal==1 );
168341:   
168342:   rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg, 
168343:       sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
168344:         "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
168345:   );
168346:   if( rc!=SQLITE_OK ){
168347:     sqlite3_result_error(pCtx, zErrmsg, -1);
168348:   }else{
168349:     int nIndex = 0;
168350:     if( SQLITE_ROW==sqlite3_step(pStmt) ){
168351:       nIndex = sqlite3_column_int(pStmt, 0);
168352:     }
168353:     rc = sqlite3_finalize(pStmt);
168354:     if( rc==SQLITE_OK ){
168355:       sqlite3_result_int(pCtx, nIndex);
168356:     }else{
168357:       sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
168358:     }
168359:   }
168360: 
168361:   sqlite3_free(zErrmsg);
168362: }
168363: 
168364: /*
168365: ** If the RBU database contains the rbu_count table, use it to initialize
168366: ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
168367: ** is assumed to contain the same columns as:
168368: **
168369: **   CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
168370: **
168371: ** There should be one row in the table for each data_xxx table in the
168372: ** database. The 'tbl' column should contain the name of a data_xxx table,
168373: ** and the cnt column the number of rows it contains.
168374: **
168375: ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
168376: ** for all rows in the rbu_count table, where nIndex is the number of 
168377: ** indexes on the corresponding target database table.
168378: */
168379: static void rbuInitPhaseOneSteps(sqlite3rbu *p){
168380:   if( p->rc==SQLITE_OK ){
168381:     sqlite3_stmt *pStmt = 0;
168382:     int bExists = 0;                /* True if rbu_count exists */
168383: 
168384:     p->nPhaseOneStep = -1;
168385: 
168386:     p->rc = sqlite3_create_function(p->dbRbu, 
168387:         "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
168388:     );
168389:   
168390:     /* Check for the rbu_count table. If it does not exist, or if an error
168391:     ** occurs, nPhaseOneStep will be left set to -1. */
168392:     if( p->rc==SQLITE_OK ){
168393:       p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168394:           "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
168395:       );
168396:     }
168397:     if( p->rc==SQLITE_OK ){
168398:       if( SQLITE_ROW==sqlite3_step(pStmt) ){
168399:         bExists = 1;
168400:       }
168401:       p->rc = sqlite3_finalize(pStmt);
168402:     }
168403:   
168404:     if( p->rc==SQLITE_OK && bExists ){
168405:       p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
168406:           "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
168407:           "FROM rbu_count"
168408:       );
168409:       if( p->rc==SQLITE_OK ){
168410:         if( SQLITE_ROW==sqlite3_step(pStmt) ){
168411:           p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
168412:         }
168413:         p->rc = sqlite3_finalize(pStmt);
168414:       }
168415:     }
168416:   }
168417: }
168418: 
168419: 
168420: static sqlite3rbu *openRbuHandle(
168421:   const char *zTarget, 
168422:   const char *zRbu,
168423:   const char *zState
168424: ){
168425:   sqlite3rbu *p;
168426:   size_t nTarget = zTarget ? strlen(zTarget) : 0;
168427:   size_t nRbu = strlen(zRbu);
168428:   size_t nState = zState ? strlen(zState) : 0;
168429:   size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
168430: 
168431:   p = (sqlite3rbu*)sqlite3_malloc64(nByte);
168432:   if( p ){
168433:     RbuState *pState = 0;
168434: 
168435:     /* Create the custom VFS. */
168436:     memset(p, 0, sizeof(sqlite3rbu));
168437:     rbuCreateVfs(p);
168438: 
168439:     /* Open the target, RBU and state databases */
168440:     if( p->rc==SQLITE_OK ){
168441:       char *pCsr = (char*)&p[1];
168442:       if( zTarget ){
168443:         p->zTarget = pCsr;
168444:         memcpy(p->zTarget, zTarget, nTarget+1);
168445:         pCsr += nTarget+1;
168446:       }
168447:       p->zRbu = pCsr;
168448:       memcpy(p->zRbu, zRbu, nRbu+1);
168449:       pCsr += nRbu+1;
168450:       if( zState ){
168451:         p->zState = pCsr;
168452:         memcpy(p->zState, zState, nState+1);
168453:       }
168454:       rbuOpenDatabase(p);
168455:     }
168456: 
168457:     if( p->rc==SQLITE_OK ){
168458:       pState = rbuLoadState(p);
168459:       assert( pState || p->rc!=SQLITE_OK );
168460:       if( p->rc==SQLITE_OK ){
168461: 
168462:         if( pState->eStage==0 ){ 
168463:           rbuDeleteOalFile(p);
168464:           rbuInitPhaseOneSteps(p);
168465:           p->eStage = RBU_STAGE_OAL;
168466:         }else{
168467:           p->eStage = pState->eStage;
168468:           p->nPhaseOneStep = pState->nPhaseOneStep;
168469:         }
168470:         p->nProgress = pState->nProgress;
168471:         p->iOalSz = pState->iOalSz;
168472:       }
168473:     }
168474:     assert( p->rc!=SQLITE_OK || p->eStage!=0 );
168475: 
168476:     if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
168477:       if( p->eStage==RBU_STAGE_OAL ){
168478:         p->rc = SQLITE_ERROR;
168479:         p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
168480:       }else if( p->eStage==RBU_STAGE_MOVE ){
168481:         p->eStage = RBU_STAGE_CKPT;
168482:         p->nStep = 0;
168483:       }
168484:     }
168485: 
168486:     if( p->rc==SQLITE_OK 
168487:      && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
168488:      && pState->eStage!=0
168489:     ){
168490:       rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
168491:       if( pFd->iCookie!=pState->iCookie ){   
168492:         /* At this point (pTargetFd->iCookie) contains the value of the
168493:         ** change-counter cookie (the thing that gets incremented when a 
168494:         ** transaction is committed in rollback mode) currently stored on 
168495:         ** page 1 of the database file. */
168496:         p->rc = SQLITE_BUSY;
168497:         p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
168498:             (rbuIsVacuum(p) ? "vacuum" : "update")
168499:         );
168500:       }
168501:     }
168502: 
168503:     if( p->rc==SQLITE_OK ){
168504:       if( p->eStage==RBU_STAGE_OAL ){
168505:         sqlite3 *db = p->dbMain;
168506:         p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
168507: 
168508:         /* Point the object iterator at the first object */
168509:         if( p->rc==SQLITE_OK ){
168510:           p->rc = rbuObjIterFirst(p, &p->objiter);
168511:         }
168512: 
168513:         /* If the RBU database contains no data_xxx tables, declare the RBU
168514:         ** update finished.  */
168515:         if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
168516:           p->rc = SQLITE_DONE;
168517:           p->eStage = RBU_STAGE_DONE;
168518:         }else{
168519:           if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
168520:             rbuCopyPragma(p, "page_size");
168521:             rbuCopyPragma(p, "auto_vacuum");
168522:           }
168523: 
168524:           /* Open transactions both databases. The *-oal file is opened or
168525:           ** created at this point. */
168526:           if( p->rc==SQLITE_OK ){
168527:             p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
168528:           }
168529: 
168530:           /* Check if the main database is a zipvfs db. If it is, set the upper
168531:           ** level pager to use "journal_mode=off". This prevents it from 
168532:           ** generating a large journal using a temp file.  */
168533:           if( p->rc==SQLITE_OK ){
168534:             int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
168535:             if( frc==SQLITE_OK ){
168536:               p->rc = sqlite3_exec(
168537:                 db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
168538:             }
168539:           }
168540: 
168541:           if( p->rc==SQLITE_OK ){
168542:             rbuSetupOal(p, pState);
168543:           }
168544:         }
168545:       }else if( p->eStage==RBU_STAGE_MOVE ){
168546:         /* no-op */
168547:       }else if( p->eStage==RBU_STAGE_CKPT ){
168548:         rbuSetupCheckpoint(p, pState);
168549:       }else if( p->eStage==RBU_STAGE_DONE ){
168550:         p->rc = SQLITE_DONE;
168551:       }else{
168552:         p->rc = SQLITE_CORRUPT;
168553:       }
168554:     }
168555: 
168556:     rbuFreeState(pState);
168557:   }
168558: 
168559:   return p;
168560: }
168561: 
168562: /*
168563: ** Open and return a new RBU handle. 
168564: */
168565: SQLITE_API sqlite3rbu *sqlite3rbu_open(
168566:   const char *zTarget, 
168567:   const char *zRbu,
168568:   const char *zState
168569: ){
168570:   /* TODO: Check that zTarget and zRbu are non-NULL */
168571:   return openRbuHandle(zTarget, zRbu, zState);
168572: }
168573: 
168574: /*
168575: ** Open a handle to begin or resume an RBU VACUUM operation.
168576: */
168577: SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
168578:   const char *zTarget, 
168579:   const char *zState
168580: ){
168581:   /* TODO: Check that both arguments are non-NULL */
168582:   return openRbuHandle(0, zTarget, zState);
168583: }
168584: 
168585: /*
168586: ** Return the database handle used by pRbu.
168587: */
168588: SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
168589:   sqlite3 *db = 0;
168590:   if( pRbu ){
168591:     db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
168592:   }
168593:   return db;
168594: }
168595: 
168596: 
168597: /*
168598: ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
168599: ** then edit any error message string so as to remove all occurrences of
168600: ** the pattern "rbu_imp_[0-9]*".
168601: */
168602: static void rbuEditErrmsg(sqlite3rbu *p){
168603:   if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
168604:     unsigned int i;
168605:     size_t nErrmsg = strlen(p->zErrmsg);
168606:     for(i=0; i<(nErrmsg-8); i++){
168607:       if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
168608:         int nDel = 8;
168609:         while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
168610:         memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
168611:         nErrmsg -= nDel;
168612:       }
168613:     }
168614:   }
168615: }
168616: 
168617: /*
168618: ** Close the RBU handle.
168619: */
168620: SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
168621:   int rc;
168622:   if( p ){
168623: 
168624:     /* Commit the transaction to the *-oal file. */
168625:     if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
168626:       p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
168627:     }
168628: 
168629:     rbuSaveState(p, p->eStage);
168630: 
168631:     if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
168632:       p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
168633:     }
168634: 
168635:     /* Close any open statement handles. */
168636:     rbuObjIterFinalize(&p->objiter);
168637: 
168638:     /* If this is an RBU vacuum handle and the vacuum has either finished
168639:     ** successfully or encountered an error, delete the contents of the 
168640:     ** state table. This causes the next call to sqlite3rbu_vacuum() 
168641:     ** specifying the current target and state databases to start a new
168642:     ** vacuum from scratch.  */
168643:     if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
168644:       int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
168645:       if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
168646:     }
168647: 
168648:     /* Close the open database handle and VFS object. */
168649:     sqlite3_close(p->dbRbu);
168650:     sqlite3_close(p->dbMain);
168651:     rbuDeleteVfs(p);
168652:     sqlite3_free(p->aBuf);
168653:     sqlite3_free(p->aFrame);
168654: 
168655:     rbuEditErrmsg(p);
168656:     rc = p->rc;
168657:     *pzErrmsg = p->zErrmsg;
168658:     sqlite3_free(p);
168659:   }else{
168660:     rc = SQLITE_NOMEM;
168661:     *pzErrmsg = 0;
168662:   }
168663:   return rc;
168664: }
168665: 
168666: /*
168667: ** Return the total number of key-value operations (inserts, deletes or 
168668: ** updates) that have been performed on the target database since the
168669: ** current RBU update was started.
168670: */
168671: SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
168672:   return pRbu->nProgress;
168673: }
168674: 
168675: /*
168676: ** Return permyriadage progress indications for the two main stages of
168677: ** an RBU update.
168678: */
168679: SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
168680:   const int MAX_PROGRESS = 10000;
168681:   switch( p->eStage ){
168682:     case RBU_STAGE_OAL:
168683:       if( p->nPhaseOneStep>0 ){
168684:         *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
168685:       }else{
168686:         *pnOne = -1;
168687:       }
168688:       *pnTwo = 0;
168689:       break;
168690: 
168691:     case RBU_STAGE_MOVE:
168692:       *pnOne = MAX_PROGRESS;
168693:       *pnTwo = 0;
168694:       break;
168695: 
168696:     case RBU_STAGE_CKPT:
168697:       *pnOne = MAX_PROGRESS;
168698:       *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
168699:       break;
168700: 
168701:     case RBU_STAGE_DONE:
168702:       *pnOne = MAX_PROGRESS;
168703:       *pnTwo = MAX_PROGRESS;
168704:       break;
168705: 
168706:     default:
168707:       assert( 0 );
168708:   }
168709: }
168710: 
168711: /*
168712: ** Return the current state of the RBU vacuum or update operation.
168713: */
168714: SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
168715:   int aRes[] = {
168716:     0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
168717:     0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
168718:   };
168719: 
168720:   assert( RBU_STAGE_OAL==1 );
168721:   assert( RBU_STAGE_MOVE==2 );
168722:   assert( RBU_STAGE_CKPT==4 );
168723:   assert( RBU_STAGE_DONE==5 );
168724:   assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
168725:   assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
168726:   assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
168727:   assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
168728: 
168729:   if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
168730:     return SQLITE_RBU_STATE_ERROR;
168731:   }else{
168732:     assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
168733:     assert( p->eStage==RBU_STAGE_OAL
168734:          || p->eStage==RBU_STAGE_MOVE
168735:          || p->eStage==RBU_STAGE_CKPT
168736:          || p->eStage==RBU_STAGE_DONE
168737:     );
168738:     return aRes[p->eStage];
168739:   }
168740: }
168741: 
168742: SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
168743:   int rc = p->rc;
168744:   if( rc==SQLITE_DONE ) return SQLITE_OK;
168745: 
168746:   assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
168747:   if( p->eStage==RBU_STAGE_OAL ){
168748:     assert( rc!=SQLITE_DONE );
168749:     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
168750:   }
168751: 
168752:   p->rc = rc;
168753:   rbuSaveState(p, p->eStage);
168754:   rc = p->rc;
168755: 
168756:   if( p->eStage==RBU_STAGE_OAL ){
168757:     assert( rc!=SQLITE_DONE );
168758:     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
168759:     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
168760:     if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
168761:   }
168762: 
168763:   p->rc = rc;
168764:   return rc;
168765: }
168766: 
168767: /**************************************************************************
168768: ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
168769: ** of a standard VFS in the following ways:
168770: **
168771: ** 1. Whenever the first page of a main database file is read or 
168772: **    written, the value of the change-counter cookie is stored in
168773: **    rbu_file.iCookie. Similarly, the value of the "write-version"
168774: **    database header field is stored in rbu_file.iWriteVer. This ensures
168775: **    that the values are always trustworthy within an open transaction.
168776: **
168777: ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
168778: **    member variable of the associated database file descriptor is set
168779: **    to point to the new file. A mutex protected linked list of all main 
168780: **    db fds opened using a particular RBU VFS is maintained at 
168781: **    rbu_vfs.pMain to facilitate this.
168782: **
168783: ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file 
168784: **    object can be marked as the target database of an RBU update. This
168785: **    turns on the following extra special behaviour:
168786: **
168787: ** 3a. If xAccess() is called to check if there exists a *-wal file 
168788: **     associated with an RBU target database currently in RBU_STAGE_OAL
168789: **     stage (preparing the *-oal file), the following special handling
168790: **     applies:
168791: **
168792: **      * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
168793: **        target database may not be in wal mode already.
168794: **
168795: **      * if the *-wal file does not exist, set the output parameter to
168796: **        non-zero (to tell SQLite that it does exist) anyway.
168797: **
168798: **     Then, when xOpen() is called to open the *-wal file associated with
168799: **     the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
168800: **     file, the rbu vfs opens the corresponding *-oal file instead. 
168801: **
168802: ** 3b. The *-shm pages returned by xShmMap() for a target db file in
168803: **     RBU_STAGE_OAL mode are actually stored in heap memory. This is to
168804: **     avoid creating a *-shm file on disk. Additionally, xShmLock() calls
168805: **     are no-ops on target database files in RBU_STAGE_OAL mode. This is
168806: **     because assert() statements in some VFS implementations fail if 
168807: **     xShmLock() is called before xShmMap().
168808: **
168809: ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
168810: **     mode except RBU_STAGE_DONE (all work completed and checkpointed), it 
168811: **     fails with an SQLITE_BUSY error. This is to stop RBU connections
168812: **     from automatically checkpointing a *-wal (or *-oal) file from within
168813: **     sqlite3_close().
168814: **
168815: ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
168816: **     all xWrite() calls on the target database file perform no IO. 
168817: **     Instead the frame and page numbers that would be read and written
168818: **     are recorded. Additionally, successful attempts to obtain exclusive
168819: **     xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target 
168820: **     database file are recorded. xShmLock() calls to unlock the same
168821: **     locks are no-ops (so that once obtained, these locks are never
168822: **     relinquished). Finally, calls to xSync() on the target database
168823: **     file fail with SQLITE_INTERNAL errors.
168824: */
168825: 
168826: static void rbuUnlockShm(rbu_file *p){
168827:   if( p->pRbu ){
168828:     int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
168829:     int i;
168830:     for(i=0; i<SQLITE_SHM_NLOCK;i++){
168831:       if( (1<<i) & p->pRbu->mLock ){
168832:         xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
168833:       }
168834:     }
168835:     p->pRbu->mLock = 0;
168836:   }
168837: }
168838: 
168839: /*
168840: ** Close an rbu file.
168841: */
168842: static int rbuVfsClose(sqlite3_file *pFile){
168843:   rbu_file *p = (rbu_file*)pFile;
168844:   int rc;
168845:   int i;
168846: 
168847:   /* Free the contents of the apShm[] array. And the array itself. */
168848:   for(i=0; i<p->nShm; i++){
168849:     sqlite3_free(p->apShm[i]);
168850:   }
168851:   sqlite3_free(p->apShm);
168852:   p->apShm = 0;
168853:   sqlite3_free(p->zDel);
168854: 
168855:   if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
168856:     rbu_file **pp;
168857:     sqlite3_mutex_enter(p->pRbuVfs->mutex);
168858:     for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
168859:     *pp = p->pMainNext;
168860:     sqlite3_mutex_leave(p->pRbuVfs->mutex);
168861:     rbuUnlockShm(p);
168862:     p->pReal->pMethods->xShmUnmap(p->pReal, 0);
168863:   }
168864: 
168865:   /* Close the underlying file handle */
168866:   rc = p->pReal->pMethods->xClose(p->pReal);
168867:   return rc;
168868: }
168869: 
168870: 
168871: /*
168872: ** Read and return an unsigned 32-bit big-endian integer from the buffer 
168873: ** passed as the only argument.
168874: */
168875: static u32 rbuGetU32(u8 *aBuf){
168876:   return ((u32)aBuf[0] << 24)
168877:        + ((u32)aBuf[1] << 16)
168878:        + ((u32)aBuf[2] <<  8)
168879:        + ((u32)aBuf[3]);
168880: }
168881: 
168882: /*
168883: ** Write an unsigned 32-bit value in big-endian format to the supplied
168884: ** buffer.
168885: */
168886: static void rbuPutU32(u8 *aBuf, u32 iVal){
168887:   aBuf[0] = (iVal >> 24) & 0xFF;
168888:   aBuf[1] = (iVal >> 16) & 0xFF;
168889:   aBuf[2] = (iVal >>  8) & 0xFF;
168890:   aBuf[3] = (iVal >>  0) & 0xFF;
168891: }
168892: 
168893: static void rbuPutU16(u8 *aBuf, u16 iVal){
168894:   aBuf[0] = (iVal >>  8) & 0xFF;
168895:   aBuf[1] = (iVal >>  0) & 0xFF;
168896: }
168897: 
168898: /*
168899: ** Read data from an rbuVfs-file.
168900: */
168901: static int rbuVfsRead(
168902:   sqlite3_file *pFile, 
168903:   void *zBuf, 
168904:   int iAmt, 
168905:   sqlite_int64 iOfst
168906: ){
168907:   rbu_file *p = (rbu_file*)pFile;
168908:   sqlite3rbu *pRbu = p->pRbu;
168909:   int rc;
168910: 
168911:   if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
168912:     assert( p->openFlags & SQLITE_OPEN_WAL );
168913:     rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
168914:   }else{
168915:     if( pRbu && pRbu->eStage==RBU_STAGE_OAL 
168916:      && (p->openFlags & SQLITE_OPEN_WAL) 
168917:      && iOfst>=pRbu->iOalSz 
168918:     ){
168919:       rc = SQLITE_OK;
168920:       memset(zBuf, 0, iAmt);
168921:     }else{
168922:       rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
168923: #if 1
168924:       /* If this is being called to read the first page of the target 
168925:       ** database as part of an rbu vacuum operation, synthesize the 
168926:       ** contents of the first page if it does not yet exist. Otherwise,
168927:       ** SQLite will not check for a *-wal file.  */
168928:       if( pRbu && rbuIsVacuum(pRbu) 
168929:           && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
168930:           && (p->openFlags & SQLITE_OPEN_MAIN_DB)
168931:           && pRbu->rc==SQLITE_OK
168932:       ){
168933:         sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
168934:         rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
168935:         if( rc==SQLITE_OK ){
168936:           u8 *aBuf = (u8*)zBuf;
168937:           u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
168938:           rbuPutU32(&aBuf[52], iRoot);      /* largest root page number */
168939:           rbuPutU32(&aBuf[36], 0);          /* number of free pages */
168940:           rbuPutU32(&aBuf[32], 0);          /* first page on free list trunk */
168941:           rbuPutU32(&aBuf[28], 1);          /* size of db file in pages */
168942:           rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1);  /* Change counter */
168943: 
168944:           if( iAmt>100 ){
168945:             memset(&aBuf[100], 0, iAmt-100);
168946:             rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
168947:             aBuf[100] = 0x0D;
168948:           }
168949:         }
168950:       }
168951: #endif
168952:     }
168953:     if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
168954:       /* These look like magic numbers. But they are stable, as they are part
168955:        ** of the definition of the SQLite file format, which may not change. */
168956:       u8 *pBuf = (u8*)zBuf;
168957:       p->iCookie = rbuGetU32(&pBuf[24]);
168958:       p->iWriteVer = pBuf[19];
168959:     }
168960:   }
168961:   return rc;
168962: }
168963: 
168964: /*
168965: ** Write data to an rbuVfs-file.
168966: */
168967: static int rbuVfsWrite(
168968:   sqlite3_file *pFile, 
168969:   const void *zBuf, 
168970:   int iAmt, 
168971:   sqlite_int64 iOfst
168972: ){
168973:   rbu_file *p = (rbu_file*)pFile;
168974:   sqlite3rbu *pRbu = p->pRbu;
168975:   int rc;
168976: 
168977:   if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
168978:     assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
168979:     rc = rbuCaptureDbWrite(p->pRbu, iOfst);
168980:   }else{
168981:     if( pRbu && pRbu->eStage==RBU_STAGE_OAL 
168982:      && (p->openFlags & SQLITE_OPEN_WAL) 
168983:      && iOfst>=pRbu->iOalSz
168984:     ){
168985:       pRbu->iOalSz = iAmt + iOfst;
168986:     }
168987:     rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
168988:     if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
168989:       /* These look like magic numbers. But they are stable, as they are part
168990:       ** of the definition of the SQLite file format, which may not change. */
168991:       u8 *pBuf = (u8*)zBuf;
168992:       p->iCookie = rbuGetU32(&pBuf[24]);
168993:       p->iWriteVer = pBuf[19];
168994:     }
168995:   }
168996:   return rc;
168997: }
168998: 
168999: /*
169000: ** Truncate an rbuVfs-file.
169001: */
169002: static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
169003:   rbu_file *p = (rbu_file*)pFile;
169004:   return p->pReal->pMethods->xTruncate(p->pReal, size);
169005: }
169006: 
169007: /*
169008: ** Sync an rbuVfs-file.
169009: */
169010: static int rbuVfsSync(sqlite3_file *pFile, int flags){
169011:   rbu_file *p = (rbu_file *)pFile;
169012:   if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
169013:     if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
169014:       return SQLITE_INTERNAL;
169015:     }
169016:     return SQLITE_OK;
169017:   }
169018:   return p->pReal->pMethods->xSync(p->pReal, flags);
169019: }
169020: 
169021: /*
169022: ** Return the current file-size of an rbuVfs-file.
169023: */
169024: static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
169025:   rbu_file *p = (rbu_file *)pFile;
169026:   int rc;
169027:   rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
169028: 
169029:   /* If this is an RBU vacuum operation and this is the target database,
169030:   ** pretend that it has at least one page. Otherwise, SQLite will not
169031:   ** check for the existance of a *-wal file. rbuVfsRead() contains 
169032:   ** similar logic.  */
169033:   if( rc==SQLITE_OK && *pSize==0 
169034:    && p->pRbu && rbuIsVacuum(p->pRbu) 
169035:    && (p->openFlags & SQLITE_OPEN_MAIN_DB)
169036:   ){
169037:     *pSize = 1024;
169038:   }
169039:   return rc;
169040: }
169041: 
169042: /*
169043: ** Lock an rbuVfs-file.
169044: */
169045: static int rbuVfsLock(sqlite3_file *pFile, int eLock){
169046:   rbu_file *p = (rbu_file*)pFile;
169047:   sqlite3rbu *pRbu = p->pRbu;
169048:   int rc = SQLITE_OK;
169049: 
169050:   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169051:   if( eLock==SQLITE_LOCK_EXCLUSIVE 
169052:    && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
169053:   ){
169054:     /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this 
169055:     ** prevents it from checkpointing the database from sqlite3_close(). */
169056:     rc = SQLITE_BUSY;
169057:   }else{
169058:     rc = p->pReal->pMethods->xLock(p->pReal, eLock);
169059:   }
169060: 
169061:   return rc;
169062: }
169063: 
169064: /*
169065: ** Unlock an rbuVfs-file.
169066: */
169067: static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
169068:   rbu_file *p = (rbu_file *)pFile;
169069:   return p->pReal->pMethods->xUnlock(p->pReal, eLock);
169070: }
169071: 
169072: /*
169073: ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
169074: */
169075: static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
169076:   rbu_file *p = (rbu_file *)pFile;
169077:   return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
169078: }
169079: 
169080: /*
169081: ** File control method. For custom operations on an rbuVfs-file.
169082: */
169083: static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
169084:   rbu_file *p = (rbu_file *)pFile;
169085:   int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
169086:   int rc;
169087: 
169088:   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
169089:        || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
169090:   );
169091:   if( op==SQLITE_FCNTL_RBU ){
169092:     sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
169093: 
169094:     /* First try to find another RBU vfs lower down in the vfs stack. If
169095:     ** one is found, this vfs will operate in pass-through mode. The lower
169096:     ** level vfs will do the special RBU handling.  */
169097:     rc = xControl(p->pReal, op, pArg);
169098: 
169099:     if( rc==SQLITE_NOTFOUND ){
169100:       /* Now search for a zipvfs instance lower down in the VFS stack. If
169101:       ** one is found, this is an error.  */
169102:       void *dummy = 0;
169103:       rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
169104:       if( rc==SQLITE_OK ){
169105:         rc = SQLITE_ERROR;
169106:         pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
169107:       }else if( rc==SQLITE_NOTFOUND ){
169108:         pRbu->pTargetFd = p;
169109:         p->pRbu = pRbu;
169110:         if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
169111:         rc = SQLITE_OK;
169112:       }
169113:     }
169114:     return rc;
169115:   }
169116:   else if( op==SQLITE_FCNTL_RBUCNT ){
169117:     sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
169118:     pRbu->nRbu++;
169119:     pRbu->pRbuFd = p;
169120:     p->bNolock = 1;
169121:   }
169122: 
169123:   rc = xControl(p->pReal, op, pArg);
169124:   if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
169125:     rbu_vfs *pRbuVfs = p->pRbuVfs;
169126:     char *zIn = *(char**)pArg;
169127:     char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
169128:     *(char**)pArg = zOut;
169129:     if( zOut==0 ) rc = SQLITE_NOMEM;
169130:   }
169131: 
169132:   return rc;
169133: }
169134: 
169135: /*
169136: ** Return the sector-size in bytes for an rbuVfs-file.
169137: */
169138: static int rbuVfsSectorSize(sqlite3_file *pFile){
169139:   rbu_file *p = (rbu_file *)pFile;
169140:   return p->pReal->pMethods->xSectorSize(p->pReal);
169141: }
169142: 
169143: /*
169144: ** Return the device characteristic flags supported by an rbuVfs-file.
169145: */
169146: static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
169147:   rbu_file *p = (rbu_file *)pFile;
169148:   return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
169149: }
169150: 
169151: /*
169152: ** Take or release a shared-memory lock.
169153: */
169154: static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
169155:   rbu_file *p = (rbu_file*)pFile;
169156:   sqlite3rbu *pRbu = p->pRbu;
169157:   int rc = SQLITE_OK;
169158: 
169159: #ifdef SQLITE_AMALGAMATION
169160:     assert( WAL_CKPT_LOCK==1 );
169161: #endif
169162: 
169163:   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169164:   if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
169165:     /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
169166:     ** taking this lock also prevents any checkpoints from occurring. 
169167:     ** todo: really, it's not clear why this might occur, as 
169168:     ** wal_autocheckpoint ought to be turned off.  */
169169:     if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
169170:   }else{
169171:     int bCapture = 0;
169172:     if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
169173:      && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
169174:      && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
169175:     ){
169176:       bCapture = 1;
169177:     }
169178: 
169179:     if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
169180:       rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
169181:       if( bCapture && rc==SQLITE_OK ){
169182:         pRbu->mLock |= (1 << ofst);
169183:       }
169184:     }
169185:   }
169186: 
169187:   return rc;
169188: }
169189: 
169190: /*
169191: ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
169192: */
169193: static int rbuVfsShmMap(
169194:   sqlite3_file *pFile, 
169195:   int iRegion, 
169196:   int szRegion, 
169197:   int isWrite, 
169198:   void volatile **pp
169199: ){
169200:   rbu_file *p = (rbu_file*)pFile;
169201:   int rc = SQLITE_OK;
169202:   int eStage = (p->pRbu ? p->pRbu->eStage : 0);
169203: 
169204:   /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
169205:   ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space 
169206:   ** instead of a file on disk.  */
169207:   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169208:   if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
169209:     if( iRegion<=p->nShm ){
169210:       int nByte = (iRegion+1) * sizeof(char*);
169211:       char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
169212:       if( apNew==0 ){
169213:         rc = SQLITE_NOMEM;
169214:       }else{
169215:         memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
169216:         p->apShm = apNew;
169217:         p->nShm = iRegion+1;
169218:       }
169219:     }
169220: 
169221:     if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
169222:       char *pNew = (char*)sqlite3_malloc64(szRegion);
169223:       if( pNew==0 ){
169224:         rc = SQLITE_NOMEM;
169225:       }else{
169226:         memset(pNew, 0, szRegion);
169227:         p->apShm[iRegion] = pNew;
169228:       }
169229:     }
169230: 
169231:     if( rc==SQLITE_OK ){
169232:       *pp = p->apShm[iRegion];
169233:     }else{
169234:       *pp = 0;
169235:     }
169236:   }else{
169237:     assert( p->apShm==0 );
169238:     rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
169239:   }
169240: 
169241:   return rc;
169242: }
169243: 
169244: /*
169245: ** Memory barrier.
169246: */
169247: static void rbuVfsShmBarrier(sqlite3_file *pFile){
169248:   rbu_file *p = (rbu_file *)pFile;
169249:   p->pReal->pMethods->xShmBarrier(p->pReal);
169250: }
169251: 
169252: /*
169253: ** The xShmUnmap method.
169254: */
169255: static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
169256:   rbu_file *p = (rbu_file*)pFile;
169257:   int rc = SQLITE_OK;
169258:   int eStage = (p->pRbu ? p->pRbu->eStage : 0);
169259: 
169260:   assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
169261:   if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
169262:     /* no-op */
169263:   }else{
169264:     /* Release the checkpointer and writer locks */
169265:     rbuUnlockShm(p);
169266:     rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
169267:   }
169268:   return rc;
169269: }
169270: 
169271: /*
169272: ** Given that zWal points to a buffer containing a wal file name passed to 
169273: ** either the xOpen() or xAccess() VFS method, return a pointer to the
169274: ** file-handle opened by the same database connection on the corresponding
169275: ** database file.
169276: */
169277: static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
169278:   rbu_file *pDb;
169279:   sqlite3_mutex_enter(pRbuVfs->mutex);
169280:   for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
169281:   sqlite3_mutex_leave(pRbuVfs->mutex);
169282:   return pDb;
169283: }
169284: 
169285: /* 
169286: ** A main database named zName has just been opened. The following 
169287: ** function returns a pointer to a buffer owned by SQLite that contains
169288: ** the name of the *-wal file this db connection will use. SQLite
169289: ** happens to pass a pointer to this buffer when using xAccess()
169290: ** or xOpen() to operate on the *-wal file.  
169291: */
169292: static const char *rbuMainToWal(const char *zName, int flags){
169293:   int n = (int)strlen(zName);
169294:   const char *z = &zName[n];
169295:   if( flags & SQLITE_OPEN_URI ){
169296:     int odd = 0;
169297:     while( 1 ){
169298:       if( z[0]==0 ){
169299:         odd = 1 - odd;
169300:         if( odd && z[1]==0 ) break;
169301:       }
169302:       z++;
169303:     }
169304:     z += 2;
169305:   }else{
169306:     while( *z==0 ) z++;
169307:   }
169308:   z += (n + 8 + 1);
169309:   return z;
169310: }
169311: 
169312: /*
169313: ** Open an rbu file handle.
169314: */
169315: static int rbuVfsOpen(
169316:   sqlite3_vfs *pVfs,
169317:   const char *zName,
169318:   sqlite3_file *pFile,
169319:   int flags,
169320:   int *pOutFlags
169321: ){
169322:   static sqlite3_io_methods rbuvfs_io_methods = {
169323:     2,                            /* iVersion */
169324:     rbuVfsClose,                  /* xClose */
169325:     rbuVfsRead,                   /* xRead */
169326:     rbuVfsWrite,                  /* xWrite */
169327:     rbuVfsTruncate,               /* xTruncate */
169328:     rbuVfsSync,                   /* xSync */
169329:     rbuVfsFileSize,               /* xFileSize */
169330:     rbuVfsLock,                   /* xLock */
169331:     rbuVfsUnlock,                 /* xUnlock */
169332:     rbuVfsCheckReservedLock,      /* xCheckReservedLock */
169333:     rbuVfsFileControl,            /* xFileControl */
169334:     rbuVfsSectorSize,             /* xSectorSize */
169335:     rbuVfsDeviceCharacteristics,  /* xDeviceCharacteristics */
169336:     rbuVfsShmMap,                 /* xShmMap */
169337:     rbuVfsShmLock,                /* xShmLock */
169338:     rbuVfsShmBarrier,             /* xShmBarrier */
169339:     rbuVfsShmUnmap,               /* xShmUnmap */
169340:     0, 0                          /* xFetch, xUnfetch */
169341:   };
169342:   rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
169343:   sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
169344:   rbu_file *pFd = (rbu_file *)pFile;
169345:   int rc = SQLITE_OK;
169346:   const char *zOpen = zName;
169347:   int oflags = flags;
169348: 
169349:   memset(pFd, 0, sizeof(rbu_file));
169350:   pFd->pReal = (sqlite3_file*)&pFd[1];
169351:   pFd->pRbuVfs = pRbuVfs;
169352:   pFd->openFlags = flags;
169353:   if( zName ){
169354:     if( flags & SQLITE_OPEN_MAIN_DB ){
169355:       /* A main database has just been opened. The following block sets
169356:       ** (pFd->zWal) to point to a buffer owned by SQLite that contains
169357:       ** the name of the *-wal file this db connection will use. SQLite
169358:       ** happens to pass a pointer to this buffer when using xAccess()
169359:       ** or xOpen() to operate on the *-wal file.  */
169360:       pFd->zWal = rbuMainToWal(zName, flags);
169361:     }
169362:     else if( flags & SQLITE_OPEN_WAL ){
169363:       rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
169364:       if( pDb ){
169365:         if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
169366:           /* This call is to open a *-wal file. Intead, open the *-oal. This
169367:           ** code ensures that the string passed to xOpen() is terminated by a
169368:           ** pair of '\0' bytes in case the VFS attempts to extract a URI 
169369:           ** parameter from it.  */
169370:           const char *zBase = zName;
169371:           size_t nCopy;
169372:           char *zCopy;
169373:           if( rbuIsVacuum(pDb->pRbu) ){
169374:             zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
169375:             zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
169376:           }
169377:           nCopy = strlen(zBase);
169378:           zCopy = sqlite3_malloc64(nCopy+2);
169379:           if( zCopy ){
169380:             memcpy(zCopy, zBase, nCopy);
169381:             zCopy[nCopy-3] = 'o';
169382:             zCopy[nCopy] = '\0';
169383:             zCopy[nCopy+1] = '\0';
169384:             zOpen = (const char*)(pFd->zDel = zCopy);
169385:           }else{
169386:             rc = SQLITE_NOMEM;
169387:           }
169388:           pFd->pRbu = pDb->pRbu;
169389:         }
169390:         pDb->pWalFd = pFd;
169391:       }
169392:     }
169393:   }
169394: 
169395:   if( oflags & SQLITE_OPEN_MAIN_DB 
169396:    && sqlite3_uri_boolean(zName, "rbu_memory", 0) 
169397:   ){
169398:     assert( oflags & SQLITE_OPEN_MAIN_DB );
169399:     oflags =  SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
169400:               SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
169401:     zOpen = 0;
169402:   }
169403: 
169404:   if( rc==SQLITE_OK ){
169405:     rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
169406:   }
169407:   if( pFd->pReal->pMethods ){
169408:     /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
169409:     ** pointer and, if the file is a main database file, link it into the
169410:     ** mutex protected linked list of all such files.  */
169411:     pFile->pMethods = &rbuvfs_io_methods;
169412:     if( flags & SQLITE_OPEN_MAIN_DB ){
169413:       sqlite3_mutex_enter(pRbuVfs->mutex);
169414:       pFd->pMainNext = pRbuVfs->pMain;
169415:       pRbuVfs->pMain = pFd;
169416:       sqlite3_mutex_leave(pRbuVfs->mutex);
169417:     }
169418:   }else{
169419:     sqlite3_free(pFd->zDel);
169420:   }
169421: 
169422:   return rc;
169423: }
169424: 
169425: /*
169426: ** Delete the file located at zPath.
169427: */
169428: static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
169429:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169430:   return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
169431: }
169432: 
169433: /*
169434: ** Test for access permissions. Return true if the requested permission
169435: ** is available, or false otherwise.
169436: */
169437: static int rbuVfsAccess(
169438:   sqlite3_vfs *pVfs, 
169439:   const char *zPath, 
169440:   int flags, 
169441:   int *pResOut
169442: ){
169443:   rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
169444:   sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
169445:   int rc;
169446: 
169447:   rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
169448: 
169449:   /* If this call is to check if a *-wal file associated with an RBU target
169450:   ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
169451:   ** the following special handling is activated:
169452:   **
169453:   **   a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
169454:   **      ensures that the RBU extension never tries to update a database
169455:   **      in wal mode, even if the first page of the database file has
169456:   **      been damaged. 
169457:   **
169458:   **   b) if the *-wal file does not exist, claim that it does anyway,
169459:   **      causing SQLite to call xOpen() to open it. This call will also
169460:   **      be intercepted (see the rbuVfsOpen() function) and the *-oal
169461:   **      file opened instead.
169462:   */
169463:   if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
169464:     rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
169465:     if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
169466:       if( *pResOut ){
169467:         rc = SQLITE_CANTOPEN;
169468:       }else{
169469:         *pResOut = 1;
169470:       }
169471:     }
169472:   }
169473: 
169474:   return rc;
169475: }
169476: 
169477: /*
169478: ** Populate buffer zOut with the full canonical pathname corresponding
169479: ** to the pathname in zPath. zOut is guaranteed to point to a buffer
169480: ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
169481: */
169482: static int rbuVfsFullPathname(
169483:   sqlite3_vfs *pVfs, 
169484:   const char *zPath, 
169485:   int nOut, 
169486:   char *zOut
169487: ){
169488:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169489:   return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
169490: }
169491: 
169492: #ifndef SQLITE_OMIT_LOAD_EXTENSION
169493: /*
169494: ** Open the dynamic library located at zPath and return a handle.
169495: */
169496: static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
169497:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169498:   return pRealVfs->xDlOpen(pRealVfs, zPath);
169499: }
169500: 
169501: /*
169502: ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
169503: ** utf-8 string describing the most recent error encountered associated 
169504: ** with dynamic libraries.
169505: */
169506: static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
169507:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169508:   pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
169509: }
169510: 
169511: /*
169512: ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
169513: */
169514: static void (*rbuVfsDlSym(
169515:   sqlite3_vfs *pVfs, 
169516:   void *pArg, 
169517:   const char *zSym
169518: ))(void){
169519:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169520:   return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
169521: }
169522: 
169523: /*
169524: ** Close the dynamic library handle pHandle.
169525: */
169526: static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
169527:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169528:   pRealVfs->xDlClose(pRealVfs, pHandle);
169529: }
169530: #endif /* SQLITE_OMIT_LOAD_EXTENSION */
169531: 
169532: /*
169533: ** Populate the buffer pointed to by zBufOut with nByte bytes of 
169534: ** random data.
169535: */
169536: static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
169537:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169538:   return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
169539: }
169540: 
169541: /*
169542: ** Sleep for nMicro microseconds. Return the number of microseconds 
169543: ** actually slept.
169544: */
169545: static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
169546:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169547:   return pRealVfs->xSleep(pRealVfs, nMicro);
169548: }
169549: 
169550: /*
169551: ** Return the current time as a Julian Day number in *pTimeOut.
169552: */
169553: static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
169554:   sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
169555:   return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
169556: }
169557: 
169558: /*
169559: ** No-op.
169560: */
169561: static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
169562:   return 0;
169563: }
169564: 
169565: /*
169566: ** Deregister and destroy an RBU vfs created by an earlier call to
169567: ** sqlite3rbu_create_vfs().
169568: */
169569: SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
169570:   sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
169571:   if( pVfs && pVfs->xOpen==rbuVfsOpen ){
169572:     sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
169573:     sqlite3_vfs_unregister(pVfs);
169574:     sqlite3_free(pVfs);
169575:   }
169576: }
169577: 
169578: /*
169579: ** Create an RBU VFS named zName that accesses the underlying file-system
169580: ** via existing VFS zParent. The new object is registered as a non-default
169581: ** VFS with SQLite before returning.
169582: */
169583: SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
169584: 
169585:   /* Template for VFS */
169586:   static sqlite3_vfs vfs_template = {
169587:     1,                            /* iVersion */
169588:     0,                            /* szOsFile */
169589:     0,                            /* mxPathname */
169590:     0,                            /* pNext */
169591:     0,                            /* zName */
169592:     0,                            /* pAppData */
169593:     rbuVfsOpen,                   /* xOpen */
169594:     rbuVfsDelete,                 /* xDelete */
169595:     rbuVfsAccess,                 /* xAccess */
169596:     rbuVfsFullPathname,           /* xFullPathname */
169597: 
169598: #ifndef SQLITE_OMIT_LOAD_EXTENSION
169599:     rbuVfsDlOpen,                 /* xDlOpen */
169600:     rbuVfsDlError,                /* xDlError */
169601:     rbuVfsDlSym,                  /* xDlSym */
169602:     rbuVfsDlClose,                /* xDlClose */
169603: #else
169604:     0, 0, 0, 0,
169605: #endif
169606: 
169607:     rbuVfsRandomness,             /* xRandomness */
169608:     rbuVfsSleep,                  /* xSleep */
169609:     rbuVfsCurrentTime,            /* xCurrentTime */
169610:     rbuVfsGetLastError,           /* xGetLastError */
169611:     0,                            /* xCurrentTimeInt64 (version 2) */
169612:     0, 0, 0                       /* Unimplemented version 3 methods */
169613:   };
169614: 
169615:   rbu_vfs *pNew = 0;              /* Newly allocated VFS */
169616:   int rc = SQLITE_OK;
169617:   size_t nName;
169618:   size_t nByte;
169619: 
169620:   nName = strlen(zName);
169621:   nByte = sizeof(rbu_vfs) + nName + 1;
169622:   pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
169623:   if( pNew==0 ){
169624:     rc = SQLITE_NOMEM;
169625:   }else{
169626:     sqlite3_vfs *pParent;           /* Parent VFS */
169627:     memset(pNew, 0, nByte);
169628:     pParent = sqlite3_vfs_find(zParent);
169629:     if( pParent==0 ){
169630:       rc = SQLITE_NOTFOUND;
169631:     }else{
169632:       char *zSpace;
169633:       memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
169634:       pNew->base.mxPathname = pParent->mxPathname;
169635:       pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
169636:       pNew->pRealVfs = pParent;
169637:       pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
169638:       memcpy(zSpace, zName, nName);
169639: 
169640:       /* Allocate the mutex and register the new VFS (not as the default) */
169641:       pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
169642:       if( pNew->mutex==0 ){
169643:         rc = SQLITE_NOMEM;
169644:       }else{
169645:         rc = sqlite3_vfs_register(&pNew->base, 0);
169646:       }
169647:     }
169648: 
169649:     if( rc!=SQLITE_OK ){
169650:       sqlite3_mutex_free(pNew->mutex);
169651:       sqlite3_free(pNew);
169652:     }
169653:   }
169654: 
169655:   return rc;
169656: }
169657: 
169658: 
169659: /**************************************************************************/
169660: 
169661: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
169662: 
169663: /************** End of sqlite3rbu.c ******************************************/
169664: /************** Begin file dbstat.c ******************************************/
169665: /*
169666: ** 2010 July 12
169667: **
169668: ** The author disclaims copyright to this source code.  In place of
169669: ** a legal notice, here is a blessing:
169670: **
169671: **    May you do good and not evil.
169672: **    May you find forgiveness for yourself and forgive others.
169673: **    May you share freely, never taking more than you give.
169674: **
169675: ******************************************************************************
169676: **
169677: ** This file contains an implementation of the "dbstat" virtual table.
169678: **
169679: ** The dbstat virtual table is used to extract low-level formatting
169680: ** information from an SQLite database in order to implement the
169681: ** "sqlite3_analyzer" utility.  See the ../tool/spaceanal.tcl script
169682: ** for an example implementation.
169683: **
169684: ** Additional information is available on the "dbstat.html" page of the
169685: ** official SQLite documentation.
169686: */
169687: 
169688: /* #include "sqliteInt.h"   ** Requires access to internal data structures ** */
169689: #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
169690:     && !defined(SQLITE_OMIT_VIRTUALTABLE)
169691: 
169692: /*
169693: ** Page paths:
169694: ** 
169695: **   The value of the 'path' column describes the path taken from the 
169696: **   root-node of the b-tree structure to each page. The value of the 
169697: **   root-node path is '/'.
169698: **
169699: **   The value of the path for the left-most child page of the root of
169700: **   a b-tree is '/000/'. (Btrees store content ordered from left to right
169701: **   so the pages to the left have smaller keys than the pages to the right.)
169702: **   The next to left-most child of the root page is
169703: **   '/001', and so on, each sibling page identified by a 3-digit hex 
169704: **   value. The children of the 451st left-most sibling have paths such
169705: **   as '/1c2/000/, '/1c2/001/' etc.
169706: **
169707: **   Overflow pages are specified by appending a '+' character and a 
169708: **   six-digit hexadecimal value to the path to the cell they are linked
169709: **   from. For example, the three overflow pages in a chain linked from 
169710: **   the left-most cell of the 450th child of the root page are identified
169711: **   by the paths:
169712: **
169713: **      '/1c2/000+000000'         // First page in overflow chain
169714: **      '/1c2/000+000001'         // Second page in overflow chain
169715: **      '/1c2/000+000002'         // Third page in overflow chain
169716: **
169717: **   If the paths are sorted using the BINARY collation sequence, then
169718: **   the overflow pages associated with a cell will appear earlier in the
169719: **   sort-order than its child page:
169720: **
169721: **      '/1c2/000/'               // Left-most child of 451st child of root
169722: */
169723: #define VTAB_SCHEMA                                                         \
169724:   "CREATE TABLE xx( "                                                       \
169725:   "  name       TEXT,             /* Name of table or index */"             \
169726:   "  path       TEXT,             /* Path to page from root */"             \
169727:   "  pageno     INTEGER,          /* Page number */"                        \
169728:   "  pagetype   TEXT,             /* 'internal', 'leaf' or 'overflow' */"   \
169729:   "  ncell      INTEGER,          /* Cells on page (0 for overflow) */"     \
169730:   "  payload    INTEGER,          /* Bytes of payload on this page */"      \
169731:   "  unused     INTEGER,          /* Bytes of unused space on this page */" \
169732:   "  mx_payload INTEGER,          /* Largest payload size of all cells */"  \
169733:   "  pgoffset   INTEGER,          /* Offset of page in file */"             \
169734:   "  pgsize     INTEGER,          /* Size of the page */"                   \
169735:   "  schema     TEXT HIDDEN       /* Database schema being analyzed */"     \
169736:   ");"
169737: 
169738: 
169739: typedef struct StatTable StatTable;
169740: typedef struct StatCursor StatCursor;
169741: typedef struct StatPage StatPage;
169742: typedef struct StatCell StatCell;
169743: 
169744: struct StatCell {
169745:   int nLocal;                     /* Bytes of local payload */
169746:   u32 iChildPg;                   /* Child node (or 0 if this is a leaf) */
169747:   int nOvfl;                      /* Entries in aOvfl[] */
169748:   u32 *aOvfl;                     /* Array of overflow page numbers */
169749:   int nLastOvfl;                  /* Bytes of payload on final overflow page */
169750:   int iOvfl;                      /* Iterates through aOvfl[] */
169751: };
169752: 
169753: struct StatPage {
169754:   u32 iPgno;
169755:   DbPage *pPg;
169756:   int iCell;
169757: 
169758:   char *zPath;                    /* Path to this page */
169759: 
169760:   /* Variables populated by statDecodePage(): */
169761:   u8 flags;                       /* Copy of flags byte */
169762:   int nCell;                      /* Number of cells on page */
169763:   int nUnused;                    /* Number of unused bytes on page */
169764:   StatCell *aCell;                /* Array of parsed cells */
169765:   u32 iRightChildPg;              /* Right-child page number (or 0) */
169766:   int nMxPayload;                 /* Largest payload of any cell on this page */
169767: };
169768: 
169769: struct StatCursor {
169770:   sqlite3_vtab_cursor base;
169771:   sqlite3_stmt *pStmt;            /* Iterates through set of root pages */
169772:   int isEof;                      /* After pStmt has returned SQLITE_DONE */
169773:   int iDb;                        /* Schema used for this query */
169774: 
169775:   StatPage aPage[32];
169776:   int iPage;                      /* Current entry in aPage[] */
169777: 
169778:   /* Values to return. */
169779:   char *zName;                    /* Value of 'name' column */
169780:   char *zPath;                    /* Value of 'path' column */
169781:   u32 iPageno;                    /* Value of 'pageno' column */
169782:   char *zPagetype;                /* Value of 'pagetype' column */
169783:   int nCell;                      /* Value of 'ncell' column */
169784:   int nPayload;                   /* Value of 'payload' column */
169785:   int nUnused;                    /* Value of 'unused' column */
169786:   int nMxPayload;                 /* Value of 'mx_payload' column */
169787:   i64 iOffset;                    /* Value of 'pgOffset' column */
169788:   int szPage;                     /* Value of 'pgSize' column */
169789: };
169790: 
169791: struct StatTable {
169792:   sqlite3_vtab base;
169793:   sqlite3 *db;
169794:   int iDb;                        /* Index of database to analyze */
169795: };
169796: 
169797: #ifndef get2byte
169798: # define get2byte(x)   ((x)[0]<<8 | (x)[1])
169799: #endif
169800: 
169801: /*
169802: ** Connect to or create a statvfs virtual table.
169803: */
169804: static int statConnect(
169805:   sqlite3 *db,
169806:   void *pAux,
169807:   int argc, const char *const*argv,
169808:   sqlite3_vtab **ppVtab,
169809:   char **pzErr
169810: ){
169811:   StatTable *pTab = 0;
169812:   int rc = SQLITE_OK;
169813:   int iDb;
169814: 
169815:   if( argc>=4 ){
169816:     Token nm;
169817:     sqlite3TokenInit(&nm, (char*)argv[3]);
169818:     iDb = sqlite3FindDb(db, &nm);
169819:     if( iDb<0 ){
169820:       *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
169821:       return SQLITE_ERROR;
169822:     }
169823:   }else{
169824:     iDb = 0;
169825:   }
169826:   rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
169827:   if( rc==SQLITE_OK ){
169828:     pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
169829:     if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
169830:   }
169831: 
169832:   assert( rc==SQLITE_OK || pTab==0 );
169833:   if( rc==SQLITE_OK ){
169834:     memset(pTab, 0, sizeof(StatTable));
169835:     pTab->db = db;
169836:     pTab->iDb = iDb;
169837:   }
169838: 
169839:   *ppVtab = (sqlite3_vtab*)pTab;
169840:   return rc;
169841: }
169842: 
169843: /*
169844: ** Disconnect from or destroy a statvfs virtual table.
169845: */
169846: static int statDisconnect(sqlite3_vtab *pVtab){
169847:   sqlite3_free(pVtab);
169848:   return SQLITE_OK;
169849: }
169850: 
169851: /*
169852: ** There is no "best-index". This virtual table always does a linear
169853: ** scan.  However, a schema=? constraint should cause this table to
169854: ** operate on a different database schema, so check for it.
169855: **
169856: ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
169857: */
169858: static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
169859:   int i;
169860: 
169861:   pIdxInfo->estimatedCost = 1.0e6;  /* Initial cost estimate */
169862: 
169863:   /* Look for a valid schema=? constraint.  If found, change the idxNum to
169864:   ** 1 and request the value of that constraint be sent to xFilter.  And
169865:   ** lower the cost estimate to encourage the constrained version to be
169866:   ** used.
169867:   */
169868:   for(i=0; i<pIdxInfo->nConstraint; i++){
169869:     if( pIdxInfo->aConstraint[i].usable==0 ) continue;
169870:     if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
169871:     if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
169872:     pIdxInfo->idxNum = 1;
169873:     pIdxInfo->estimatedCost = 1.0;
169874:     pIdxInfo->aConstraintUsage[i].argvIndex = 1;
169875:     pIdxInfo->aConstraintUsage[i].omit = 1;
169876:     break;
169877:   }
169878: 
169879: 
169880:   /* Records are always returned in ascending order of (name, path). 
169881:   ** If this will satisfy the client, set the orderByConsumed flag so that 
169882:   ** SQLite does not do an external sort.
169883:   */
169884:   if( ( pIdxInfo->nOrderBy==1
169885:      && pIdxInfo->aOrderBy[0].iColumn==0
169886:      && pIdxInfo->aOrderBy[0].desc==0
169887:      ) ||
169888:       ( pIdxInfo->nOrderBy==2
169889:      && pIdxInfo->aOrderBy[0].iColumn==0
169890:      && pIdxInfo->aOrderBy[0].desc==0
169891:      && pIdxInfo->aOrderBy[1].iColumn==1
169892:      && pIdxInfo->aOrderBy[1].desc==0
169893:      )
169894:   ){
169895:     pIdxInfo->orderByConsumed = 1;
169896:   }
169897: 
169898:   return SQLITE_OK;
169899: }
169900: 
169901: /*
169902: ** Open a new statvfs cursor.
169903: */
169904: static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
169905:   StatTable *pTab = (StatTable *)pVTab;
169906:   StatCursor *pCsr;
169907: 
169908:   pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
169909:   if( pCsr==0 ){
169910:     return SQLITE_NOMEM_BKPT;
169911:   }else{
169912:     memset(pCsr, 0, sizeof(StatCursor));
169913:     pCsr->base.pVtab = pVTab;
169914:     pCsr->iDb = pTab->iDb;
169915:   }
169916: 
169917:   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
169918:   return SQLITE_OK;
169919: }
169920: 
169921: static void statClearPage(StatPage *p){
169922:   int i;
169923:   if( p->aCell ){
169924:     for(i=0; i<p->nCell; i++){
169925:       sqlite3_free(p->aCell[i].aOvfl);
169926:     }
169927:     sqlite3_free(p->aCell);
169928:   }
169929:   sqlite3PagerUnref(p->pPg);
169930:   sqlite3_free(p->zPath);
169931:   memset(p, 0, sizeof(StatPage));
169932: }
169933: 
169934: static void statResetCsr(StatCursor *pCsr){
169935:   int i;
169936:   sqlite3_reset(pCsr->pStmt);
169937:   for(i=0; i<ArraySize(pCsr->aPage); i++){
169938:     statClearPage(&pCsr->aPage[i]);
169939:   }
169940:   pCsr->iPage = 0;
169941:   sqlite3_free(pCsr->zPath);
169942:   pCsr->zPath = 0;
169943:   pCsr->isEof = 0;
169944: }
169945: 
169946: /*
169947: ** Close a statvfs cursor.
169948: */
169949: static int statClose(sqlite3_vtab_cursor *pCursor){
169950:   StatCursor *pCsr = (StatCursor *)pCursor;
169951:   statResetCsr(pCsr);
169952:   sqlite3_finalize(pCsr->pStmt);
169953:   sqlite3_free(pCsr);
169954:   return SQLITE_OK;
169955: }
169956: 
169957: static void getLocalPayload(
169958:   int nUsable,                    /* Usable bytes per page */
169959:   u8 flags,                       /* Page flags */
169960:   int nTotal,                     /* Total record (payload) size */
169961:   int *pnLocal                    /* OUT: Bytes stored locally */
169962: ){
169963:   int nLocal;
169964:   int nMinLocal;
169965:   int nMaxLocal;
169966:  
169967:   if( flags==0x0D ){              /* Table leaf node */
169968:     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
169969:     nMaxLocal = nUsable - 35;
169970:   }else{                          /* Index interior and leaf nodes */
169971:     nMinLocal = (nUsable - 12) * 32 / 255 - 23;
169972:     nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
169973:   }
169974: 
169975:   nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
169976:   if( nLocal>nMaxLocal ) nLocal = nMinLocal;
169977:   *pnLocal = nLocal;
169978: }
169979: 
169980: static int statDecodePage(Btree *pBt, StatPage *p){
169981:   int nUnused;
169982:   int iOff;
169983:   int nHdr;
169984:   int isLeaf;
169985:   int szPage;
169986: 
169987:   u8 *aData = sqlite3PagerGetData(p->pPg);
169988:   u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
169989: 
169990:   p->flags = aHdr[0];
169991:   p->nCell = get2byte(&aHdr[3]);
169992:   p->nMxPayload = 0;
169993: 
169994:   isLeaf = (p->flags==0x0A || p->flags==0x0D);
169995:   nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
169996: 
169997:   nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
169998:   nUnused += (int)aHdr[7];
169999:   iOff = get2byte(&aHdr[1]);
170000:   while( iOff ){
170001:     nUnused += get2byte(&aData[iOff+2]);
170002:     iOff = get2byte(&aData[iOff]);
170003:   }
170004:   p->nUnused = nUnused;
170005:   p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
170006:   szPage = sqlite3BtreeGetPageSize(pBt);
170007: 
170008:   if( p->nCell ){
170009:     int i;                        /* Used to iterate through cells */
170010:     int nUsable;                  /* Usable bytes per page */
170011: 
170012:     sqlite3BtreeEnter(pBt);
170013:     nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
170014:     sqlite3BtreeLeave(pBt);
170015:     p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
170016:     if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
170017:     memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
170018: 
170019:     for(i=0; i<p->nCell; i++){
170020:       StatCell *pCell = &p->aCell[i];
170021: 
170022:       iOff = get2byte(&aData[nHdr+i*2]);
170023:       if( !isLeaf ){
170024:         pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
170025:         iOff += 4;
170026:       }
170027:       if( p->flags==0x05 ){
170028:         /* A table interior node. nPayload==0. */
170029:       }else{
170030:         u32 nPayload;             /* Bytes of payload total (local+overflow) */
170031:         int nLocal;               /* Bytes of payload stored locally */
170032:         iOff += getVarint32(&aData[iOff], nPayload);
170033:         if( p->flags==0x0D ){
170034:           u64 dummy;
170035:           iOff += sqlite3GetVarint(&aData[iOff], &dummy);
170036:         }
170037:         if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
170038:         getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
170039:         pCell->nLocal = nLocal;
170040:         assert( nLocal>=0 );
170041:         assert( nPayload>=(u32)nLocal );
170042:         assert( nLocal<=(nUsable-35) );
170043:         if( nPayload>(u32)nLocal ){
170044:           int j;
170045:           int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
170046:           pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
170047:           pCell->nOvfl = nOvfl;
170048:           pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
170049:           if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
170050:           pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
170051:           for(j=1; j<nOvfl; j++){
170052:             int rc;
170053:             u32 iPrev = pCell->aOvfl[j-1];
170054:             DbPage *pPg = 0;
170055:             rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
170056:             if( rc!=SQLITE_OK ){
170057:               assert( pPg==0 );
170058:               return rc;
170059:             } 
170060:             pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
170061:             sqlite3PagerUnref(pPg);
170062:           }
170063:         }
170064:       }
170065:     }
170066:   }
170067: 
170068:   return SQLITE_OK;
170069: }
170070: 
170071: /*
170072: ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
170073: ** the current value of pCsr->iPageno.
170074: */
170075: static void statSizeAndOffset(StatCursor *pCsr){
170076:   StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
170077:   Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
170078:   Pager *pPager = sqlite3BtreePager(pBt);
170079:   sqlite3_file *fd;
170080:   sqlite3_int64 x[2];
170081: 
170082:   /* The default page size and offset */
170083:   pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
170084:   pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
170085: 
170086:   /* If connected to a ZIPVFS backend, override the page size and
170087:   ** offset with actual values obtained from ZIPVFS.
170088:   */
170089:   fd = sqlite3PagerFile(pPager);
170090:   x[0] = pCsr->iPageno;
170091:   if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
170092:     pCsr->iOffset = x[0];
170093:     pCsr->szPage = (int)x[1];
170094:   }
170095: }
170096: 
170097: /*
170098: ** Move a statvfs cursor to the next entry in the file.
170099: */
170100: static int statNext(sqlite3_vtab_cursor *pCursor){
170101:   int rc;
170102:   int nPayload;
170103:   char *z;
170104:   StatCursor *pCsr = (StatCursor *)pCursor;
170105:   StatTable *pTab = (StatTable *)pCursor->pVtab;
170106:   Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
170107:   Pager *pPager = sqlite3BtreePager(pBt);
170108: 
170109:   sqlite3_free(pCsr->zPath);
170110:   pCsr->zPath = 0;
170111: 
170112: statNextRestart:
170113:   if( pCsr->aPage[0].pPg==0 ){
170114:     rc = sqlite3_step(pCsr->pStmt);
170115:     if( rc==SQLITE_ROW ){
170116:       int nPage;
170117:       u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
170118:       sqlite3PagerPagecount(pPager, &nPage);
170119:       if( nPage==0 ){
170120:         pCsr->isEof = 1;
170121:         return sqlite3_reset(pCsr->pStmt);
170122:       }
170123:       rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
170124:       pCsr->aPage[0].iPgno = iRoot;
170125:       pCsr->aPage[0].iCell = 0;
170126:       pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
170127:       pCsr->iPage = 0;
170128:       if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170129:     }else{
170130:       pCsr->isEof = 1;
170131:       return sqlite3_reset(pCsr->pStmt);
170132:     }
170133:   }else{
170134: 
170135:     /* Page p itself has already been visited. */
170136:     StatPage *p = &pCsr->aPage[pCsr->iPage];
170137: 
170138:     while( p->iCell<p->nCell ){
170139:       StatCell *pCell = &p->aCell[p->iCell];
170140:       if( pCell->iOvfl<pCell->nOvfl ){
170141:         int nUsable;
170142:         sqlite3BtreeEnter(pBt);
170143:         nUsable = sqlite3BtreeGetPageSize(pBt) - 
170144:                         sqlite3BtreeGetReserveNoMutex(pBt);
170145:         sqlite3BtreeLeave(pBt);
170146:         pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
170147:         pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
170148:         pCsr->zPagetype = "overflow";
170149:         pCsr->nCell = 0;
170150:         pCsr->nMxPayload = 0;
170151:         pCsr->zPath = z = sqlite3_mprintf(
170152:             "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
170153:         );
170154:         if( pCell->iOvfl<pCell->nOvfl-1 ){
170155:           pCsr->nUnused = 0;
170156:           pCsr->nPayload = nUsable - 4;
170157:         }else{
170158:           pCsr->nPayload = pCell->nLastOvfl;
170159:           pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
170160:         }
170161:         pCell->iOvfl++;
170162:         statSizeAndOffset(pCsr);
170163:         return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
170164:       }
170165:       if( p->iRightChildPg ) break;
170166:       p->iCell++;
170167:     }
170168: 
170169:     if( !p->iRightChildPg || p->iCell>p->nCell ){
170170:       statClearPage(p);
170171:       if( pCsr->iPage==0 ) return statNext(pCursor);
170172:       pCsr->iPage--;
170173:       goto statNextRestart; /* Tail recursion */
170174:     }
170175:     pCsr->iPage++;
170176:     assert( p==&pCsr->aPage[pCsr->iPage-1] );
170177: 
170178:     if( p->iCell==p->nCell ){
170179:       p[1].iPgno = p->iRightChildPg;
170180:     }else{
170181:       p[1].iPgno = p->aCell[p->iCell].iChildPg;
170182:     }
170183:     rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
170184:     p[1].iCell = 0;
170185:     p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
170186:     p->iCell++;
170187:     if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170188:   }
170189: 
170190: 
170191:   /* Populate the StatCursor fields with the values to be returned
170192:   ** by the xColumn() and xRowid() methods.
170193:   */
170194:   if( rc==SQLITE_OK ){
170195:     int i;
170196:     StatPage *p = &pCsr->aPage[pCsr->iPage];
170197:     pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
170198:     pCsr->iPageno = p->iPgno;
170199: 
170200:     rc = statDecodePage(pBt, p);
170201:     if( rc==SQLITE_OK ){
170202:       statSizeAndOffset(pCsr);
170203: 
170204:       switch( p->flags ){
170205:         case 0x05:             /* table internal */
170206:         case 0x02:             /* index internal */
170207:           pCsr->zPagetype = "internal";
170208:           break;
170209:         case 0x0D:             /* table leaf */
170210:         case 0x0A:             /* index leaf */
170211:           pCsr->zPagetype = "leaf";
170212:           break;
170213:         default:
170214:           pCsr->zPagetype = "corrupted";
170215:           break;
170216:       }
170217:       pCsr->nCell = p->nCell;
170218:       pCsr->nUnused = p->nUnused;
170219:       pCsr->nMxPayload = p->nMxPayload;
170220:       pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
170221:       if( z==0 ) rc = SQLITE_NOMEM_BKPT;
170222:       nPayload = 0;
170223:       for(i=0; i<p->nCell; i++){
170224:         nPayload += p->aCell[i].nLocal;
170225:       }
170226:       pCsr->nPayload = nPayload;
170227:     }
170228:   }
170229: 
170230:   return rc;
170231: }
170232: 
170233: static int statEof(sqlite3_vtab_cursor *pCursor){
170234:   StatCursor *pCsr = (StatCursor *)pCursor;
170235:   return pCsr->isEof;
170236: }
170237: 
170238: static int statFilter(
170239:   sqlite3_vtab_cursor *pCursor, 
170240:   int idxNum, const char *idxStr,
170241:   int argc, sqlite3_value **argv
170242: ){
170243:   StatCursor *pCsr = (StatCursor *)pCursor;
170244:   StatTable *pTab = (StatTable*)(pCursor->pVtab);
170245:   char *zSql;
170246:   int rc = SQLITE_OK;
170247:   char *zMaster;
170248: 
170249:   if( idxNum==1 ){
170250:     const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
170251:     pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
170252:     if( pCsr->iDb<0 ){
170253:       sqlite3_free(pCursor->pVtab->zErrMsg);
170254:       pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
170255:       return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
170256:     }
170257:   }else{
170258:     pCsr->iDb = pTab->iDb;
170259:   }
170260:   statResetCsr(pCsr);
170261:   sqlite3_finalize(pCsr->pStmt);
170262:   pCsr->pStmt = 0;
170263:   zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
170264:   zSql = sqlite3_mprintf(
170265:       "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
170266:       "  UNION ALL  "
170267:       "SELECT name, rootpage, type"
170268:       "  FROM \"%w\".%s WHERE rootpage!=0"
170269:       "  ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
170270:   if( zSql==0 ){
170271:     return SQLITE_NOMEM_BKPT;
170272:   }else{
170273:     rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
170274:     sqlite3_free(zSql);
170275:   }
170276: 
170277:   if( rc==SQLITE_OK ){
170278:     rc = statNext(pCursor);
170279:   }
170280:   return rc;
170281: }
170282: 
170283: static int statColumn(
170284:   sqlite3_vtab_cursor *pCursor, 
170285:   sqlite3_context *ctx, 
170286:   int i
170287: ){
170288:   StatCursor *pCsr = (StatCursor *)pCursor;
170289:   switch( i ){
170290:     case 0:            /* name */
170291:       sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
170292:       break;
170293:     case 1:            /* path */
170294:       sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
170295:       break;
170296:     case 2:            /* pageno */
170297:       sqlite3_result_int64(ctx, pCsr->iPageno);
170298:       break;
170299:     case 3:            /* pagetype */
170300:       sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
170301:       break;
170302:     case 4:            /* ncell */
170303:       sqlite3_result_int(ctx, pCsr->nCell);
170304:       break;
170305:     case 5:            /* payload */
170306:       sqlite3_result_int(ctx, pCsr->nPayload);
170307:       break;
170308:     case 6:            /* unused */
170309:       sqlite3_result_int(ctx, pCsr->nUnused);
170310:       break;
170311:     case 7:            /* mx_payload */
170312:       sqlite3_result_int(ctx, pCsr->nMxPayload);
170313:       break;
170314:     case 8:            /* pgoffset */
170315:       sqlite3_result_int64(ctx, pCsr->iOffset);
170316:       break;
170317:     case 9:            /* pgsize */
170318:       sqlite3_result_int(ctx, pCsr->szPage);
170319:       break;
170320:     default: {          /* schema */
170321:       sqlite3 *db = sqlite3_context_db_handle(ctx);
170322:       int iDb = pCsr->iDb;
170323:       sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
170324:       break;
170325:     }
170326:   }
170327:   return SQLITE_OK;
170328: }
170329: 
170330: static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
170331:   StatCursor *pCsr = (StatCursor *)pCursor;
170332:   *pRowid = pCsr->iPageno;
170333:   return SQLITE_OK;
170334: }
170335: 
170336: /*
170337: ** Invoke this routine to register the "dbstat" virtual table module
170338: */
170339: SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
170340:   static sqlite3_module dbstat_module = {
170341:     0,                            /* iVersion */
170342:     statConnect,                  /* xCreate */
170343:     statConnect,                  /* xConnect */
170344:     statBestIndex,                /* xBestIndex */
170345:     statDisconnect,               /* xDisconnect */
170346:     statDisconnect,               /* xDestroy */
170347:     statOpen,                     /* xOpen - open a cursor */
170348:     statClose,                    /* xClose - close a cursor */
170349:     statFilter,                   /* xFilter - configure scan constraints */
170350:     statNext,                     /* xNext - advance a cursor */
170351:     statEof,                      /* xEof - check for end of scan */
170352:     statColumn,                   /* xColumn - read data */
170353:     statRowid,                    /* xRowid - read data */
170354:     0,                            /* xUpdate */
170355:     0,                            /* xBegin */
170356:     0,                            /* xSync */
170357:     0,                            /* xCommit */
170358:     0,                            /* xRollback */
170359:     0,                            /* xFindMethod */
170360:     0,                            /* xRename */
170361:   };
170362:   return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
170363: }
170364: #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
170365: SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
170366: #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
170367: 
170368: /************** End of dbstat.c **********************************************/
170369: /************** Begin file sqlite3session.c **********************************/
170370: 
170371: #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
170372: /* #include "sqlite3session.h" */
170373: /* #include <assert.h> */
170374: /* #include <string.h> */
170375: 
170376: #ifndef SQLITE_AMALGAMATION
170377: /* # include "sqliteInt.h" */
170378: /* # include "vdbeInt.h" */
170379: #endif
170380: 
170381: typedef struct SessionTable SessionTable;
170382: typedef struct SessionChange SessionChange;
170383: typedef struct SessionBuffer SessionBuffer;
170384: typedef struct SessionInput SessionInput;
170385: 
170386: /*
170387: ** Minimum chunk size used by streaming versions of functions.
170388: */
170389: #ifndef SESSIONS_STRM_CHUNK_SIZE
170390: # ifdef SQLITE_TEST
170391: #   define SESSIONS_STRM_CHUNK_SIZE 64
170392: # else
170393: #   define SESSIONS_STRM_CHUNK_SIZE 1024
170394: # endif
170395: #endif
170396: 
170397: typedef struct SessionHook SessionHook;
170398: struct SessionHook {
170399:   void *pCtx;
170400:   int (*xOld)(void*,int,sqlite3_value**);
170401:   int (*xNew)(void*,int,sqlite3_value**);
170402:   int (*xCount)(void*);
170403:   int (*xDepth)(void*);
170404: };
170405: 
170406: /*
170407: ** Session handle structure.
170408: */
170409: struct sqlite3_session {
170410:   sqlite3 *db;                    /* Database handle session is attached to */
170411:   char *zDb;                      /* Name of database session is attached to */
170412:   int bEnable;                    /* True if currently recording */
170413:   int bIndirect;                  /* True if all changes are indirect */
170414:   int bAutoAttach;                /* True to auto-attach tables */
170415:   int rc;                         /* Non-zero if an error has occurred */
170416:   void *pFilterCtx;               /* First argument to pass to xTableFilter */
170417:   int (*xTableFilter)(void *pCtx, const char *zTab);
170418:   sqlite3_session *pNext;         /* Next session object on same db. */
170419:   SessionTable *pTable;           /* List of attached tables */
170420:   SessionHook hook;               /* APIs to grab new and old data with */
170421: };
170422: 
170423: /*
170424: ** Instances of this structure are used to build strings or binary records.
170425: */
170426: struct SessionBuffer {
170427:   u8 *aBuf;                       /* Pointer to changeset buffer */
170428:   int nBuf;                       /* Size of buffer aBuf */
170429:   int nAlloc;                     /* Size of allocation containing aBuf */
170430: };
170431: 
170432: /*
170433: ** An object of this type is used internally as an abstraction for 
170434: ** input data. Input data may be supplied either as a single large buffer
170435: ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
170436: **  sqlite3changeset_start_strm()).
170437: */
170438: struct SessionInput {
170439:   int bNoDiscard;                 /* If true, discard no data */
170440:   int iCurrent;                   /* Offset in aData[] of current change */
170441:   int iNext;                      /* Offset in aData[] of next change */
170442:   u8 *aData;                      /* Pointer to buffer containing changeset */
170443:   int nData;                      /* Number of bytes in aData */
170444: 
170445:   SessionBuffer buf;              /* Current read buffer */
170446:   int (*xInput)(void*, void*, int*);        /* Input stream call (or NULL) */
170447:   void *pIn;                                /* First argument to xInput */
170448:   int bEof;                       /* Set to true after xInput finished */
170449: };
170450: 
170451: /*
170452: ** Structure for changeset iterators.
170453: */
170454: struct sqlite3_changeset_iter {
170455:   SessionInput in;                /* Input buffer or stream */
170456:   SessionBuffer tblhdr;           /* Buffer to hold apValue/zTab/abPK/ */
170457:   int bPatchset;                  /* True if this is a patchset */
170458:   int rc;                         /* Iterator error code */
170459:   sqlite3_stmt *pConflict;        /* Points to conflicting row, if any */
170460:   char *zTab;                     /* Current table */
170461:   int nCol;                       /* Number of columns in zTab */
170462:   int op;                         /* Current operation */
170463:   int bIndirect;                  /* True if current change was indirect */
170464:   u8 *abPK;                       /* Primary key array */
170465:   sqlite3_value **apValue;        /* old.* and new.* values */
170466: };
170467: 
170468: /*
170469: ** Each session object maintains a set of the following structures, one
170470: ** for each table the session object is monitoring. The structures are
170471: ** stored in a linked list starting at sqlite3_session.pTable.
170472: **
170473: ** The keys of the SessionTable.aChange[] hash table are all rows that have
170474: ** been modified in any way since the session object was attached to the
170475: ** table.
170476: **
170477: ** The data associated with each hash-table entry is a structure containing
170478: ** a subset of the initial values that the modified row contained at the
170479: ** start of the session. Or no initial values if the row was inserted.
170480: */
170481: struct SessionTable {
170482:   SessionTable *pNext;
170483:   char *zName;                    /* Local name of table */
170484:   int nCol;                       /* Number of columns in table zName */
170485:   const char **azCol;             /* Column names */
170486:   u8 *abPK;                       /* Array of primary key flags */
170487:   int nEntry;                     /* Total number of entries in hash table */
170488:   int nChange;                    /* Size of apChange[] array */
170489:   SessionChange **apChange;       /* Hash table buckets */
170490: };
170491: 
170492: /* 
170493: ** RECORD FORMAT:
170494: **
170495: ** The following record format is similar to (but not compatible with) that 
170496: ** used in SQLite database files. This format is used as part of the 
170497: ** change-set binary format, and so must be architecture independent.
170498: **
170499: ** Unlike the SQLite database record format, each field is self-contained -
170500: ** there is no separation of header and data. Each field begins with a
170501: ** single byte describing its type, as follows:
170502: **
170503: **       0x00: Undefined value.
170504: **       0x01: Integer value.
170505: **       0x02: Real value.
170506: **       0x03: Text value.
170507: **       0x04: Blob value.
170508: **       0x05: SQL NULL value.
170509: **
170510: ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
170511: ** and so on in sqlite3.h. For undefined and NULL values, the field consists
170512: ** only of the single type byte. For other types of values, the type byte
170513: ** is followed by:
170514: **
170515: **   Text values:
170516: **     A varint containing the number of bytes in the value (encoded using
170517: **     UTF-8). Followed by a buffer containing the UTF-8 representation
170518: **     of the text value. There is no nul terminator.
170519: **
170520: **   Blob values:
170521: **     A varint containing the number of bytes in the value, followed by
170522: **     a buffer containing the value itself.
170523: **
170524: **   Integer values:
170525: **     An 8-byte big-endian integer value.
170526: **
170527: **   Real values:
170528: **     An 8-byte big-endian IEEE 754-2008 real value.
170529: **
170530: ** Varint values are encoded in the same way as varints in the SQLite 
170531: ** record format.
170532: **
170533: ** CHANGESET FORMAT:
170534: **
170535: ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
170536: ** one or more tables. Operations on a single table are grouped together,
170537: ** but may occur in any order (i.e. deletes, updates and inserts are all
170538: ** mixed together).
170539: **
170540: ** Each group of changes begins with a table header:
170541: **
170542: **   1 byte: Constant 0x54 (capital 'T')
170543: **   Varint: Number of columns in the table.
170544: **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
170545: **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
170546: **
170547: ** Followed by one or more changes to the table.
170548: **
170549: **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
170550: **   1 byte: The "indirect-change" flag.
170551: **   old.* record: (delete and update only)
170552: **   new.* record: (insert and update only)
170553: **
170554: ** The "old.*" and "new.*" records, if present, are N field records in the
170555: ** format described above under "RECORD FORMAT", where N is the number of
170556: ** columns in the table. The i'th field of each record is associated with
170557: ** the i'th column of the table, counting from left to right in the order
170558: ** in which columns were declared in the CREATE TABLE statement.
170559: **
170560: ** The new.* record that is part of each INSERT change contains the values
170561: ** that make up the new row. Similarly, the old.* record that is part of each
170562: ** DELETE change contains the values that made up the row that was deleted 
170563: ** from the database. In the changeset format, the records that are part
170564: ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
170565: ** fields.
170566: **
170567: ** Within the old.* record associated with an UPDATE change, all fields
170568: ** associated with table columns that are not PRIMARY KEY columns and are
170569: ** not modified by the UPDATE change are set to "undefined". Other fields
170570: ** are set to the values that made up the row before the UPDATE that the
170571: ** change records took place. Within the new.* record, fields associated 
170572: ** with table columns modified by the UPDATE change contain the new 
170573: ** values. Fields associated with table columns that are not modified
170574: ** are set to "undefined".
170575: **
170576: ** PATCHSET FORMAT:
170577: **
170578: ** A patchset is also a collection of changes. It is similar to a changeset,
170579: ** but leaves undefined those fields that are not useful if no conflict
170580: ** resolution is required when applying the changeset.
170581: **
170582: ** Each group of changes begins with a table header:
170583: **
170584: **   1 byte: Constant 0x50 (capital 'P')
170585: **   Varint: Number of columns in the table.
170586: **   nCol bytes: 0x01 for PK columns, 0x00 otherwise.
170587: **   N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
170588: **
170589: ** Followed by one or more changes to the table.
170590: **
170591: **   1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
170592: **   1 byte: The "indirect-change" flag.
170593: **   single record: (PK fields for DELETE, PK and modified fields for UPDATE,
170594: **                   full record for INSERT).
170595: **
170596: ** As in the changeset format, each field of the single record that is part
170597: ** of a patchset change is associated with the correspondingly positioned
170598: ** table column, counting from left to right within the CREATE TABLE 
170599: ** statement.
170600: **
170601: ** For a DELETE change, all fields within the record except those associated
170602: ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
170603: ** contain the values identifying the row to delete.
170604: **
170605: ** For an UPDATE change, all fields except those associated with PRIMARY KEY
170606: ** columns and columns that are modified by the UPDATE are set to "undefined".
170607: ** PRIMARY KEY fields contain the values identifying the table row to update,
170608: ** and fields associated with modified columns contain the new column values.
170609: **
170610: ** The records associated with INSERT changes are in the same format as for
170611: ** changesets. It is not possible for a record associated with an INSERT
170612: ** change to contain a field set to "undefined".
170613: */
170614: 
170615: /*
170616: ** For each row modified during a session, there exists a single instance of
170617: ** this structure stored in a SessionTable.aChange[] hash table.
170618: */
170619: struct SessionChange {
170620:   int op;                         /* One of UPDATE, DELETE, INSERT */
170621:   int bIndirect;                  /* True if this change is "indirect" */
170622:   int nRecord;                    /* Number of bytes in buffer aRecord[] */
170623:   u8 *aRecord;                    /* Buffer containing old.* record */
170624:   SessionChange *pNext;           /* For hash-table collisions */
170625: };
170626: 
170627: /*
170628: ** Write a varint with value iVal into the buffer at aBuf. Return the 
170629: ** number of bytes written.
170630: */
170631: static int sessionVarintPut(u8 *aBuf, int iVal){
170632:   return putVarint32(aBuf, iVal);
170633: }
170634: 
170635: /*
170636: ** Return the number of bytes required to store value iVal as a varint.
170637: */
170638: static int sessionVarintLen(int iVal){
170639:   return sqlite3VarintLen(iVal);
170640: }
170641: 
170642: /*
170643: ** Read a varint value from aBuf[] into *piVal. Return the number of 
170644: ** bytes read.
170645: */
170646: static int sessionVarintGet(u8 *aBuf, int *piVal){
170647:   return getVarint32(aBuf, *piVal);
170648: }
170649: 
170650: /* Load an unaligned and unsigned 32-bit integer */
170651: #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
170652: 
170653: /*
170654: ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
170655: ** the value read.
170656: */
170657: static sqlite3_int64 sessionGetI64(u8 *aRec){
170658:   u64 x = SESSION_UINT32(aRec);
170659:   u32 y = SESSION_UINT32(aRec+4);
170660:   x = (x<<32) + y;
170661:   return (sqlite3_int64)x;
170662: }
170663: 
170664: /*
170665: ** Write a 64-bit big-endian integer value to the buffer aBuf[].
170666: */
170667: static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
170668:   aBuf[0] = (i>>56) & 0xFF;
170669:   aBuf[1] = (i>>48) & 0xFF;
170670:   aBuf[2] = (i>>40) & 0xFF;
170671:   aBuf[3] = (i>>32) & 0xFF;
170672:   aBuf[4] = (i>>24) & 0xFF;
170673:   aBuf[5] = (i>>16) & 0xFF;
170674:   aBuf[6] = (i>> 8) & 0xFF;
170675:   aBuf[7] = (i>> 0) & 0xFF;
170676: }
170677: 
170678: /*
170679: ** This function is used to serialize the contents of value pValue (see
170680: ** comment titled "RECORD FORMAT" above).
170681: **
170682: ** If it is non-NULL, the serialized form of the value is written to 
170683: ** buffer aBuf. *pnWrite is set to the number of bytes written before
170684: ** returning. Or, if aBuf is NULL, the only thing this function does is
170685: ** set *pnWrite.
170686: **
170687: ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
170688: ** within a call to sqlite3_value_text() (may fail if the db is utf-16)) 
170689: ** SQLITE_NOMEM is returned.
170690: */
170691: static int sessionSerializeValue(
170692:   u8 *aBuf,                       /* If non-NULL, write serialized value here */
170693:   sqlite3_value *pValue,          /* Value to serialize */
170694:   int *pnWrite                    /* IN/OUT: Increment by bytes written */
170695: ){
170696:   int nByte;                      /* Size of serialized value in bytes */
170697: 
170698:   if( pValue ){
170699:     int eType;                    /* Value type (SQLITE_NULL, TEXT etc.) */
170700:   
170701:     eType = sqlite3_value_type(pValue);
170702:     if( aBuf ) aBuf[0] = eType;
170703:   
170704:     switch( eType ){
170705:       case SQLITE_NULL: 
170706:         nByte = 1;
170707:         break;
170708:   
170709:       case SQLITE_INTEGER: 
170710:       case SQLITE_FLOAT:
170711:         if( aBuf ){
170712:           /* TODO: SQLite does something special to deal with mixed-endian
170713:           ** floating point values (e.g. ARM7). This code probably should
170714:           ** too.  */
170715:           u64 i;
170716:           if( eType==SQLITE_INTEGER ){
170717:             i = (u64)sqlite3_value_int64(pValue);
170718:           }else{
170719:             double r;
170720:             assert( sizeof(double)==8 && sizeof(u64)==8 );
170721:             r = sqlite3_value_double(pValue);
170722:             memcpy(&i, &r, 8);
170723:           }
170724:           sessionPutI64(&aBuf[1], i);
170725:         }
170726:         nByte = 9; 
170727:         break;
170728:   
170729:       default: {
170730:         u8 *z;
170731:         int n;
170732:         int nVarint;
170733:   
170734:         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
170735:         if( eType==SQLITE_TEXT ){
170736:           z = (u8 *)sqlite3_value_text(pValue);
170737:         }else{
170738:           z = (u8 *)sqlite3_value_blob(pValue);
170739:         }
170740:         n = sqlite3_value_bytes(pValue);
170741:         if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
170742:         nVarint = sessionVarintLen(n);
170743:   
170744:         if( aBuf ){
170745:           sessionVarintPut(&aBuf[1], n);
170746:           memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ? 
170747:               sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
170748:           );
170749:         }
170750:   
170751:         nByte = 1 + nVarint + n;
170752:         break;
170753:       }
170754:     }
170755:   }else{
170756:     nByte = 1;
170757:     if( aBuf ) aBuf[0] = '\0';
170758:   }
170759: 
170760:   if( pnWrite ) *pnWrite += nByte;
170761:   return SQLITE_OK;
170762: }
170763: 
170764: 
170765: /*
170766: ** This macro is used to calculate hash key values for data structures. In
170767: ** order to use this macro, the entire data structure must be represented
170768: ** as a series of unsigned integers. In order to calculate a hash-key value
170769: ** for a data structure represented as three such integers, the macro may
170770: ** then be used as follows:
170771: **
170772: **    int hash_key_value;
170773: **    hash_key_value = HASH_APPEND(0, <value 1>);
170774: **    hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
170775: **    hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
170776: **
170777: ** In practice, the data structures this macro is used for are the primary
170778: ** key values of modified rows.
170779: */
170780: #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
170781: 
170782: /*
170783: ** Append the hash of the 64-bit integer passed as the second argument to the
170784: ** hash-key value passed as the first. Return the new hash-key value.
170785: */
170786: static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
170787:   h = HASH_APPEND(h, i & 0xFFFFFFFF);
170788:   return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
170789: }
170790: 
170791: /*
170792: ** Append the hash of the blob passed via the second and third arguments to 
170793: ** the hash-key value passed as the first. Return the new hash-key value.
170794: */
170795: static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
170796:   int i;
170797:   for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
170798:   return h;
170799: }
170800: 
170801: /*
170802: ** Append the hash of the data type passed as the second argument to the
170803: ** hash-key value passed as the first. Return the new hash-key value.
170804: */
170805: static unsigned int sessionHashAppendType(unsigned int h, int eType){
170806:   return HASH_APPEND(h, eType);
170807: }
170808: 
170809: /*
170810: ** This function may only be called from within a pre-update callback.
170811: ** It calculates a hash based on the primary key values of the old.* or 
170812: ** new.* row currently available and, assuming no error occurs, writes it to
170813: ** *piHash before returning. If the primary key contains one or more NULL
170814: ** values, *pbNullPK is set to true before returning.
170815: **
170816: ** If an error occurs, an SQLite error code is returned and the final values
170817: ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
170818: ** and the output variables are set as described above.
170819: */
170820: static int sessionPreupdateHash(
170821:   sqlite3_session *pSession,      /* Session object that owns pTab */
170822:   SessionTable *pTab,             /* Session table handle */
170823:   int bNew,                       /* True to hash the new.* PK */
170824:   int *piHash,                    /* OUT: Hash value */
170825:   int *pbNullPK                   /* OUT: True if there are NULL values in PK */
170826: ){
170827:   unsigned int h = 0;             /* Hash value to return */
170828:   int i;                          /* Used to iterate through columns */
170829: 
170830:   assert( *pbNullPK==0 );
170831:   assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
170832:   for(i=0; i<pTab->nCol; i++){
170833:     if( pTab->abPK[i] ){
170834:       int rc;
170835:       int eType;
170836:       sqlite3_value *pVal;
170837: 
170838:       if( bNew ){
170839:         rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
170840:       }else{
170841:         rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
170842:       }
170843:       if( rc!=SQLITE_OK ) return rc;
170844: 
170845:       eType = sqlite3_value_type(pVal);
170846:       h = sessionHashAppendType(h, eType);
170847:       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170848:         i64 iVal;
170849:         if( eType==SQLITE_INTEGER ){
170850:           iVal = sqlite3_value_int64(pVal);
170851:         }else{
170852:           double rVal = sqlite3_value_double(pVal);
170853:           assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
170854:           memcpy(&iVal, &rVal, 8);
170855:         }
170856:         h = sessionHashAppendI64(h, iVal);
170857:       }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
170858:         const u8 *z;
170859:         int n;
170860:         if( eType==SQLITE_TEXT ){
170861:           z = (const u8 *)sqlite3_value_text(pVal);
170862:         }else{
170863:           z = (const u8 *)sqlite3_value_blob(pVal);
170864:         }
170865:         n = sqlite3_value_bytes(pVal);
170866:         if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
170867:         h = sessionHashAppendBlob(h, n, z);
170868:       }else{
170869:         assert( eType==SQLITE_NULL );
170870:         *pbNullPK = 1;
170871:       }
170872:     }
170873:   }
170874: 
170875:   *piHash = (h % pTab->nChange);
170876:   return SQLITE_OK;
170877: }
170878: 
170879: /*
170880: ** The buffer that the argument points to contains a serialized SQL value.
170881: ** Return the number of bytes of space occupied by the value (including
170882: ** the type byte).
170883: */
170884: static int sessionSerialLen(u8 *a){
170885:   int e = *a;
170886:   int n;
170887:   if( e==0 ) return 1;
170888:   if( e==SQLITE_NULL ) return 1;
170889:   if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
170890:   return sessionVarintGet(&a[1], &n) + 1 + n;
170891: }
170892: 
170893: /*
170894: ** Based on the primary key values stored in change aRecord, calculate a
170895: ** hash key. Assume the has table has nBucket buckets. The hash keys
170896: ** calculated by this function are compatible with those calculated by
170897: ** sessionPreupdateHash().
170898: **
170899: ** The bPkOnly argument is non-zero if the record at aRecord[] is from
170900: ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
170901: */
170902: static unsigned int sessionChangeHash(
170903:   SessionTable *pTab,             /* Table handle */
170904:   int bPkOnly,                    /* Record consists of PK fields only */
170905:   u8 *aRecord,                    /* Change record */
170906:   int nBucket                     /* Assume this many buckets in hash table */
170907: ){
170908:   unsigned int h = 0;             /* Value to return */
170909:   int i;                          /* Used to iterate through columns */
170910:   u8 *a = aRecord;                /* Used to iterate through change record */
170911: 
170912:   for(i=0; i<pTab->nCol; i++){
170913:     int eType = *a;
170914:     int isPK = pTab->abPK[i];
170915:     if( bPkOnly && isPK==0 ) continue;
170916: 
170917:     /* It is not possible for eType to be SQLITE_NULL here. The session 
170918:     ** module does not record changes for rows with NULL values stored in
170919:     ** primary key columns. */
170920:     assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT 
170921:          || eType==SQLITE_TEXT || eType==SQLITE_BLOB 
170922:          || eType==SQLITE_NULL || eType==0 
170923:     );
170924:     assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
170925: 
170926:     if( isPK ){
170927:       a++;
170928:       h = sessionHashAppendType(h, eType);
170929:       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170930:         h = sessionHashAppendI64(h, sessionGetI64(a));
170931:         a += 8;
170932:       }else{
170933:         int n; 
170934:         a += sessionVarintGet(a, &n);
170935:         h = sessionHashAppendBlob(h, n, a);
170936:         a += n;
170937:       }
170938:     }else{
170939:       a += sessionSerialLen(a);
170940:     }
170941:   }
170942:   return (h % nBucket);
170943: }
170944: 
170945: /*
170946: ** Arguments aLeft and aRight are pointers to change records for table pTab.
170947: ** This function returns true if the two records apply to the same row (i.e.
170948: ** have the same values stored in the primary key columns), or false 
170949: ** otherwise.
170950: */
170951: static int sessionChangeEqual(
170952:   SessionTable *pTab,             /* Table used for PK definition */
170953:   int bLeftPkOnly,                /* True if aLeft[] contains PK fields only */
170954:   u8 *aLeft,                      /* Change record */
170955:   int bRightPkOnly,               /* True if aRight[] contains PK fields only */
170956:   u8 *aRight                      /* Change record */
170957: ){
170958:   u8 *a1 = aLeft;                 /* Cursor to iterate through aLeft */
170959:   u8 *a2 = aRight;                /* Cursor to iterate through aRight */
170960:   int iCol;                       /* Used to iterate through table columns */
170961: 
170962:   for(iCol=0; iCol<pTab->nCol; iCol++){
170963:     if( pTab->abPK[iCol] ){
170964:       int n1 = sessionSerialLen(a1);
170965:       int n2 = sessionSerialLen(a2);
170966: 
170967:       if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
170968:         return 0;
170969:       }
170970:       a1 += n1;
170971:       a2 += n2;
170972:     }else{
170973:       if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
170974:       if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
170975:     }
170976:   }
170977: 
170978:   return 1;
170979: }
170980: 
170981: /*
170982: ** Arguments aLeft and aRight both point to buffers containing change
170983: ** records with nCol columns. This function "merges" the two records into
170984: ** a single records which is written to the buffer at *paOut. *paOut is
170985: ** then set to point to one byte after the last byte written before 
170986: ** returning.
170987: **
170988: ** The merging of records is done as follows: For each column, if the 
170989: ** aRight record contains a value for the column, copy the value from
170990: ** their. Otherwise, if aLeft contains a value, copy it. If neither
170991: ** record contains a value for a given column, then neither does the
170992: ** output record.
170993: */
170994: static void sessionMergeRecord(
170995:   u8 **paOut, 
170996:   int nCol,
170997:   u8 *aLeft,
170998:   u8 *aRight
170999: ){
171000:   u8 *a1 = aLeft;                 /* Cursor used to iterate through aLeft */
171001:   u8 *a2 = aRight;                /* Cursor used to iterate through aRight */
171002:   u8 *aOut = *paOut;              /* Output cursor */
171003:   int iCol;                       /* Used to iterate from 0 to nCol */
171004: 
171005:   for(iCol=0; iCol<nCol; iCol++){
171006:     int n1 = sessionSerialLen(a1);
171007:     int n2 = sessionSerialLen(a2);
171008:     if( *a2 ){
171009:       memcpy(aOut, a2, n2);
171010:       aOut += n2;
171011:     }else{
171012:       memcpy(aOut, a1, n1);
171013:       aOut += n1;
171014:     }
171015:     a1 += n1;
171016:     a2 += n2;
171017:   }
171018: 
171019:   *paOut = aOut;
171020: }
171021: 
171022: /*
171023: ** This is a helper function used by sessionMergeUpdate().
171024: **
171025: ** When this function is called, both *paOne and *paTwo point to a value 
171026: ** within a change record. Before it returns, both have been advanced so 
171027: ** as to point to the next value in the record.
171028: **
171029: ** If, when this function is called, *paTwo points to a valid value (i.e.
171030: ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
171031: ** pointer is returned and *pnVal is set to the number of bytes in the 
171032: ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
171033: ** set to the number of bytes in the value at *paOne. If *paOne points
171034: ** to the "no value" placeholder, *pnVal is set to 1. In other words:
171035: **
171036: **   if( *paTwo is valid ) return *paTwo;
171037: **   return *paOne;
171038: **
171039: */
171040: static u8 *sessionMergeValue(
171041:   u8 **paOne,                     /* IN/OUT: Left-hand buffer pointer */
171042:   u8 **paTwo,                     /* IN/OUT: Right-hand buffer pointer */
171043:   int *pnVal                      /* OUT: Bytes in returned value */
171044: ){
171045:   u8 *a1 = *paOne;
171046:   u8 *a2 = *paTwo;
171047:   u8 *pRet = 0;
171048:   int n1;
171049: 
171050:   assert( a1 );
171051:   if( a2 ){
171052:     int n2 = sessionSerialLen(a2);
171053:     if( *a2 ){
171054:       *pnVal = n2;
171055:       pRet = a2;
171056:     }
171057:     *paTwo = &a2[n2];
171058:   }
171059: 
171060:   n1 = sessionSerialLen(a1);
171061:   if( pRet==0 ){
171062:     *pnVal = n1;
171063:     pRet = a1;
171064:   }
171065:   *paOne = &a1[n1];
171066: 
171067:   return pRet;
171068: }
171069: 
171070: /*
171071: ** This function is used by changeset_concat() to merge two UPDATE changes
171072: ** on the same row.
171073: */
171074: static int sessionMergeUpdate(
171075:   u8 **paOut,                     /* IN/OUT: Pointer to output buffer */
171076:   SessionTable *pTab,             /* Table change pertains to */
171077:   int bPatchset,                  /* True if records are patchset records */
171078:   u8 *aOldRecord1,                /* old.* record for first change */
171079:   u8 *aOldRecord2,                /* old.* record for second change */
171080:   u8 *aNewRecord1,                /* new.* record for first change */
171081:   u8 *aNewRecord2                 /* new.* record for second change */
171082: ){
171083:   u8 *aOld1 = aOldRecord1;
171084:   u8 *aOld2 = aOldRecord2;
171085:   u8 *aNew1 = aNewRecord1;
171086:   u8 *aNew2 = aNewRecord2;
171087: 
171088:   u8 *aOut = *paOut;
171089:   int i;
171090: 
171091:   if( bPatchset==0 ){
171092:     int bRequired = 0;
171093: 
171094:     assert( aOldRecord1 && aNewRecord1 );
171095: 
171096:     /* Write the old.* vector first. */
171097:     for(i=0; i<pTab->nCol; i++){
171098:       int nOld;
171099:       u8 *aOld;
171100:       int nNew;
171101:       u8 *aNew;
171102: 
171103:       aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
171104:       aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
171105:       if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
171106:         if( pTab->abPK[i]==0 ) bRequired = 1;
171107:         memcpy(aOut, aOld, nOld);
171108:         aOut += nOld;
171109:       }else{
171110:         *(aOut++) = '\0';
171111:       }
171112:     }
171113: 
171114:     if( !bRequired ) return 0;
171115:   }
171116: 
171117:   /* Write the new.* vector */
171118:   aOld1 = aOldRecord1;
171119:   aOld2 = aOldRecord2;
171120:   aNew1 = aNewRecord1;
171121:   aNew2 = aNewRecord2;
171122:   for(i=0; i<pTab->nCol; i++){
171123:     int nOld;
171124:     u8 *aOld;
171125:     int nNew;
171126:     u8 *aNew;
171127: 
171128:     aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
171129:     aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
171130:     if( bPatchset==0 
171131:      && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew))) 
171132:     ){
171133:       *(aOut++) = '\0';
171134:     }else{
171135:       memcpy(aOut, aNew, nNew);
171136:       aOut += nNew;
171137:     }
171138:   }
171139: 
171140:   *paOut = aOut;
171141:   return 1;
171142: }
171143: 
171144: /*
171145: ** This function is only called from within a pre-update-hook callback.
171146: ** It determines if the current pre-update-hook change affects the same row
171147: ** as the change stored in argument pChange. If so, it returns true. Otherwise
171148: ** if the pre-update-hook does not affect the same row as pChange, it returns
171149: ** false.
171150: */
171151: static int sessionPreupdateEqual(
171152:   sqlite3_session *pSession,      /* Session object that owns SessionTable */
171153:   SessionTable *pTab,             /* Table associated with change */
171154:   SessionChange *pChange,         /* Change to compare to */
171155:   int op                          /* Current pre-update operation */
171156: ){
171157:   int iCol;                       /* Used to iterate through columns */
171158:   u8 *a = pChange->aRecord;       /* Cursor used to scan change record */
171159: 
171160:   assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
171161:   for(iCol=0; iCol<pTab->nCol; iCol++){
171162:     if( !pTab->abPK[iCol] ){
171163:       a += sessionSerialLen(a);
171164:     }else{
171165:       sqlite3_value *pVal;        /* Value returned by preupdate_new/old */
171166:       int rc;                     /* Error code from preupdate_new/old */
171167:       int eType = *a++;           /* Type of value from change record */
171168: 
171169:       /* The following calls to preupdate_new() and preupdate_old() can not
171170:       ** fail. This is because they cache their return values, and by the
171171:       ** time control flows to here they have already been called once from
171172:       ** within sessionPreupdateHash(). The first two asserts below verify
171173:       ** this (that the method has already been called). */
171174:       if( op==SQLITE_INSERT ){
171175:         /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
171176:         rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
171177:       }else{
171178:         /* assert( db->pPreUpdate->pUnpacked ); */
171179:         rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
171180:       }
171181:       assert( rc==SQLITE_OK );
171182:       if( sqlite3_value_type(pVal)!=eType ) return 0;
171183: 
171184:       /* A SessionChange object never has a NULL value in a PK column */
171185:       assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
171186:            || eType==SQLITE_BLOB    || eType==SQLITE_TEXT
171187:       );
171188: 
171189:       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171190:         i64 iVal = sessionGetI64(a);
171191:         a += 8;
171192:         if( eType==SQLITE_INTEGER ){
171193:           if( sqlite3_value_int64(pVal)!=iVal ) return 0;
171194:         }else{
171195:           double rVal;
171196:           assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
171197:           memcpy(&rVal, &iVal, 8);
171198:           if( sqlite3_value_double(pVal)!=rVal ) return 0;
171199:         }
171200:       }else{
171201:         int n;
171202:         const u8 *z;
171203:         a += sessionVarintGet(a, &n);
171204:         if( sqlite3_value_bytes(pVal)!=n ) return 0;
171205:         if( eType==SQLITE_TEXT ){
171206:           z = sqlite3_value_text(pVal);
171207:         }else{
171208:           z = sqlite3_value_blob(pVal);
171209:         }
171210:         if( memcmp(a, z, n) ) return 0;
171211:         a += n;
171212:         break;
171213:       }
171214:     }
171215:   }
171216: 
171217:   return 1;
171218: }
171219: 
171220: /*
171221: ** If required, grow the hash table used to store changes on table pTab 
171222: ** (part of the session pSession). If a fatal OOM error occurs, set the
171223: ** session object to failed and return SQLITE_ERROR. Otherwise, return
171224: ** SQLITE_OK.
171225: **
171226: ** It is possible that a non-fatal OOM error occurs in this function. In
171227: ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
171228: ** Growing the hash table in this case is a performance optimization only,
171229: ** it is not required for correct operation.
171230: */
171231: static int sessionGrowHash(int bPatchset, SessionTable *pTab){
171232:   if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
171233:     int i;
171234:     SessionChange **apNew;
171235:     int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
171236: 
171237:     apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
171238:     if( apNew==0 ){
171239:       if( pTab->nChange==0 ){
171240:         return SQLITE_ERROR;
171241:       }
171242:       return SQLITE_OK;
171243:     }
171244:     memset(apNew, 0, sizeof(SessionChange *) * nNew);
171245: 
171246:     for(i=0; i<pTab->nChange; i++){
171247:       SessionChange *p;
171248:       SessionChange *pNext;
171249:       for(p=pTab->apChange[i]; p; p=pNext){
171250:         int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
171251:         int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
171252:         pNext = p->pNext;
171253:         p->pNext = apNew[iHash];
171254:         apNew[iHash] = p;
171255:       }
171256:     }
171257: 
171258:     sqlite3_free(pTab->apChange);
171259:     pTab->nChange = nNew;
171260:     pTab->apChange = apNew;
171261:   }
171262: 
171263:   return SQLITE_OK;
171264: }
171265: 
171266: /*
171267: ** This function queries the database for the names of the columns of table
171268: ** zThis, in schema zDb. It is expected that the table has nCol columns. If
171269: ** not, SQLITE_SCHEMA is returned and none of the output variables are
171270: ** populated.
171271: **
171272: ** Otherwise, if they are not NULL, variable *pnCol is set to the number
171273: ** of columns in the database table and variable *pzTab is set to point to a
171274: ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
171275: ** point to an array of pointers to column names. And *pabPK (again, if not
171276: ** NULL) is set to point to an array of booleans - true if the corresponding
171277: ** column is part of the primary key.
171278: **
171279: ** For example, if the table is declared as:
171280: **
171281: **     CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
171282: **
171283: ** Then the four output variables are populated as follows:
171284: **
171285: **     *pnCol  = 4
171286: **     *pzTab  = "tbl1"
171287: **     *pazCol = {"w", "x", "y", "z"}
171288: **     *pabPK  = {1, 0, 0, 1}
171289: **
171290: ** All returned buffers are part of the same single allocation, which must
171291: ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
171292: ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
171293: ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
171294: */
171295: static int sessionTableInfo(
171296:   sqlite3 *db,                    /* Database connection */
171297:   const char *zDb,                /* Name of attached database (e.g. "main") */
171298:   const char *zThis,              /* Table name */
171299:   int *pnCol,                     /* OUT: number of columns */
171300:   const char **pzTab,             /* OUT: Copy of zThis */
171301:   const char ***pazCol,           /* OUT: Array of column names for table */
171302:   u8 **pabPK                      /* OUT: Array of booleans - true for PK col */
171303: ){
171304:   char *zPragma;
171305:   sqlite3_stmt *pStmt;
171306:   int rc;
171307:   int nByte;
171308:   int nDbCol = 0;
171309:   int nThis;
171310:   int i;
171311:   u8 *pAlloc = 0;
171312:   char **azCol = 0;
171313:   u8 *abPK = 0;
171314: 
171315:   assert( pazCol && pabPK );
171316: 
171317:   nThis = sqlite3Strlen30(zThis);
171318:   zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
171319:   if( !zPragma ) return SQLITE_NOMEM;
171320: 
171321:   rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
171322:   sqlite3_free(zPragma);
171323:   if( rc!=SQLITE_OK ) return rc;
171324: 
171325:   nByte = nThis + 1;
171326:   while( SQLITE_ROW==sqlite3_step(pStmt) ){
171327:     nByte += sqlite3_column_bytes(pStmt, 1);
171328:     nDbCol++;
171329:   }
171330:   rc = sqlite3_reset(pStmt);
171331: 
171332:   if( rc==SQLITE_OK ){
171333:     nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
171334:     pAlloc = sqlite3_malloc(nByte);
171335:     if( pAlloc==0 ){
171336:       rc = SQLITE_NOMEM;
171337:     }
171338:   }
171339:   if( rc==SQLITE_OK ){
171340:     azCol = (char **)pAlloc;
171341:     pAlloc = (u8 *)&azCol[nDbCol];
171342:     abPK = (u8 *)pAlloc;
171343:     pAlloc = &abPK[nDbCol];
171344:     if( pzTab ){
171345:       memcpy(pAlloc, zThis, nThis+1);
171346:       *pzTab = (char *)pAlloc;
171347:       pAlloc += nThis+1;
171348:     }
171349:   
171350:     i = 0;
171351:     while( SQLITE_ROW==sqlite3_step(pStmt) ){
171352:       int nName = sqlite3_column_bytes(pStmt, 1);
171353:       const unsigned char *zName = sqlite3_column_text(pStmt, 1);
171354:       if( zName==0 ) break;
171355:       memcpy(pAlloc, zName, nName+1);
171356:       azCol[i] = (char *)pAlloc;
171357:       pAlloc += nName+1;
171358:       abPK[i] = sqlite3_column_int(pStmt, 5);
171359:       i++;
171360:     }
171361:     rc = sqlite3_reset(pStmt);
171362:   
171363:   }
171364: 
171365:   /* If successful, populate the output variables. Otherwise, zero them and
171366:   ** free any allocation made. An error code will be returned in this case.
171367:   */
171368:   if( rc==SQLITE_OK ){
171369:     *pazCol = (const char **)azCol;
171370:     *pabPK = abPK;
171371:     *pnCol = nDbCol;
171372:   }else{
171373:     *pazCol = 0;
171374:     *pabPK = 0;
171375:     *pnCol = 0;
171376:     if( pzTab ) *pzTab = 0;
171377:     sqlite3_free(azCol);
171378:   }
171379:   sqlite3_finalize(pStmt);
171380:   return rc;
171381: }
171382: 
171383: /*
171384: ** This function is only called from within a pre-update handler for a
171385: ** write to table pTab, part of session pSession. If this is the first
171386: ** write to this table, initalize the SessionTable.nCol, azCol[] and
171387: ** abPK[] arrays accordingly.
171388: **
171389: ** If an error occurs, an error code is stored in sqlite3_session.rc and
171390: ** non-zero returned. Or, if no error occurs but the table has no primary
171391: ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
171392: ** indicate that updates on this table should be ignored. SessionTable.abPK 
171393: ** is set to NULL in this case.
171394: */
171395: static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
171396:   if( pTab->nCol==0 ){
171397:     u8 *abPK;
171398:     assert( pTab->azCol==0 || pTab->abPK==0 );
171399:     pSession->rc = sessionTableInfo(pSession->db, pSession->zDb, 
171400:         pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
171401:     );
171402:     if( pSession->rc==SQLITE_OK ){
171403:       int i;
171404:       for(i=0; i<pTab->nCol; i++){
171405:         if( abPK[i] ){
171406:           pTab->abPK = abPK;
171407:           break;
171408:         }
171409:       }
171410:     }
171411:   }
171412:   return (pSession->rc || pTab->abPK==0);
171413: }
171414: 
171415: /*
171416: ** This function is only called from with a pre-update-hook reporting a 
171417: ** change on table pTab (attached to session pSession). The type of change
171418: ** (UPDATE, INSERT, DELETE) is specified by the first argument.
171419: **
171420: ** Unless one is already present or an error occurs, an entry is added
171421: ** to the changed-rows hash table associated with table pTab.
171422: */
171423: static void sessionPreupdateOneChange(
171424:   int op,                         /* One of SQLITE_UPDATE, INSERT, DELETE */
171425:   sqlite3_session *pSession,      /* Session object pTab is attached to */
171426:   SessionTable *pTab              /* Table that change applies to */
171427: ){
171428:   int iHash; 
171429:   int bNull = 0; 
171430:   int rc = SQLITE_OK;
171431: 
171432:   if( pSession->rc ) return;
171433: 
171434:   /* Load table details if required */
171435:   if( sessionInitTable(pSession, pTab) ) return;
171436: 
171437:   /* Check the number of columns in this xPreUpdate call matches the 
171438:   ** number of columns in the table.  */
171439:   if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
171440:     pSession->rc = SQLITE_SCHEMA;
171441:     return;
171442:   }
171443: 
171444:   /* Grow the hash table if required */
171445:   if( sessionGrowHash(0, pTab) ){
171446:     pSession->rc = SQLITE_NOMEM;
171447:     return;
171448:   }
171449: 
171450:   /* Calculate the hash-key for this change. If the primary key of the row
171451:   ** includes a NULL value, exit early. Such changes are ignored by the
171452:   ** session module. */
171453:   rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
171454:   if( rc!=SQLITE_OK ) goto error_out;
171455: 
171456:   if( bNull==0 ){
171457:     /* Search the hash table for an existing record for this row. */
171458:     SessionChange *pC;
171459:     for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
171460:       if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
171461:     }
171462: 
171463:     if( pC==0 ){
171464:       /* Create a new change object containing all the old values (if
171465:       ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
171466:       ** values (if this is an INSERT). */
171467:       SessionChange *pChange; /* New change object */
171468:       int nByte;              /* Number of bytes to allocate */
171469:       int i;                  /* Used to iterate through columns */
171470:   
171471:       assert( rc==SQLITE_OK );
171472:       pTab->nEntry++;
171473:   
171474:       /* Figure out how large an allocation is required */
171475:       nByte = sizeof(SessionChange);
171476:       for(i=0; i<pTab->nCol; i++){
171477:         sqlite3_value *p = 0;
171478:         if( op!=SQLITE_INSERT ){
171479:           TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
171480:           assert( trc==SQLITE_OK );
171481:         }else if( pTab->abPK[i] ){
171482:           TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
171483:           assert( trc==SQLITE_OK );
171484:         }
171485: 
171486:         /* This may fail if SQLite value p contains a utf-16 string that must
171487:         ** be converted to utf-8 and an OOM error occurs while doing so. */
171488:         rc = sessionSerializeValue(0, p, &nByte);
171489:         if( rc!=SQLITE_OK ) goto error_out;
171490:       }
171491:   
171492:       /* Allocate the change object */
171493:       pChange = (SessionChange *)sqlite3_malloc(nByte);
171494:       if( !pChange ){
171495:         rc = SQLITE_NOMEM;
171496:         goto error_out;
171497:       }else{
171498:         memset(pChange, 0, sizeof(SessionChange));
171499:         pChange->aRecord = (u8 *)&pChange[1];
171500:       }
171501:   
171502:       /* Populate the change object. None of the preupdate_old(),
171503:       ** preupdate_new() or SerializeValue() calls below may fail as all
171504:       ** required values and encodings have already been cached in memory.
171505:       ** It is not possible for an OOM to occur in this block. */
171506:       nByte = 0;
171507:       for(i=0; i<pTab->nCol; i++){
171508:         sqlite3_value *p = 0;
171509:         if( op!=SQLITE_INSERT ){
171510:           pSession->hook.xOld(pSession->hook.pCtx, i, &p);
171511:         }else if( pTab->abPK[i] ){
171512:           pSession->hook.xNew(pSession->hook.pCtx, i, &p);
171513:         }
171514:         sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
171515:       }
171516: 
171517:       /* Add the change to the hash-table */
171518:       if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
171519:         pChange->bIndirect = 1;
171520:       }
171521:       pChange->nRecord = nByte;
171522:       pChange->op = op;
171523:       pChange->pNext = pTab->apChange[iHash];
171524:       pTab->apChange[iHash] = pChange;
171525: 
171526:     }else if( pC->bIndirect ){
171527:       /* If the existing change is considered "indirect", but this current
171528:       ** change is "direct", mark the change object as direct. */
171529:       if( pSession->hook.xDepth(pSession->hook.pCtx)==0 
171530:        && pSession->bIndirect==0 
171531:       ){
171532:         pC->bIndirect = 0;
171533:       }
171534:     }
171535:   }
171536: 
171537:   /* If an error has occurred, mark the session object as failed. */
171538:  error_out:
171539:   if( rc!=SQLITE_OK ){
171540:     pSession->rc = rc;
171541:   }
171542: }
171543: 
171544: static int sessionFindTable(
171545:   sqlite3_session *pSession, 
171546:   const char *zName,
171547:   SessionTable **ppTab
171548: ){
171549:   int rc = SQLITE_OK;
171550:   int nName = sqlite3Strlen30(zName);
171551:   SessionTable *pRet;
171552: 
171553:   /* Search for an existing table */
171554:   for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
171555:     if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
171556:   }
171557: 
171558:   if( pRet==0 && pSession->bAutoAttach ){
171559:     /* If there is a table-filter configured, invoke it. If it returns 0,
171560:     ** do not automatically add the new table. */
171561:     if( pSession->xTableFilter==0
171562:      || pSession->xTableFilter(pSession->pFilterCtx, zName) 
171563:     ){
171564:       rc = sqlite3session_attach(pSession, zName);
171565:       if( rc==SQLITE_OK ){
171566:         for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
171567:         assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
171568:       }
171569:     }
171570:   }
171571: 
171572:   assert( rc==SQLITE_OK || pRet==0 );
171573:   *ppTab = pRet;
171574:   return rc;
171575: }
171576: 
171577: /*
171578: ** The 'pre-update' hook registered by this module with SQLite databases.
171579: */
171580: static void xPreUpdate(
171581:   void *pCtx,                     /* Copy of third arg to preupdate_hook() */
171582:   sqlite3 *db,                    /* Database handle */
171583:   int op,                         /* SQLITE_UPDATE, DELETE or INSERT */
171584:   char const *zDb,                /* Database name */
171585:   char const *zName,              /* Table name */
171586:   sqlite3_int64 iKey1,            /* Rowid of row about to be deleted/updated */
171587:   sqlite3_int64 iKey2             /* New rowid value (for a rowid UPDATE) */
171588: ){
171589:   sqlite3_session *pSession;
171590:   int nDb = sqlite3Strlen30(zDb);
171591: 
171592:   assert( sqlite3_mutex_held(db->mutex) );
171593: 
171594:   for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
171595:     SessionTable *pTab;
171596: 
171597:     /* If this session is attached to a different database ("main", "temp" 
171598:     ** etc.), or if it is not currently enabled, there is nothing to do. Skip 
171599:     ** to the next session object attached to this database. */
171600:     if( pSession->bEnable==0 ) continue;
171601:     if( pSession->rc ) continue;
171602:     if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
171603: 
171604:     pSession->rc = sessionFindTable(pSession, zName, &pTab);
171605:     if( pTab ){
171606:       assert( pSession->rc==SQLITE_OK );
171607:       sessionPreupdateOneChange(op, pSession, pTab);
171608:       if( op==SQLITE_UPDATE ){
171609:         sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
171610:       }
171611:     }
171612:   }
171613: }
171614: 
171615: /*
171616: ** The pre-update hook implementations.
171617: */
171618: static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
171619:   return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
171620: }
171621: static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
171622:   return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
171623: }
171624: static int sessionPreupdateCount(void *pCtx){
171625:   return sqlite3_preupdate_count((sqlite3*)pCtx);
171626: }
171627: static int sessionPreupdateDepth(void *pCtx){
171628:   return sqlite3_preupdate_depth((sqlite3*)pCtx);
171629: }
171630: 
171631: /*
171632: ** Install the pre-update hooks on the session object passed as the only
171633: ** argument.
171634: */
171635: static void sessionPreupdateHooks(
171636:   sqlite3_session *pSession
171637: ){
171638:   pSession->hook.pCtx = (void*)pSession->db;
171639:   pSession->hook.xOld = sessionPreupdateOld;
171640:   pSession->hook.xNew = sessionPreupdateNew;
171641:   pSession->hook.xCount = sessionPreupdateCount;
171642:   pSession->hook.xDepth = sessionPreupdateDepth;
171643: }
171644: 
171645: typedef struct SessionDiffCtx SessionDiffCtx;
171646: struct SessionDiffCtx {
171647:   sqlite3_stmt *pStmt;
171648:   int nOldOff;
171649: };
171650: 
171651: /*
171652: ** The diff hook implementations.
171653: */
171654: static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
171655:   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171656:   *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
171657:   return SQLITE_OK;
171658: }
171659: static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
171660:   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171661:   *ppVal = sqlite3_column_value(p->pStmt, iVal);
171662:    return SQLITE_OK;
171663: }
171664: static int sessionDiffCount(void *pCtx){
171665:   SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
171666:   return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
171667: }
171668: static int sessionDiffDepth(void *pCtx){
171669:   return 0;
171670: }
171671: 
171672: /*
171673: ** Install the diff hooks on the session object passed as the only
171674: ** argument.
171675: */
171676: static void sessionDiffHooks(
171677:   sqlite3_session *pSession,
171678:   SessionDiffCtx *pDiffCtx
171679: ){
171680:   pSession->hook.pCtx = (void*)pDiffCtx;
171681:   pSession->hook.xOld = sessionDiffOld;
171682:   pSession->hook.xNew = sessionDiffNew;
171683:   pSession->hook.xCount = sessionDiffCount;
171684:   pSession->hook.xDepth = sessionDiffDepth;
171685: }
171686: 
171687: static char *sessionExprComparePK(
171688:   int nCol,
171689:   const char *zDb1, const char *zDb2, 
171690:   const char *zTab,
171691:   const char **azCol, u8 *abPK
171692: ){
171693:   int i;
171694:   const char *zSep = "";
171695:   char *zRet = 0;
171696: 
171697:   for(i=0; i<nCol; i++){
171698:     if( abPK[i] ){
171699:       zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
171700:           zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
171701:       );
171702:       zSep = " AND ";
171703:       if( zRet==0 ) break;
171704:     }
171705:   }
171706: 
171707:   return zRet;
171708: }
171709: 
171710: static char *sessionExprCompareOther(
171711:   int nCol,
171712:   const char *zDb1, const char *zDb2, 
171713:   const char *zTab,
171714:   const char **azCol, u8 *abPK
171715: ){
171716:   int i;
171717:   const char *zSep = "";
171718:   char *zRet = 0;
171719:   int bHave = 0;
171720: 
171721:   for(i=0; i<nCol; i++){
171722:     if( abPK[i]==0 ){
171723:       bHave = 1;
171724:       zRet = sqlite3_mprintf(
171725:           "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
171726:           zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
171727:       );
171728:       zSep = " OR ";
171729:       if( zRet==0 ) break;
171730:     }
171731:   }
171732: 
171733:   if( bHave==0 ){
171734:     assert( zRet==0 );
171735:     zRet = sqlite3_mprintf("0");
171736:   }
171737: 
171738:   return zRet;
171739: }
171740: 
171741: static char *sessionSelectFindNew(
171742:   int nCol,
171743:   const char *zDb1,      /* Pick rows in this db only */
171744:   const char *zDb2,      /* But not in this one */
171745:   const char *zTbl,      /* Table name */
171746:   const char *zExpr
171747: ){
171748:   char *zRet = sqlite3_mprintf(
171749:       "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
171750:       "  SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
171751:       ")",
171752:       zDb1, zTbl, zDb2, zTbl, zExpr
171753:   );
171754:   return zRet;
171755: }
171756: 
171757: static int sessionDiffFindNew(
171758:   int op,
171759:   sqlite3_session *pSession,
171760:   SessionTable *pTab,
171761:   const char *zDb1,
171762:   const char *zDb2,
171763:   char *zExpr
171764: ){
171765:   int rc = SQLITE_OK;
171766:   char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
171767: 
171768:   if( zStmt==0 ){
171769:     rc = SQLITE_NOMEM;
171770:   }else{
171771:     sqlite3_stmt *pStmt;
171772:     rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
171773:     if( rc==SQLITE_OK ){
171774:       SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
171775:       pDiffCtx->pStmt = pStmt;
171776:       pDiffCtx->nOldOff = 0;
171777:       while( SQLITE_ROW==sqlite3_step(pStmt) ){
171778:         sessionPreupdateOneChange(op, pSession, pTab);
171779:       }
171780:       rc = sqlite3_finalize(pStmt);
171781:     }
171782:     sqlite3_free(zStmt);
171783:   }
171784: 
171785:   return rc;
171786: }
171787: 
171788: static int sessionDiffFindModified(
171789:   sqlite3_session *pSession, 
171790:   SessionTable *pTab, 
171791:   const char *zFrom, 
171792:   const char *zExpr
171793: ){
171794:   int rc = SQLITE_OK;
171795: 
171796:   char *zExpr2 = sessionExprCompareOther(pTab->nCol,
171797:       pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
171798:   );
171799:   if( zExpr2==0 ){
171800:     rc = SQLITE_NOMEM;
171801:   }else{
171802:     char *zStmt = sqlite3_mprintf(
171803:         "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
171804:         pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
171805:     );
171806:     if( zStmt==0 ){
171807:       rc = SQLITE_NOMEM;
171808:     }else{
171809:       sqlite3_stmt *pStmt;
171810:       rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
171811: 
171812:       if( rc==SQLITE_OK ){
171813:         SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
171814:         pDiffCtx->pStmt = pStmt;
171815:         pDiffCtx->nOldOff = pTab->nCol;
171816:         while( SQLITE_ROW==sqlite3_step(pStmt) ){
171817:           sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
171818:         }
171819:         rc = sqlite3_finalize(pStmt);
171820:       }
171821:       sqlite3_free(zStmt);
171822:     }
171823:   }
171824: 
171825:   return rc;
171826: }
171827: 
171828: SQLITE_API int sqlite3session_diff(
171829:   sqlite3_session *pSession,
171830:   const char *zFrom,
171831:   const char *zTbl,
171832:   char **pzErrMsg
171833: ){
171834:   const char *zDb = pSession->zDb;
171835:   int rc = pSession->rc;
171836:   SessionDiffCtx d;
171837: 
171838:   memset(&d, 0, sizeof(d));
171839:   sessionDiffHooks(pSession, &d);
171840: 
171841:   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171842:   if( pzErrMsg ) *pzErrMsg = 0;
171843:   if( rc==SQLITE_OK ){
171844:     char *zExpr = 0;
171845:     sqlite3 *db = pSession->db;
171846:     SessionTable *pTo;            /* Table zTbl */
171847: 
171848:     /* Locate and if necessary initialize the target table object */
171849:     rc = sessionFindTable(pSession, zTbl, &pTo);
171850:     if( pTo==0 ) goto diff_out;
171851:     if( sessionInitTable(pSession, pTo) ){
171852:       rc = pSession->rc;
171853:       goto diff_out;
171854:     }
171855: 
171856:     /* Check the table schemas match */
171857:     if( rc==SQLITE_OK ){
171858:       int bHasPk = 0;
171859:       int bMismatch = 0;
171860:       int nCol;                   /* Columns in zFrom.zTbl */
171861:       u8 *abPK;
171862:       const char **azCol = 0;
171863:       rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
171864:       if( rc==SQLITE_OK ){
171865:         if( pTo->nCol!=nCol ){
171866:           bMismatch = 1;
171867:         }else{
171868:           int i;
171869:           for(i=0; i<nCol; i++){
171870:             if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
171871:             if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
171872:             if( abPK[i] ) bHasPk = 1;
171873:           }
171874:         }
171875: 
171876:       }
171877:       sqlite3_free((char*)azCol);
171878:       if( bMismatch ){
171879:         *pzErrMsg = sqlite3_mprintf("table schemas do not match");
171880:         rc = SQLITE_SCHEMA;
171881:       }
171882:       if( bHasPk==0 ){
171883:         /* Ignore tables with no primary keys */
171884:         goto diff_out;
171885:       }
171886:     }
171887: 
171888:     if( rc==SQLITE_OK ){
171889:       zExpr = sessionExprComparePK(pTo->nCol, 
171890:           zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
171891:       );
171892:     }
171893: 
171894:     /* Find new rows */
171895:     if( rc==SQLITE_OK ){
171896:       rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
171897:     }
171898: 
171899:     /* Find old rows */
171900:     if( rc==SQLITE_OK ){
171901:       rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
171902:     }
171903: 
171904:     /* Find modified rows */
171905:     if( rc==SQLITE_OK ){
171906:       rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
171907:     }
171908: 
171909:     sqlite3_free(zExpr);
171910:   }
171911: 
171912:  diff_out:
171913:   sessionPreupdateHooks(pSession);
171914:   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171915:   return rc;
171916: }
171917: 
171918: /*
171919: ** Create a session object. This session object will record changes to
171920: ** database zDb attached to connection db.
171921: */
171922: SQLITE_API int sqlite3session_create(
171923:   sqlite3 *db,                    /* Database handle */
171924:   const char *zDb,                /* Name of db (e.g. "main") */
171925:   sqlite3_session **ppSession     /* OUT: New session object */
171926: ){
171927:   sqlite3_session *pNew;          /* Newly allocated session object */
171928:   sqlite3_session *pOld;          /* Session object already attached to db */
171929:   int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
171930: 
171931:   /* Zero the output value in case an error occurs. */
171932:   *ppSession = 0;
171933: 
171934:   /* Allocate and populate the new session object. */
171935:   pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
171936:   if( !pNew ) return SQLITE_NOMEM;
171937:   memset(pNew, 0, sizeof(sqlite3_session));
171938:   pNew->db = db;
171939:   pNew->zDb = (char *)&pNew[1];
171940:   pNew->bEnable = 1;
171941:   memcpy(pNew->zDb, zDb, nDb+1);
171942:   sessionPreupdateHooks(pNew);
171943: 
171944:   /* Add the new session object to the linked list of session objects 
171945:   ** attached to database handle $db. Do this under the cover of the db
171946:   ** handle mutex.  */
171947:   sqlite3_mutex_enter(sqlite3_db_mutex(db));
171948:   pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
171949:   pNew->pNext = pOld;
171950:   sqlite3_mutex_leave(sqlite3_db_mutex(db));
171951: 
171952:   *ppSession = pNew;
171953:   return SQLITE_OK;
171954: }
171955: 
171956: /*
171957: ** Free the list of table objects passed as the first argument. The contents
171958: ** of the changed-rows hash tables are also deleted.
171959: */
171960: static void sessionDeleteTable(SessionTable *pList){
171961:   SessionTable *pNext;
171962:   SessionTable *pTab;
171963: 
171964:   for(pTab=pList; pTab; pTab=pNext){
171965:     int i;
171966:     pNext = pTab->pNext;
171967:     for(i=0; i<pTab->nChange; i++){
171968:       SessionChange *p;
171969:       SessionChange *pNextChange;
171970:       for(p=pTab->apChange[i]; p; p=pNextChange){
171971:         pNextChange = p->pNext;
171972:         sqlite3_free(p);
171973:       }
171974:     }
171975:     sqlite3_free((char*)pTab->azCol);  /* cast works around VC++ bug */
171976:     sqlite3_free(pTab->apChange);
171977:     sqlite3_free(pTab);
171978:   }
171979: }
171980: 
171981: /*
171982: ** Delete a session object previously allocated using sqlite3session_create().
171983: */
171984: SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
171985:   sqlite3 *db = pSession->db;
171986:   sqlite3_session *pHead;
171987:   sqlite3_session **pp;
171988: 
171989:   /* Unlink the session from the linked list of sessions attached to the
171990:   ** database handle. Hold the db mutex while doing so.  */
171991:   sqlite3_mutex_enter(sqlite3_db_mutex(db));
171992:   pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
171993:   for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
171994:     if( (*pp)==pSession ){
171995:       *pp = (*pp)->pNext;
171996:       if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
171997:       break;
171998:     }
171999:   }
172000:   sqlite3_mutex_leave(sqlite3_db_mutex(db));
172001: 
172002:   /* Delete all attached table objects. And the contents of their 
172003:   ** associated hash-tables. */
172004:   sessionDeleteTable(pSession->pTable);
172005: 
172006:   /* Free the session object itself. */
172007:   sqlite3_free(pSession);
172008: }
172009: 
172010: /*
172011: ** Set a table filter on a Session Object.
172012: */
172013: SQLITE_API void sqlite3session_table_filter(
172014:   sqlite3_session *pSession, 
172015:   int(*xFilter)(void*, const char*),
172016:   void *pCtx                      /* First argument passed to xFilter */
172017: ){
172018:   pSession->bAutoAttach = 1;
172019:   pSession->pFilterCtx = pCtx;
172020:   pSession->xTableFilter = xFilter;
172021: }
172022: 
172023: /*
172024: ** Attach a table to a session. All subsequent changes made to the table
172025: ** while the session object is enabled will be recorded.
172026: **
172027: ** Only tables that have a PRIMARY KEY defined may be attached. It does
172028: ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
172029: ** or not.
172030: */
172031: SQLITE_API int sqlite3session_attach(
172032:   sqlite3_session *pSession,      /* Session object */
172033:   const char *zName               /* Table name */
172034: ){
172035:   int rc = SQLITE_OK;
172036:   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172037: 
172038:   if( !zName ){
172039:     pSession->bAutoAttach = 1;
172040:   }else{
172041:     SessionTable *pTab;           /* New table object (if required) */
172042:     int nName;                    /* Number of bytes in string zName */
172043: 
172044:     /* First search for an existing entry. If one is found, this call is
172045:     ** a no-op. Return early. */
172046:     nName = sqlite3Strlen30(zName);
172047:     for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
172048:       if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
172049:     }
172050: 
172051:     if( !pTab ){
172052:       /* Allocate new SessionTable object. */
172053:       pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
172054:       if( !pTab ){
172055:         rc = SQLITE_NOMEM;
172056:       }else{
172057:         /* Populate the new SessionTable object and link it into the list.
172058:         ** The new object must be linked onto the end of the list, not 
172059:         ** simply added to the start of it in order to ensure that tables
172060:         ** appear in the correct order when a changeset or patchset is
172061:         ** eventually generated. */
172062:         SessionTable **ppTab;
172063:         memset(pTab, 0, sizeof(SessionTable));
172064:         pTab->zName = (char *)&pTab[1];
172065:         memcpy(pTab->zName, zName, nName+1);
172066:         for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
172067:         *ppTab = pTab;
172068:       }
172069:     }
172070:   }
172071: 
172072:   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172073:   return rc;
172074: }
172075: 
172076: /*
172077: ** Ensure that there is room in the buffer to append nByte bytes of data.
172078: ** If not, use sqlite3_realloc() to grow the buffer so that there is.
172079: **
172080: ** If successful, return zero. Otherwise, if an OOM condition is encountered,
172081: ** set *pRc to SQLITE_NOMEM and return non-zero.
172082: */
172083: static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
172084:   if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
172085:     u8 *aNew;
172086:     int nNew = p->nAlloc ? p->nAlloc : 128;
172087:     do {
172088:       nNew = nNew*2;
172089:     }while( nNew<(p->nBuf+nByte) );
172090: 
172091:     aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
172092:     if( 0==aNew ){
172093:       *pRc = SQLITE_NOMEM;
172094:     }else{
172095:       p->aBuf = aNew;
172096:       p->nAlloc = nNew;
172097:     }
172098:   }
172099:   return (*pRc!=SQLITE_OK);
172100: }
172101: 
172102: /*
172103: ** Append the value passed as the second argument to the buffer passed
172104: ** as the first.
172105: **
172106: ** This function is a no-op if *pRc is non-zero when it is called.
172107: ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
172108: ** before returning.
172109: */
172110: static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
172111:   int rc = *pRc;
172112:   if( rc==SQLITE_OK ){
172113:     int nByte = 0;
172114:     rc = sessionSerializeValue(0, pVal, &nByte);
172115:     sessionBufferGrow(p, nByte, &rc);
172116:     if( rc==SQLITE_OK ){
172117:       rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
172118:       p->nBuf += nByte;
172119:     }else{
172120:       *pRc = rc;
172121:     }
172122:   }
172123: }
172124: 
172125: /*
172126: ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
172127: ** called. Otherwise, append a single byte to the buffer. 
172128: **
172129: ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172130: ** returning.
172131: */
172132: static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
172133:   if( 0==sessionBufferGrow(p, 1, pRc) ){
172134:     p->aBuf[p->nBuf++] = v;
172135:   }
172136: }
172137: 
172138: /*
172139: ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
172140: ** called. Otherwise, append a single varint to the buffer. 
172141: **
172142: ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172143: ** returning.
172144: */
172145: static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
172146:   if( 0==sessionBufferGrow(p, 9, pRc) ){
172147:     p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
172148:   }
172149: }
172150: 
172151: /*
172152: ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
172153: ** called. Otherwise, append a blob of data to the buffer. 
172154: **
172155: ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172156: ** returning.
172157: */
172158: static void sessionAppendBlob(
172159:   SessionBuffer *p, 
172160:   const u8 *aBlob, 
172161:   int nBlob, 
172162:   int *pRc
172163: ){
172164:   if( 0==sessionBufferGrow(p, nBlob, pRc) ){
172165:     memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
172166:     p->nBuf += nBlob;
172167:   }
172168: }
172169: 
172170: /*
172171: ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
172172: ** called. Otherwise, append a string to the buffer. All bytes in the string
172173: ** up to (but not including) the nul-terminator are written to the buffer.
172174: **
172175: ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172176: ** returning.
172177: */
172178: static void sessionAppendStr(
172179:   SessionBuffer *p, 
172180:   const char *zStr, 
172181:   int *pRc
172182: ){
172183:   int nStr = sqlite3Strlen30(zStr);
172184:   if( 0==sessionBufferGrow(p, nStr, pRc) ){
172185:     memcpy(&p->aBuf[p->nBuf], zStr, nStr);
172186:     p->nBuf += nStr;
172187:   }
172188: }
172189: 
172190: /*
172191: ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
172192: ** called. Otherwise, append the string representation of integer iVal
172193: ** to the buffer. No nul-terminator is written.
172194: **
172195: ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172196: ** returning.
172197: */
172198: static void sessionAppendInteger(
172199:   SessionBuffer *p,               /* Buffer to append to */
172200:   int iVal,                       /* Value to write the string rep. of */
172201:   int *pRc                        /* IN/OUT: Error code */
172202: ){
172203:   char aBuf[24];
172204:   sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
172205:   sessionAppendStr(p, aBuf, pRc);
172206: }
172207: 
172208: /*
172209: ** This function is a no-op if *pRc is other than SQLITE_OK when it is 
172210: ** called. Otherwise, append the string zStr enclosed in quotes (") and
172211: ** with any embedded quote characters escaped to the buffer. No 
172212: ** nul-terminator byte is written.
172213: **
172214: ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
172215: ** returning.
172216: */
172217: static void sessionAppendIdent(
172218:   SessionBuffer *p,               /* Buffer to a append to */
172219:   const char *zStr,               /* String to quote, escape and append */
172220:   int *pRc                        /* IN/OUT: Error code */
172221: ){
172222:   int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
172223:   if( 0==sessionBufferGrow(p, nStr, pRc) ){
172224:     char *zOut = (char *)&p->aBuf[p->nBuf];
172225:     const char *zIn = zStr;
172226:     *zOut++ = '"';
172227:     while( *zIn ){
172228:       if( *zIn=='"' ) *zOut++ = '"';
172229:       *zOut++ = *(zIn++);
172230:     }
172231:     *zOut++ = '"';
172232:     p->nBuf = (int)((u8 *)zOut - p->aBuf);
172233:   }
172234: }
172235: 
172236: /*
172237: ** This function is a no-op if *pRc is other than SQLITE_OK when it is
172238: ** called. Otherwse, it appends the serialized version of the value stored
172239: ** in column iCol of the row that SQL statement pStmt currently points
172240: ** to to the buffer.
172241: */
172242: static void sessionAppendCol(
172243:   SessionBuffer *p,               /* Buffer to append to */
172244:   sqlite3_stmt *pStmt,            /* Handle pointing to row containing value */
172245:   int iCol,                       /* Column to read value from */
172246:   int *pRc                        /* IN/OUT: Error code */
172247: ){
172248:   if( *pRc==SQLITE_OK ){
172249:     int eType = sqlite3_column_type(pStmt, iCol);
172250:     sessionAppendByte(p, (u8)eType, pRc);
172251:     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172252:       sqlite3_int64 i;
172253:       u8 aBuf[8];
172254:       if( eType==SQLITE_INTEGER ){
172255:         i = sqlite3_column_int64(pStmt, iCol);
172256:       }else{
172257:         double r = sqlite3_column_double(pStmt, iCol);
172258:         memcpy(&i, &r, 8);
172259:       }
172260:       sessionPutI64(aBuf, i);
172261:       sessionAppendBlob(p, aBuf, 8, pRc);
172262:     }
172263:     if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
172264:       u8 *z;
172265:       int nByte;
172266:       if( eType==SQLITE_BLOB ){
172267:         z = (u8 *)sqlite3_column_blob(pStmt, iCol);
172268:       }else{
172269:         z = (u8 *)sqlite3_column_text(pStmt, iCol);
172270:       }
172271:       nByte = sqlite3_column_bytes(pStmt, iCol);
172272:       if( z || (eType==SQLITE_BLOB && nByte==0) ){
172273:         sessionAppendVarint(p, nByte, pRc);
172274:         sessionAppendBlob(p, z, nByte, pRc);
172275:       }else{
172276:         *pRc = SQLITE_NOMEM;
172277:       }
172278:     }
172279:   }
172280: }
172281: 
172282: /*
172283: **
172284: ** This function appends an update change to the buffer (see the comments 
172285: ** under "CHANGESET FORMAT" at the top of the file). An update change 
172286: ** consists of:
172287: **
172288: **   1 byte:  SQLITE_UPDATE (0x17)
172289: **   n bytes: old.* record (see RECORD FORMAT)
172290: **   m bytes: new.* record (see RECORD FORMAT)
172291: **
172292: ** The SessionChange object passed as the third argument contains the
172293: ** values that were stored in the row when the session began (the old.*
172294: ** values). The statement handle passed as the second argument points
172295: ** at the current version of the row (the new.* values).
172296: **
172297: ** If all of the old.* values are equal to their corresponding new.* value
172298: ** (i.e. nothing has changed), then no data at all is appended to the buffer.
172299: **
172300: ** Otherwise, the old.* record contains all primary key values and the 
172301: ** original values of any fields that have been modified. The new.* record 
172302: ** contains the new values of only those fields that have been modified.
172303: */ 
172304: static int sessionAppendUpdate(
172305:   SessionBuffer *pBuf,            /* Buffer to append to */
172306:   int bPatchset,                  /* True for "patchset", 0 for "changeset" */
172307:   sqlite3_stmt *pStmt,            /* Statement handle pointing at new row */
172308:   SessionChange *p,               /* Object containing old values */
172309:   u8 *abPK                        /* Boolean array - true for PK columns */
172310: ){
172311:   int rc = SQLITE_OK;
172312:   SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
172313:   int bNoop = 1;                /* Set to zero if any values are modified */
172314:   int nRewind = pBuf->nBuf;     /* Set to zero if any values are modified */
172315:   int i;                        /* Used to iterate through columns */
172316:   u8 *pCsr = p->aRecord;        /* Used to iterate through old.* values */
172317: 
172318:   sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
172319:   sessionAppendByte(pBuf, p->bIndirect, &rc);
172320:   for(i=0; i<sqlite3_column_count(pStmt); i++){
172321:     int bChanged = 0;
172322:     int nAdvance;
172323:     int eType = *pCsr;
172324:     switch( eType ){
172325:       case SQLITE_NULL:
172326:         nAdvance = 1;
172327:         if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
172328:           bChanged = 1;
172329:         }
172330:         break;
172331: 
172332:       case SQLITE_FLOAT:
172333:       case SQLITE_INTEGER: {
172334:         nAdvance = 9;
172335:         if( eType==sqlite3_column_type(pStmt, i) ){
172336:           sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
172337:           if( eType==SQLITE_INTEGER ){
172338:             if( iVal==sqlite3_column_int64(pStmt, i) ) break;
172339:           }else{
172340:             double dVal;
172341:             memcpy(&dVal, &iVal, 8);
172342:             if( dVal==sqlite3_column_double(pStmt, i) ) break;
172343:           }
172344:         }
172345:         bChanged = 1;
172346:         break;
172347:       }
172348: 
172349:       default: {
172350:         int nByte;
172351:         int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
172352:         assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
172353:         nAdvance = nHdr + nByte;
172354:         if( eType==sqlite3_column_type(pStmt, i) 
172355:          && nByte==sqlite3_column_bytes(pStmt, i) 
172356:          && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
172357:         ){
172358:           break;
172359:         }
172360:         bChanged = 1;
172361:       }
172362:     }
172363: 
172364:     /* If at least one field has been modified, this is not a no-op. */
172365:     if( bChanged ) bNoop = 0;
172366: 
172367:     /* Add a field to the old.* record. This is omitted if this modules is
172368:     ** currently generating a patchset. */
172369:     if( bPatchset==0 ){
172370:       if( bChanged || abPK[i] ){
172371:         sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
172372:       }else{
172373:         sessionAppendByte(pBuf, 0, &rc);
172374:       }
172375:     }
172376: 
172377:     /* Add a field to the new.* record. Or the only record if currently
172378:     ** generating a patchset.  */
172379:     if( bChanged || (bPatchset && abPK[i]) ){
172380:       sessionAppendCol(&buf2, pStmt, i, &rc);
172381:     }else{
172382:       sessionAppendByte(&buf2, 0, &rc);
172383:     }
172384: 
172385:     pCsr += nAdvance;
172386:   }
172387: 
172388:   if( bNoop ){
172389:     pBuf->nBuf = nRewind;
172390:   }else{
172391:     sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
172392:   }
172393:   sqlite3_free(buf2.aBuf);
172394: 
172395:   return rc;
172396: }
172397: 
172398: /*
172399: ** Append a DELETE change to the buffer passed as the first argument. Use
172400: ** the changeset format if argument bPatchset is zero, or the patchset
172401: ** format otherwise.
172402: */
172403: static int sessionAppendDelete(
172404:   SessionBuffer *pBuf,            /* Buffer to append to */
172405:   int bPatchset,                  /* True for "patchset", 0 for "changeset" */
172406:   SessionChange *p,               /* Object containing old values */
172407:   int nCol,                       /* Number of columns in table */
172408:   u8 *abPK                        /* Boolean array - true for PK columns */
172409: ){
172410:   int rc = SQLITE_OK;
172411: 
172412:   sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
172413:   sessionAppendByte(pBuf, p->bIndirect, &rc);
172414: 
172415:   if( bPatchset==0 ){
172416:     sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
172417:   }else{
172418:     int i;
172419:     u8 *a = p->aRecord;
172420:     for(i=0; i<nCol; i++){
172421:       u8 *pStart = a;
172422:       int eType = *a++;
172423: 
172424:       switch( eType ){
172425:         case 0:
172426:         case SQLITE_NULL:
172427:           assert( abPK[i]==0 );
172428:           break;
172429: 
172430:         case SQLITE_FLOAT:
172431:         case SQLITE_INTEGER:
172432:           a += 8;
172433:           break;
172434: 
172435:         default: {
172436:           int n;
172437:           a += sessionVarintGet(a, &n);
172438:           a += n;
172439:           break;
172440:         }
172441:       }
172442:       if( abPK[i] ){
172443:         sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
172444:       }
172445:     }
172446:     assert( (a - p->aRecord)==p->nRecord );
172447:   }
172448: 
172449:   return rc;
172450: }
172451: 
172452: /*
172453: ** Formulate and prepare a SELECT statement to retrieve a row from table
172454: ** zTab in database zDb based on its primary key. i.e.
172455: **
172456: **   SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
172457: */
172458: static int sessionSelectStmt(
172459:   sqlite3 *db,                    /* Database handle */
172460:   const char *zDb,                /* Database name */
172461:   const char *zTab,               /* Table name */
172462:   int nCol,                       /* Number of columns in table */
172463:   const char **azCol,             /* Names of table columns */
172464:   u8 *abPK,                       /* PRIMARY KEY  array */
172465:   sqlite3_stmt **ppStmt           /* OUT: Prepared SELECT statement */
172466: ){
172467:   int rc = SQLITE_OK;
172468:   int i;
172469:   const char *zSep = "";
172470:   SessionBuffer buf = {0, 0, 0};
172471: 
172472:   sessionAppendStr(&buf, "SELECT * FROM ", &rc);
172473:   sessionAppendIdent(&buf, zDb, &rc);
172474:   sessionAppendStr(&buf, ".", &rc);
172475:   sessionAppendIdent(&buf, zTab, &rc);
172476:   sessionAppendStr(&buf, " WHERE ", &rc);
172477:   for(i=0; i<nCol; i++){
172478:     if( abPK[i] ){
172479:       sessionAppendStr(&buf, zSep, &rc);
172480:       sessionAppendIdent(&buf, azCol[i], &rc);
172481:       sessionAppendStr(&buf, " = ?", &rc);
172482:       sessionAppendInteger(&buf, i+1, &rc);
172483:       zSep = " AND ";
172484:     }
172485:   }
172486:   if( rc==SQLITE_OK ){
172487:     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
172488:   }
172489:   sqlite3_free(buf.aBuf);
172490:   return rc;
172491: }
172492: 
172493: /*
172494: ** Bind the PRIMARY KEY values from the change passed in argument pChange
172495: ** to the SELECT statement passed as the first argument. The SELECT statement
172496: ** is as prepared by function sessionSelectStmt().
172497: **
172498: ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
172499: ** error code (e.g. SQLITE_NOMEM) otherwise.
172500: */
172501: static int sessionSelectBind(
172502:   sqlite3_stmt *pSelect,          /* SELECT from sessionSelectStmt() */
172503:   int nCol,                       /* Number of columns in table */
172504:   u8 *abPK,                       /* PRIMARY KEY array */
172505:   SessionChange *pChange          /* Change structure */
172506: ){
172507:   int i;
172508:   int rc = SQLITE_OK;
172509:   u8 *a = pChange->aRecord;
172510: 
172511:   for(i=0; i<nCol && rc==SQLITE_OK; i++){
172512:     int eType = *a++;
172513: 
172514:     switch( eType ){
172515:       case 0:
172516:       case SQLITE_NULL:
172517:         assert( abPK[i]==0 );
172518:         break;
172519: 
172520:       case SQLITE_INTEGER: {
172521:         if( abPK[i] ){
172522:           i64 iVal = sessionGetI64(a);
172523:           rc = sqlite3_bind_int64(pSelect, i+1, iVal);
172524:         }
172525:         a += 8;
172526:         break;
172527:       }
172528: 
172529:       case SQLITE_FLOAT: {
172530:         if( abPK[i] ){
172531:           double rVal;
172532:           i64 iVal = sessionGetI64(a);
172533:           memcpy(&rVal, &iVal, 8);
172534:           rc = sqlite3_bind_double(pSelect, i+1, rVal);
172535:         }
172536:         a += 8;
172537:         break;
172538:       }
172539: 
172540:       case SQLITE_TEXT: {
172541:         int n;
172542:         a += sessionVarintGet(a, &n);
172543:         if( abPK[i] ){
172544:           rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
172545:         }
172546:         a += n;
172547:         break;
172548:       }
172549: 
172550:       default: {
172551:         int n;
172552:         assert( eType==SQLITE_BLOB );
172553:         a += sessionVarintGet(a, &n);
172554:         if( abPK[i] ){
172555:           rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
172556:         }
172557:         a += n;
172558:         break;
172559:       }
172560:     }
172561:   }
172562: 
172563:   return rc;
172564: }
172565: 
172566: /*
172567: ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
172568: ** is called. Otherwise, append a serialized table header (part of the binary 
172569: ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
172570: ** SQLite error code before returning.
172571: */
172572: static void sessionAppendTableHdr(
172573:   SessionBuffer *pBuf,            /* Append header to this buffer */
172574:   int bPatchset,                  /* Use the patchset format if true */
172575:   SessionTable *pTab,             /* Table object to append header for */
172576:   int *pRc                        /* IN/OUT: Error code */
172577: ){
172578:   /* Write a table header */
172579:   sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
172580:   sessionAppendVarint(pBuf, pTab->nCol, pRc);
172581:   sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
172582:   sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
172583: }
172584: 
172585: /*
172586: ** Generate either a changeset (if argument bPatchset is zero) or a patchset
172587: ** (if it is non-zero) based on the current contents of the session object
172588: ** passed as the first argument.
172589: **
172590: ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
172591: ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
172592: ** occurs, an SQLite error code is returned and both output variables set 
172593: ** to 0.
172594: */
172595: static int sessionGenerateChangeset(
172596:   sqlite3_session *pSession,      /* Session object */
172597:   int bPatchset,                  /* True for patchset, false for changeset */
172598:   int (*xOutput)(void *pOut, const void *pData, int nData),
172599:   void *pOut,                     /* First argument for xOutput */
172600:   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
172601:   void **ppChangeset              /* OUT: Buffer containing changeset */
172602: ){
172603:   sqlite3 *db = pSession->db;     /* Source database handle */
172604:   SessionTable *pTab;             /* Used to iterate through attached tables */
172605:   SessionBuffer buf = {0,0,0};    /* Buffer in which to accumlate changeset */
172606:   int rc;                         /* Return code */
172607: 
172608:   assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
172609: 
172610:   /* Zero the output variables in case an error occurs. If this session
172611:   ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
172612:   ** this call will be a no-op.  */
172613:   if( xOutput==0 ){
172614:     *pnChangeset = 0;
172615:     *ppChangeset = 0;
172616:   }
172617: 
172618:   if( pSession->rc ) return pSession->rc;
172619:   rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
172620:   if( rc!=SQLITE_OK ) return rc;
172621: 
172622:   sqlite3_mutex_enter(sqlite3_db_mutex(db));
172623: 
172624:   for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
172625:     if( pTab->nEntry ){
172626:       const char *zName = pTab->zName;
172627:       int nCol;                   /* Number of columns in table */
172628:       u8 *abPK;                   /* Primary key array */
172629:       const char **azCol = 0;     /* Table columns */
172630:       int i;                      /* Used to iterate through hash buckets */
172631:       sqlite3_stmt *pSel = 0;     /* SELECT statement to query table pTab */
172632:       int nRewind = buf.nBuf;     /* Initial size of write buffer */
172633:       int nNoop;                  /* Size of buffer after writing tbl header */
172634: 
172635:       /* Check the table schema is still Ok. */
172636:       rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
172637:       if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
172638:         rc = SQLITE_SCHEMA;
172639:       }
172640: 
172641:       /* Write a table header */
172642:       sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
172643: 
172644:       /* Build and compile a statement to execute: */
172645:       if( rc==SQLITE_OK ){
172646:         rc = sessionSelectStmt(
172647:             db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
172648:       }
172649: 
172650:       nNoop = buf.nBuf;
172651:       for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
172652:         SessionChange *p;         /* Used to iterate through changes */
172653: 
172654:         for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
172655:           rc = sessionSelectBind(pSel, nCol, abPK, p);
172656:           if( rc!=SQLITE_OK ) continue;
172657:           if( sqlite3_step(pSel)==SQLITE_ROW ){
172658:             if( p->op==SQLITE_INSERT ){
172659:               int iCol;
172660:               sessionAppendByte(&buf, SQLITE_INSERT, &rc);
172661:               sessionAppendByte(&buf, p->bIndirect, &rc);
172662:               for(iCol=0; iCol<nCol; iCol++){
172663:                 sessionAppendCol(&buf, pSel, iCol, &rc);
172664:               }
172665:             }else{
172666:               rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
172667:             }
172668:           }else if( p->op!=SQLITE_INSERT ){
172669:             rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
172670:           }
172671:           if( rc==SQLITE_OK ){
172672:             rc = sqlite3_reset(pSel);
172673:           }
172674: 
172675:           /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
172676:           ** its contents to the xOutput() callback. */
172677:           if( xOutput 
172678:            && rc==SQLITE_OK 
172679:            && buf.nBuf>nNoop 
172680:            && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE 
172681:           ){
172682:             rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
172683:             nNoop = -1;
172684:             buf.nBuf = 0;
172685:           }
172686: 
172687:         }
172688:       }
172689: 
172690:       sqlite3_finalize(pSel);
172691:       if( buf.nBuf==nNoop ){
172692:         buf.nBuf = nRewind;
172693:       }
172694:       sqlite3_free((char*)azCol);  /* cast works around VC++ bug */
172695:     }
172696:   }
172697: 
172698:   if( rc==SQLITE_OK ){
172699:     if( xOutput==0 ){
172700:       *pnChangeset = buf.nBuf;
172701:       *ppChangeset = buf.aBuf;
172702:       buf.aBuf = 0;
172703:     }else if( buf.nBuf>0 ){
172704:       rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
172705:     }
172706:   }
172707: 
172708:   sqlite3_free(buf.aBuf);
172709:   sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
172710:   sqlite3_mutex_leave(sqlite3_db_mutex(db));
172711:   return rc;
172712: }
172713: 
172714: /*
172715: ** Obtain a changeset object containing all changes recorded by the 
172716: ** session object passed as the first argument.
172717: **
172718: ** It is the responsibility of the caller to eventually free the buffer 
172719: ** using sqlite3_free().
172720: */
172721: SQLITE_API int sqlite3session_changeset(
172722:   sqlite3_session *pSession,      /* Session object */
172723:   int *pnChangeset,               /* OUT: Size of buffer at *ppChangeset */
172724:   void **ppChangeset              /* OUT: Buffer containing changeset */
172725: ){
172726:   return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
172727: }
172728: 
172729: /*
172730: ** Streaming version of sqlite3session_changeset().
172731: */
172732: SQLITE_API int sqlite3session_changeset_strm(
172733:   sqlite3_session *pSession,
172734:   int (*xOutput)(void *pOut, const void *pData, int nData),
172735:   void *pOut
172736: ){
172737:   return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
172738: }
172739: 
172740: /*
172741: ** Streaming version of sqlite3session_patchset().
172742: */
172743: SQLITE_API int sqlite3session_patchset_strm(
172744:   sqlite3_session *pSession,
172745:   int (*xOutput)(void *pOut, const void *pData, int nData),
172746:   void *pOut
172747: ){
172748:   return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
172749: }
172750: 
172751: /*
172752: ** Obtain a patchset object containing all changes recorded by the 
172753: ** session object passed as the first argument.
172754: **
172755: ** It is the responsibility of the caller to eventually free the buffer 
172756: ** using sqlite3_free().
172757: */
172758: SQLITE_API int sqlite3session_patchset(
172759:   sqlite3_session *pSession,      /* Session object */
172760:   int *pnPatchset,                /* OUT: Size of buffer at *ppChangeset */
172761:   void **ppPatchset               /* OUT: Buffer containing changeset */
172762: ){
172763:   return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
172764: }
172765: 
172766: /*
172767: ** Enable or disable the session object passed as the first argument.
172768: */
172769: SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
172770:   int ret;
172771:   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172772:   if( bEnable>=0 ){
172773:     pSession->bEnable = bEnable;
172774:   }
172775:   ret = pSession->bEnable;
172776:   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172777:   return ret;
172778: }
172779: 
172780: /*
172781: ** Enable or disable the session object passed as the first argument.
172782: */
172783: SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
172784:   int ret;
172785:   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172786:   if( bIndirect>=0 ){
172787:     pSession->bIndirect = bIndirect;
172788:   }
172789:   ret = pSession->bIndirect;
172790:   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172791:   return ret;
172792: }
172793: 
172794: /*
172795: ** Return true if there have been no changes to monitored tables recorded
172796: ** by the session object passed as the only argument.
172797: */
172798: SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
172799:   int ret = 0;
172800:   SessionTable *pTab;
172801: 
172802:   sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
172803:   for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
172804:     ret = (pTab->nEntry>0);
172805:   }
172806:   sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
172807: 
172808:   return (ret==0);
172809: }
172810: 
172811: /*
172812: ** Do the work for either sqlite3changeset_start() or start_strm().
172813: */
172814: static int sessionChangesetStart(
172815:   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172816:   int (*xInput)(void *pIn, void *pData, int *pnData),
172817:   void *pIn,
172818:   int nChangeset,                 /* Size of buffer pChangeset in bytes */
172819:   void *pChangeset                /* Pointer to buffer containing changeset */
172820: ){
172821:   sqlite3_changeset_iter *pRet;   /* Iterator to return */
172822:   int nByte;                      /* Number of bytes to allocate for iterator */
172823: 
172824:   assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
172825: 
172826:   /* Zero the output variable in case an error occurs. */
172827:   *pp = 0;
172828: 
172829:   /* Allocate and initialize the iterator structure. */
172830:   nByte = sizeof(sqlite3_changeset_iter);
172831:   pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
172832:   if( !pRet ) return SQLITE_NOMEM;
172833:   memset(pRet, 0, sizeof(sqlite3_changeset_iter));
172834:   pRet->in.aData = (u8 *)pChangeset;
172835:   pRet->in.nData = nChangeset;
172836:   pRet->in.xInput = xInput;
172837:   pRet->in.pIn = pIn;
172838:   pRet->in.bEof = (xInput ? 0 : 1);
172839: 
172840:   /* Populate the output variable and return success. */
172841:   *pp = pRet;
172842:   return SQLITE_OK;
172843: }
172844: 
172845: /*
172846: ** Create an iterator used to iterate through the contents of a changeset.
172847: */
172848: SQLITE_API int sqlite3changeset_start(
172849:   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172850:   int nChangeset,                 /* Size of buffer pChangeset in bytes */
172851:   void *pChangeset                /* Pointer to buffer containing changeset */
172852: ){
172853:   return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
172854: }
172855: 
172856: /*
172857: ** Streaming version of sqlite3changeset_start().
172858: */
172859: SQLITE_API int sqlite3changeset_start_strm(
172860:   sqlite3_changeset_iter **pp,    /* OUT: Changeset iterator handle */
172861:   int (*xInput)(void *pIn, void *pData, int *pnData),
172862:   void *pIn
172863: ){
172864:   return sessionChangesetStart(pp, xInput, pIn, 0, 0);
172865: }
172866: 
172867: /*
172868: ** If the SessionInput object passed as the only argument is a streaming
172869: ** object and the buffer is full, discard some data to free up space.
172870: */
172871: static void sessionDiscardData(SessionInput *pIn){
172872:   if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
172873:     int nMove = pIn->buf.nBuf - pIn->iNext;
172874:     assert( nMove>=0 );
172875:     if( nMove>0 ){
172876:       memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
172877:     }
172878:     pIn->buf.nBuf -= pIn->iNext;
172879:     pIn->iNext = 0;
172880:     pIn->nData = pIn->buf.nBuf;
172881:   }
172882: }
172883: 
172884: /*
172885: ** Ensure that there are at least nByte bytes available in the buffer. Or,
172886: ** if there are not nByte bytes remaining in the input, that all available
172887: ** data is in the buffer.
172888: **
172889: ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
172890: */
172891: static int sessionInputBuffer(SessionInput *pIn, int nByte){
172892:   int rc = SQLITE_OK;
172893:   if( pIn->xInput ){
172894:     while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
172895:       int nNew = SESSIONS_STRM_CHUNK_SIZE;
172896: 
172897:       if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
172898:       if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
172899:         rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
172900:         if( nNew==0 ){
172901:           pIn->bEof = 1;
172902:         }else{
172903:           pIn->buf.nBuf += nNew;
172904:         }
172905:       }
172906: 
172907:       pIn->aData = pIn->buf.aBuf;
172908:       pIn->nData = pIn->buf.nBuf;
172909:     }
172910:   }
172911:   return rc;
172912: }
172913: 
172914: /*
172915: ** When this function is called, *ppRec points to the start of a record
172916: ** that contains nCol values. This function advances the pointer *ppRec
172917: ** until it points to the byte immediately following that record.
172918: */
172919: static void sessionSkipRecord(
172920:   u8 **ppRec,                     /* IN/OUT: Record pointer */
172921:   int nCol                        /* Number of values in record */
172922: ){
172923:   u8 *aRec = *ppRec;
172924:   int i;
172925:   for(i=0; i<nCol; i++){
172926:     int eType = *aRec++;
172927:     if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172928:       int nByte;
172929:       aRec += sessionVarintGet((u8*)aRec, &nByte);
172930:       aRec += nByte;
172931:     }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172932:       aRec += 8;
172933:     }
172934:   }
172935: 
172936:   *ppRec = aRec;
172937: }
172938: 
172939: /*
172940: ** This function sets the value of the sqlite3_value object passed as the
172941: ** first argument to a copy of the string or blob held in the aData[] 
172942: ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
172943: ** error occurs.
172944: */
172945: static int sessionValueSetStr(
172946:   sqlite3_value *pVal,            /* Set the value of this object */
172947:   u8 *aData,                      /* Buffer containing string or blob data */
172948:   int nData,                      /* Size of buffer aData[] in bytes */
172949:   u8 enc                          /* String encoding (0 for blobs) */
172950: ){
172951:   /* In theory this code could just pass SQLITE_TRANSIENT as the final
172952:   ** argument to sqlite3ValueSetStr() and have the copy created 
172953:   ** automatically. But doing so makes it difficult to detect any OOM
172954:   ** error. Hence the code to create the copy externally. */
172955:   u8 *aCopy = sqlite3_malloc(nData+1);
172956:   if( aCopy==0 ) return SQLITE_NOMEM;
172957:   memcpy(aCopy, aData, nData);
172958:   sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
172959:   return SQLITE_OK;
172960: }
172961: 
172962: /*
172963: ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
172964: ** for details.
172965: **
172966: ** When this function is called, *paChange points to the start of the record
172967: ** to deserialize. Assuming no error occurs, *paChange is set to point to
172968: ** one byte after the end of the same record before this function returns.
172969: ** If the argument abPK is NULL, then the record contains nCol values. Or,
172970: ** if abPK is other than NULL, then the record contains only the PK fields
172971: ** (in other words, it is a patchset DELETE record).
172972: **
172973: ** If successful, each element of the apOut[] array (allocated by the caller)
172974: ** is set to point to an sqlite3_value object containing the value read
172975: ** from the corresponding position in the record. If that value is not
172976: ** included in the record (i.e. because the record is part of an UPDATE change
172977: ** and the field was not modified), the corresponding element of apOut[] is
172978: ** set to NULL.
172979: **
172980: ** It is the responsibility of the caller to free all sqlite_value structures
172981: ** using sqlite3_free().
172982: **
172983: ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
172984: ** The apOut[] array may have been partially populated in this case.
172985: */
172986: static int sessionReadRecord(
172987:   SessionInput *pIn,              /* Input data */
172988:   int nCol,                       /* Number of values in record */
172989:   u8 *abPK,                       /* Array of primary key flags, or NULL */
172990:   sqlite3_value **apOut           /* Write values to this array */
172991: ){
172992:   int i;                          /* Used to iterate through columns */
172993:   int rc = SQLITE_OK;
172994: 
172995:   for(i=0; i<nCol && rc==SQLITE_OK; i++){
172996:     int eType = 0;                /* Type of value (SQLITE_NULL, TEXT etc.) */
172997:     if( abPK && abPK[i]==0 ) continue;
172998:     rc = sessionInputBuffer(pIn, 9);
172999:     if( rc==SQLITE_OK ){
173000:       eType = pIn->aData[pIn->iNext++];
173001:     }
173002: 
173003:     assert( apOut[i]==0 );
173004:     if( eType ){
173005:       apOut[i] = sqlite3ValueNew(0);
173006:       if( !apOut[i] ) rc = SQLITE_NOMEM;
173007:     }
173008: 
173009:     if( rc==SQLITE_OK ){
173010:       u8 *aVal = &pIn->aData[pIn->iNext];
173011:       if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
173012:         int nByte;
173013:         pIn->iNext += sessionVarintGet(aVal, &nByte);
173014:         rc = sessionInputBuffer(pIn, nByte);
173015:         if( rc==SQLITE_OK ){
173016:           u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
173017:           rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
173018:         }
173019:         pIn->iNext += nByte;
173020:       }
173021:       if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
173022:         sqlite3_int64 v = sessionGetI64(aVal);
173023:         if( eType==SQLITE_INTEGER ){
173024:           sqlite3VdbeMemSetInt64(apOut[i], v);
173025:         }else{
173026:           double d;
173027:           memcpy(&d, &v, 8);
173028:           sqlite3VdbeMemSetDouble(apOut[i], d);
173029:         }
173030:         pIn->iNext += 8;
173031:       }
173032:     }
173033:   }
173034: 
173035:   return rc;
173036: }
173037: 
173038: /*
173039: ** The input pointer currently points to the second byte of a table-header.
173040: ** Specifically, to the following:
173041: **
173042: **   + number of columns in table (varint)
173043: **   + array of PK flags (1 byte per column),
173044: **   + table name (nul terminated).
173045: **
173046: ** This function ensures that all of the above is present in the input 
173047: ** buffer (i.e. that it can be accessed without any calls to xInput()).
173048: ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
173049: ** The input pointer is not moved.
173050: */
173051: static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
173052:   int rc = SQLITE_OK;
173053:   int nCol = 0;
173054:   int nRead = 0;
173055: 
173056:   rc = sessionInputBuffer(pIn, 9);
173057:   if( rc==SQLITE_OK ){
173058:     nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
173059:     rc = sessionInputBuffer(pIn, nRead+nCol+100);
173060:     nRead += nCol;
173061:   }
173062: 
173063:   while( rc==SQLITE_OK ){
173064:     while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
173065:       nRead++;
173066:     }
173067:     if( (pIn->iNext + nRead)<pIn->nData ) break;
173068:     rc = sessionInputBuffer(pIn, nRead + 100);
173069:   }
173070:   *pnByte = nRead+1;
173071:   return rc;
173072: }
173073: 
173074: /*
173075: ** The input pointer currently points to the first byte of the first field
173076: ** of a record consisting of nCol columns. This function ensures the entire
173077: ** record is buffered. It does not move the input pointer.
173078: **
173079: ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
173080: ** the record in bytes. Otherwise, an SQLite error code is returned. The
173081: ** final value of *pnByte is undefined in this case.
173082: */
173083: static int sessionChangesetBufferRecord(
173084:   SessionInput *pIn,              /* Input data */
173085:   int nCol,                       /* Number of columns in record */
173086:   int *pnByte                     /* OUT: Size of record in bytes */
173087: ){
173088:   int rc = SQLITE_OK;
173089:   int nByte = 0;
173090:   int i;
173091:   for(i=0; rc==SQLITE_OK && i<nCol; i++){
173092:     int eType;
173093:     rc = sessionInputBuffer(pIn, nByte + 10);
173094:     if( rc==SQLITE_OK ){
173095:       eType = pIn->aData[pIn->iNext + nByte++];
173096:       if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
173097:         int n;
173098:         nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
173099:         nByte += n;
173100:         rc = sessionInputBuffer(pIn, nByte);
173101:       }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
173102:         nByte += 8;
173103:       }
173104:     }
173105:   }
173106:   *pnByte = nByte;
173107:   return rc;
173108: }
173109: 
173110: /*
173111: ** The input pointer currently points to the second byte of a table-header.
173112: ** Specifically, to the following:
173113: **
173114: **   + number of columns in table (varint)
173115: **   + array of PK flags (1 byte per column),
173116: **   + table name (nul terminated).
173117: **
173118: ** This function decodes the table-header and populates the p->nCol, 
173119: ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is 
173120: ** also allocated or resized according to the new value of p->nCol. The
173121: ** input pointer is left pointing to the byte following the table header.
173122: **
173123: ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
173124: ** is returned and the final values of the various fields enumerated above
173125: ** are undefined.
173126: */
173127: static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
173128:   int rc;
173129:   int nCopy;
173130:   assert( p->rc==SQLITE_OK );
173131: 
173132:   rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
173133:   if( rc==SQLITE_OK ){
173134:     int nByte;
173135:     int nVarint;
173136:     nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
173137:     nCopy -= nVarint;
173138:     p->in.iNext += nVarint;
173139:     nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
173140:     p->tblhdr.nBuf = 0;
173141:     sessionBufferGrow(&p->tblhdr, nByte, &rc);
173142:   }
173143: 
173144:   if( rc==SQLITE_OK ){
173145:     int iPK = sizeof(sqlite3_value*)*p->nCol*2;
173146:     memset(p->tblhdr.aBuf, 0, iPK);
173147:     memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
173148:     p->in.iNext += nCopy;
173149:   }
173150: 
173151:   p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
173152:   p->abPK = (u8*)&p->apValue[p->nCol*2];
173153:   p->zTab = (char*)&p->abPK[p->nCol];
173154:   return (p->rc = rc);
173155: }
173156: 
173157: /*
173158: ** Advance the changeset iterator to the next change.
173159: **
173160: ** If both paRec and pnRec are NULL, then this function works like the public
173161: ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
173162: ** sqlite3changeset_new() and old() APIs may be used to query for values.
173163: **
173164: ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
173165: ** record is written to *paRec before returning and the number of bytes in
173166: ** the record to *pnRec.
173167: **
173168: ** Either way, this function returns SQLITE_ROW if the iterator is 
173169: ** successfully advanced to the next change in the changeset, an SQLite 
173170: ** error code if an error occurs, or SQLITE_DONE if there are no further 
173171: ** changes in the changeset.
173172: */
173173: static int sessionChangesetNext(
173174:   sqlite3_changeset_iter *p,      /* Changeset iterator */
173175:   u8 **paRec,                     /* If non-NULL, store record pointer here */
173176:   int *pnRec                      /* If non-NULL, store size of record here */
173177: ){
173178:   int i;
173179:   u8 op;
173180: 
173181:   assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
173182: 
173183:   /* If the iterator is in the error-state, return immediately. */
173184:   if( p->rc!=SQLITE_OK ) return p->rc;
173185: 
173186:   /* Free the current contents of p->apValue[], if any. */
173187:   if( p->apValue ){
173188:     for(i=0; i<p->nCol*2; i++){
173189:       sqlite3ValueFree(p->apValue[i]);
173190:     }
173191:     memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
173192:   }
173193: 
173194:   /* Make sure the buffer contains at least 10 bytes of input data, or all
173195:   ** remaining data if there are less than 10 bytes available. This is
173196:   ** sufficient either for the 'T' or 'P' byte and the varint that follows
173197:   ** it, or for the two single byte values otherwise. */
173198:   p->rc = sessionInputBuffer(&p->in, 2);
173199:   if( p->rc!=SQLITE_OK ) return p->rc;
173200: 
173201:   /* If the iterator is already at the end of the changeset, return DONE. */
173202:   if( p->in.iNext>=p->in.nData ){
173203:     return SQLITE_DONE;
173204:   }
173205: 
173206:   sessionDiscardData(&p->in);
173207:   p->in.iCurrent = p->in.iNext;
173208: 
173209:   op = p->in.aData[p->in.iNext++];
173210:   if( op=='T' || op=='P' ){
173211:     p->bPatchset = (op=='P');
173212:     if( sessionChangesetReadTblhdr(p) ) return p->rc;
173213:     if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
173214:     p->in.iCurrent = p->in.iNext;
173215:     op = p->in.aData[p->in.iNext++];
173216:   }
173217: 
173218:   p->op = op;
173219:   p->bIndirect = p->in.aData[p->in.iNext++];
173220:   if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
173221:     return (p->rc = SQLITE_CORRUPT_BKPT);
173222:   }
173223: 
173224:   if( paRec ){ 
173225:     int nVal;                     /* Number of values to buffer */
173226:     if( p->bPatchset==0 && op==SQLITE_UPDATE ){
173227:       nVal = p->nCol * 2;
173228:     }else if( p->bPatchset && op==SQLITE_DELETE ){
173229:       nVal = 0;
173230:       for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
173231:     }else{
173232:       nVal = p->nCol;
173233:     }
173234:     p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
173235:     if( p->rc!=SQLITE_OK ) return p->rc;
173236:     *paRec = &p->in.aData[p->in.iNext];
173237:     p->in.iNext += *pnRec;
173238:   }else{
173239: 
173240:     /* If this is an UPDATE or DELETE, read the old.* record. */
173241:     if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
173242:       u8 *abPK = p->bPatchset ? p->abPK : 0;
173243:       p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
173244:       if( p->rc!=SQLITE_OK ) return p->rc;
173245:     }
173246: 
173247:     /* If this is an INSERT or UPDATE, read the new.* record. */
173248:     if( p->op!=SQLITE_DELETE ){
173249:       p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
173250:       if( p->rc!=SQLITE_OK ) return p->rc;
173251:     }
173252: 
173253:     if( p->bPatchset && p->op==SQLITE_UPDATE ){
173254:       /* If this is an UPDATE that is part of a patchset, then all PK and
173255:       ** modified fields are present in the new.* record. The old.* record
173256:       ** is currently completely empty. This block shifts the PK fields from
173257:       ** new.* to old.*, to accommodate the code that reads these arrays.  */
173258:       for(i=0; i<p->nCol; i++){
173259:         assert( p->apValue[i]==0 );
173260:         assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
173261:         if( p->abPK[i] ){
173262:           p->apValue[i] = p->apValue[i+p->nCol];
173263:           p->apValue[i+p->nCol] = 0;
173264:         }
173265:       }
173266:     }
173267:   }
173268: 
173269:   return SQLITE_ROW;
173270: }
173271: 
173272: /*
173273: ** Advance an iterator created by sqlite3changeset_start() to the next
173274: ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
173275: ** or SQLITE_CORRUPT.
173276: **
173277: ** This function may not be called on iterators passed to a conflict handler
173278: ** callback by changeset_apply().
173279: */
173280: SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
173281:   return sessionChangesetNext(p, 0, 0);
173282: }
173283: 
173284: /*
173285: ** The following function extracts information on the current change
173286: ** from a changeset iterator. It may only be called after changeset_next()
173287: ** has returned SQLITE_ROW.
173288: */
173289: SQLITE_API int sqlite3changeset_op(
173290:   sqlite3_changeset_iter *pIter,  /* Iterator handle */
173291:   const char **pzTab,             /* OUT: Pointer to table name */
173292:   int *pnCol,                     /* OUT: Number of columns in table */
173293:   int *pOp,                       /* OUT: SQLITE_INSERT, DELETE or UPDATE */
173294:   int *pbIndirect                 /* OUT: True if change is indirect */
173295: ){
173296:   *pOp = pIter->op;
173297:   *pnCol = pIter->nCol;
173298:   *pzTab = pIter->zTab;
173299:   if( pbIndirect ) *pbIndirect = pIter->bIndirect;
173300:   return SQLITE_OK;
173301: }
173302: 
173303: /*
173304: ** Return information regarding the PRIMARY KEY and number of columns in
173305: ** the database table affected by the change that pIter currently points
173306: ** to. This function may only be called after changeset_next() returns
173307: ** SQLITE_ROW.
173308: */
173309: SQLITE_API int sqlite3changeset_pk(
173310:   sqlite3_changeset_iter *pIter,  /* Iterator object */
173311:   unsigned char **pabPK,          /* OUT: Array of boolean - true for PK cols */
173312:   int *pnCol                      /* OUT: Number of entries in output array */
173313: ){
173314:   *pabPK = pIter->abPK;
173315:   if( pnCol ) *pnCol = pIter->nCol;
173316:   return SQLITE_OK;
173317: }
173318: 
173319: /*
173320: ** This function may only be called while the iterator is pointing to an
173321: ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
173322: ** Otherwise, SQLITE_MISUSE is returned.
173323: **
173324: ** It sets *ppValue to point to an sqlite3_value structure containing the
173325: ** iVal'th value in the old.* record. Or, if that particular value is not
173326: ** included in the record (because the change is an UPDATE and the field
173327: ** was not modified and is not a PK column), set *ppValue to NULL.
173328: **
173329: ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
173330: ** not modified. Otherwise, SQLITE_OK.
173331: */
173332: SQLITE_API int sqlite3changeset_old(
173333:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173334:   int iVal,                       /* Index of old.* value to retrieve */
173335:   sqlite3_value **ppValue         /* OUT: Old value (or NULL pointer) */
173336: ){
173337:   if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
173338:     return SQLITE_MISUSE;
173339:   }
173340:   if( iVal<0 || iVal>=pIter->nCol ){
173341:     return SQLITE_RANGE;
173342:   }
173343:   *ppValue = pIter->apValue[iVal];
173344:   return SQLITE_OK;
173345: }
173346: 
173347: /*
173348: ** This function may only be called while the iterator is pointing to an
173349: ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
173350: ** Otherwise, SQLITE_MISUSE is returned.
173351: **
173352: ** It sets *ppValue to point to an sqlite3_value structure containing the
173353: ** iVal'th value in the new.* record. Or, if that particular value is not
173354: ** included in the record (because the change is an UPDATE and the field
173355: ** was not modified), set *ppValue to NULL.
173356: **
173357: ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
173358: ** not modified. Otherwise, SQLITE_OK.
173359: */
173360: SQLITE_API int sqlite3changeset_new(
173361:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173362:   int iVal,                       /* Index of new.* value to retrieve */
173363:   sqlite3_value **ppValue         /* OUT: New value (or NULL pointer) */
173364: ){
173365:   if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
173366:     return SQLITE_MISUSE;
173367:   }
173368:   if( iVal<0 || iVal>=pIter->nCol ){
173369:     return SQLITE_RANGE;
173370:   }
173371:   *ppValue = pIter->apValue[pIter->nCol+iVal];
173372:   return SQLITE_OK;
173373: }
173374: 
173375: /*
173376: ** The following two macros are used internally. They are similar to the
173377: ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
173378: ** they omit all error checking and return a pointer to the requested value.
173379: */
173380: #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
173381: #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
173382: 
173383: /*
173384: ** This function may only be called with a changeset iterator that has been
173385: ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT 
173386: ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
173387: **
173388: ** If successful, *ppValue is set to point to an sqlite3_value structure
173389: ** containing the iVal'th value of the conflicting record.
173390: **
173391: ** If value iVal is out-of-range or some other error occurs, an SQLite error
173392: ** code is returned. Otherwise, SQLITE_OK.
173393: */
173394: SQLITE_API int sqlite3changeset_conflict(
173395:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173396:   int iVal,                       /* Index of conflict record value to fetch */
173397:   sqlite3_value **ppValue         /* OUT: Value from conflicting row */
173398: ){
173399:   if( !pIter->pConflict ){
173400:     return SQLITE_MISUSE;
173401:   }
173402:   if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
173403:     return SQLITE_RANGE;
173404:   }
173405:   *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
173406:   return SQLITE_OK;
173407: }
173408: 
173409: /*
173410: ** This function may only be called with an iterator passed to an
173411: ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
173412: ** it sets the output variable to the total number of known foreign key
173413: ** violations in the destination database and returns SQLITE_OK.
173414: **
173415: ** In all other cases this function returns SQLITE_MISUSE.
173416: */
173417: SQLITE_API int sqlite3changeset_fk_conflicts(
173418:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173419:   int *pnOut                      /* OUT: Number of FK violations */
173420: ){
173421:   if( pIter->pConflict || pIter->apValue ){
173422:     return SQLITE_MISUSE;
173423:   }
173424:   *pnOut = pIter->nCol;
173425:   return SQLITE_OK;
173426: }
173427: 
173428: 
173429: /*
173430: ** Finalize an iterator allocated with sqlite3changeset_start().
173431: **
173432: ** This function may not be called on iterators passed to a conflict handler
173433: ** callback by changeset_apply().
173434: */
173435: SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
173436:   int rc = SQLITE_OK;
173437:   if( p ){
173438:     int i;                        /* Used to iterate through p->apValue[] */
173439:     rc = p->rc;
173440:     if( p->apValue ){
173441:       for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
173442:     }
173443:     sqlite3_free(p->tblhdr.aBuf);
173444:     sqlite3_free(p->in.buf.aBuf);
173445:     sqlite3_free(p);
173446:   }
173447:   return rc;
173448: }
173449: 
173450: static int sessionChangesetInvert(
173451:   SessionInput *pInput,           /* Input changeset */
173452:   int (*xOutput)(void *pOut, const void *pData, int nData),
173453:   void *pOut,
173454:   int *pnInverted,                /* OUT: Number of bytes in output changeset */
173455:   void **ppInverted               /* OUT: Inverse of pChangeset */
173456: ){
173457:   int rc = SQLITE_OK;             /* Return value */
173458:   SessionBuffer sOut;             /* Output buffer */
173459:   int nCol = 0;                   /* Number of cols in current table */
173460:   u8 *abPK = 0;                   /* PK array for current table */
173461:   sqlite3_value **apVal = 0;      /* Space for values for UPDATE inversion */
173462:   SessionBuffer sPK = {0, 0, 0};  /* PK array for current table */
173463: 
173464:   /* Initialize the output buffer */
173465:   memset(&sOut, 0, sizeof(SessionBuffer));
173466: 
173467:   /* Zero the output variables in case an error occurs. */
173468:   if( ppInverted ){
173469:     *ppInverted = 0;
173470:     *pnInverted = 0;
173471:   }
173472: 
173473:   while( 1 ){
173474:     u8 eType;
173475: 
173476:     /* Test for EOF. */
173477:     if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
173478:     if( pInput->iNext>=pInput->nData ) break;
173479:     eType = pInput->aData[pInput->iNext];
173480: 
173481:     switch( eType ){
173482:       case 'T': {
173483:         /* A 'table' record consists of:
173484:         **
173485:         **   * A constant 'T' character,
173486:         **   * Number of columns in said table (a varint),
173487:         **   * An array of nCol bytes (sPK),
173488:         **   * A nul-terminated table name.
173489:         */
173490:         int nByte;
173491:         int nVar;
173492:         pInput->iNext++;
173493:         if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
173494:           goto finished_invert;
173495:         }
173496:         nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
173497:         sPK.nBuf = 0;
173498:         sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
173499:         sessionAppendByte(&sOut, eType, &rc);
173500:         sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
173501:         if( rc ) goto finished_invert;
173502: 
173503:         pInput->iNext += nByte;
173504:         sqlite3_free(apVal);
173505:         apVal = 0;
173506:         abPK = sPK.aBuf;
173507:         break;
173508:       }
173509: 
173510:       case SQLITE_INSERT:
173511:       case SQLITE_DELETE: {
173512:         int nByte;
173513:         int bIndirect = pInput->aData[pInput->iNext+1];
173514:         int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
173515:         pInput->iNext += 2;
173516:         assert( rc==SQLITE_OK );
173517:         rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
173518:         sessionAppendByte(&sOut, eType2, &rc);
173519:         sessionAppendByte(&sOut, bIndirect, &rc);
173520:         sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
173521:         pInput->iNext += nByte;
173522:         if( rc ) goto finished_invert;
173523:         break;
173524:       }
173525: 
173526:       case SQLITE_UPDATE: {
173527:         int iCol;
173528: 
173529:         if( 0==apVal ){
173530:           apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
173531:           if( 0==apVal ){
173532:             rc = SQLITE_NOMEM;
173533:             goto finished_invert;
173534:           }
173535:           memset(apVal, 0, sizeof(apVal[0])*nCol*2);
173536:         }
173537: 
173538:         /* Write the header for the new UPDATE change. Same as the original. */
173539:         sessionAppendByte(&sOut, eType, &rc);
173540:         sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
173541: 
173542:         /* Read the old.* and new.* records for the update change. */
173543:         pInput->iNext += 2;
173544:         rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
173545:         if( rc==SQLITE_OK ){
173546:           rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
173547:         }
173548: 
173549:         /* Write the new old.* record. Consists of the PK columns from the
173550:         ** original old.* record, and the other values from the original
173551:         ** new.* record. */
173552:         for(iCol=0; iCol<nCol; iCol++){
173553:           sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
173554:           sessionAppendValue(&sOut, pVal, &rc);
173555:         }
173556: 
173557:         /* Write the new new.* record. Consists of a copy of all values
173558:         ** from the original old.* record, except for the PK columns, which
173559:         ** are set to "undefined". */
173560:         for(iCol=0; iCol<nCol; iCol++){
173561:           sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
173562:           sessionAppendValue(&sOut, pVal, &rc);
173563:         }
173564: 
173565:         for(iCol=0; iCol<nCol*2; iCol++){
173566:           sqlite3ValueFree(apVal[iCol]);
173567:         }
173568:         memset(apVal, 0, sizeof(apVal[0])*nCol*2);
173569:         if( rc!=SQLITE_OK ){
173570:           goto finished_invert;
173571:         }
173572: 
173573:         break;
173574:       }
173575: 
173576:       default:
173577:         rc = SQLITE_CORRUPT_BKPT;
173578:         goto finished_invert;
173579:     }
173580: 
173581:     assert( rc==SQLITE_OK );
173582:     if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
173583:       rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
173584:       sOut.nBuf = 0;
173585:       if( rc!=SQLITE_OK ) goto finished_invert;
173586:     }
173587:   }
173588: 
173589:   assert( rc==SQLITE_OK );
173590:   if( pnInverted ){
173591:     *pnInverted = sOut.nBuf;
173592:     *ppInverted = sOut.aBuf;
173593:     sOut.aBuf = 0;
173594:   }else if( sOut.nBuf>0 ){
173595:     rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
173596:   }
173597: 
173598:  finished_invert:
173599:   sqlite3_free(sOut.aBuf);
173600:   sqlite3_free(apVal);
173601:   sqlite3_free(sPK.aBuf);
173602:   return rc;
173603: }
173604: 
173605: 
173606: /*
173607: ** Invert a changeset object.
173608: */
173609: SQLITE_API int sqlite3changeset_invert(
173610:   int nChangeset,                 /* Number of bytes in input */
173611:   const void *pChangeset,         /* Input changeset */
173612:   int *pnInverted,                /* OUT: Number of bytes in output changeset */
173613:   void **ppInverted               /* OUT: Inverse of pChangeset */
173614: ){
173615:   SessionInput sInput;
173616: 
173617:   /* Set up the input stream */
173618:   memset(&sInput, 0, sizeof(SessionInput));
173619:   sInput.nData = nChangeset;
173620:   sInput.aData = (u8*)pChangeset;
173621: 
173622:   return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
173623: }
173624: 
173625: /*
173626: ** Streaming version of sqlite3changeset_invert().
173627: */
173628: SQLITE_API int sqlite3changeset_invert_strm(
173629:   int (*xInput)(void *pIn, void *pData, int *pnData),
173630:   void *pIn,
173631:   int (*xOutput)(void *pOut, const void *pData, int nData),
173632:   void *pOut
173633: ){
173634:   SessionInput sInput;
173635:   int rc;
173636: 
173637:   /* Set up the input stream */
173638:   memset(&sInput, 0, sizeof(SessionInput));
173639:   sInput.xInput = xInput;
173640:   sInput.pIn = pIn;
173641: 
173642:   rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
173643:   sqlite3_free(sInput.buf.aBuf);
173644:   return rc;
173645: }
173646: 
173647: typedef struct SessionApplyCtx SessionApplyCtx;
173648: struct SessionApplyCtx {
173649:   sqlite3 *db;
173650:   sqlite3_stmt *pDelete;          /* DELETE statement */
173651:   sqlite3_stmt *pUpdate;          /* UPDATE statement */
173652:   sqlite3_stmt *pInsert;          /* INSERT statement */
173653:   sqlite3_stmt *pSelect;          /* SELECT statement */
173654:   int nCol;                       /* Size of azCol[] and abPK[] arrays */
173655:   const char **azCol;             /* Array of column names */
173656:   u8 *abPK;                       /* Boolean array - true if column is in PK */
173657: 
173658:   int bDeferConstraints;          /* True to defer constraints */
173659:   SessionBuffer constraints;      /* Deferred constraints are stored here */
173660: };
173661: 
173662: /*
173663: ** Formulate a statement to DELETE a row from database db. Assuming a table
173664: ** structure like this:
173665: **
173666: **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173667: **
173668: ** The DELETE statement looks like this:
173669: **
173670: **     DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
173671: **
173672: ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
173673: ** matching b and d values, or 1 otherwise. The second case comes up if the
173674: ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
173675: **
173676: ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
173677: ** pointing to the prepared version of the SQL statement.
173678: */
173679: static int sessionDeleteRow(
173680:   sqlite3 *db,                    /* Database handle */
173681:   const char *zTab,               /* Table name */
173682:   SessionApplyCtx *p              /* Session changeset-apply context */
173683: ){
173684:   int i;
173685:   const char *zSep = "";
173686:   int rc = SQLITE_OK;
173687:   SessionBuffer buf = {0, 0, 0};
173688:   int nPk = 0;
173689: 
173690:   sessionAppendStr(&buf, "DELETE FROM ", &rc);
173691:   sessionAppendIdent(&buf, zTab, &rc);
173692:   sessionAppendStr(&buf, " WHERE ", &rc);
173693: 
173694:   for(i=0; i<p->nCol; i++){
173695:     if( p->abPK[i] ){
173696:       nPk++;
173697:       sessionAppendStr(&buf, zSep, &rc);
173698:       sessionAppendIdent(&buf, p->azCol[i], &rc);
173699:       sessionAppendStr(&buf, " = ?", &rc);
173700:       sessionAppendInteger(&buf, i+1, &rc);
173701:       zSep = " AND ";
173702:     }
173703:   }
173704: 
173705:   if( nPk<p->nCol ){
173706:     sessionAppendStr(&buf, " AND (?", &rc);
173707:     sessionAppendInteger(&buf, p->nCol+1, &rc);
173708:     sessionAppendStr(&buf, " OR ", &rc);
173709: 
173710:     zSep = "";
173711:     for(i=0; i<p->nCol; i++){
173712:       if( !p->abPK[i] ){
173713:         sessionAppendStr(&buf, zSep, &rc);
173714:         sessionAppendIdent(&buf, p->azCol[i], &rc);
173715:         sessionAppendStr(&buf, " IS ?", &rc);
173716:         sessionAppendInteger(&buf, i+1, &rc);
173717:         zSep = "AND ";
173718:       }
173719:     }
173720:     sessionAppendStr(&buf, ")", &rc);
173721:   }
173722: 
173723:   if( rc==SQLITE_OK ){
173724:     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
173725:   }
173726:   sqlite3_free(buf.aBuf);
173727: 
173728:   return rc;
173729: }
173730: 
173731: /*
173732: ** Formulate and prepare a statement to UPDATE a row from database db. 
173733: ** Assuming a table structure like this:
173734: **
173735: **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173736: **
173737: ** The UPDATE statement looks like this:
173738: **
173739: **     UPDATE x SET
173740: **     a = CASE WHEN ?2  THEN ?3  ELSE a END,
173741: **     b = CASE WHEN ?5  THEN ?6  ELSE b END,
173742: **     c = CASE WHEN ?8  THEN ?9  ELSE c END,
173743: **     d = CASE WHEN ?11 THEN ?12 ELSE d END
173744: **     WHERE a = ?1 AND c = ?7 AND (?13 OR 
173745: **       (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
173746: **     )
173747: **
173748: ** For each column in the table, there are three variables to bind:
173749: **
173750: **     ?(i*3+1)    The old.* value of the column, if any.
173751: **     ?(i*3+2)    A boolean flag indicating that the value is being modified.
173752: **     ?(i*3+3)    The new.* value of the column, if any.
173753: **
173754: ** Also, a boolean flag that, if set to true, causes the statement to update
173755: ** a row even if the non-PK values do not match. This is required if the
173756: ** conflict-handler is invoked with CHANGESET_DATA and returns
173757: ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
173758: **
173759: ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
173760: ** pointing to the prepared version of the SQL statement.
173761: */
173762: static int sessionUpdateRow(
173763:   sqlite3 *db,                    /* Database handle */
173764:   const char *zTab,               /* Table name */
173765:   SessionApplyCtx *p              /* Session changeset-apply context */
173766: ){
173767:   int rc = SQLITE_OK;
173768:   int i;
173769:   const char *zSep = "";
173770:   SessionBuffer buf = {0, 0, 0};
173771: 
173772:   /* Append "UPDATE tbl SET " */
173773:   sessionAppendStr(&buf, "UPDATE ", &rc);
173774:   sessionAppendIdent(&buf, zTab, &rc);
173775:   sessionAppendStr(&buf, " SET ", &rc);
173776: 
173777:   /* Append the assignments */
173778:   for(i=0; i<p->nCol; i++){
173779:     sessionAppendStr(&buf, zSep, &rc);
173780:     sessionAppendIdent(&buf, p->azCol[i], &rc);
173781:     sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
173782:     sessionAppendInteger(&buf, i*3+2, &rc);
173783:     sessionAppendStr(&buf, " THEN ?", &rc);
173784:     sessionAppendInteger(&buf, i*3+3, &rc);
173785:     sessionAppendStr(&buf, " ELSE ", &rc);
173786:     sessionAppendIdent(&buf, p->azCol[i], &rc);
173787:     sessionAppendStr(&buf, " END", &rc);
173788:     zSep = ", ";
173789:   }
173790: 
173791:   /* Append the PK part of the WHERE clause */
173792:   sessionAppendStr(&buf, " WHERE ", &rc);
173793:   for(i=0; i<p->nCol; i++){
173794:     if( p->abPK[i] ){
173795:       sessionAppendIdent(&buf, p->azCol[i], &rc);
173796:       sessionAppendStr(&buf, " = ?", &rc);
173797:       sessionAppendInteger(&buf, i*3+1, &rc);
173798:       sessionAppendStr(&buf, " AND ", &rc);
173799:     }
173800:   }
173801: 
173802:   /* Append the non-PK part of the WHERE clause */
173803:   sessionAppendStr(&buf, " (?", &rc);
173804:   sessionAppendInteger(&buf, p->nCol*3+1, &rc);
173805:   sessionAppendStr(&buf, " OR 1", &rc);
173806:   for(i=0; i<p->nCol; i++){
173807:     if( !p->abPK[i] ){
173808:       sessionAppendStr(&buf, " AND (?", &rc);
173809:       sessionAppendInteger(&buf, i*3+2, &rc);
173810:       sessionAppendStr(&buf, "=0 OR ", &rc);
173811:       sessionAppendIdent(&buf, p->azCol[i], &rc);
173812:       sessionAppendStr(&buf, " IS ?", &rc);
173813:       sessionAppendInteger(&buf, i*3+1, &rc);
173814:       sessionAppendStr(&buf, ")", &rc);
173815:     }
173816:   }
173817:   sessionAppendStr(&buf, ")", &rc);
173818: 
173819:   if( rc==SQLITE_OK ){
173820:     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
173821:   }
173822:   sqlite3_free(buf.aBuf);
173823: 
173824:   return rc;
173825: }
173826: 
173827: /*
173828: ** Formulate and prepare an SQL statement to query table zTab by primary
173829: ** key. Assuming the following table structure:
173830: **
173831: **     CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
173832: **
173833: ** The SELECT statement looks like this:
173834: **
173835: **     SELECT * FROM x WHERE a = ?1 AND c = ?3
173836: **
173837: ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
173838: ** pointing to the prepared version of the SQL statement.
173839: */
173840: static int sessionSelectRow(
173841:   sqlite3 *db,                    /* Database handle */
173842:   const char *zTab,               /* Table name */
173843:   SessionApplyCtx *p              /* Session changeset-apply context */
173844: ){
173845:   return sessionSelectStmt(
173846:       db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
173847: }
173848: 
173849: /*
173850: ** Formulate and prepare an INSERT statement to add a record to table zTab.
173851: ** For example:
173852: **
173853: **     INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
173854: **
173855: ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
173856: ** pointing to the prepared version of the SQL statement.
173857: */
173858: static int sessionInsertRow(
173859:   sqlite3 *db,                    /* Database handle */
173860:   const char *zTab,               /* Table name */
173861:   SessionApplyCtx *p              /* Session changeset-apply context */
173862: ){
173863:   int rc = SQLITE_OK;
173864:   int i;
173865:   SessionBuffer buf = {0, 0, 0};
173866: 
173867:   sessionAppendStr(&buf, "INSERT INTO main.", &rc);
173868:   sessionAppendIdent(&buf, zTab, &rc);
173869:   sessionAppendStr(&buf, " VALUES(?", &rc);
173870:   for(i=1; i<p->nCol; i++){
173871:     sessionAppendStr(&buf, ", ?", &rc);
173872:   }
173873:   sessionAppendStr(&buf, ")", &rc);
173874: 
173875:   if( rc==SQLITE_OK ){
173876:     rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
173877:   }
173878:   sqlite3_free(buf.aBuf);
173879:   return rc;
173880: }
173881: 
173882: /*
173883: ** A wrapper around sqlite3_bind_value() that detects an extra problem. 
173884: ** See comments in the body of this function for details.
173885: */
173886: static int sessionBindValue(
173887:   sqlite3_stmt *pStmt,            /* Statement to bind value to */
173888:   int i,                          /* Parameter number to bind to */
173889:   sqlite3_value *pVal             /* Value to bind */
173890: ){
173891:   int eType = sqlite3_value_type(pVal);
173892:   /* COVERAGE: The (pVal->z==0) branch is never true using current versions
173893:   ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
173894:   ** the (pVal->z) variable remains as it was or the type of the value is
173895:   ** set to SQLITE_NULL.  */
173896:   if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
173897:     /* This condition occurs when an earlier OOM in a call to
173898:     ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
173899:     ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
173900:     return SQLITE_NOMEM;
173901:   }
173902:   return sqlite3_bind_value(pStmt, i, pVal);
173903: }
173904: 
173905: /*
173906: ** Iterator pIter must point to an SQLITE_INSERT entry. This function 
173907: ** transfers new.* values from the current iterator entry to statement
173908: ** pStmt. The table being inserted into has nCol columns.
173909: **
173910: ** New.* value $i from the iterator is bound to variable ($i+1) of 
173911: ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
173912: ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
173913: ** to an array nCol elements in size. In this case only those values for 
173914: ** which abPK[$i] is true are read from the iterator and bound to the 
173915: ** statement.
173916: **
173917: ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
173918: */
173919: static int sessionBindRow(
173920:   sqlite3_changeset_iter *pIter,  /* Iterator to read values from */
173921:   int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
173922:   int nCol,                       /* Number of columns */
173923:   u8 *abPK,                       /* If not NULL, bind only if true */
173924:   sqlite3_stmt *pStmt             /* Bind values to this statement */
173925: ){
173926:   int i;
173927:   int rc = SQLITE_OK;
173928: 
173929:   /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
173930:   ** argument iterator points to a suitable entry. Make sure that xValue 
173931:   ** is one of these to guarantee that it is safe to ignore the return 
173932:   ** in the code below. */
173933:   assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
173934: 
173935:   for(i=0; rc==SQLITE_OK && i<nCol; i++){
173936:     if( !abPK || abPK[i] ){
173937:       sqlite3_value *pVal;
173938:       (void)xValue(pIter, i, &pVal);
173939:       rc = sessionBindValue(pStmt, i+1, pVal);
173940:     }
173941:   }
173942:   return rc;
173943: }
173944: 
173945: /*
173946: ** SQL statement pSelect is as generated by the sessionSelectRow() function.
173947: ** This function binds the primary key values from the change that changeset
173948: ** iterator pIter points to to the SELECT and attempts to seek to the table
173949: ** entry. If a row is found, the SELECT statement left pointing at the row 
173950: ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
173951: ** has occured, the statement is reset and SQLITE_OK is returned. If an
173952: ** error occurs, the statement is reset and an SQLite error code is returned.
173953: **
173954: ** If this function returns SQLITE_ROW, the caller must eventually reset() 
173955: ** statement pSelect. If any other value is returned, the statement does
173956: ** not require a reset().
173957: **
173958: ** If the iterator currently points to an INSERT record, bind values from the
173959: ** new.* record to the SELECT statement. Or, if it points to a DELETE or
173960: ** UPDATE, bind values from the old.* record. 
173961: */
173962: static int sessionSeekToRow(
173963:   sqlite3 *db,                    /* Database handle */
173964:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
173965:   u8 *abPK,                       /* Primary key flags array */
173966:   sqlite3_stmt *pSelect           /* SELECT statement from sessionSelectRow() */
173967: ){
173968:   int rc;                         /* Return code */
173969:   int nCol;                       /* Number of columns in table */
173970:   int op;                         /* Changset operation (SQLITE_UPDATE etc.) */
173971:   const char *zDummy;             /* Unused */
173972: 
173973:   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173974:   rc = sessionBindRow(pIter, 
173975:       op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
173976:       nCol, abPK, pSelect
173977:   );
173978: 
173979:   if( rc==SQLITE_OK ){
173980:     rc = sqlite3_step(pSelect);
173981:     if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
173982:   }
173983: 
173984:   return rc;
173985: }
173986: 
173987: /*
173988: ** Invoke the conflict handler for the change that the changeset iterator
173989: ** currently points to.
173990: **
173991: ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
173992: ** If argument pbReplace is NULL, then the type of conflict handler invoked
173993: ** depends solely on eType, as follows:
173994: **
173995: **    eType value                 Value passed to xConflict
173996: **    -------------------------------------------------
173997: **    CHANGESET_DATA              CHANGESET_NOTFOUND
173998: **    CHANGESET_CONFLICT          CHANGESET_CONSTRAINT
173999: **
174000: ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
174001: ** record with the same primary key as the record about to be deleted, updated
174002: ** or inserted. If such a record can be found, it is available to the conflict
174003: ** handler as the "conflicting" record. In this case the type of conflict
174004: ** handler invoked is as follows:
174005: **
174006: **    eType value         PK Record found?   Value passed to xConflict
174007: **    ----------------------------------------------------------------
174008: **    CHANGESET_DATA      Yes                CHANGESET_DATA
174009: **    CHANGESET_DATA      No                 CHANGESET_NOTFOUND
174010: **    CHANGESET_CONFLICT  Yes                CHANGESET_CONFLICT
174011: **    CHANGESET_CONFLICT  No                 CHANGESET_CONSTRAINT
174012: **
174013: ** If pbReplace is not NULL, and a record with a matching PK is found, and
174014: ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
174015: ** is set to non-zero before returning SQLITE_OK.
174016: **
174017: ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
174018: ** returned. Or, if the conflict handler returns an invalid value, 
174019: ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
174020: ** this function returns SQLITE_OK.
174021: */
174022: static int sessionConflictHandler(
174023:   int eType,                      /* Either CHANGESET_DATA or CONFLICT */
174024:   SessionApplyCtx *p,             /* changeset_apply() context */
174025:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
174026:   int(*xConflict)(void *, int, sqlite3_changeset_iter*),
174027:   void *pCtx,                     /* First argument for conflict handler */
174028:   int *pbReplace                  /* OUT: Set to true if PK row is found */
174029: ){
174030:   int res = 0;                    /* Value returned by conflict handler */
174031:   int rc;
174032:   int nCol;
174033:   int op;
174034:   const char *zDummy;
174035: 
174036:   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
174037: 
174038:   assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
174039:   assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
174040:   assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
174041: 
174042:   /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
174043:   if( pbReplace ){
174044:     rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
174045:   }else{
174046:     rc = SQLITE_OK;
174047:   }
174048: 
174049:   if( rc==SQLITE_ROW ){
174050:     /* There exists another row with the new.* primary key. */
174051:     pIter->pConflict = p->pSelect;
174052:     res = xConflict(pCtx, eType, pIter);
174053:     pIter->pConflict = 0;
174054:     rc = sqlite3_reset(p->pSelect);
174055:   }else if( rc==SQLITE_OK ){
174056:     if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
174057:       /* Instead of invoking the conflict handler, append the change blob
174058:       ** to the SessionApplyCtx.constraints buffer. */
174059:       u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
174060:       int nBlob = pIter->in.iNext - pIter->in.iCurrent;
174061:       sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
174062:       res = SQLITE_CHANGESET_OMIT;
174063:     }else{
174064:       /* No other row with the new.* primary key. */
174065:       res = xConflict(pCtx, eType+1, pIter);
174066:       if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
174067:     }
174068:   }
174069: 
174070:   if( rc==SQLITE_OK ){
174071:     switch( res ){
174072:       case SQLITE_CHANGESET_REPLACE:
174073:         assert( pbReplace );
174074:         *pbReplace = 1;
174075:         break;
174076: 
174077:       case SQLITE_CHANGESET_OMIT:
174078:         break;
174079: 
174080:       case SQLITE_CHANGESET_ABORT:
174081:         rc = SQLITE_ABORT;
174082:         break;
174083: 
174084:       default:
174085:         rc = SQLITE_MISUSE;
174086:         break;
174087:     }
174088:   }
174089: 
174090:   return rc;
174091: }
174092: 
174093: /*
174094: ** Attempt to apply the change that the iterator passed as the first argument
174095: ** currently points to to the database. If a conflict is encountered, invoke
174096: ** the conflict handler callback.
174097: **
174098: ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
174099: ** one is encountered, update or delete the row with the matching primary key
174100: ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
174101: ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
174102: ** to true before returning. In this case the caller will invoke this function
174103: ** again, this time with pbRetry set to NULL.
174104: **
174105: ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is 
174106: ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
174107: ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
174108: ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
174109: ** before retrying. In this case the caller attempts to remove the conflicting
174110: ** row before invoking this function again, this time with pbReplace set 
174111: ** to NULL.
174112: **
174113: ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
174114: ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is 
174115: ** returned.
174116: */
174117: static int sessionApplyOneOp(
174118:   sqlite3_changeset_iter *pIter,  /* Changeset iterator */
174119:   SessionApplyCtx *p,             /* changeset_apply() context */
174120:   int(*xConflict)(void *, int, sqlite3_changeset_iter *),
174121:   void *pCtx,                     /* First argument for the conflict handler */
174122:   int *pbReplace,                 /* OUT: True to remove PK row and retry */
174123:   int *pbRetry                    /* OUT: True to retry. */
174124: ){
174125:   const char *zDummy;
174126:   int op;
174127:   int nCol;
174128:   int rc = SQLITE_OK;
174129: 
174130:   assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
174131:   assert( p->azCol && p->abPK );
174132:   assert( !pbReplace || *pbReplace==0 );
174133: 
174134:   sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
174135: 
174136:   if( op==SQLITE_DELETE ){
174137: 
174138:     /* Bind values to the DELETE statement. If conflict handling is required,
174139:     ** bind values for all columns and set bound variable (nCol+1) to true.
174140:     ** Or, if conflict handling is not required, bind just the PK column
174141:     ** values and, if it exists, set (nCol+1) to false. Conflict handling
174142:     ** is not required if:
174143:     **
174144:     **   * this is a patchset, or
174145:     **   * (pbRetry==0), or
174146:     **   * all columns of the table are PK columns (in this case there is
174147:     **     no (nCol+1) variable to bind to).
174148:     */
174149:     u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
174150:     rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
174151:     if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
174152:       rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
174153:     }
174154:     if( rc!=SQLITE_OK ) return rc;
174155: 
174156:     sqlite3_step(p->pDelete);
174157:     rc = sqlite3_reset(p->pDelete);
174158:     if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
174159:       rc = sessionConflictHandler(
174160:           SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
174161:       );
174162:     }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
174163:       rc = sessionConflictHandler(
174164:           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
174165:       );
174166:     }
174167: 
174168:   }else if( op==SQLITE_UPDATE ){
174169:     int i;
174170: 
174171:     /* Bind values to the UPDATE statement. */
174172:     for(i=0; rc==SQLITE_OK && i<nCol; i++){
174173:       sqlite3_value *pOld = sessionChangesetOld(pIter, i);
174174:       sqlite3_value *pNew = sessionChangesetNew(pIter, i);
174175: 
174176:       sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
174177:       if( pOld ){
174178:         rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
174179:       }
174180:       if( rc==SQLITE_OK && pNew ){
174181:         rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
174182:       }
174183:     }
174184:     if( rc==SQLITE_OK ){
174185:       sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
174186:     }
174187:     if( rc!=SQLITE_OK ) return rc;
174188: 
174189:     /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
174190:     ** the result will be SQLITE_OK with 0 rows modified. */
174191:     sqlite3_step(p->pUpdate);
174192:     rc = sqlite3_reset(p->pUpdate);
174193: 
174194:     if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
174195:       /* A NOTFOUND or DATA error. Search the table to see if it contains
174196:       ** a row with a matching primary key. If so, this is a DATA conflict.
174197:       ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
174198: 
174199:       rc = sessionConflictHandler(
174200:           SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
174201:       );
174202: 
174203:     }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
174204:       /* This is always a CONSTRAINT conflict. */
174205:       rc = sessionConflictHandler(
174206:           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
174207:       );
174208:     }
174209: 
174210:   }else{
174211:     assert( op==SQLITE_INSERT );
174212:     rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
174213:     if( rc!=SQLITE_OK ) return rc;
174214: 
174215:     sqlite3_step(p->pInsert);
174216:     rc = sqlite3_reset(p->pInsert);
174217:     if( (rc&0xff)==SQLITE_CONSTRAINT ){
174218:       rc = sessionConflictHandler(
174219:           SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
174220:       );
174221:     }
174222:   }
174223: 
174224:   return rc;
174225: }
174226: 
174227: /*
174228: ** Attempt to apply the change that the iterator passed as the first argument
174229: ** currently points to to the database. If a conflict is encountered, invoke
174230: ** the conflict handler callback.
174231: **
174232: ** The difference between this function and sessionApplyOne() is that this
174233: ** function handles the case where the conflict-handler is invoked and 
174234: ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
174235: ** retried in some manner.
174236: */
174237: static int sessionApplyOneWithRetry(
174238:   sqlite3 *db,                    /* Apply change to "main" db of this handle */
174239:   sqlite3_changeset_iter *pIter,  /* Changeset iterator to read change from */
174240:   SessionApplyCtx *pApply,        /* Apply context */
174241:   int(*xConflict)(void*, int, sqlite3_changeset_iter*),
174242:   void *pCtx                      /* First argument passed to xConflict */
174243: ){
174244:   int bReplace = 0;
174245:   int bRetry = 0;
174246:   int rc;
174247: 
174248:   rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
174249:   assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
174250: 
174251:   /* If the bRetry flag is set, the change has not been applied due to an
174252:   ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
174253:   ** a row with the correct PK is present in the db, but one or more other
174254:   ** fields do not contain the expected values) and the conflict handler 
174255:   ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
174256:   ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
174257:   ** the SQLITE_CHANGESET_DATA problem.  */
174258:   if( bRetry ){
174259:     assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
174260:     rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
174261:   }
174262: 
174263:   /* If the bReplace flag is set, the change is an INSERT that has not
174264:   ** been performed because the database already contains a row with the
174265:   ** specified primary key and the conflict handler returned
174266:   ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
174267:   ** before reattempting the INSERT.  */
174268:   else if( bReplace ){
174269:     assert( pIter->op==SQLITE_INSERT );
174270:     rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
174271:     if( rc==SQLITE_OK ){
174272:       rc = sessionBindRow(pIter, 
174273:           sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
174274:       sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
174275:     }
174276:     if( rc==SQLITE_OK ){
174277:       sqlite3_step(pApply->pDelete);
174278:       rc = sqlite3_reset(pApply->pDelete);
174279:     }
174280:     if( rc==SQLITE_OK ){
174281:       rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
174282:     }
174283:     if( rc==SQLITE_OK ){
174284:       rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
174285:     }
174286:   }
174287: 
174288:   return rc;
174289: }
174290: 
174291: /*
174292: ** Retry the changes accumulated in the pApply->constraints buffer.
174293: */
174294: static int sessionRetryConstraints(
174295:   sqlite3 *db, 
174296:   int bPatchset,
174297:   const char *zTab,
174298:   SessionApplyCtx *pApply,
174299:   int(*xConflict)(void*, int, sqlite3_changeset_iter*),
174300:   void *pCtx                      /* First argument passed to xConflict */
174301: ){
174302:   int rc = SQLITE_OK;
174303: 
174304:   while( pApply->constraints.nBuf ){
174305:     sqlite3_changeset_iter *pIter2 = 0;
174306:     SessionBuffer cons = pApply->constraints;
174307:     memset(&pApply->constraints, 0, sizeof(SessionBuffer));
174308: 
174309:     rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
174310:     if( rc==SQLITE_OK ){
174311:       int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
174312:       int rc2;
174313:       pIter2->bPatchset = bPatchset;
174314:       pIter2->zTab = (char*)zTab;
174315:       pIter2->nCol = pApply->nCol;
174316:       pIter2->abPK = pApply->abPK;
174317:       sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
174318:       pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
174319:       if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
174320: 
174321:       while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
174322:         rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
174323:       }
174324: 
174325:       rc2 = sqlite3changeset_finalize(pIter2);
174326:       if( rc==SQLITE_OK ) rc = rc2;
174327:     }
174328:     assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
174329: 
174330:     sqlite3_free(cons.aBuf);
174331:     if( rc!=SQLITE_OK ) break;
174332:     if( pApply->constraints.nBuf>=cons.nBuf ){
174333:       /* No progress was made on the last round. */
174334:       pApply->bDeferConstraints = 0;
174335:     }
174336:   }
174337: 
174338:   return rc;
174339: }
174340: 
174341: /*
174342: ** Argument pIter is a changeset iterator that has been initialized, but
174343: ** not yet passed to sqlite3changeset_next(). This function applies the 
174344: ** changeset to the main database attached to handle "db". The supplied
174345: ** conflict handler callback is invoked to resolve any conflicts encountered
174346: ** while applying the change.
174347: */
174348: static int sessionChangesetApply(
174349:   sqlite3 *db,                    /* Apply change to "main" db of this handle */
174350:   sqlite3_changeset_iter *pIter,  /* Changeset to apply */
174351:   int(*xFilter)(
174352:     void *pCtx,                   /* Copy of sixth arg to _apply() */
174353:     const char *zTab              /* Table name */
174354:   ),
174355:   int(*xConflict)(
174356:     void *pCtx,                   /* Copy of fifth arg to _apply() */
174357:     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174358:     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174359:   ),
174360:   void *pCtx                      /* First argument passed to xConflict */
174361: ){
174362:   int schemaMismatch = 0;
174363:   int rc;                         /* Return code */
174364:   const char *zTab = 0;           /* Name of current table */
174365:   int nTab = 0;                   /* Result of sqlite3Strlen30(zTab) */
174366:   SessionApplyCtx sApply;         /* changeset_apply() context object */
174367:   int bPatchset;
174368: 
174369:   assert( xConflict!=0 );
174370: 
174371:   pIter->in.bNoDiscard = 1;
174372:   memset(&sApply, 0, sizeof(sApply));
174373:   sqlite3_mutex_enter(sqlite3_db_mutex(db));
174374:   rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
174375:   if( rc==SQLITE_OK ){
174376:     rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
174377:   }
174378:   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
174379:     int nCol;
174380:     int op;
174381:     const char *zNew;
174382:     
174383:     sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
174384: 
174385:     if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
174386:       u8 *abPK;
174387: 
174388:       rc = sessionRetryConstraints(
174389:           db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
174390:       );
174391:       if( rc!=SQLITE_OK ) break;
174392: 
174393:       sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
174394:       sqlite3_finalize(sApply.pDelete);
174395:       sqlite3_finalize(sApply.pUpdate); 
174396:       sqlite3_finalize(sApply.pInsert);
174397:       sqlite3_finalize(sApply.pSelect);
174398:       memset(&sApply, 0, sizeof(sApply));
174399:       sApply.db = db;
174400:       sApply.bDeferConstraints = 1;
174401: 
174402:       /* If an xFilter() callback was specified, invoke it now. If the 
174403:       ** xFilter callback returns zero, skip this table. If it returns
174404:       ** non-zero, proceed. */
174405:       schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
174406:       if( schemaMismatch ){
174407:         zTab = sqlite3_mprintf("%s", zNew);
174408:         if( zTab==0 ){
174409:           rc = SQLITE_NOMEM;
174410:           break;
174411:         }
174412:         nTab = (int)strlen(zTab);
174413:         sApply.azCol = (const char **)zTab;
174414:       }else{
174415:         sqlite3changeset_pk(pIter, &abPK, 0);
174416:         rc = sessionTableInfo(
174417:             db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
174418:         );
174419:         if( rc!=SQLITE_OK ) break;
174420:   
174421:         if( sApply.nCol==0 ){
174422:           schemaMismatch = 1;
174423:           sqlite3_log(SQLITE_SCHEMA, 
174424:               "sqlite3changeset_apply(): no such table: %s", zTab
174425:           );
174426:         }
174427:         else if( sApply.nCol!=nCol ){
174428:           schemaMismatch = 1;
174429:           sqlite3_log(SQLITE_SCHEMA, 
174430:               "sqlite3changeset_apply(): table %s has %d columns, expected %d", 
174431:               zTab, sApply.nCol, nCol
174432:           );
174433:         }
174434:         else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
174435:           schemaMismatch = 1;
174436:           sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
174437:               "primary key mismatch for table %s", zTab
174438:           );
174439:         }
174440:         else if( 
174441:             (rc = sessionSelectRow(db, zTab, &sApply))
174442:          || (rc = sessionUpdateRow(db, zTab, &sApply))
174443:          || (rc = sessionDeleteRow(db, zTab, &sApply))
174444:          || (rc = sessionInsertRow(db, zTab, &sApply))
174445:         ){
174446:           break;
174447:         }
174448:         nTab = sqlite3Strlen30(zTab);
174449:       }
174450:     }
174451: 
174452:     /* If there is a schema mismatch on the current table, proceed to the
174453:     ** next change. A log message has already been issued. */
174454:     if( schemaMismatch ) continue;
174455: 
174456:     rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
174457:   }
174458: 
174459:   bPatchset = pIter->bPatchset;
174460:   if( rc==SQLITE_OK ){
174461:     rc = sqlite3changeset_finalize(pIter);
174462:   }else{
174463:     sqlite3changeset_finalize(pIter);
174464:   }
174465: 
174466:   if( rc==SQLITE_OK ){
174467:     rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
174468:   }
174469: 
174470:   if( rc==SQLITE_OK ){
174471:     int nFk, notUsed;
174472:     sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
174473:     if( nFk!=0 ){
174474:       int res = SQLITE_CHANGESET_ABORT;
174475:       sqlite3_changeset_iter sIter;
174476:       memset(&sIter, 0, sizeof(sIter));
174477:       sIter.nCol = nFk;
174478:       res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
174479:       if( res!=SQLITE_CHANGESET_OMIT ){
174480:         rc = SQLITE_CONSTRAINT;
174481:       }
174482:     }
174483:   }
174484:   sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
174485: 
174486:   if( rc==SQLITE_OK ){
174487:     rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
174488:   }else{
174489:     sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
174490:     sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
174491:   }
174492: 
174493:   sqlite3_finalize(sApply.pInsert);
174494:   sqlite3_finalize(sApply.pDelete);
174495:   sqlite3_finalize(sApply.pUpdate);
174496:   sqlite3_finalize(sApply.pSelect);
174497:   sqlite3_free((char*)sApply.azCol);  /* cast works around VC++ bug */
174498:   sqlite3_free((char*)sApply.constraints.aBuf);
174499:   sqlite3_mutex_leave(sqlite3_db_mutex(db));
174500:   return rc;
174501: }
174502: 
174503: /*
174504: ** Apply the changeset passed via pChangeset/nChangeset to the main database
174505: ** attached to handle "db". Invoke the supplied conflict handler callback
174506: ** to resolve any conflicts encountered while applying the change.
174507: */
174508: SQLITE_API int sqlite3changeset_apply(
174509:   sqlite3 *db,                    /* Apply change to "main" db of this handle */
174510:   int nChangeset,                 /* Size of changeset in bytes */
174511:   void *pChangeset,               /* Changeset blob */
174512:   int(*xFilter)(
174513:     void *pCtx,                   /* Copy of sixth arg to _apply() */
174514:     const char *zTab              /* Table name */
174515:   ),
174516:   int(*xConflict)(
174517:     void *pCtx,                   /* Copy of fifth arg to _apply() */
174518:     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174519:     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174520:   ),
174521:   void *pCtx                      /* First argument passed to xConflict */
174522: ){
174523:   sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
174524:   int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
174525:   if( rc==SQLITE_OK ){
174526:     rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
174527:   }
174528:   return rc;
174529: }
174530: 
174531: /*
174532: ** Apply the changeset passed via xInput/pIn to the main database
174533: ** attached to handle "db". Invoke the supplied conflict handler callback
174534: ** to resolve any conflicts encountered while applying the change.
174535: */
174536: SQLITE_API int sqlite3changeset_apply_strm(
174537:   sqlite3 *db,                    /* Apply change to "main" db of this handle */
174538:   int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
174539:   void *pIn,                                          /* First arg for xInput */
174540:   int(*xFilter)(
174541:     void *pCtx,                   /* Copy of sixth arg to _apply() */
174542:     const char *zTab              /* Table name */
174543:   ),
174544:   int(*xConflict)(
174545:     void *pCtx,                   /* Copy of sixth arg to _apply() */
174546:     int eConflict,                /* DATA, MISSING, CONFLICT, CONSTRAINT */
174547:     sqlite3_changeset_iter *p     /* Handle describing change and conflict */
174548:   ),
174549:   void *pCtx                      /* First argument passed to xConflict */
174550: ){
174551:   sqlite3_changeset_iter *pIter;  /* Iterator to skip through changeset */  
174552:   int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
174553:   if( rc==SQLITE_OK ){
174554:     rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
174555:   }
174556:   return rc;
174557: }
174558: 
174559: /*
174560: ** sqlite3_changegroup handle.
174561: */
174562: struct sqlite3_changegroup {
174563:   int rc;                         /* Error code */
174564:   int bPatch;                     /* True to accumulate patchsets */
174565:   SessionTable *pList;            /* List of tables in current patch */
174566: };
174567: 
174568: /*
174569: ** This function is called to merge two changes to the same row together as
174570: ** part of an sqlite3changeset_concat() operation. A new change object is
174571: ** allocated and a pointer to it stored in *ppNew.
174572: */
174573: static int sessionChangeMerge(
174574:   SessionTable *pTab,             /* Table structure */
174575:   int bPatchset,                  /* True for patchsets */
174576:   SessionChange *pExist,          /* Existing change */
174577:   int op2,                        /* Second change operation */
174578:   int bIndirect,                  /* True if second change is indirect */
174579:   u8 *aRec,                       /* Second change record */
174580:   int nRec,                       /* Number of bytes in aRec */
174581:   SessionChange **ppNew           /* OUT: Merged change */
174582: ){
174583:   SessionChange *pNew = 0;
174584: 
174585:   if( !pExist ){
174586:     pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
174587:     if( !pNew ){
174588:       return SQLITE_NOMEM;
174589:     }
174590:     memset(pNew, 0, sizeof(SessionChange));
174591:     pNew->op = op2;
174592:     pNew->bIndirect = bIndirect;
174593:     pNew->nRecord = nRec;
174594:     pNew->aRecord = (u8*)&pNew[1];
174595:     memcpy(pNew->aRecord, aRec, nRec);
174596:   }else{
174597:     int op1 = pExist->op;
174598: 
174599:     /* 
174600:     **   op1=INSERT, op2=INSERT      ->      Unsupported. Discard op2.
174601:     **   op1=INSERT, op2=UPDATE      ->      INSERT.
174602:     **   op1=INSERT, op2=DELETE      ->      (none)
174603:     **
174604:     **   op1=UPDATE, op2=INSERT      ->      Unsupported. Discard op2.
174605:     **   op1=UPDATE, op2=UPDATE      ->      UPDATE.
174606:     **   op1=UPDATE, op2=DELETE      ->      DELETE.
174607:     **
174608:     **   op1=DELETE, op2=INSERT      ->      UPDATE.
174609:     **   op1=DELETE, op2=UPDATE      ->      Unsupported. Discard op2.
174610:     **   op1=DELETE, op2=DELETE      ->      Unsupported. Discard op2.
174611:     */   
174612:     if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
174613:      || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
174614:      || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
174615:      || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
174616:     ){
174617:       pNew = pExist;
174618:     }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
174619:       sqlite3_free(pExist);
174620:       assert( pNew==0 );
174621:     }else{
174622:       u8 *aExist = pExist->aRecord;
174623:       int nByte;
174624:       u8 *aCsr;
174625: 
174626:       /* Allocate a new SessionChange object. Ensure that the aRecord[]
174627:       ** buffer of the new object is large enough to hold any record that
174628:       ** may be generated by combining the input records.  */
174629:       nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
174630:       pNew = (SessionChange *)sqlite3_malloc(nByte);
174631:       if( !pNew ){
174632:         sqlite3_free(pExist);
174633:         return SQLITE_NOMEM;
174634:       }
174635:       memset(pNew, 0, sizeof(SessionChange));
174636:       pNew->bIndirect = (bIndirect && pExist->bIndirect);
174637:       aCsr = pNew->aRecord = (u8 *)&pNew[1];
174638: 
174639:       if( op1==SQLITE_INSERT ){             /* INSERT + UPDATE */
174640:         u8 *a1 = aRec;
174641:         assert( op2==SQLITE_UPDATE );
174642:         pNew->op = SQLITE_INSERT;
174643:         if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
174644:         sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
174645:       }else if( op1==SQLITE_DELETE ){       /* DELETE + INSERT */
174646:         assert( op2==SQLITE_INSERT );
174647:         pNew->op = SQLITE_UPDATE;
174648:         if( bPatchset ){
174649:           memcpy(aCsr, aRec, nRec);
174650:           aCsr += nRec;
174651:         }else{
174652:           if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
174653:             sqlite3_free(pNew);
174654:             pNew = 0;
174655:           }
174656:         }
174657:       }else if( op2==SQLITE_UPDATE ){       /* UPDATE + UPDATE */
174658:         u8 *a1 = aExist;
174659:         u8 *a2 = aRec;
174660:         assert( op1==SQLITE_UPDATE );
174661:         if( bPatchset==0 ){
174662:           sessionSkipRecord(&a1, pTab->nCol);
174663:           sessionSkipRecord(&a2, pTab->nCol);
174664:         }
174665:         pNew->op = SQLITE_UPDATE;
174666:         if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
174667:           sqlite3_free(pNew);
174668:           pNew = 0;
174669:         }
174670:       }else{                                /* UPDATE + DELETE */
174671:         assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
174672:         pNew->op = SQLITE_DELETE;
174673:         if( bPatchset ){
174674:           memcpy(aCsr, aRec, nRec);
174675:           aCsr += nRec;
174676:         }else{
174677:           sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
174678:         }
174679:       }
174680: 
174681:       if( pNew ){
174682:         pNew->nRecord = (int)(aCsr - pNew->aRecord);
174683:       }
174684:       sqlite3_free(pExist);
174685:     }
174686:   }
174687: 
174688:   *ppNew = pNew;
174689:   return SQLITE_OK;
174690: }
174691: 
174692: /*
174693: ** Add all changes in the changeset traversed by the iterator passed as
174694: ** the first argument to the changegroup hash tables.
174695: */
174696: static int sessionChangesetToHash(
174697:   sqlite3_changeset_iter *pIter,   /* Iterator to read from */
174698:   sqlite3_changegroup *pGrp        /* Changegroup object to add changeset to */
174699: ){
174700:   u8 *aRec;
174701:   int nRec;
174702:   int rc = SQLITE_OK;
174703:   SessionTable *pTab = 0;
174704: 
174705: 
174706:   while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
174707:     const char *zNew;
174708:     int nCol;
174709:     int op;
174710:     int iHash;
174711:     int bIndirect;
174712:     SessionChange *pChange;
174713:     SessionChange *pExist = 0;
174714:     SessionChange **pp;
174715: 
174716:     if( pGrp->pList==0 ){
174717:       pGrp->bPatch = pIter->bPatchset;
174718:     }else if( pIter->bPatchset!=pGrp->bPatch ){
174719:       rc = SQLITE_ERROR;
174720:       break;
174721:     }
174722: 
174723:     sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
174724:     if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
174725:       /* Search the list for a matching table */
174726:       int nNew = (int)strlen(zNew);
174727:       u8 *abPK;
174728: 
174729:       sqlite3changeset_pk(pIter, &abPK, 0);
174730:       for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
174731:         if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
174732:       }
174733:       if( !pTab ){
174734:         SessionTable **ppTab;
174735: 
174736:         pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
174737:         if( !pTab ){
174738:           rc = SQLITE_NOMEM;
174739:           break;
174740:         }
174741:         memset(pTab, 0, sizeof(SessionTable));
174742:         pTab->nCol = nCol;
174743:         pTab->abPK = (u8*)&pTab[1];
174744:         memcpy(pTab->abPK, abPK, nCol);
174745:         pTab->zName = (char*)&pTab->abPK[nCol];
174746:         memcpy(pTab->zName, zNew, nNew+1);
174747: 
174748:         /* The new object must be linked on to the end of the list, not
174749:         ** simply added to the start of it. This is to ensure that the
174750:         ** tables within the output of sqlite3changegroup_output() are in 
174751:         ** the right order.  */
174752:         for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
174753:         *ppTab = pTab;
174754:       }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
174755:         rc = SQLITE_SCHEMA;
174756:         break;
174757:       }
174758:     }
174759: 
174760:     if( sessionGrowHash(pIter->bPatchset, pTab) ){
174761:       rc = SQLITE_NOMEM;
174762:       break;
174763:     }
174764:     iHash = sessionChangeHash(
174765:         pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
174766:     );
174767: 
174768:     /* Search for existing entry. If found, remove it from the hash table. 
174769:     ** Code below may link it back in.
174770:     */
174771:     for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
174772:       int bPkOnly1 = 0;
174773:       int bPkOnly2 = 0;
174774:       if( pIter->bPatchset ){
174775:         bPkOnly1 = (*pp)->op==SQLITE_DELETE;
174776:         bPkOnly2 = op==SQLITE_DELETE;
174777:       }
174778:       if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
174779:         pExist = *pp;
174780:         *pp = (*pp)->pNext;
174781:         pTab->nEntry--;
174782:         break;
174783:       }
174784:     }
174785: 
174786:     rc = sessionChangeMerge(pTab, 
174787:         pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
174788:     );
174789:     if( rc ) break;
174790:     if( pChange ){
174791:       pChange->pNext = pTab->apChange[iHash];
174792:       pTab->apChange[iHash] = pChange;
174793:       pTab->nEntry++;
174794:     }
174795:   }
174796: 
174797:   if( rc==SQLITE_OK ) rc = pIter->rc;
174798:   return rc;
174799: }
174800: 
174801: /*
174802: ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
174803: ** added to the changegroup object passed as the first argument.
174804: **
174805: ** If xOutput is not NULL, then the changeset/patchset is returned to the
174806: ** user via one or more calls to xOutput, as with the other streaming
174807: ** interfaces. 
174808: **
174809: ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
174810: ** buffer containing the output changeset before this function returns. In
174811: ** this case (*pnOut) is set to the size of the output buffer in bytes. It
174812: ** is the responsibility of the caller to free the output buffer using
174813: ** sqlite3_free() when it is no longer required.
174814: **
174815: ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
174816: ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
174817: ** are both set to 0 before returning.
174818: */
174819: static int sessionChangegroupOutput(
174820:   sqlite3_changegroup *pGrp,
174821:   int (*xOutput)(void *pOut, const void *pData, int nData),
174822:   void *pOut,
174823:   int *pnOut,
174824:   void **ppOut
174825: ){
174826:   int rc = SQLITE_OK;
174827:   SessionBuffer buf = {0, 0, 0};
174828:   SessionTable *pTab;
174829:   assert( xOutput==0 || (ppOut==0 && pnOut==0) );
174830: 
174831:   /* Create the serialized output changeset based on the contents of the
174832:   ** hash tables attached to the SessionTable objects in list p->pList. 
174833:   */
174834:   for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
174835:     int i;
174836:     if( pTab->nEntry==0 ) continue;
174837: 
174838:     sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
174839:     for(i=0; i<pTab->nChange; i++){
174840:       SessionChange *p;
174841:       for(p=pTab->apChange[i]; p; p=p->pNext){
174842:         sessionAppendByte(&buf, p->op, &rc);
174843:         sessionAppendByte(&buf, p->bIndirect, &rc);
174844:         sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
174845:       }
174846:     }
174847: 
174848:     if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
174849:       rc = xOutput(pOut, buf.aBuf, buf.nBuf);
174850:       buf.nBuf = 0;
174851:     }
174852:   }
174853: 
174854:   if( rc==SQLITE_OK ){
174855:     if( xOutput ){
174856:       if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
174857:     }else{
174858:       *ppOut = buf.aBuf;
174859:       *pnOut = buf.nBuf;
174860:       buf.aBuf = 0;
174861:     }
174862:   }
174863:   sqlite3_free(buf.aBuf);
174864: 
174865:   return rc;
174866: }
174867: 
174868: /*
174869: ** Allocate a new, empty, sqlite3_changegroup.
174870: */
174871: SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
174872:   int rc = SQLITE_OK;             /* Return code */
174873:   sqlite3_changegroup *p;         /* New object */
174874:   p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
174875:   if( p==0 ){
174876:     rc = SQLITE_NOMEM;
174877:   }else{
174878:     memset(p, 0, sizeof(sqlite3_changegroup));
174879:   }
174880:   *pp = p;
174881:   return rc;
174882: }
174883: 
174884: /*
174885: ** Add the changeset currently stored in buffer pData, size nData bytes,
174886: ** to changeset-group p.
174887: */
174888: SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
174889:   sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
174890:   int rc;                         /* Return code */
174891: 
174892:   rc = sqlite3changeset_start(&pIter, nData, pData);
174893:   if( rc==SQLITE_OK ){
174894:     rc = sessionChangesetToHash(pIter, pGrp);
174895:   }
174896:   sqlite3changeset_finalize(pIter);
174897:   return rc;
174898: }
174899: 
174900: /*
174901: ** Obtain a buffer containing a changeset representing the concatenation
174902: ** of all changesets added to the group so far.
174903: */
174904: SQLITE_API int sqlite3changegroup_output(
174905:     sqlite3_changegroup *pGrp,
174906:     int *pnData,
174907:     void **ppData
174908: ){
174909:   return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
174910: }
174911: 
174912: /*
174913: ** Streaming versions of changegroup_add().
174914: */
174915: SQLITE_API int sqlite3changegroup_add_strm(
174916:   sqlite3_changegroup *pGrp,
174917:   int (*xInput)(void *pIn, void *pData, int *pnData),
174918:   void *pIn
174919: ){
174920:   sqlite3_changeset_iter *pIter;  /* Iterator opened on pData/nData */
174921:   int rc;                         /* Return code */
174922: 
174923:   rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
174924:   if( rc==SQLITE_OK ){
174925:     rc = sessionChangesetToHash(pIter, pGrp);
174926:   }
174927:   sqlite3changeset_finalize(pIter);
174928:   return rc;
174929: }
174930: 
174931: /*
174932: ** Streaming versions of changegroup_output().
174933: */
174934: SQLITE_API int sqlite3changegroup_output_strm(
174935:   sqlite3_changegroup *pGrp,
174936:   int (*xOutput)(void *pOut, const void *pData, int nData), 
174937:   void *pOut
174938: ){
174939:   return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
174940: }
174941: 
174942: /*
174943: ** Delete a changegroup object.
174944: */
174945: SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
174946:   if( pGrp ){
174947:     sessionDeleteTable(pGrp->pList);
174948:     sqlite3_free(pGrp);
174949:   }
174950: }
174951: 
174952: /* 
174953: ** Combine two changesets together.
174954: */
174955: SQLITE_API int sqlite3changeset_concat(
174956:   int nLeft,                      /* Number of bytes in lhs input */
174957:   void *pLeft,                    /* Lhs input changeset */
174958:   int nRight                      /* Number of bytes in rhs input */,
174959:   void *pRight,                   /* Rhs input changeset */
174960:   int *pnOut,                     /* OUT: Number of bytes in output changeset */
174961:   void **ppOut                    /* OUT: changeset (left <concat> right) */
174962: ){
174963:   sqlite3_changegroup *pGrp;
174964:   int rc;
174965: 
174966:   rc = sqlite3changegroup_new(&pGrp);
174967:   if( rc==SQLITE_OK ){
174968:     rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
174969:   }
174970:   if( rc==SQLITE_OK ){
174971:     rc = sqlite3changegroup_add(pGrp, nRight, pRight);
174972:   }
174973:   if( rc==SQLITE_OK ){
174974:     rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
174975:   }
174976:   sqlite3changegroup_delete(pGrp);
174977: 
174978:   return rc;
174979: }
174980: 
174981: /*
174982: ** Streaming version of sqlite3changeset_concat().
174983: */
174984: SQLITE_API int sqlite3changeset_concat_strm(
174985:   int (*xInputA)(void *pIn, void *pData, int *pnData),
174986:   void *pInA,
174987:   int (*xInputB)(void *pIn, void *pData, int *pnData),
174988:   void *pInB,
174989:   int (*xOutput)(void *pOut, const void *pData, int nData),
174990:   void *pOut
174991: ){
174992:   sqlite3_changegroup *pGrp;
174993:   int rc;
174994: 
174995:   rc = sqlite3changegroup_new(&pGrp);
174996:   if( rc==SQLITE_OK ){
174997:     rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
174998:   }
174999:   if( rc==SQLITE_OK ){
175000:     rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
175001:   }
175002:   if( rc==SQLITE_OK ){
175003:     rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
175004:   }
175005:   sqlite3changegroup_delete(pGrp);
175006: 
175007:   return rc;
175008: }
175009: 
175010: #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
175011: 
175012: /************** End of sqlite3session.c **************************************/
175013: /************** Begin file json1.c *******************************************/
175014: /*
175015: ** 2015-08-12
175016: **
175017: ** The author disclaims copyright to this source code.  In place of
175018: ** a legal notice, here is a blessing:
175019: **
175020: **    May you do good and not evil.
175021: **    May you find forgiveness for yourself and forgive others.
175022: **    May you share freely, never taking more than you give.
175023: **
175024: ******************************************************************************
175025: **
175026: ** This SQLite extension implements JSON functions.  The interface is
175027: ** modeled after MySQL JSON functions:
175028: **
175029: **     https://dev.mysql.com/doc/refman/5.7/en/json.html
175030: **
175031: ** For the time being, all JSON is stored as pure text.  (We might add
175032: ** a JSONB type in the future which stores a binary encoding of JSON in
175033: ** a BLOB, but there is no support for JSONB in the current implementation.
175034: ** This implementation parses JSON text at 250 MB/s, so it is hard to see
175035: ** how JSONB might improve on that.)
175036: */
175037: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
175038: #if !defined(_SQLITEINT_H_)
175039: /* #include "sqlite3ext.h" */
175040: #endif
175041: SQLITE_EXTENSION_INIT1
175042: /* #include <assert.h> */
175043: /* #include <string.h> */
175044: /* #include <stdlib.h> */
175045: /* #include <stdarg.h> */
175046: 
175047: /* Mark a function parameter as unused, to suppress nuisance compiler
175048: ** warnings. */
175049: #ifndef UNUSED_PARAM
175050: # define UNUSED_PARAM(X)  (void)(X)
175051: #endif
175052: 
175053: #ifndef LARGEST_INT64
175054: # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
175055: # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
175056: #endif
175057: 
175058: /*
175059: ** Versions of isspace(), isalnum() and isdigit() to which it is safe
175060: ** to pass signed char values.
175061: */
175062: #ifdef sqlite3Isdigit
175063:    /* Use the SQLite core versions if this routine is part of the
175064:    ** SQLite amalgamation */
175065: #  define safe_isdigit(x) sqlite3Isdigit(x)
175066: #  define safe_isalnum(x) sqlite3Isalnum(x)
175067: #else
175068:    /* Use the standard library for separate compilation */
175069: #include <ctype.h>  /* amalgamator: keep */
175070: #  define safe_isdigit(x) isdigit((unsigned char)(x))
175071: #  define safe_isalnum(x) isalnum((unsigned char)(x))
175072: #endif
175073: 
175074: /*
175075: ** Growing our own isspace() routine this way is twice as fast as
175076: ** the library isspace() function, resulting in a 7% overall performance
175077: ** increase for the parser.  (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
175078: */
175079: static const char jsonIsSpace[] = {
175080:   0, 0, 0, 0, 0, 0, 0, 0,     0, 1, 1, 0, 0, 1, 0, 0,
175081:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175082:   1, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175083:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175084:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175085:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175086:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175087:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175088:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175089:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175090:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175091:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175092:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175093:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175094:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175095:   0, 0, 0, 0, 0, 0, 0, 0,     0, 0, 0, 0, 0, 0, 0, 0,
175096: };
175097: #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
175098: 
175099: #ifndef SQLITE_AMALGAMATION
175100:   /* Unsigned integer types.  These are already defined in the sqliteInt.h,
175101:   ** but the definitions need to be repeated for separate compilation. */
175102:   typedef sqlite3_uint64 u64;
175103:   typedef unsigned int u32;
175104:   typedef unsigned char u8;
175105: #endif
175106: 
175107: /* Objects */
175108: typedef struct JsonString JsonString;
175109: typedef struct JsonNode JsonNode;
175110: typedef struct JsonParse JsonParse;
175111: 
175112: /* An instance of this object represents a JSON string
175113: ** under construction.  Really, this is a generic string accumulator
175114: ** that can be and is used to create strings other than JSON.
175115: */
175116: struct JsonString {
175117:   sqlite3_context *pCtx;   /* Function context - put error messages here */
175118:   char *zBuf;              /* Append JSON content here */
175119:   u64 nAlloc;              /* Bytes of storage available in zBuf[] */
175120:   u64 nUsed;               /* Bytes of zBuf[] currently used */
175121:   u8 bStatic;              /* True if zBuf is static space */
175122:   u8 bErr;                 /* True if an error has been encountered */
175123:   char zSpace[100];        /* Initial static space */
175124: };
175125: 
175126: /* JSON type values
175127: */
175128: #define JSON_NULL     0
175129: #define JSON_TRUE     1
175130: #define JSON_FALSE    2
175131: #define JSON_INT      3
175132: #define JSON_REAL     4
175133: #define JSON_STRING   5
175134: #define JSON_ARRAY    6
175135: #define JSON_OBJECT   7
175136: 
175137: /* The "subtype" set for JSON values */
175138: #define JSON_SUBTYPE  74    /* Ascii for "J" */
175139: 
175140: /*
175141: ** Names of the various JSON types:
175142: */
175143: static const char * const jsonType[] = {
175144:   "null", "true", "false", "integer", "real", "text", "array", "object"
175145: };
175146: 
175147: /* Bit values for the JsonNode.jnFlag field
175148: */
175149: #define JNODE_RAW     0x01         /* Content is raw, not JSON encoded */
175150: #define JNODE_ESCAPE  0x02         /* Content is text with \ escapes */
175151: #define JNODE_REMOVE  0x04         /* Do not output */
175152: #define JNODE_REPLACE 0x08         /* Replace with JsonNode.iVal */
175153: #define JNODE_APPEND  0x10         /* More ARRAY/OBJECT entries at u.iAppend */
175154: #define JNODE_LABEL   0x20         /* Is a label of an object */
175155: 
175156: 
175157: /* A single node of parsed JSON
175158: */
175159: struct JsonNode {
175160:   u8 eType;              /* One of the JSON_ type values */
175161:   u8 jnFlags;            /* JNODE flags */
175162:   u8 iVal;               /* Replacement value when JNODE_REPLACE */
175163:   u32 n;                 /* Bytes of content, or number of sub-nodes */
175164:   union {
175165:     const char *zJContent; /* Content for INT, REAL, and STRING */
175166:     u32 iAppend;           /* More terms for ARRAY and OBJECT */
175167:     u32 iKey;              /* Key for ARRAY objects in json_tree() */
175168:   } u;
175169: };
175170: 
175171: /* A completely parsed JSON string
175172: */
175173: struct JsonParse {
175174:   u32 nNode;         /* Number of slots of aNode[] used */
175175:   u32 nAlloc;        /* Number of slots of aNode[] allocated */
175176:   JsonNode *aNode;   /* Array of nodes containing the parse */
175177:   const char *zJson; /* Original JSON string */
175178:   u32 *aUp;          /* Index of parent of each node */
175179:   u8 oom;            /* Set to true if out of memory */
175180:   u8 nErr;           /* Number of errors seen */
175181: };
175182: 
175183: /**************************************************************************
175184: ** Utility routines for dealing with JsonString objects
175185: **************************************************************************/
175186: 
175187: /* Set the JsonString object to an empty string
175188: */
175189: static void jsonZero(JsonString *p){
175190:   p->zBuf = p->zSpace;
175191:   p->nAlloc = sizeof(p->zSpace);
175192:   p->nUsed = 0;
175193:   p->bStatic = 1;
175194: }
175195: 
175196: /* Initialize the JsonString object
175197: */
175198: static void jsonInit(JsonString *p, sqlite3_context *pCtx){
175199:   p->pCtx = pCtx;
175200:   p->bErr = 0;
175201:   jsonZero(p);
175202: }
175203: 
175204: 
175205: /* Free all allocated memory and reset the JsonString object back to its
175206: ** initial state.
175207: */
175208: static void jsonReset(JsonString *p){
175209:   if( !p->bStatic ) sqlite3_free(p->zBuf);
175210:   jsonZero(p);
175211: }
175212: 
175213: 
175214: /* Report an out-of-memory (OOM) condition 
175215: */
175216: static void jsonOom(JsonString *p){
175217:   p->bErr = 1;
175218:   sqlite3_result_error_nomem(p->pCtx);
175219:   jsonReset(p);
175220: }
175221: 
175222: /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
175223: ** Return zero on success.  Return non-zero on an OOM error
175224: */
175225: static int jsonGrow(JsonString *p, u32 N){
175226:   u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
175227:   char *zNew;
175228:   if( p->bStatic ){
175229:     if( p->bErr ) return 1;
175230:     zNew = sqlite3_malloc64(nTotal);
175231:     if( zNew==0 ){
175232:       jsonOom(p);
175233:       return SQLITE_NOMEM;
175234:     }
175235:     memcpy(zNew, p->zBuf, (size_t)p->nUsed);
175236:     p->zBuf = zNew;
175237:     p->bStatic = 0;
175238:   }else{
175239:     zNew = sqlite3_realloc64(p->zBuf, nTotal);
175240:     if( zNew==0 ){
175241:       jsonOom(p);
175242:       return SQLITE_NOMEM;
175243:     }
175244:     p->zBuf = zNew;
175245:   }
175246:   p->nAlloc = nTotal;
175247:   return SQLITE_OK;
175248: }
175249: 
175250: /* Append N bytes from zIn onto the end of the JsonString string.
175251: */
175252: static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
175253:   if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
175254:   memcpy(p->zBuf+p->nUsed, zIn, N);
175255:   p->nUsed += N;
175256: }
175257: 
175258: /* Append formatted text (not to exceed N bytes) to the JsonString.
175259: */
175260: static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
175261:   va_list ap;
175262:   if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
175263:   va_start(ap, zFormat);
175264:   sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
175265:   va_end(ap);
175266:   p->nUsed += (int)strlen(p->zBuf+p->nUsed);
175267: }
175268: 
175269: /* Append a single character
175270: */
175271: static void jsonAppendChar(JsonString *p, char c){
175272:   if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
175273:   p->zBuf[p->nUsed++] = c;
175274: }
175275: 
175276: /* Append a comma separator to the output buffer, if the previous
175277: ** character is not '[' or '{'.
175278: */
175279: static void jsonAppendSeparator(JsonString *p){
175280:   char c;
175281:   if( p->nUsed==0 ) return;
175282:   c = p->zBuf[p->nUsed-1];
175283:   if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
175284: }
175285: 
175286: /* Append the N-byte string in zIn to the end of the JsonString string
175287: ** under construction.  Enclose the string in "..." and escape
175288: ** any double-quotes or backslash characters contained within the
175289: ** string.
175290: */
175291: static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
175292:   u32 i;
175293:   if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
175294:   p->zBuf[p->nUsed++] = '"';
175295:   for(i=0; i<N; i++){
175296:     unsigned char c = ((unsigned const char*)zIn)[i];
175297:     if( c=='"' || c=='\\' ){
175298:       json_simple_escape:
175299:       if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
175300:       p->zBuf[p->nUsed++] = '\\';
175301:     }else if( c<=0x1f ){
175302:       static const char aSpecial[] = {
175303:          0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
175304:          0, 0, 0, 0, 0, 0, 0, 0,   0,   0,   0, 0,   0,   0, 0, 0
175305:       };
175306:       assert( sizeof(aSpecial)==32 );
175307:       assert( aSpecial['\b']=='b' );
175308:       assert( aSpecial['\f']=='f' );
175309:       assert( aSpecial['\n']=='n' );
175310:       assert( aSpecial['\r']=='r' );
175311:       assert( aSpecial['\t']=='t' );
175312:       if( aSpecial[c] ){
175313:         c = aSpecial[c];
175314:         goto json_simple_escape;
175315:       }
175316:       if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
175317:       p->zBuf[p->nUsed++] = '\\';
175318:       p->zBuf[p->nUsed++] = 'u';
175319:       p->zBuf[p->nUsed++] = '0';
175320:       p->zBuf[p->nUsed++] = '0';
175321:       p->zBuf[p->nUsed++] = '0' + (c>>4);
175322:       c = "0123456789abcdef"[c&0xf];
175323:     }
175324:     p->zBuf[p->nUsed++] = c;
175325:   }
175326:   p->zBuf[p->nUsed++] = '"';
175327:   assert( p->nUsed<p->nAlloc );
175328: }
175329: 
175330: /*
175331: ** Append a function parameter value to the JSON string under 
175332: ** construction.
175333: */
175334: static void jsonAppendValue(
175335:   JsonString *p,                 /* Append to this JSON string */
175336:   sqlite3_value *pValue          /* Value to append */
175337: ){
175338:   switch( sqlite3_value_type(pValue) ){
175339:     case SQLITE_NULL: {
175340:       jsonAppendRaw(p, "null", 4);
175341:       break;
175342:     }
175343:     case SQLITE_INTEGER:
175344:     case SQLITE_FLOAT: {
175345:       const char *z = (const char*)sqlite3_value_text(pValue);
175346:       u32 n = (u32)sqlite3_value_bytes(pValue);
175347:       jsonAppendRaw(p, z, n);
175348:       break;
175349:     }
175350:     case SQLITE_TEXT: {
175351:       const char *z = (const char*)sqlite3_value_text(pValue);
175352:       u32 n = (u32)sqlite3_value_bytes(pValue);
175353:       if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
175354:         jsonAppendRaw(p, z, n);
175355:       }else{
175356:         jsonAppendString(p, z, n);
175357:       }
175358:       break;
175359:     }
175360:     default: {
175361:       if( p->bErr==0 ){
175362:         sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
175363:         p->bErr = 2;
175364:         jsonReset(p);
175365:       }
175366:       break;
175367:     }
175368:   }
175369: }
175370: 
175371: 
175372: /* Make the JSON in p the result of the SQL function.
175373: */
175374: static void jsonResult(JsonString *p){
175375:   if( p->bErr==0 ){
175376:     sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed, 
175377:                           p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
175378:                           SQLITE_UTF8);
175379:     jsonZero(p);
175380:   }
175381:   assert( p->bStatic );
175382: }
175383: 
175384: /**************************************************************************
175385: ** Utility routines for dealing with JsonNode and JsonParse objects
175386: **************************************************************************/
175387: 
175388: /*
175389: ** Return the number of consecutive JsonNode slots need to represent
175390: ** the parsed JSON at pNode.  The minimum answer is 1.  For ARRAY and
175391: ** OBJECT types, the number might be larger.
175392: **
175393: ** Appended elements are not counted.  The value returned is the number
175394: ** by which the JsonNode counter should increment in order to go to the
175395: ** next peer value.
175396: */
175397: static u32 jsonNodeSize(JsonNode *pNode){
175398:   return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
175399: }
175400: 
175401: /*
175402: ** Reclaim all memory allocated by a JsonParse object.  But do not
175403: ** delete the JsonParse object itself.
175404: */
175405: static void jsonParseReset(JsonParse *pParse){
175406:   sqlite3_free(pParse->aNode);
175407:   pParse->aNode = 0;
175408:   pParse->nNode = 0;
175409:   pParse->nAlloc = 0;
175410:   sqlite3_free(pParse->aUp);
175411:   pParse->aUp = 0;
175412: }
175413: 
175414: /*
175415: ** Convert the JsonNode pNode into a pure JSON string and
175416: ** append to pOut.  Subsubstructure is also included.  Return
175417: ** the number of JsonNode objects that are encoded.
175418: */
175419: static void jsonRenderNode(
175420:   JsonNode *pNode,               /* The node to render */
175421:   JsonString *pOut,              /* Write JSON here */
175422:   sqlite3_value **aReplace       /* Replacement values */
175423: ){
175424:   switch( pNode->eType ){
175425:     default: {
175426:       assert( pNode->eType==JSON_NULL );
175427:       jsonAppendRaw(pOut, "null", 4);
175428:       break;
175429:     }
175430:     case JSON_TRUE: {
175431:       jsonAppendRaw(pOut, "true", 4);
175432:       break;
175433:     }
175434:     case JSON_FALSE: {
175435:       jsonAppendRaw(pOut, "false", 5);
175436:       break;
175437:     }
175438:     case JSON_STRING: {
175439:       if( pNode->jnFlags & JNODE_RAW ){
175440:         jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
175441:         break;
175442:       }
175443:       /* Fall through into the next case */
175444:     }
175445:     case JSON_REAL:
175446:     case JSON_INT: {
175447:       jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
175448:       break;
175449:     }
175450:     case JSON_ARRAY: {
175451:       u32 j = 1;
175452:       jsonAppendChar(pOut, '[');
175453:       for(;;){
175454:         while( j<=pNode->n ){
175455:           if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
175456:             if( pNode[j].jnFlags & JNODE_REPLACE ){
175457:               jsonAppendSeparator(pOut);
175458:               jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
175459:             }
175460:           }else{
175461:             jsonAppendSeparator(pOut);
175462:             jsonRenderNode(&pNode[j], pOut, aReplace);
175463:           }
175464:           j += jsonNodeSize(&pNode[j]);
175465:         }
175466:         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
175467:         pNode = &pNode[pNode->u.iAppend];
175468:         j = 1;
175469:       }
175470:       jsonAppendChar(pOut, ']');
175471:       break;
175472:     }
175473:     case JSON_OBJECT: {
175474:       u32 j = 1;
175475:       jsonAppendChar(pOut, '{');
175476:       for(;;){
175477:         while( j<=pNode->n ){
175478:           if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
175479:             jsonAppendSeparator(pOut);
175480:             jsonRenderNode(&pNode[j], pOut, aReplace);
175481:             jsonAppendChar(pOut, ':');
175482:             if( pNode[j+1].jnFlags & JNODE_REPLACE ){
175483:               jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
175484:             }else{
175485:               jsonRenderNode(&pNode[j+1], pOut, aReplace);
175486:             }
175487:           }
175488:           j += 1 + jsonNodeSize(&pNode[j+1]);
175489:         }
175490:         if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
175491:         pNode = &pNode[pNode->u.iAppend];
175492:         j = 1;
175493:       }
175494:       jsonAppendChar(pOut, '}');
175495:       break;
175496:     }
175497:   }
175498: }
175499: 
175500: /*
175501: ** Return a JsonNode and all its descendents as a JSON string.
175502: */
175503: static void jsonReturnJson(
175504:   JsonNode *pNode,            /* Node to return */
175505:   sqlite3_context *pCtx,      /* Return value for this function */
175506:   sqlite3_value **aReplace    /* Array of replacement values */
175507: ){
175508:   JsonString s;
175509:   jsonInit(&s, pCtx);
175510:   jsonRenderNode(pNode, &s, aReplace);
175511:   jsonResult(&s);
175512:   sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
175513: }
175514: 
175515: /*
175516: ** Make the JsonNode the return value of the function.
175517: */
175518: static void jsonReturn(
175519:   JsonNode *pNode,            /* Node to return */
175520:   sqlite3_context *pCtx,      /* Return value for this function */
175521:   sqlite3_value **aReplace    /* Array of replacement values */
175522: ){
175523:   switch( pNode->eType ){
175524:     default: {
175525:       assert( pNode->eType==JSON_NULL );
175526:       sqlite3_result_null(pCtx);
175527:       break;
175528:     }
175529:     case JSON_TRUE: {
175530:       sqlite3_result_int(pCtx, 1);
175531:       break;
175532:     }
175533:     case JSON_FALSE: {
175534:       sqlite3_result_int(pCtx, 0);
175535:       break;
175536:     }
175537:     case JSON_INT: {
175538:       sqlite3_int64 i = 0;
175539:       const char *z = pNode->u.zJContent;
175540:       if( z[0]=='-' ){ z++; }
175541:       while( z[0]>='0' && z[0]<='9' ){
175542:         unsigned v = *(z++) - '0';
175543:         if( i>=LARGEST_INT64/10 ){
175544:           if( i>LARGEST_INT64/10 ) goto int_as_real;
175545:           if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
175546:           if( v==9 ) goto int_as_real;
175547:           if( v==8 ){
175548:             if( pNode->u.zJContent[0]=='-' ){
175549:               sqlite3_result_int64(pCtx, SMALLEST_INT64);
175550:               goto int_done;
175551:             }else{
175552:               goto int_as_real;
175553:             }
175554:           }
175555:         }
175556:         i = i*10 + v;
175557:       }
175558:       if( pNode->u.zJContent[0]=='-' ){ i = -i; }
175559:       sqlite3_result_int64(pCtx, i);
175560:       int_done:
175561:       break;
175562:       int_as_real: /* fall through to real */;
175563:     }
175564:     case JSON_REAL: {
175565:       double r;
175566: #ifdef SQLITE_AMALGAMATION
175567:       const char *z = pNode->u.zJContent;
175568:       sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
175569: #else
175570:       r = strtod(pNode->u.zJContent, 0);
175571: #endif
175572:       sqlite3_result_double(pCtx, r);
175573:       break;
175574:     }
175575:     case JSON_STRING: {
175576: #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
175577:       ** json_insert() and json_replace() and those routines do not
175578:       ** call jsonReturn() */
175579:       if( pNode->jnFlags & JNODE_RAW ){
175580:         sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
175581:                             SQLITE_TRANSIENT);
175582:       }else 
175583: #endif
175584:       assert( (pNode->jnFlags & JNODE_RAW)==0 );
175585:       if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
175586:         /* JSON formatted without any backslash-escapes */
175587:         sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
175588:                             SQLITE_TRANSIENT);
175589:       }else{
175590:         /* Translate JSON formatted string into raw text */
175591:         u32 i;
175592:         u32 n = pNode->n;
175593:         const char *z = pNode->u.zJContent;
175594:         char *zOut;
175595:         u32 j;
175596:         zOut = sqlite3_malloc( n+1 );
175597:         if( zOut==0 ){
175598:           sqlite3_result_error_nomem(pCtx);
175599:           break;
175600:         }
175601:         for(i=1, j=0; i<n-1; i++){
175602:           char c = z[i];
175603:           if( c!='\\' ){
175604:             zOut[j++] = c;
175605:           }else{
175606:             c = z[++i];
175607:             if( c=='u' ){
175608:               u32 v = 0, k;
175609:               for(k=0; k<4 && i<n-2; i++, k++){
175610:                 c = z[i+1];
175611:                 if( c>='0' && c<='9' ) v = v*16 + c - '0';
175612:                 else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
175613:                 else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
175614:                 else break;
175615:               }
175616:               if( v==0 ) break;
175617:               if( v<=0x7f ){
175618:                 zOut[j++] = (char)v;
175619:               }else if( v<=0x7ff ){
175620:                 zOut[j++] = (char)(0xc0 | (v>>6));
175621:                 zOut[j++] = 0x80 | (v&0x3f);
175622:               }else{
175623:                 zOut[j++] = (char)(0xe0 | (v>>12));
175624:                 zOut[j++] = 0x80 | ((v>>6)&0x3f);
175625:                 zOut[j++] = 0x80 | (v&0x3f);
175626:               }
175627:             }else{
175628:               if( c=='b' ){
175629:                 c = '\b';
175630:               }else if( c=='f' ){
175631:                 c = '\f';
175632:               }else if( c=='n' ){
175633:                 c = '\n';
175634:               }else if( c=='r' ){
175635:                 c = '\r';
175636:               }else if( c=='t' ){
175637:                 c = '\t';
175638:               }
175639:               zOut[j++] = c;
175640:             }
175641:           }
175642:         }
175643:         zOut[j] = 0;
175644:         sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
175645:       }
175646:       break;
175647:     }
175648:     case JSON_ARRAY:
175649:     case JSON_OBJECT: {
175650:       jsonReturnJson(pNode, pCtx, aReplace);
175651:       break;
175652:     }
175653:   }
175654: }
175655: 
175656: /* Forward reference */
175657: static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
175658: 
175659: /*
175660: ** A macro to hint to the compiler that a function should not be
175661: ** inlined.
175662: */
175663: #if defined(__GNUC__)
175664: #  define JSON_NOINLINE  __attribute__((noinline))
175665: #elif defined(_MSC_VER) && _MSC_VER>=1310
175666: #  define JSON_NOINLINE  __declspec(noinline)
175667: #else
175668: #  define JSON_NOINLINE
175669: #endif
175670: 
175671: 
175672: static JSON_NOINLINE int jsonParseAddNodeExpand(
175673:   JsonParse *pParse,        /* Append the node to this object */
175674:   u32 eType,                /* Node type */
175675:   u32 n,                    /* Content size or sub-node count */
175676:   const char *zContent      /* Content */
175677: ){
175678:   u32 nNew;
175679:   JsonNode *pNew;
175680:   assert( pParse->nNode>=pParse->nAlloc );
175681:   if( pParse->oom ) return -1;
175682:   nNew = pParse->nAlloc*2 + 10;
175683:   pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
175684:   if( pNew==0 ){
175685:     pParse->oom = 1;
175686:     return -1;
175687:   }
175688:   pParse->nAlloc = nNew;
175689:   pParse->aNode = pNew;
175690:   assert( pParse->nNode<pParse->nAlloc );
175691:   return jsonParseAddNode(pParse, eType, n, zContent);
175692: }
175693: 
175694: /*
175695: ** Create a new JsonNode instance based on the arguments and append that
175696: ** instance to the JsonParse.  Return the index in pParse->aNode[] of the
175697: ** new node, or -1 if a memory allocation fails.
175698: */
175699: static int jsonParseAddNode(
175700:   JsonParse *pParse,        /* Append the node to this object */
175701:   u32 eType,                /* Node type */
175702:   u32 n,                    /* Content size or sub-node count */
175703:   const char *zContent      /* Content */
175704: ){
175705:   JsonNode *p;
175706:   if( pParse->nNode>=pParse->nAlloc ){
175707:     return jsonParseAddNodeExpand(pParse, eType, n, zContent);
175708:   }
175709:   p = &pParse->aNode[pParse->nNode];
175710:   p->eType = (u8)eType;
175711:   p->jnFlags = 0;
175712:   p->iVal = 0;
175713:   p->n = n;
175714:   p->u.zJContent = zContent;
175715:   return pParse->nNode++;
175716: }
175717: 
175718: /*
175719: ** Parse a single JSON value which begins at pParse->zJson[i].  Return the
175720: ** index of the first character past the end of the value parsed.
175721: **
175722: ** Return negative for a syntax error.  Special cases:  return -2 if the
175723: ** first non-whitespace character is '}' and return -3 if the first
175724: ** non-whitespace character is ']'.
175725: */
175726: static int jsonParseValue(JsonParse *pParse, u32 i){
175727:   char c;
175728:   u32 j;
175729:   int iThis;
175730:   int x;
175731:   JsonNode *pNode;
175732:   while( safe_isspace(pParse->zJson[i]) ){ i++; }
175733:   if( (c = pParse->zJson[i])=='{' ){
175734:     /* Parse object */
175735:     iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
175736:     if( iThis<0 ) return -1;
175737:     for(j=i+1;;j++){
175738:       while( safe_isspace(pParse->zJson[j]) ){ j++; }
175739:       x = jsonParseValue(pParse, j);
175740:       if( x<0 ){
175741:         if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
175742:         return -1;
175743:       }
175744:       if( pParse->oom ) return -1;
175745:       pNode = &pParse->aNode[pParse->nNode-1];
175746:       if( pNode->eType!=JSON_STRING ) return -1;
175747:       pNode->jnFlags |= JNODE_LABEL;
175748:       j = x;
175749:       while( safe_isspace(pParse->zJson[j]) ){ j++; }
175750:       if( pParse->zJson[j]!=':' ) return -1;
175751:       j++;
175752:       x = jsonParseValue(pParse, j);
175753:       if( x<0 ) return -1;
175754:       j = x;
175755:       while( safe_isspace(pParse->zJson[j]) ){ j++; }
175756:       c = pParse->zJson[j];
175757:       if( c==',' ) continue;
175758:       if( c!='}' ) return -1;
175759:       break;
175760:     }
175761:     pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
175762:     return j+1;
175763:   }else if( c=='[' ){
175764:     /* Parse array */
175765:     iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
175766:     if( iThis<0 ) return -1;
175767:     for(j=i+1;;j++){
175768:       while( safe_isspace(pParse->zJson[j]) ){ j++; }
175769:       x = jsonParseValue(pParse, j);
175770:       if( x<0 ){
175771:         if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
175772:         return -1;
175773:       }
175774:       j = x;
175775:       while( safe_isspace(pParse->zJson[j]) ){ j++; }
175776:       c = pParse->zJson[j];
175777:       if( c==',' ) continue;
175778:       if( c!=']' ) return -1;
175779:       break;
175780:     }
175781:     pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
175782:     return j+1;
175783:   }else if( c=='"' ){
175784:     /* Parse string */
175785:     u8 jnFlags = 0;
175786:     j = i+1;
175787:     for(;;){
175788:       c = pParse->zJson[j];
175789:       if( c==0 ) return -1;
175790:       if( c=='\\' ){
175791:         c = pParse->zJson[++j];
175792:         if( c==0 ) return -1;
175793:         jnFlags = JNODE_ESCAPE;
175794:       }else if( c=='"' ){
175795:         break;
175796:       }
175797:       j++;
175798:     }
175799:     jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
175800:     if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
175801:     return j+1;
175802:   }else if( c=='n'
175803:          && strncmp(pParse->zJson+i,"null",4)==0
175804:          && !safe_isalnum(pParse->zJson[i+4]) ){
175805:     jsonParseAddNode(pParse, JSON_NULL, 0, 0);
175806:     return i+4;
175807:   }else if( c=='t'
175808:          && strncmp(pParse->zJson+i,"true",4)==0
175809:          && !safe_isalnum(pParse->zJson[i+4]) ){
175810:     jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
175811:     return i+4;
175812:   }else if( c=='f'
175813:          && strncmp(pParse->zJson+i,"false",5)==0
175814:          && !safe_isalnum(pParse->zJson[i+5]) ){
175815:     jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
175816:     return i+5;
175817:   }else if( c=='-' || (c>='0' && c<='9') ){
175818:     /* Parse number */
175819:     u8 seenDP = 0;
175820:     u8 seenE = 0;
175821:     j = i+1;
175822:     for(;; j++){
175823:       c = pParse->zJson[j];
175824:       if( c>='0' && c<='9' ) continue;
175825:       if( c=='.' ){
175826:         if( pParse->zJson[j-1]=='-' ) return -1;
175827:         if( seenDP ) return -1;
175828:         seenDP = 1;
175829:         continue;
175830:       }
175831:       if( c=='e' || c=='E' ){
175832:         if( pParse->zJson[j-1]<'0' ) return -1;
175833:         if( seenE ) return -1;
175834:         seenDP = seenE = 1;
175835:         c = pParse->zJson[j+1];
175836:         if( c=='+' || c=='-' ){
175837:           j++;
175838:           c = pParse->zJson[j+1];
175839:         }
175840:         if( c<'0' || c>'9' ) return -1;
175841:         continue;
175842:       }
175843:       break;
175844:     }
175845:     if( pParse->zJson[j-1]<'0' ) return -1;
175846:     jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
175847:                         j - i, &pParse->zJson[i]);
175848:     return j;
175849:   }else if( c=='}' ){
175850:     return -2;  /* End of {...} */
175851:   }else if( c==']' ){
175852:     return -3;  /* End of [...] */
175853:   }else if( c==0 ){
175854:     return 0;   /* End of file */
175855:   }else{
175856:     return -1;  /* Syntax error */
175857:   }
175858: }
175859: 
175860: /*
175861: ** Parse a complete JSON string.  Return 0 on success or non-zero if there
175862: ** are any errors.  If an error occurs, free all memory associated with
175863: ** pParse.
175864: **
175865: ** pParse is uninitialized when this routine is called.
175866: */
175867: static int jsonParse(
175868:   JsonParse *pParse,           /* Initialize and fill this JsonParse object */
175869:   sqlite3_context *pCtx,       /* Report errors here */
175870:   const char *zJson            /* Input JSON text to be parsed */
175871: ){
175872:   int i;
175873:   memset(pParse, 0, sizeof(*pParse));
175874:   if( zJson==0 ) return 1;
175875:   pParse->zJson = zJson;
175876:   i = jsonParseValue(pParse, 0);
175877:   if( pParse->oom ) i = -1;
175878:   if( i>0 ){
175879:     while( safe_isspace(zJson[i]) ) i++;
175880:     if( zJson[i] ) i = -1;
175881:   }
175882:   if( i<=0 ){
175883:     if( pCtx!=0 ){
175884:       if( pParse->oom ){
175885:         sqlite3_result_error_nomem(pCtx);
175886:       }else{
175887:         sqlite3_result_error(pCtx, "malformed JSON", -1);
175888:       }
175889:     }
175890:     jsonParseReset(pParse);
175891:     return 1;
175892:   }
175893:   return 0;
175894: }
175895: 
175896: /* Mark node i of pParse as being a child of iParent.  Call recursively
175897: ** to fill in all the descendants of node i.
175898: */
175899: static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
175900:   JsonNode *pNode = &pParse->aNode[i];
175901:   u32 j;
175902:   pParse->aUp[i] = iParent;
175903:   switch( pNode->eType ){
175904:     case JSON_ARRAY: {
175905:       for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
175906:         jsonParseFillInParentage(pParse, i+j, i);
175907:       }
175908:       break;
175909:     }
175910:     case JSON_OBJECT: {
175911:       for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
175912:         pParse->aUp[i+j] = i;
175913:         jsonParseFillInParentage(pParse, i+j+1, i);
175914:       }
175915:       break;
175916:     }
175917:     default: {
175918:       break;
175919:     }
175920:   }
175921: }
175922: 
175923: /*
175924: ** Compute the parentage of all nodes in a completed parse.
175925: */
175926: static int jsonParseFindParents(JsonParse *pParse){
175927:   u32 *aUp;
175928:   assert( pParse->aUp==0 );
175929:   aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
175930:   if( aUp==0 ){
175931:     pParse->oom = 1;
175932:     return SQLITE_NOMEM;
175933:   }
175934:   jsonParseFillInParentage(pParse, 0, 0);
175935:   return SQLITE_OK;
175936: }
175937: 
175938: /*
175939: ** Compare the OBJECT label at pNode against zKey,nKey.  Return true on
175940: ** a match.
175941: */
175942: static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
175943:   if( pNode->jnFlags & JNODE_RAW ){
175944:     if( pNode->n!=nKey ) return 0;
175945:     return strncmp(pNode->u.zJContent, zKey, nKey)==0;
175946:   }else{
175947:     if( pNode->n!=nKey+2 ) return 0;
175948:     return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
175949:   }
175950: }
175951: 
175952: /* forward declaration */
175953: static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
175954: 
175955: /*
175956: ** Search along zPath to find the node specified.  Return a pointer
175957: ** to that node, or NULL if zPath is malformed or if there is no such
175958: ** node.
175959: **
175960: ** If pApnd!=0, then try to append new nodes to complete zPath if it is
175961: ** possible to do so and if no existing node corresponds to zPath.  If
175962: ** new nodes are appended *pApnd is set to 1.
175963: */
175964: static JsonNode *jsonLookupStep(
175965:   JsonParse *pParse,      /* The JSON to search */
175966:   u32 iRoot,              /* Begin the search at this node */
175967:   const char *zPath,      /* The path to search */
175968:   int *pApnd,             /* Append nodes to complete path if not NULL */
175969:   const char **pzErr      /* Make *pzErr point to any syntax error in zPath */
175970: ){
175971:   u32 i, j, nKey;
175972:   const char *zKey;
175973:   JsonNode *pRoot = &pParse->aNode[iRoot];
175974:   if( zPath[0]==0 ) return pRoot;
175975:   if( zPath[0]=='.' ){
175976:     if( pRoot->eType!=JSON_OBJECT ) return 0;
175977:     zPath++;
175978:     if( zPath[0]=='"' ){
175979:       zKey = zPath + 1;
175980:       for(i=1; zPath[i] && zPath[i]!='"'; i++){}
175981:       nKey = i-1;
175982:       if( zPath[i] ){
175983:         i++;
175984:       }else{
175985:         *pzErr = zPath;
175986:         return 0;
175987:       }
175988:     }else{
175989:       zKey = zPath;
175990:       for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
175991:       nKey = i;
175992:     }
175993:     if( nKey==0 ){
175994:       *pzErr = zPath;
175995:       return 0;
175996:     }
175997:     j = 1;
175998:     for(;;){
175999:       while( j<=pRoot->n ){
176000:         if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
176001:           return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
176002:         }
176003:         j++;
176004:         j += jsonNodeSize(&pRoot[j]);
176005:       }
176006:       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
176007:       iRoot += pRoot->u.iAppend;
176008:       pRoot = &pParse->aNode[iRoot];
176009:       j = 1;
176010:     }
176011:     if( pApnd ){
176012:       u32 iStart, iLabel;
176013:       JsonNode *pNode;
176014:       iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
176015:       iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
176016:       zPath += i;
176017:       pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
176018:       if( pParse->oom ) return 0;
176019:       if( pNode ){
176020:         pRoot = &pParse->aNode[iRoot];
176021:         pRoot->u.iAppend = iStart - iRoot;
176022:         pRoot->jnFlags |= JNODE_APPEND;
176023:         pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
176024:       }
176025:       return pNode;
176026:     }
176027:   }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
176028:     if( pRoot->eType!=JSON_ARRAY ) return 0;
176029:     i = 0;
176030:     j = 1;
176031:     while( safe_isdigit(zPath[j]) ){
176032:       i = i*10 + zPath[j] - '0';
176033:       j++;
176034:     }
176035:     if( zPath[j]!=']' ){
176036:       *pzErr = zPath;
176037:       return 0;
176038:     }
176039:     zPath += j + 1;
176040:     j = 1;
176041:     for(;;){
176042:       while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
176043:         if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
176044:         j += jsonNodeSize(&pRoot[j]);
176045:       }
176046:       if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
176047:       iRoot += pRoot->u.iAppend;
176048:       pRoot = &pParse->aNode[iRoot];
176049:       j = 1;
176050:     }
176051:     if( j<=pRoot->n ){
176052:       return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
176053:     }
176054:     if( i==0 && pApnd ){
176055:       u32 iStart;
176056:       JsonNode *pNode;
176057:       iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
176058:       pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
176059:       if( pParse->oom ) return 0;
176060:       if( pNode ){
176061:         pRoot = &pParse->aNode[iRoot];
176062:         pRoot->u.iAppend = iStart - iRoot;
176063:         pRoot->jnFlags |= JNODE_APPEND;
176064:       }
176065:       return pNode;
176066:     }
176067:   }else{
176068:     *pzErr = zPath;
176069:   }
176070:   return 0;
176071: }
176072: 
176073: /*
176074: ** Append content to pParse that will complete zPath.  Return a pointer
176075: ** to the inserted node, or return NULL if the append fails.
176076: */
176077: static JsonNode *jsonLookupAppend(
176078:   JsonParse *pParse,     /* Append content to the JSON parse */
176079:   const char *zPath,     /* Description of content to append */
176080:   int *pApnd,            /* Set this flag to 1 */
176081:   const char **pzErr     /* Make this point to any syntax error */
176082: ){
176083:   *pApnd = 1;
176084:   if( zPath[0]==0 ){
176085:     jsonParseAddNode(pParse, JSON_NULL, 0, 0);
176086:     return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
176087:   }
176088:   if( zPath[0]=='.' ){
176089:     jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
176090:   }else if( strncmp(zPath,"[0]",3)==0 ){
176091:     jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
176092:   }else{
176093:     return 0;
176094:   }
176095:   if( pParse->oom ) return 0;
176096:   return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
176097: }
176098: 
176099: /*
176100: ** Return the text of a syntax error message on a JSON path.  Space is
176101: ** obtained from sqlite3_malloc().
176102: */
176103: static char *jsonPathSyntaxError(const char *zErr){
176104:   return sqlite3_mprintf("JSON path error near '%q'", zErr);
176105: }
176106: 
176107: /*
176108: ** Do a node lookup using zPath.  Return a pointer to the node on success.
176109: ** Return NULL if not found or if there is an error.
176110: **
176111: ** On an error, write an error message into pCtx and increment the
176112: ** pParse->nErr counter.
176113: **
176114: ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
176115: ** nodes are appended.
176116: */
176117: static JsonNode *jsonLookup(
176118:   JsonParse *pParse,      /* The JSON to search */
176119:   const char *zPath,      /* The path to search */
176120:   int *pApnd,             /* Append nodes to complete path if not NULL */
176121:   sqlite3_context *pCtx   /* Report errors here, if not NULL */
176122: ){
176123:   const char *zErr = 0;
176124:   JsonNode *pNode = 0;
176125:   char *zMsg;
176126: 
176127:   if( zPath==0 ) return 0;
176128:   if( zPath[0]!='$' ){
176129:     zErr = zPath;
176130:     goto lookup_err;
176131:   }
176132:   zPath++;
176133:   pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
176134:   if( zErr==0 ) return pNode;
176135: 
176136: lookup_err:
176137:   pParse->nErr++;
176138:   assert( zErr!=0 && pCtx!=0 );
176139:   zMsg = jsonPathSyntaxError(zErr);
176140:   if( zMsg ){
176141:     sqlite3_result_error(pCtx, zMsg, -1);
176142:     sqlite3_free(zMsg);
176143:   }else{
176144:     sqlite3_result_error_nomem(pCtx);
176145:   }
176146:   return 0;
176147: }
176148: 
176149: 
176150: /*
176151: ** Report the wrong number of arguments for json_insert(), json_replace()
176152: ** or json_set().
176153: */
176154: static void jsonWrongNumArgs(
176155:   sqlite3_context *pCtx,
176156:   const char *zFuncName
176157: ){
176158:   char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
176159:                                zFuncName);
176160:   sqlite3_result_error(pCtx, zMsg, -1);
176161:   sqlite3_free(zMsg);     
176162: }
176163: 
176164: 
176165: /****************************************************************************
176166: ** SQL functions used for testing and debugging
176167: ****************************************************************************/
176168: 
176169: #ifdef SQLITE_DEBUG
176170: /*
176171: ** The json_parse(JSON) function returns a string which describes
176172: ** a parse of the JSON provided.  Or it returns NULL if JSON is not
176173: ** well-formed.
176174: */
176175: static void jsonParseFunc(
176176:   sqlite3_context *ctx,
176177:   int argc,
176178:   sqlite3_value **argv
176179: ){
176180:   JsonString s;       /* Output string - not real JSON */
176181:   JsonParse x;        /* The parse */
176182:   u32 i;
176183: 
176184:   assert( argc==1 );
176185:   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176186:   jsonParseFindParents(&x);
176187:   jsonInit(&s, ctx);
176188:   for(i=0; i<x.nNode; i++){
176189:     const char *zType;
176190:     if( x.aNode[i].jnFlags & JNODE_LABEL ){
176191:       assert( x.aNode[i].eType==JSON_STRING );
176192:       zType = "label";
176193:     }else{
176194:       zType = jsonType[x.aNode[i].eType];
176195:     }
176196:     jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
176197:                i, zType, x.aNode[i].n, x.aUp[i]);
176198:     if( x.aNode[i].u.zJContent!=0 ){
176199:       jsonAppendRaw(&s, " ", 1);
176200:       jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
176201:     }
176202:     jsonAppendRaw(&s, "\n", 1);
176203:   }
176204:   jsonParseReset(&x);
176205:   jsonResult(&s);
176206: }
176207: 
176208: /*
176209: ** The json_test1(JSON) function return true (1) if the input is JSON
176210: ** text generated by another json function.  It returns (0) if the input
176211: ** is not known to be JSON.
176212: */
176213: static void jsonTest1Func(
176214:   sqlite3_context *ctx,
176215:   int argc,
176216:   sqlite3_value **argv
176217: ){
176218:   UNUSED_PARAM(argc);
176219:   sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
176220: }
176221: #endif /* SQLITE_DEBUG */
176222: 
176223: /****************************************************************************
176224: ** Scalar SQL function implementations
176225: ****************************************************************************/
176226: 
176227: /*
176228: ** Implementation of the json_QUOTE(VALUE) function.  Return a JSON value
176229: ** corresponding to the SQL value input.  Mostly this means putting 
176230: ** double-quotes around strings and returning the unquoted string "null"
176231: ** when given a NULL input.
176232: */
176233: static void jsonQuoteFunc(
176234:   sqlite3_context *ctx,
176235:   int argc,
176236:   sqlite3_value **argv
176237: ){
176238:   JsonString jx;
176239:   UNUSED_PARAM(argc);
176240: 
176241:   jsonInit(&jx, ctx);
176242:   jsonAppendValue(&jx, argv[0]);
176243:   jsonResult(&jx);
176244:   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176245: }
176246: 
176247: /*
176248: ** Implementation of the json_array(VALUE,...) function.  Return a JSON
176249: ** array that contains all values given in arguments.  Or if any argument
176250: ** is a BLOB, throw an error.
176251: */
176252: static void jsonArrayFunc(
176253:   sqlite3_context *ctx,
176254:   int argc,
176255:   sqlite3_value **argv
176256: ){
176257:   int i;
176258:   JsonString jx;
176259: 
176260:   jsonInit(&jx, ctx);
176261:   jsonAppendChar(&jx, '[');
176262:   for(i=0; i<argc; i++){
176263:     jsonAppendSeparator(&jx);
176264:     jsonAppendValue(&jx, argv[i]);
176265:   }
176266:   jsonAppendChar(&jx, ']');
176267:   jsonResult(&jx);
176268:   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176269: }
176270: 
176271: 
176272: /*
176273: ** json_array_length(JSON)
176274: ** json_array_length(JSON, PATH)
176275: **
176276: ** Return the number of elements in the top-level JSON array.  
176277: ** Return 0 if the input is not a well-formed JSON array.
176278: */
176279: static void jsonArrayLengthFunc(
176280:   sqlite3_context *ctx,
176281:   int argc,
176282:   sqlite3_value **argv
176283: ){
176284:   JsonParse x;          /* The parse */
176285:   sqlite3_int64 n = 0;
176286:   u32 i;
176287:   JsonNode *pNode;
176288: 
176289:   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176290:   assert( x.nNode );
176291:   if( argc==2 ){
176292:     const char *zPath = (const char*)sqlite3_value_text(argv[1]);
176293:     pNode = jsonLookup(&x, zPath, 0, ctx);
176294:   }else{
176295:     pNode = x.aNode;
176296:   }
176297:   if( pNode==0 ){
176298:     x.nErr = 1;
176299:   }else if( pNode->eType==JSON_ARRAY ){
176300:     assert( (pNode->jnFlags & JNODE_APPEND)==0 );
176301:     for(i=1; i<=pNode->n; n++){
176302:       i += jsonNodeSize(&pNode[i]);
176303:     }
176304:   }
176305:   if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
176306:   jsonParseReset(&x);
176307: }
176308: 
176309: /*
176310: ** json_extract(JSON, PATH, ...)
176311: **
176312: ** Return the element described by PATH.  Return NULL if there is no
176313: ** PATH element.  If there are multiple PATHs, then return a JSON array
176314: ** with the result from each path.  Throw an error if the JSON or any PATH
176315: ** is malformed.
176316: */
176317: static void jsonExtractFunc(
176318:   sqlite3_context *ctx,
176319:   int argc,
176320:   sqlite3_value **argv
176321: ){
176322:   JsonParse x;          /* The parse */
176323:   JsonNode *pNode;
176324:   const char *zPath;
176325:   JsonString jx;
176326:   int i;
176327: 
176328:   if( argc<2 ) return;
176329:   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176330:   jsonInit(&jx, ctx);
176331:   jsonAppendChar(&jx, '[');
176332:   for(i=1; i<argc; i++){
176333:     zPath = (const char*)sqlite3_value_text(argv[i]);
176334:     pNode = jsonLookup(&x, zPath, 0, ctx);
176335:     if( x.nErr ) break;
176336:     if( argc>2 ){
176337:       jsonAppendSeparator(&jx);
176338:       if( pNode ){
176339:         jsonRenderNode(pNode, &jx, 0);
176340:       }else{
176341:         jsonAppendRaw(&jx, "null", 4);
176342:       }
176343:     }else if( pNode ){
176344:       jsonReturn(pNode, ctx, 0);
176345:     }
176346:   }
176347:   if( argc>2 && i==argc ){
176348:     jsonAppendChar(&jx, ']');
176349:     jsonResult(&jx);
176350:     sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176351:   }
176352:   jsonReset(&jx);
176353:   jsonParseReset(&x);
176354: }
176355: 
176356: /*
176357: ** Implementation of the json_object(NAME,VALUE,...) function.  Return a JSON
176358: ** object that contains all name/value given in arguments.  Or if any name
176359: ** is not a string or if any value is a BLOB, throw an error.
176360: */
176361: static void jsonObjectFunc(
176362:   sqlite3_context *ctx,
176363:   int argc,
176364:   sqlite3_value **argv
176365: ){
176366:   int i;
176367:   JsonString jx;
176368:   const char *z;
176369:   u32 n;
176370: 
176371:   if( argc&1 ){
176372:     sqlite3_result_error(ctx, "json_object() requires an even number "
176373:                                   "of arguments", -1);
176374:     return;
176375:   }
176376:   jsonInit(&jx, ctx);
176377:   jsonAppendChar(&jx, '{');
176378:   for(i=0; i<argc; i+=2){
176379:     if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
176380:       sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
176381:       jsonReset(&jx);
176382:       return;
176383:     }
176384:     jsonAppendSeparator(&jx);
176385:     z = (const char*)sqlite3_value_text(argv[i]);
176386:     n = (u32)sqlite3_value_bytes(argv[i]);
176387:     jsonAppendString(&jx, z, n);
176388:     jsonAppendChar(&jx, ':');
176389:     jsonAppendValue(&jx, argv[i+1]);
176390:   }
176391:   jsonAppendChar(&jx, '}');
176392:   jsonResult(&jx);
176393:   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176394: }
176395: 
176396: 
176397: /*
176398: ** json_remove(JSON, PATH, ...)
176399: **
176400: ** Remove the named elements from JSON and return the result.  malformed
176401: ** JSON or PATH arguments result in an error.
176402: */
176403: static void jsonRemoveFunc(
176404:   sqlite3_context *ctx,
176405:   int argc,
176406:   sqlite3_value **argv
176407: ){
176408:   JsonParse x;          /* The parse */
176409:   JsonNode *pNode;
176410:   const char *zPath;
176411:   u32 i;
176412: 
176413:   if( argc<1 ) return;
176414:   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176415:   assert( x.nNode );
176416:   for(i=1; i<(u32)argc; i++){
176417:     zPath = (const char*)sqlite3_value_text(argv[i]);
176418:     if( zPath==0 ) goto remove_done;
176419:     pNode = jsonLookup(&x, zPath, 0, ctx);
176420:     if( x.nErr ) goto remove_done;
176421:     if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
176422:   }
176423:   if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
176424:     jsonReturnJson(x.aNode, ctx, 0);
176425:   }
176426: remove_done:
176427:   jsonParseReset(&x);
176428: }
176429: 
176430: /*
176431: ** json_replace(JSON, PATH, VALUE, ...)
176432: **
176433: ** Replace the value at PATH with VALUE.  If PATH does not already exist,
176434: ** this routine is a no-op.  If JSON or PATH is malformed, throw an error.
176435: */
176436: static void jsonReplaceFunc(
176437:   sqlite3_context *ctx,
176438:   int argc,
176439:   sqlite3_value **argv
176440: ){
176441:   JsonParse x;          /* The parse */
176442:   JsonNode *pNode;
176443:   const char *zPath;
176444:   u32 i;
176445: 
176446:   if( argc<1 ) return;
176447:   if( (argc&1)==0 ) {
176448:     jsonWrongNumArgs(ctx, "replace");
176449:     return;
176450:   }
176451:   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176452:   assert( x.nNode );
176453:   for(i=1; i<(u32)argc; i+=2){
176454:     zPath = (const char*)sqlite3_value_text(argv[i]);
176455:     pNode = jsonLookup(&x, zPath, 0, ctx);
176456:     if( x.nErr ) goto replace_err;
176457:     if( pNode ){
176458:       pNode->jnFlags |= (u8)JNODE_REPLACE;
176459:       pNode->iVal = (u8)(i+1);
176460:     }
176461:   }
176462:   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
176463:     sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
176464:   }else{
176465:     jsonReturnJson(x.aNode, ctx, argv);
176466:   }
176467: replace_err:
176468:   jsonParseReset(&x);
176469: }
176470: 
176471: /*
176472: ** json_set(JSON, PATH, VALUE, ...)
176473: **
176474: ** Set the value at PATH to VALUE.  Create the PATH if it does not already
176475: ** exist.  Overwrite existing values that do exist.
176476: ** If JSON or PATH is malformed, throw an error.
176477: **
176478: ** json_insert(JSON, PATH, VALUE, ...)
176479: **
176480: ** Create PATH and initialize it to VALUE.  If PATH already exists, this
176481: ** routine is a no-op.  If JSON or PATH is malformed, throw an error.
176482: */
176483: static void jsonSetFunc(
176484:   sqlite3_context *ctx,
176485:   int argc,
176486:   sqlite3_value **argv
176487: ){
176488:   JsonParse x;          /* The parse */
176489:   JsonNode *pNode;
176490:   const char *zPath;
176491:   u32 i;
176492:   int bApnd;
176493:   int bIsSet = *(int*)sqlite3_user_data(ctx);
176494: 
176495:   if( argc<1 ) return;
176496:   if( (argc&1)==0 ) {
176497:     jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
176498:     return;
176499:   }
176500:   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176501:   assert( x.nNode );
176502:   for(i=1; i<(u32)argc; i+=2){
176503:     zPath = (const char*)sqlite3_value_text(argv[i]);
176504:     bApnd = 0;
176505:     pNode = jsonLookup(&x, zPath, &bApnd, ctx);
176506:     if( x.oom ){
176507:       sqlite3_result_error_nomem(ctx);
176508:       goto jsonSetDone;
176509:     }else if( x.nErr ){
176510:       goto jsonSetDone;
176511:     }else if( pNode && (bApnd || bIsSet) ){
176512:       pNode->jnFlags |= (u8)JNODE_REPLACE;
176513:       pNode->iVal = (u8)(i+1);
176514:     }
176515:   }
176516:   if( x.aNode[0].jnFlags & JNODE_REPLACE ){
176517:     sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
176518:   }else{
176519:     jsonReturnJson(x.aNode, ctx, argv);
176520:   }
176521: jsonSetDone:
176522:   jsonParseReset(&x);
176523: }
176524: 
176525: /*
176526: ** json_type(JSON)
176527: ** json_type(JSON, PATH)
176528: **
176529: ** Return the top-level "type" of a JSON string.  Throw an error if
176530: ** either the JSON or PATH inputs are not well-formed.
176531: */
176532: static void jsonTypeFunc(
176533:   sqlite3_context *ctx,
176534:   int argc,
176535:   sqlite3_value **argv
176536: ){
176537:   JsonParse x;          /* The parse */
176538:   const char *zPath;
176539:   JsonNode *pNode;
176540: 
176541:   if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
176542:   assert( x.nNode );
176543:   if( argc==2 ){
176544:     zPath = (const char*)sqlite3_value_text(argv[1]);
176545:     pNode = jsonLookup(&x, zPath, 0, ctx);
176546:   }else{
176547:     pNode = x.aNode;
176548:   }
176549:   if( pNode ){
176550:     sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
176551:   }
176552:   jsonParseReset(&x);
176553: }
176554: 
176555: /*
176556: ** json_valid(JSON)
176557: **
176558: ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
176559: ** Return 0 otherwise.
176560: */
176561: static void jsonValidFunc(
176562:   sqlite3_context *ctx,
176563:   int argc,
176564:   sqlite3_value **argv
176565: ){
176566:   JsonParse x;          /* The parse */
176567:   int rc = 0;
176568: 
176569:   UNUSED_PARAM(argc);
176570:   if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
176571:     rc = 1;
176572:   }
176573:   jsonParseReset(&x);
176574:   sqlite3_result_int(ctx, rc);
176575: }
176576: 
176577: 
176578: /****************************************************************************
176579: ** Aggregate SQL function implementations
176580: ****************************************************************************/
176581: /*
176582: ** json_group_array(VALUE)
176583: **
176584: ** Return a JSON array composed of all values in the aggregate.
176585: */
176586: static void jsonArrayStep(
176587:   sqlite3_context *ctx,
176588:   int argc,
176589:   sqlite3_value **argv
176590: ){
176591:   JsonString *pStr;
176592:   UNUSED_PARAM(argc);
176593:   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
176594:   if( pStr ){
176595:     if( pStr->zBuf==0 ){
176596:       jsonInit(pStr, ctx);
176597:       jsonAppendChar(pStr, '[');
176598:     }else{
176599:       jsonAppendChar(pStr, ',');
176600:       pStr->pCtx = ctx;
176601:     }
176602:     jsonAppendValue(pStr, argv[0]);
176603:   }
176604: }
176605: static void jsonArrayFinal(sqlite3_context *ctx){
176606:   JsonString *pStr;
176607:   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
176608:   if( pStr ){
176609:     pStr->pCtx = ctx;
176610:     jsonAppendChar(pStr, ']');
176611:     if( pStr->bErr ){
176612:       if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
176613:       assert( pStr->bStatic );
176614:     }else{
176615:       sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
176616:                           pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
176617:       pStr->bStatic = 1;
176618:     }
176619:   }else{
176620:     sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
176621:   }
176622:   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176623: }
176624: 
176625: /*
176626: ** json_group_obj(NAME,VALUE)
176627: **
176628: ** Return a JSON object composed of all names and values in the aggregate.
176629: */
176630: static void jsonObjectStep(
176631:   sqlite3_context *ctx,
176632:   int argc,
176633:   sqlite3_value **argv
176634: ){
176635:   JsonString *pStr;
176636:   const char *z;
176637:   u32 n;
176638:   UNUSED_PARAM(argc);
176639:   pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
176640:   if( pStr ){
176641:     if( pStr->zBuf==0 ){
176642:       jsonInit(pStr, ctx);
176643:       jsonAppendChar(pStr, '{');
176644:     }else{
176645:       jsonAppendChar(pStr, ',');
176646:       pStr->pCtx = ctx;
176647:     }
176648:     z = (const char*)sqlite3_value_text(argv[0]);
176649:     n = (u32)sqlite3_value_bytes(argv[0]);
176650:     jsonAppendString(pStr, z, n);
176651:     jsonAppendChar(pStr, ':');
176652:     jsonAppendValue(pStr, argv[1]);
176653:   }
176654: }
176655: static void jsonObjectFinal(sqlite3_context *ctx){
176656:   JsonString *pStr;
176657:   pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
176658:   if( pStr ){
176659:     jsonAppendChar(pStr, '}');
176660:     if( pStr->bErr ){
176661:       if( pStr->bErr==0 ) sqlite3_result_error_nomem(ctx);
176662:       assert( pStr->bStatic );
176663:     }else{
176664:       sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
176665:                           pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
176666:       pStr->bStatic = 1;
176667:     }
176668:   }else{
176669:     sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
176670:   }
176671:   sqlite3_result_subtype(ctx, JSON_SUBTYPE);
176672: }
176673: 
176674: 
176675: #ifndef SQLITE_OMIT_VIRTUALTABLE
176676: /****************************************************************************
176677: ** The json_each virtual table
176678: ****************************************************************************/
176679: typedef struct JsonEachCursor JsonEachCursor;
176680: struct JsonEachCursor {
176681:   sqlite3_vtab_cursor base;  /* Base class - must be first */
176682:   u32 iRowid;                /* The rowid */
176683:   u32 iBegin;                /* The first node of the scan */
176684:   u32 i;                     /* Index in sParse.aNode[] of current row */
176685:   u32 iEnd;                  /* EOF when i equals or exceeds this value */
176686:   u8 eType;                  /* Type of top-level element */
176687:   u8 bRecursive;             /* True for json_tree().  False for json_each() */
176688:   char *zJson;               /* Input JSON */
176689:   char *zRoot;               /* Path by which to filter zJson */
176690:   JsonParse sParse;          /* Parse of the input JSON */
176691: };
176692: 
176693: /* Constructor for the json_each virtual table */
176694: static int jsonEachConnect(
176695:   sqlite3 *db,
176696:   void *pAux,
176697:   int argc, const char *const*argv,
176698:   sqlite3_vtab **ppVtab,
176699:   char **pzErr
176700: ){
176701:   sqlite3_vtab *pNew;
176702:   int rc;
176703: 
176704: /* Column numbers */
176705: #define JEACH_KEY     0
176706: #define JEACH_VALUE   1
176707: #define JEACH_TYPE    2
176708: #define JEACH_ATOM    3
176709: #define JEACH_ID      4
176710: #define JEACH_PARENT  5
176711: #define JEACH_FULLKEY 6
176712: #define JEACH_PATH    7
176713: #define JEACH_JSON    8
176714: #define JEACH_ROOT    9
176715: 
176716:   UNUSED_PARAM(pzErr);
176717:   UNUSED_PARAM(argv);
176718:   UNUSED_PARAM(argc);
176719:   UNUSED_PARAM(pAux);
176720:   rc = sqlite3_declare_vtab(db, 
176721:      "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
176722:                     "json HIDDEN,root HIDDEN)");
176723:   if( rc==SQLITE_OK ){
176724:     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
176725:     if( pNew==0 ) return SQLITE_NOMEM;
176726:     memset(pNew, 0, sizeof(*pNew));
176727:   }
176728:   return rc;
176729: }
176730: 
176731: /* destructor for json_each virtual table */
176732: static int jsonEachDisconnect(sqlite3_vtab *pVtab){
176733:   sqlite3_free(pVtab);
176734:   return SQLITE_OK;
176735: }
176736: 
176737: /* constructor for a JsonEachCursor object for json_each(). */
176738: static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
176739:   JsonEachCursor *pCur;
176740: 
176741:   UNUSED_PARAM(p);
176742:   pCur = sqlite3_malloc( sizeof(*pCur) );
176743:   if( pCur==0 ) return SQLITE_NOMEM;
176744:   memset(pCur, 0, sizeof(*pCur));
176745:   *ppCursor = &pCur->base;
176746:   return SQLITE_OK;
176747: }
176748: 
176749: /* constructor for a JsonEachCursor object for json_tree(). */
176750: static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
176751:   int rc = jsonEachOpenEach(p, ppCursor);
176752:   if( rc==SQLITE_OK ){
176753:     JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
176754:     pCur->bRecursive = 1;
176755:   }
176756:   return rc;
176757: }
176758: 
176759: /* Reset a JsonEachCursor back to its original state.  Free any memory
176760: ** held. */
176761: static void jsonEachCursorReset(JsonEachCursor *p){
176762:   sqlite3_free(p->zJson);
176763:   sqlite3_free(p->zRoot);
176764:   jsonParseReset(&p->sParse);
176765:   p->iRowid = 0;
176766:   p->i = 0;
176767:   p->iEnd = 0;
176768:   p->eType = 0;
176769:   p->zJson = 0;
176770:   p->zRoot = 0;
176771: }
176772: 
176773: /* Destructor for a jsonEachCursor object */
176774: static int jsonEachClose(sqlite3_vtab_cursor *cur){
176775:   JsonEachCursor *p = (JsonEachCursor*)cur;
176776:   jsonEachCursorReset(p);
176777:   sqlite3_free(cur);
176778:   return SQLITE_OK;
176779: }
176780: 
176781: /* Return TRUE if the jsonEachCursor object has been advanced off the end
176782: ** of the JSON object */
176783: static int jsonEachEof(sqlite3_vtab_cursor *cur){
176784:   JsonEachCursor *p = (JsonEachCursor*)cur;
176785:   return p->i >= p->iEnd;
176786: }
176787: 
176788: /* Advance the cursor to the next element for json_tree() */
176789: static int jsonEachNext(sqlite3_vtab_cursor *cur){
176790:   JsonEachCursor *p = (JsonEachCursor*)cur;
176791:   if( p->bRecursive ){
176792:     if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
176793:     p->i++;
176794:     p->iRowid++;
176795:     if( p->i<p->iEnd ){
176796:       u32 iUp = p->sParse.aUp[p->i];
176797:       JsonNode *pUp = &p->sParse.aNode[iUp];
176798:       p->eType = pUp->eType;
176799:       if( pUp->eType==JSON_ARRAY ){
176800:         if( iUp==p->i-1 ){
176801:           pUp->u.iKey = 0;
176802:         }else{
176803:           pUp->u.iKey++;
176804:         }
176805:       }
176806:     }
176807:   }else{
176808:     switch( p->eType ){
176809:       case JSON_ARRAY: {
176810:         p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
176811:         p->iRowid++;
176812:         break;
176813:       }
176814:       case JSON_OBJECT: {
176815:         p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
176816:         p->iRowid++;
176817:         break;
176818:       }
176819:       default: {
176820:         p->i = p->iEnd;
176821:         break;
176822:       }
176823:     }
176824:   }
176825:   return SQLITE_OK;
176826: }
176827: 
176828: /* Append the name of the path for element i to pStr
176829: */
176830: static void jsonEachComputePath(
176831:   JsonEachCursor *p,       /* The cursor */
176832:   JsonString *pStr,        /* Write the path here */
176833:   u32 i                    /* Path to this element */
176834: ){
176835:   JsonNode *pNode, *pUp;
176836:   u32 iUp;
176837:   if( i==0 ){
176838:     jsonAppendChar(pStr, '$');
176839:     return;
176840:   }
176841:   iUp = p->sParse.aUp[i];
176842:   jsonEachComputePath(p, pStr, iUp);
176843:   pNode = &p->sParse.aNode[i];
176844:   pUp = &p->sParse.aNode[iUp];
176845:   if( pUp->eType==JSON_ARRAY ){
176846:     jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
176847:   }else{
176848:     assert( pUp->eType==JSON_OBJECT );
176849:     if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
176850:     assert( pNode->eType==JSON_STRING );
176851:     assert( pNode->jnFlags & JNODE_LABEL );
176852:     jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
176853:   }
176854: }
176855: 
176856: /* Return the value of a column */
176857: static int jsonEachColumn(
176858:   sqlite3_vtab_cursor *cur,   /* The cursor */
176859:   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
176860:   int i                       /* Which column to return */
176861: ){
176862:   JsonEachCursor *p = (JsonEachCursor*)cur;
176863:   JsonNode *pThis = &p->sParse.aNode[p->i];
176864:   switch( i ){
176865:     case JEACH_KEY: {
176866:       if( p->i==0 ) break;
176867:       if( p->eType==JSON_OBJECT ){
176868:         jsonReturn(pThis, ctx, 0);
176869:       }else if( p->eType==JSON_ARRAY ){
176870:         u32 iKey;
176871:         if( p->bRecursive ){
176872:           if( p->iRowid==0 ) break;
176873:           iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
176874:         }else{
176875:           iKey = p->iRowid;
176876:         }
176877:         sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
176878:       }
176879:       break;
176880:     }
176881:     case JEACH_VALUE: {
176882:       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176883:       jsonReturn(pThis, ctx, 0);
176884:       break;
176885:     }
176886:     case JEACH_TYPE: {
176887:       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176888:       sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
176889:       break;
176890:     }
176891:     case JEACH_ATOM: {
176892:       if( pThis->jnFlags & JNODE_LABEL ) pThis++;
176893:       if( pThis->eType>=JSON_ARRAY ) break;
176894:       jsonReturn(pThis, ctx, 0);
176895:       break;
176896:     }
176897:     case JEACH_ID: {
176898:       sqlite3_result_int64(ctx, 
176899:          (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
176900:       break;
176901:     }
176902:     case JEACH_PARENT: {
176903:       if( p->i>p->iBegin && p->bRecursive ){
176904:         sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
176905:       }
176906:       break;
176907:     }
176908:     case JEACH_FULLKEY: {
176909:       JsonString x;
176910:       jsonInit(&x, ctx);
176911:       if( p->bRecursive ){
176912:         jsonEachComputePath(p, &x, p->i);
176913:       }else{
176914:         if( p->zRoot ){
176915:           jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
176916:         }else{
176917:           jsonAppendChar(&x, '$');
176918:         }
176919:         if( p->eType==JSON_ARRAY ){
176920:           jsonPrintf(30, &x, "[%d]", p->iRowid);
176921:         }else{
176922:           jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
176923:         }
176924:       }
176925:       jsonResult(&x);
176926:       break;
176927:     }
176928:     case JEACH_PATH: {
176929:       if( p->bRecursive ){
176930:         JsonString x;
176931:         jsonInit(&x, ctx);
176932:         jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
176933:         jsonResult(&x);
176934:         break;
176935:       }
176936:       /* For json_each() path and root are the same so fall through
176937:       ** into the root case */
176938:     }
176939:     case JEACH_ROOT: {
176940:       const char *zRoot = p->zRoot;
176941:        if( zRoot==0 ) zRoot = "$";
176942:       sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
176943:       break;
176944:     }
176945:     case JEACH_JSON: {
176946:       assert( i==JEACH_JSON );
176947:       sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
176948:       break;
176949:     }
176950:   }
176951:   return SQLITE_OK;
176952: }
176953: 
176954: /* Return the current rowid value */
176955: static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
176956:   JsonEachCursor *p = (JsonEachCursor*)cur;
176957:   *pRowid = p->iRowid;
176958:   return SQLITE_OK;
176959: }
176960: 
176961: /* The query strategy is to look for an equality constraint on the json
176962: ** column.  Without such a constraint, the table cannot operate.  idxNum is
176963: ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
176964: ** and 0 otherwise.
176965: */
176966: static int jsonEachBestIndex(
176967:   sqlite3_vtab *tab,
176968:   sqlite3_index_info *pIdxInfo
176969: ){
176970:   int i;
176971:   int jsonIdx = -1;
176972:   int rootIdx = -1;
176973:   const struct sqlite3_index_constraint *pConstraint;
176974: 
176975:   UNUSED_PARAM(tab);
176976:   pConstraint = pIdxInfo->aConstraint;
176977:   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
176978:     if( pConstraint->usable==0 ) continue;
176979:     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
176980:     switch( pConstraint->iColumn ){
176981:       case JEACH_JSON:   jsonIdx = i;    break;
176982:       case JEACH_ROOT:   rootIdx = i;    break;
176983:       default:           /* no-op */     break;
176984:     }
176985:   }
176986:   if( jsonIdx<0 ){
176987:     pIdxInfo->idxNum = 0;
176988:     pIdxInfo->estimatedCost = 1e99;
176989:   }else{
176990:     pIdxInfo->estimatedCost = 1.0;
176991:     pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
176992:     pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
176993:     if( rootIdx<0 ){
176994:       pIdxInfo->idxNum = 1;
176995:     }else{
176996:       pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
176997:       pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
176998:       pIdxInfo->idxNum = 3;
176999:     }
177000:   }
177001:   return SQLITE_OK;
177002: }
177003: 
177004: /* Start a search on a new JSON string */
177005: static int jsonEachFilter(
177006:   sqlite3_vtab_cursor *cur,
177007:   int idxNum, const char *idxStr,
177008:   int argc, sqlite3_value **argv
177009: ){
177010:   JsonEachCursor *p = (JsonEachCursor*)cur;
177011:   const char *z;
177012:   const char *zRoot = 0;
177013:   sqlite3_int64 n;
177014: 
177015:   UNUSED_PARAM(idxStr);
177016:   UNUSED_PARAM(argc);
177017:   jsonEachCursorReset(p);
177018:   if( idxNum==0 ) return SQLITE_OK;
177019:   z = (const char*)sqlite3_value_text(argv[0]);
177020:   if( z==0 ) return SQLITE_OK;
177021:   n = sqlite3_value_bytes(argv[0]);
177022:   p->zJson = sqlite3_malloc64( n+1 );
177023:   if( p->zJson==0 ) return SQLITE_NOMEM;
177024:   memcpy(p->zJson, z, (size_t)n+1);
177025:   if( jsonParse(&p->sParse, 0, p->zJson) ){
177026:     int rc = SQLITE_NOMEM;
177027:     if( p->sParse.oom==0 ){
177028:       sqlite3_free(cur->pVtab->zErrMsg);
177029:       cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
177030:       if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
177031:     }
177032:     jsonEachCursorReset(p);
177033:     return rc;
177034:   }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
177035:     jsonEachCursorReset(p);
177036:     return SQLITE_NOMEM;
177037:   }else{
177038:     JsonNode *pNode = 0;
177039:     if( idxNum==3 ){
177040:       const char *zErr = 0;
177041:       zRoot = (const char*)sqlite3_value_text(argv[1]);
177042:       if( zRoot==0 ) return SQLITE_OK;
177043:       n = sqlite3_value_bytes(argv[1]);
177044:       p->zRoot = sqlite3_malloc64( n+1 );
177045:       if( p->zRoot==0 ) return SQLITE_NOMEM;
177046:       memcpy(p->zRoot, zRoot, (size_t)n+1);
177047:       if( zRoot[0]!='$' ){
177048:         zErr = zRoot;
177049:       }else{
177050:         pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
177051:       }
177052:       if( zErr ){
177053:         sqlite3_free(cur->pVtab->zErrMsg);
177054:         cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
177055:         jsonEachCursorReset(p);
177056:         return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
177057:       }else if( pNode==0 ){
177058:         return SQLITE_OK;
177059:       }
177060:     }else{
177061:       pNode = p->sParse.aNode;
177062:     }
177063:     p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
177064:     p->eType = pNode->eType;
177065:     if( p->eType>=JSON_ARRAY ){
177066:       pNode->u.iKey = 0;
177067:       p->iEnd = p->i + pNode->n + 1;
177068:       if( p->bRecursive ){
177069:         p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
177070:         if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
177071:           p->i--;
177072:         }
177073:       }else{
177074:         p->i++;
177075:       }
177076:     }else{
177077:       p->iEnd = p->i+1;
177078:     }
177079:   }
177080:   return SQLITE_OK;
177081: }
177082: 
177083: /* The methods of the json_each virtual table */
177084: static sqlite3_module jsonEachModule = {
177085:   0,                         /* iVersion */
177086:   0,                         /* xCreate */
177087:   jsonEachConnect,           /* xConnect */
177088:   jsonEachBestIndex,         /* xBestIndex */
177089:   jsonEachDisconnect,        /* xDisconnect */
177090:   0,                         /* xDestroy */
177091:   jsonEachOpenEach,          /* xOpen - open a cursor */
177092:   jsonEachClose,             /* xClose - close a cursor */
177093:   jsonEachFilter,            /* xFilter - configure scan constraints */
177094:   jsonEachNext,              /* xNext - advance a cursor */
177095:   jsonEachEof,               /* xEof - check for end of scan */
177096:   jsonEachColumn,            /* xColumn - read data */
177097:   jsonEachRowid,             /* xRowid - read data */
177098:   0,                         /* xUpdate */
177099:   0,                         /* xBegin */
177100:   0,                         /* xSync */
177101:   0,                         /* xCommit */
177102:   0,                         /* xRollback */
177103:   0,                         /* xFindMethod */
177104:   0,                         /* xRename */
177105:   0,                         /* xSavepoint */
177106:   0,                         /* xRelease */
177107:   0                          /* xRollbackTo */
177108: };
177109: 
177110: /* The methods of the json_tree virtual table. */
177111: static sqlite3_module jsonTreeModule = {
177112:   0,                         /* iVersion */
177113:   0,                         /* xCreate */
177114:   jsonEachConnect,           /* xConnect */
177115:   jsonEachBestIndex,         /* xBestIndex */
177116:   jsonEachDisconnect,        /* xDisconnect */
177117:   0,                         /* xDestroy */
177118:   jsonEachOpenTree,          /* xOpen - open a cursor */
177119:   jsonEachClose,             /* xClose - close a cursor */
177120:   jsonEachFilter,            /* xFilter - configure scan constraints */
177121:   jsonEachNext,              /* xNext - advance a cursor */
177122:   jsonEachEof,               /* xEof - check for end of scan */
177123:   jsonEachColumn,            /* xColumn - read data */
177124:   jsonEachRowid,             /* xRowid - read data */
177125:   0,                         /* xUpdate */
177126:   0,                         /* xBegin */
177127:   0,                         /* xSync */
177128:   0,                         /* xCommit */
177129:   0,                         /* xRollback */
177130:   0,                         /* xFindMethod */
177131:   0,                         /* xRename */
177132:   0,                         /* xSavepoint */
177133:   0,                         /* xRelease */
177134:   0                          /* xRollbackTo */
177135: };
177136: #endif /* SQLITE_OMIT_VIRTUALTABLE */
177137: 
177138: /****************************************************************************
177139: ** The following routines are the only publically visible identifiers in this
177140: ** file.  Call the following routines in order to register the various SQL
177141: ** functions and the virtual table implemented by this file.
177142: ****************************************************************************/
177143: 
177144: SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
177145:   int rc = SQLITE_OK;
177146:   unsigned int i;
177147:   static const struct {
177148:      const char *zName;
177149:      int nArg;
177150:      int flag;
177151:      void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
177152:   } aFunc[] = {
177153:     { "json",                 1, 0,   jsonRemoveFunc        },
177154:     { "json_array",          -1, 0,   jsonArrayFunc         },
177155:     { "json_array_length",    1, 0,   jsonArrayLengthFunc   },
177156:     { "json_array_length",    2, 0,   jsonArrayLengthFunc   },
177157:     { "json_extract",        -1, 0,   jsonExtractFunc       },
177158:     { "json_insert",         -1, 0,   jsonSetFunc           },
177159:     { "json_object",         -1, 0,   jsonObjectFunc        },
177160:     { "json_quote",           1, 0,   jsonQuoteFunc         },
177161:     { "json_remove",         -1, 0,   jsonRemoveFunc        },
177162:     { "json_replace",        -1, 0,   jsonReplaceFunc       },
177163:     { "json_set",            -1, 1,   jsonSetFunc           },
177164:     { "json_type",            1, 0,   jsonTypeFunc          },
177165:     { "json_type",            2, 0,   jsonTypeFunc          },
177166:     { "json_valid",           1, 0,   jsonValidFunc         },
177167: 
177168: #if SQLITE_DEBUG
177169:     /* DEBUG and TESTING functions */
177170:     { "json_parse",           1, 0,   jsonParseFunc         },
177171:     { "json_test1",           1, 0,   jsonTest1Func         },
177172: #endif
177173:   };
177174:   static const struct {
177175:      const char *zName;
177176:      int nArg;
177177:      void (*xStep)(sqlite3_context*,int,sqlite3_value**);
177178:      void (*xFinal)(sqlite3_context*);
177179:   } aAgg[] = {
177180:     { "json_group_array",     1,   jsonArrayStep,   jsonArrayFinal  },
177181:     { "json_group_object",    2,   jsonObjectStep,  jsonObjectFinal },
177182:   };
177183: #ifndef SQLITE_OMIT_VIRTUALTABLE
177184:   static const struct {
177185:      const char *zName;
177186:      sqlite3_module *pModule;
177187:   } aMod[] = {
177188:     { "json_each",            &jsonEachModule               },
177189:     { "json_tree",            &jsonTreeModule               },
177190:   };
177191: #endif
177192:   for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
177193:     rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
177194:                                  SQLITE_UTF8 | SQLITE_DETERMINISTIC, 
177195:                                  (void*)&aFunc[i].flag,
177196:                                  aFunc[i].xFunc, 0, 0);
177197:   }
177198:   for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
177199:     rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
177200:                                  SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
177201:                                  0, aAgg[i].xStep, aAgg[i].xFinal);
177202:   }
177203: #ifndef SQLITE_OMIT_VIRTUALTABLE
177204:   for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
177205:     rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
177206:   }
177207: #endif
177208:   return rc;
177209: }
177210: 
177211: 
177212: #ifndef SQLITE_CORE
177213: #ifdef _WIN32
177214: __declspec(dllexport)
177215: #endif
177216: SQLITE_API int sqlite3_json_init(
177217:   sqlite3 *db, 
177218:   char **pzErrMsg, 
177219:   const sqlite3_api_routines *pApi
177220: ){
177221:   SQLITE_EXTENSION_INIT2(pApi);
177222:   (void)pzErrMsg;  /* Unused parameter */
177223:   return sqlite3Json1Init(db);
177224: }
177225: #endif
177226: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
177227: 
177228: /************** End of json1.c ***********************************************/
177229: /************** Begin file fts5.c ********************************************/
177230: 
177231: 
177232: #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) 
177233: 
177234: #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
177235: # define NDEBUG 1
177236: #endif
177237: #if defined(NDEBUG) && defined(SQLITE_DEBUG)
177238: # undef NDEBUG
177239: #endif
177240: 
177241: /*
177242: ** 2014 May 31
177243: **
177244: ** The author disclaims copyright to this source code.  In place of
177245: ** a legal notice, here is a blessing:
177246: **
177247: **    May you do good and not evil.
177248: **    May you find forgiveness for yourself and forgive others.
177249: **    May you share freely, never taking more than you give.
177250: **
177251: ******************************************************************************
177252: **
177253: ** Interfaces to extend FTS5. Using the interfaces defined in this file, 
177254: ** FTS5 may be extended with:
177255: **
177256: **     * custom tokenizers, and
177257: **     * custom auxiliary functions.
177258: */
177259: 
177260: 
177261: #ifndef _FTS5_H
177262: #define _FTS5_H
177263: 
177264: /* #include "sqlite3.h" */
177265: 
177266: #if 0
177267: extern "C" {
177268: #endif
177269: 
177270: /*************************************************************************
177271: ** CUSTOM AUXILIARY FUNCTIONS
177272: **
177273: ** Virtual table implementations may overload SQL functions by implementing
177274: ** the sqlite3_module.xFindFunction() method.
177275: */
177276: 
177277: typedef struct Fts5ExtensionApi Fts5ExtensionApi;
177278: typedef struct Fts5Context Fts5Context;
177279: typedef struct Fts5PhraseIter Fts5PhraseIter;
177280: 
177281: typedef void (*fts5_extension_function)(
177282:   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
177283:   Fts5Context *pFts,              /* First arg to pass to pApi functions */
177284:   sqlite3_context *pCtx,          /* Context for returning result/error */
177285:   int nVal,                       /* Number of values in apVal[] array */
177286:   sqlite3_value **apVal           /* Array of trailing arguments */
177287: );
177288: 
177289: struct Fts5PhraseIter {
177290:   const unsigned char *a;
177291:   const unsigned char *b;
177292: };
177293: 
177294: /*
177295: ** EXTENSION API FUNCTIONS
177296: **
177297: ** xUserData(pFts):
177298: **   Return a copy of the context pointer the extension function was 
177299: **   registered with.
177300: **
177301: ** xColumnTotalSize(pFts, iCol, pnToken):
177302: **   If parameter iCol is less than zero, set output variable *pnToken
177303: **   to the total number of tokens in the FTS5 table. Or, if iCol is
177304: **   non-negative but less than the number of columns in the table, return
177305: **   the total number of tokens in column iCol, considering all rows in 
177306: **   the FTS5 table.
177307: **
177308: **   If parameter iCol is greater than or equal to the number of columns
177309: **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
177310: **   an OOM condition or IO error), an appropriate SQLite error code is 
177311: **   returned.
177312: **
177313: ** xColumnCount(pFts):
177314: **   Return the number of columns in the table.
177315: **
177316: ** xColumnSize(pFts, iCol, pnToken):
177317: **   If parameter iCol is less than zero, set output variable *pnToken
177318: **   to the total number of tokens in the current row. Or, if iCol is
177319: **   non-negative but less than the number of columns in the table, set
177320: **   *pnToken to the number of tokens in column iCol of the current row.
177321: **
177322: **   If parameter iCol is greater than or equal to the number of columns
177323: **   in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
177324: **   an OOM condition or IO error), an appropriate SQLite error code is 
177325: **   returned.
177326: **
177327: **   This function may be quite inefficient if used with an FTS5 table
177328: **   created with the "columnsize=0" option.
177329: **
177330: ** xColumnText:
177331: **   This function attempts to retrieve the text of column iCol of the
177332: **   current document. If successful, (*pz) is set to point to a buffer
177333: **   containing the text in utf-8 encoding, (*pn) is set to the size in bytes
177334: **   (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
177335: **   if an error occurs, an SQLite error code is returned and the final values
177336: **   of (*pz) and (*pn) are undefined.
177337: **
177338: ** xPhraseCount:
177339: **   Returns the number of phrases in the current query expression.
177340: **
177341: ** xPhraseSize:
177342: **   Returns the number of tokens in phrase iPhrase of the query. Phrases
177343: **   are numbered starting from zero.
177344: **
177345: ** xInstCount:
177346: **   Set *pnInst to the total number of occurrences of all phrases within
177347: **   the query within the current row. Return SQLITE_OK if successful, or
177348: **   an error code (i.e. SQLITE_NOMEM) if an error occurs.
177349: **
177350: **   This API can be quite slow if used with an FTS5 table created with the
177351: **   "detail=none" or "detail=column" option. If the FTS5 table is created 
177352: **   with either "detail=none" or "detail=column" and "content=" option 
177353: **   (i.e. if it is a contentless table), then this API always returns 0.
177354: **
177355: ** xInst:
177356: **   Query for the details of phrase match iIdx within the current row.
177357: **   Phrase matches are numbered starting from zero, so the iIdx argument
177358: **   should be greater than or equal to zero and smaller than the value
177359: **   output by xInstCount().
177360: **
177361: **   Usually, output parameter *piPhrase is set to the phrase number, *piCol
177362: **   to the column in which it occurs and *piOff the token offset of the
177363: **   first token of the phrase. The exception is if the table was created
177364: **   with the offsets=0 option specified. In this case *piOff is always
177365: **   set to -1.
177366: **
177367: **   Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM) 
177368: **   if an error occurs.
177369: **
177370: **   This API can be quite slow if used with an FTS5 table created with the
177371: **   "detail=none" or "detail=column" option. 
177372: **
177373: ** xRowid:
177374: **   Returns the rowid of the current row.
177375: **
177376: ** xTokenize:
177377: **   Tokenize text using the tokenizer belonging to the FTS5 table.
177378: **
177379: ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
177380: **   This API function is used to query the FTS table for phrase iPhrase
177381: **   of the current query. Specifically, a query equivalent to:
177382: **
177383: **       ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
177384: **
177385: **   with $p set to a phrase equivalent to the phrase iPhrase of the
177386: **   current query is executed. Any column filter that applies to
177387: **   phrase iPhrase of the current query is included in $p. For each 
177388: **   row visited, the callback function passed as the fourth argument 
177389: **   is invoked. The context and API objects passed to the callback 
177390: **   function may be used to access the properties of each matched row.
177391: **   Invoking Api.xUserData() returns a copy of the pointer passed as 
177392: **   the third argument to pUserData.
177393: **
177394: **   If the callback function returns any value other than SQLITE_OK, the
177395: **   query is abandoned and the xQueryPhrase function returns immediately.
177396: **   If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
177397: **   Otherwise, the error code is propagated upwards.
177398: **
177399: **   If the query runs to completion without incident, SQLITE_OK is returned.
177400: **   Or, if some error occurs before the query completes or is aborted by
177401: **   the callback, an SQLite error code is returned.
177402: **
177403: **
177404: ** xSetAuxdata(pFts5, pAux, xDelete)
177405: **
177406: **   Save the pointer passed as the second argument as the extension functions 
177407: **   "auxiliary data". The pointer may then be retrieved by the current or any
177408: **   future invocation of the same fts5 extension function made as part of
177409: **   of the same MATCH query using the xGetAuxdata() API.
177410: **
177411: **   Each extension function is allocated a single auxiliary data slot for
177412: **   each FTS query (MATCH expression). If the extension function is invoked 
177413: **   more than once for a single FTS query, then all invocations share a 
177414: **   single auxiliary data context.
177415: **
177416: **   If there is already an auxiliary data pointer when this function is
177417: **   invoked, then it is replaced by the new pointer. If an xDelete callback
177418: **   was specified along with the original pointer, it is invoked at this
177419: **   point.
177420: **
177421: **   The xDelete callback, if one is specified, is also invoked on the
177422: **   auxiliary data pointer after the FTS5 query has finished.
177423: **
177424: **   If an error (e.g. an OOM condition) occurs within this function, an
177425: **   the auxiliary data is set to NULL and an error code returned. If the
177426: **   xDelete parameter was not NULL, it is invoked on the auxiliary data
177427: **   pointer before returning.
177428: **
177429: **
177430: ** xGetAuxdata(pFts5, bClear)
177431: **
177432: **   Returns the current auxiliary data pointer for the fts5 extension 
177433: **   function. See the xSetAuxdata() method for details.
177434: **
177435: **   If the bClear argument is non-zero, then the auxiliary data is cleared
177436: **   (set to NULL) before this function returns. In this case the xDelete,
177437: **   if any, is not invoked.
177438: **
177439: **
177440: ** xRowCount(pFts5, pnRow)
177441: **
177442: **   This function is used to retrieve the total number of rows in the table.
177443: **   In other words, the same value that would be returned by:
177444: **
177445: **        SELECT count(*) FROM ftstable;
177446: **
177447: ** xPhraseFirst()
177448: **   This function is used, along with type Fts5PhraseIter and the xPhraseNext
177449: **   method, to iterate through all instances of a single query phrase within
177450: **   the current row. This is the same information as is accessible via the
177451: **   xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
177452: **   to use, this API may be faster under some circumstances. To iterate 
177453: **   through instances of phrase iPhrase, use the following code:
177454: **
177455: **       Fts5PhraseIter iter;
177456: **       int iCol, iOff;
177457: **       for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
177458: **           iCol>=0;
177459: **           pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
177460: **       ){
177461: **         // An instance of phrase iPhrase at offset iOff of column iCol
177462: **       }
177463: **
177464: **   The Fts5PhraseIter structure is defined above. Applications should not
177465: **   modify this structure directly - it should only be used as shown above
177466: **   with the xPhraseFirst() and xPhraseNext() API methods (and by
177467: **   xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
177468: **
177469: **   This API can be quite slow if used with an FTS5 table created with the
177470: **   "detail=none" or "detail=column" option. If the FTS5 table is created 
177471: **   with either "detail=none" or "detail=column" and "content=" option 
177472: **   (i.e. if it is a contentless table), then this API always iterates
177473: **   through an empty set (all calls to xPhraseFirst() set iCol to -1).
177474: **
177475: ** xPhraseNext()
177476: **   See xPhraseFirst above.
177477: **
177478: ** xPhraseFirstColumn()
177479: **   This function and xPhraseNextColumn() are similar to the xPhraseFirst()
177480: **   and xPhraseNext() APIs described above. The difference is that instead
177481: **   of iterating through all instances of a phrase in the current row, these
177482: **   APIs are used to iterate through the set of columns in the current row
177483: **   that contain one or more instances of a specified phrase. For example:
177484: **
177485: **       Fts5PhraseIter iter;
177486: **       int iCol;
177487: **       for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
177488: **           iCol>=0;
177489: **           pApi->xPhraseNextColumn(pFts, &iter, &iCol)
177490: **       ){
177491: **         // Column iCol contains at least one instance of phrase iPhrase
177492: **       }
177493: **
177494: **   This API can be quite slow if used with an FTS5 table created with the
177495: **   "detail=none" option. If the FTS5 table is created with either 
177496: **   "detail=none" "content=" option (i.e. if it is a contentless table), 
177497: **   then this API always iterates through an empty set (all calls to 
177498: **   xPhraseFirstColumn() set iCol to -1).
177499: **
177500: **   The information accessed using this API and its companion
177501: **   xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
177502: **   (or xInst/xInstCount). The chief advantage of this API is that it is
177503: **   significantly more efficient than those alternatives when used with
177504: **   "detail=column" tables.  
177505: **
177506: ** xPhraseNextColumn()
177507: **   See xPhraseFirstColumn above.
177508: */
177509: struct Fts5ExtensionApi {
177510:   int iVersion;                   /* Currently always set to 3 */
177511: 
177512:   void *(*xUserData)(Fts5Context*);
177513: 
177514:   int (*xColumnCount)(Fts5Context*);
177515:   int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
177516:   int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
177517: 
177518:   int (*xTokenize)(Fts5Context*, 
177519:     const char *pText, int nText, /* Text to tokenize */
177520:     void *pCtx,                   /* Context passed to xToken() */
177521:     int (*xToken)(void*, int, const char*, int, int, int)       /* Callback */
177522:   );
177523: 
177524:   int (*xPhraseCount)(Fts5Context*);
177525:   int (*xPhraseSize)(Fts5Context*, int iPhrase);
177526: 
177527:   int (*xInstCount)(Fts5Context*, int *pnInst);
177528:   int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
177529: 
177530:   sqlite3_int64 (*xRowid)(Fts5Context*);
177531:   int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
177532:   int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
177533: 
177534:   int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
177535:     int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
177536:   );
177537:   int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
177538:   void *(*xGetAuxdata)(Fts5Context*, int bClear);
177539: 
177540:   int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
177541:   void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
177542: 
177543:   int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
177544:   void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
177545: };
177546: 
177547: /* 
177548: ** CUSTOM AUXILIARY FUNCTIONS
177549: *************************************************************************/
177550: 
177551: /*************************************************************************
177552: ** CUSTOM TOKENIZERS
177553: **
177554: ** Applications may also register custom tokenizer types. A tokenizer 
177555: ** is registered by providing fts5 with a populated instance of the 
177556: ** following structure. All structure methods must be defined, setting
177557: ** any member of the fts5_tokenizer struct to NULL leads to undefined
177558: ** behaviour. The structure methods are expected to function as follows:
177559: **
177560: ** xCreate:
177561: **   This function is used to allocate and initialize a tokenizer instance.
177562: **   A tokenizer instance is required to actually tokenize text.
177563: **
177564: **   The first argument passed to this function is a copy of the (void*)
177565: **   pointer provided by the application when the fts5_tokenizer object
177566: **   was registered with FTS5 (the third argument to xCreateTokenizer()). 
177567: **   The second and third arguments are an array of nul-terminated strings
177568: **   containing the tokenizer arguments, if any, specified following the
177569: **   tokenizer name as part of the CREATE VIRTUAL TABLE statement used
177570: **   to create the FTS5 table.
177571: **
177572: **   The final argument is an output variable. If successful, (*ppOut) 
177573: **   should be set to point to the new tokenizer handle and SQLITE_OK
177574: **   returned. If an error occurs, some value other than SQLITE_OK should
177575: **   be returned. In this case, fts5 assumes that the final value of *ppOut 
177576: **   is undefined.
177577: **
177578: ** xDelete:
177579: **   This function is invoked to delete a tokenizer handle previously
177580: **   allocated using xCreate(). Fts5 guarantees that this function will
177581: **   be invoked exactly once for each successful call to xCreate().
177582: **
177583: ** xTokenize:
177584: **   This function is expected to tokenize the nText byte string indicated 
177585: **   by argument pText. pText may or may not be nul-terminated. The first
177586: **   argument passed to this function is a pointer to an Fts5Tokenizer object
177587: **   returned by an earlier call to xCreate().
177588: **
177589: **   The second argument indicates the reason that FTS5 is requesting
177590: **   tokenization of the supplied text. This is always one of the following
177591: **   four values:
177592: **
177593: **   <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
177594: **            or removed from the FTS table. The tokenizer is being invoked to
177595: **            determine the set of tokens to add to (or delete from) the
177596: **            FTS index.
177597: **
177598: **       <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed 
177599: **            against the FTS index. The tokenizer is being called to tokenize 
177600: **            a bareword or quoted string specified as part of the query.
177601: **
177602: **       <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
177603: **            FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
177604: **            followed by a "*" character, indicating that the last token
177605: **            returned by the tokenizer will be treated as a token prefix.
177606: **
177607: **       <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to 
177608: **            satisfy an fts5_api.xTokenize() request made by an auxiliary
177609: **            function. Or an fts5_api.xColumnSize() request made by the same
177610: **            on a columnsize=0 database.  
177611: **   </ul>
177612: **
177613: **   For each token in the input string, the supplied callback xToken() must
177614: **   be invoked. The first argument to it should be a copy of the pointer
177615: **   passed as the second argument to xTokenize(). The third and fourth
177616: **   arguments are a pointer to a buffer containing the token text, and the
177617: **   size of the token in bytes. The 4th and 5th arguments are the byte offsets
177618: **   of the first byte of and first byte immediately following the text from
177619: **   which the token is derived within the input.
177620: **
177621: **   The second argument passed to the xToken() callback ("tflags") should
177622: **   normally be set to 0. The exception is if the tokenizer supports 
177623: **   synonyms. In this case see the discussion below for details.
177624: **
177625: **   FTS5 assumes the xToken() callback is invoked for each token in the 
177626: **   order that they occur within the input text.
177627: **
177628: **   If an xToken() callback returns any value other than SQLITE_OK, then
177629: **   the tokenization should be abandoned and the xTokenize() method should
177630: **   immediately return a copy of the xToken() return value. Or, if the
177631: **   input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
177632: **   if an error occurs with the xTokenize() implementation itself, it
177633: **   may abandon the tokenization and return any error code other than
177634: **   SQLITE_OK or SQLITE_DONE.
177635: **
177636: ** SYNONYM SUPPORT
177637: **
177638: **   Custom tokenizers may also support synonyms. Consider a case in which a
177639: **   user wishes to query for a phrase such as "first place". Using the 
177640: **   built-in tokenizers, the FTS5 query 'first + place' will match instances
177641: **   of "first place" within the document set, but not alternative forms
177642: **   such as "1st place". In some applications, it would be better to match
177643: **   all instances of "first place" or "1st place" regardless of which form
177644: **   the user specified in the MATCH query text.
177645: **
177646: **   There are several ways to approach this in FTS5:
177647: **
177648: **   <ol><li> By mapping all synonyms to a single token. In this case, the 
177649: **            In the above example, this means that the tokenizer returns the
177650: **            same token for inputs "first" and "1st". Say that token is in
177651: **            fact "first", so that when the user inserts the document "I won
177652: **            1st place" entries are added to the index for tokens "i", "won",
177653: **            "first" and "place". If the user then queries for '1st + place',
177654: **            the tokenizer substitutes "first" for "1st" and the query works
177655: **            as expected.
177656: **
177657: **       <li> By adding multiple synonyms for a single term to the FTS index.
177658: **            In this case, when tokenizing query text, the tokenizer may 
177659: **            provide multiple synonyms for a single term within the document.
177660: **            FTS5 then queries the index for each synonym individually. For
177661: **            example, faced with the query:
177662: **
177663: **   <codeblock>
177664: **     ... MATCH 'first place'</codeblock>
177665: **
177666: **            the tokenizer offers both "1st" and "first" as synonyms for the
177667: **            first token in the MATCH query and FTS5 effectively runs a query 
177668: **            similar to:
177669: **
177670: **   <codeblock>
177671: **     ... MATCH '(first OR 1st) place'</codeblock>
177672: **
177673: **            except that, for the purposes of auxiliary functions, the query
177674: **            still appears to contain just two phrases - "(first OR 1st)" 
177675: **            being treated as a single phrase.
177676: **
177677: **       <li> By adding multiple synonyms for a single term to the FTS index.
177678: **            Using this method, when tokenizing document text, the tokenizer
177679: **            provides multiple synonyms for each token. So that when a 
177680: **            document such as "I won first place" is tokenized, entries are
177681: **            added to the FTS index for "i", "won", "first", "1st" and
177682: **            "place".
177683: **
177684: **            This way, even if the tokenizer does not provide synonyms
177685: **            when tokenizing query text (it should not - to do would be
177686: **            inefficient), it doesn't matter if the user queries for 
177687: **            'first + place' or '1st + place', as there are entires in the
177688: **            FTS index corresponding to both forms of the first token.
177689: **   </ol>
177690: **
177691: **   Whether it is parsing document or query text, any call to xToken that
177692: **   specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
177693: **   is considered to supply a synonym for the previous token. For example,
177694: **   when parsing the document "I won first place", a tokenizer that supports
177695: **   synonyms would call xToken() 5 times, as follows:
177696: **
177697: **   <codeblock>
177698: **       xToken(pCtx, 0, "i",                      1,  0,  1);
177699: **       xToken(pCtx, 0, "won",                    3,  2,  5);
177700: **       xToken(pCtx, 0, "first",                  5,  6, 11);
177701: **       xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3,  6, 11);
177702: **       xToken(pCtx, 0, "place",                  5, 12, 17);
177703: **</codeblock>
177704: **
177705: **   It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
177706: **   xToken() is called. Multiple synonyms may be specified for a single token
177707: **   by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence. 
177708: **   There is no limit to the number of synonyms that may be provided for a
177709: **   single token.
177710: **
177711: **   In many cases, method (1) above is the best approach. It does not add 
177712: **   extra data to the FTS index or require FTS5 to query for multiple terms,
177713: **   so it is efficient in terms of disk space and query speed. However, it
177714: **   does not support prefix queries very well. If, as suggested above, the
177715: **   token "first" is subsituted for "1st" by the tokenizer, then the query:
177716: **
177717: **   <codeblock>
177718: **     ... MATCH '1s*'</codeblock>
177719: **
177720: **   will not match documents that contain the token "1st" (as the tokenizer
177721: **   will probably not map "1s" to any prefix of "first").
177722: **
177723: **   For full prefix support, method (3) may be preferred. In this case, 
177724: **   because the index contains entries for both "first" and "1st", prefix
177725: **   queries such as 'fi*' or '1s*' will match correctly. However, because
177726: **   extra entries are added to the FTS index, this method uses more space
177727: **   within the database.
177728: **
177729: **   Method (2) offers a midpoint between (1) and (3). Using this method,
177730: **   a query such as '1s*' will match documents that contain the literal 
177731: **   token "1st", but not "first" (assuming the tokenizer is not able to
177732: **   provide synonyms for prefixes). However, a non-prefix query like '1st'
177733: **   will match against "1st" and "first". This method does not require
177734: **   extra disk space, as no extra entries are added to the FTS index. 
177735: **   On the other hand, it may require more CPU cycles to run MATCH queries,
177736: **   as separate queries of the FTS index are required for each synonym.
177737: **
177738: **   When using methods (2) or (3), it is important that the tokenizer only
177739: **   provide synonyms when tokenizing document text (method (2)) or query
177740: **   text (method (3)), not both. Doing so will not cause any errors, but is
177741: **   inefficient.
177742: */
177743: typedef struct Fts5Tokenizer Fts5Tokenizer;
177744: typedef struct fts5_tokenizer fts5_tokenizer;
177745: struct fts5_tokenizer {
177746:   int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
177747:   void (*xDelete)(Fts5Tokenizer*);
177748:   int (*xTokenize)(Fts5Tokenizer*, 
177749:       void *pCtx,
177750:       int flags,            /* Mask of FTS5_TOKENIZE_* flags */
177751:       const char *pText, int nText, 
177752:       int (*xToken)(
177753:         void *pCtx,         /* Copy of 2nd argument to xTokenize() */
177754:         int tflags,         /* Mask of FTS5_TOKEN_* flags */
177755:         const char *pToken, /* Pointer to buffer containing token */
177756:         int nToken,         /* Size of token in bytes */
177757:         int iStart,         /* Byte offset of token within input text */
177758:         int iEnd            /* Byte offset of end of token within input text */
177759:       )
177760:   );
177761: };
177762: 
177763: /* Flags that may be passed as the third argument to xTokenize() */
177764: #define FTS5_TOKENIZE_QUERY     0x0001
177765: #define FTS5_TOKENIZE_PREFIX    0x0002
177766: #define FTS5_TOKENIZE_DOCUMENT  0x0004
177767: #define FTS5_TOKENIZE_AUX       0x0008
177768: 
177769: /* Flags that may be passed by the tokenizer implementation back to FTS5
177770: ** as the third argument to the supplied xToken callback. */
177771: #define FTS5_TOKEN_COLOCATED    0x0001      /* Same position as prev. token */
177772: 
177773: /*
177774: ** END OF CUSTOM TOKENIZERS
177775: *************************************************************************/
177776: 
177777: /*************************************************************************
177778: ** FTS5 EXTENSION REGISTRATION API
177779: */
177780: typedef struct fts5_api fts5_api;
177781: struct fts5_api {
177782:   int iVersion;                   /* Currently always set to 2 */
177783: 
177784:   /* Create a new tokenizer */
177785:   int (*xCreateTokenizer)(
177786:     fts5_api *pApi,
177787:     const char *zName,
177788:     void *pContext,
177789:     fts5_tokenizer *pTokenizer,
177790:     void (*xDestroy)(void*)
177791:   );
177792: 
177793:   /* Find an existing tokenizer */
177794:   int (*xFindTokenizer)(
177795:     fts5_api *pApi,
177796:     const char *zName,
177797:     void **ppContext,
177798:     fts5_tokenizer *pTokenizer
177799:   );
177800: 
177801:   /* Create a new auxiliary function */
177802:   int (*xCreateFunction)(
177803:     fts5_api *pApi,
177804:     const char *zName,
177805:     void *pContext,
177806:     fts5_extension_function xFunction,
177807:     void (*xDestroy)(void*)
177808:   );
177809: };
177810: 
177811: /*
177812: ** END OF REGISTRATION API
177813: *************************************************************************/
177814: 
177815: #if 0
177816: }  /* end of the 'extern "C"' block */
177817: #endif
177818: 
177819: #endif /* _FTS5_H */
177820: 
177821: /*
177822: ** 2014 May 31
177823: **
177824: ** The author disclaims copyright to this source code.  In place of
177825: ** a legal notice, here is a blessing:
177826: **
177827: **    May you do good and not evil.
177828: **    May you find forgiveness for yourself and forgive others.
177829: **    May you share freely, never taking more than you give.
177830: **
177831: ******************************************************************************
177832: **
177833: */
177834: #ifndef _FTS5INT_H
177835: #define _FTS5INT_H
177836: 
177837: /* #include "fts5.h" */
177838: /* #include "sqlite3ext.h" */
177839: SQLITE_EXTENSION_INIT1
177840: 
177841: /* #include <string.h> */
177842: /* #include <assert.h> */
177843: 
177844: #ifndef SQLITE_AMALGAMATION
177845: 
177846: typedef unsigned char  u8;
177847: typedef unsigned int   u32;
177848: typedef unsigned short u16;
177849: typedef short i16;
177850: typedef sqlite3_int64 i64;
177851: typedef sqlite3_uint64 u64;
177852: 
177853: #define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
177854: 
177855: #define testcase(x)
177856: #define ALWAYS(x) 1
177857: #define NEVER(x) 0
177858: 
177859: #define MIN(x,y) (((x) < (y)) ? (x) : (y))
177860: #define MAX(x,y) (((x) > (y)) ? (x) : (y))
177861: 
177862: /*
177863: ** Constants for the largest and smallest possible 64-bit signed integers.
177864: */
177865: # define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
177866: # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
177867: 
177868: #endif
177869: 
177870: /* Truncate very long tokens to this many bytes. Hard limit is 
177871: ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
177872: ** field that occurs at the start of each leaf page (see fts5_index.c). */
177873: #define FTS5_MAX_TOKEN_SIZE 32768
177874: 
177875: /*
177876: ** Maximum number of prefix indexes on single FTS5 table. This must be
177877: ** less than 32. If it is set to anything large than that, an #error
177878: ** directive in fts5_index.c will cause the build to fail.
177879: */
177880: #define FTS5_MAX_PREFIX_INDEXES 31
177881: 
177882: #define FTS5_DEFAULT_NEARDIST 10
177883: #define FTS5_DEFAULT_RANK     "bm25"
177884: 
177885: /* Name of rank and rowid columns */
177886: #define FTS5_RANK_NAME "rank"
177887: #define FTS5_ROWID_NAME "rowid"
177888: 
177889: #ifdef SQLITE_DEBUG
177890: # define FTS5_CORRUPT sqlite3Fts5Corrupt()
177891: static int sqlite3Fts5Corrupt(void);
177892: #else
177893: # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
177894: #endif
177895: 
177896: /*
177897: ** The assert_nc() macro is similar to the assert() macro, except that it
177898: ** is used for assert() conditions that are true only if it can be 
177899: ** guranteed that the database is not corrupt.
177900: */
177901: #ifdef SQLITE_DEBUG
177902: SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
177903: # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
177904: #else
177905: # define assert_nc(x) assert(x)
177906: #endif
177907: 
177908: /* Mark a function parameter as unused, to suppress nuisance compiler
177909: ** warnings. */
177910: #ifndef UNUSED_PARAM
177911: # define UNUSED_PARAM(X)  (void)(X)
177912: #endif
177913: 
177914: #ifndef UNUSED_PARAM2
177915: # define UNUSED_PARAM2(X, Y)  (void)(X), (void)(Y)
177916: #endif
177917: 
177918: typedef struct Fts5Global Fts5Global;
177919: typedef struct Fts5Colset Fts5Colset;
177920: 
177921: /* If a NEAR() clump or phrase may only match a specific set of columns, 
177922: ** then an object of the following type is used to record the set of columns.
177923: ** Each entry in the aiCol[] array is a column that may be matched.
177924: **
177925: ** This object is used by fts5_expr.c and fts5_index.c.
177926: */
177927: struct Fts5Colset {
177928:   int nCol;
177929:   int aiCol[1];
177930: };
177931: 
177932: 
177933: 
177934: /**************************************************************************
177935: ** Interface to code in fts5_config.c. fts5_config.c contains contains code
177936: ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
177937: */
177938: 
177939: typedef struct Fts5Config Fts5Config;
177940: 
177941: /*
177942: ** An instance of the following structure encodes all information that can
177943: ** be gleaned from the CREATE VIRTUAL TABLE statement.
177944: **
177945: ** And all information loaded from the %_config table.
177946: **
177947: ** nAutomerge:
177948: **   The minimum number of segments that an auto-merge operation should
177949: **   attempt to merge together. A value of 1 sets the object to use the 
177950: **   compile time default. Zero disables auto-merge altogether.
177951: **
177952: ** zContent:
177953: **
177954: ** zContentRowid:
177955: **   The value of the content_rowid= option, if one was specified. Or 
177956: **   the string "rowid" otherwise. This text is not quoted - if it is
177957: **   used as part of an SQL statement it needs to be quoted appropriately.
177958: **
177959: ** zContentExprlist:
177960: **
177961: ** pzErrmsg:
177962: **   This exists in order to allow the fts5_index.c module to return a 
177963: **   decent error message if it encounters a file-format version it does
177964: **   not understand.
177965: **
177966: ** bColumnsize:
177967: **   True if the %_docsize table is created.
177968: **
177969: ** bPrefixIndex:
177970: **   This is only used for debugging. If set to false, any prefix indexes
177971: **   are ignored. This value is configured using:
177972: **
177973: **       INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
177974: **
177975: */
177976: struct Fts5Config {
177977:   sqlite3 *db;                    /* Database handle */
177978:   char *zDb;                      /* Database holding FTS index (e.g. "main") */
177979:   char *zName;                    /* Name of FTS index */
177980:   int nCol;                       /* Number of columns */
177981:   char **azCol;                   /* Column names */
177982:   u8 *abUnindexed;                /* True for unindexed columns */
177983:   int nPrefix;                    /* Number of prefix indexes */
177984:   int *aPrefix;                   /* Sizes in bytes of nPrefix prefix indexes */
177985:   int eContent;                   /* An FTS5_CONTENT value */
177986:   char *zContent;                 /* content table */ 
177987:   char *zContentRowid;            /* "content_rowid=" option value */ 
177988:   int bColumnsize;                /* "columnsize=" option value (dflt==1) */
177989:   int eDetail;                    /* FTS5_DETAIL_XXX value */
177990:   char *zContentExprlist;
177991:   Fts5Tokenizer *pTok;
177992:   fts5_tokenizer *pTokApi;
177993: 
177994:   /* Values loaded from the %_config table */
177995:   int iCookie;                    /* Incremented when %_config is modified */
177996:   int pgsz;                       /* Approximate page size used in %_data */
177997:   int nAutomerge;                 /* 'automerge' setting */
177998:   int nCrisisMerge;               /* Maximum allowed segments per level */
177999:   int nUsermerge;                 /* 'usermerge' setting */
178000:   int nHashSize;                  /* Bytes of memory for in-memory hash */
178001:   char *zRank;                    /* Name of rank function */
178002:   char *zRankArgs;                /* Arguments to rank function */
178003: 
178004:   /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
178005:   char **pzErrmsg;
178006: 
178007: #ifdef SQLITE_DEBUG
178008:   int bPrefixIndex;               /* True to use prefix-indexes */
178009: #endif
178010: };
178011: 
178012: /* Current expected value of %_config table 'version' field */
178013: #define FTS5_CURRENT_VERSION 4
178014: 
178015: #define FTS5_CONTENT_NORMAL   0
178016: #define FTS5_CONTENT_NONE     1
178017: #define FTS5_CONTENT_EXTERNAL 2
178018: 
178019: #define FTS5_DETAIL_FULL    0
178020: #define FTS5_DETAIL_NONE    1
178021: #define FTS5_DETAIL_COLUMNS 2
178022: 
178023: 
178024: 
178025: static int sqlite3Fts5ConfigParse(
178026:     Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
178027: );
178028: static void sqlite3Fts5ConfigFree(Fts5Config*);
178029: 
178030: static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
178031: 
178032: static int sqlite3Fts5Tokenize(
178033:   Fts5Config *pConfig,            /* FTS5 Configuration object */
178034:   int flags,                      /* FTS5_TOKENIZE_* flags */
178035:   const char *pText, int nText,   /* Text to tokenize */
178036:   void *pCtx,                     /* Context passed to xToken() */
178037:   int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
178038: );
178039: 
178040: static void sqlite3Fts5Dequote(char *z);
178041: 
178042: /* Load the contents of the %_config table */
178043: static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
178044: 
178045: /* Set the value of a single config attribute */
178046: static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
178047: 
178048: static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
178049: 
178050: /*
178051: ** End of interface to code in fts5_config.c.
178052: **************************************************************************/
178053: 
178054: /**************************************************************************
178055: ** Interface to code in fts5_buffer.c.
178056: */
178057: 
178058: /*
178059: ** Buffer object for the incremental building of string data.
178060: */
178061: typedef struct Fts5Buffer Fts5Buffer;
178062: struct Fts5Buffer {
178063:   u8 *p;
178064:   int n;
178065:   int nSpace;
178066: };
178067: 
178068: static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
178069: static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
178070: static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
178071: static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
178072: static void sqlite3Fts5BufferFree(Fts5Buffer*);
178073: static void sqlite3Fts5BufferZero(Fts5Buffer*);
178074: static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
178075: static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
178076: 
178077: static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
178078: 
178079: #define fts5BufferZero(x)             sqlite3Fts5BufferZero(x)
178080: #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
178081: #define fts5BufferFree(a)             sqlite3Fts5BufferFree(a)
178082: #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
178083: #define fts5BufferSet(a,b,c,d)        sqlite3Fts5BufferSet(a,b,c,d)
178084: 
178085: #define fts5BufferGrow(pRc,pBuf,nn) ( \
178086:   (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
178087:     sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
178088: )
178089: 
178090: /* Write and decode big-endian 32-bit integer values */
178091: static void sqlite3Fts5Put32(u8*, int);
178092: static int sqlite3Fts5Get32(const u8*);
178093: 
178094: #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
178095: #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
178096: 
178097: typedef struct Fts5PoslistReader Fts5PoslistReader;
178098: struct Fts5PoslistReader {
178099:   /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
178100:   const u8 *a;                    /* Position list to iterate through */
178101:   int n;                          /* Size of buffer at a[] in bytes */
178102:   int i;                          /* Current offset in a[] */
178103: 
178104:   u8 bFlag;                       /* For client use (any custom purpose) */
178105: 
178106:   /* Output variables */
178107:   u8 bEof;                        /* Set to true at EOF */
178108:   i64 iPos;                       /* (iCol<<32) + iPos */
178109: };
178110: static int sqlite3Fts5PoslistReaderInit(
178111:   const u8 *a, int n,             /* Poslist buffer to iterate through */
178112:   Fts5PoslistReader *pIter        /* Iterator object to initialize */
178113: );
178114: static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
178115: 
178116: typedef struct Fts5PoslistWriter Fts5PoslistWriter;
178117: struct Fts5PoslistWriter {
178118:   i64 iPrev;
178119: };
178120: static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
178121: static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
178122: 
178123: static int sqlite3Fts5PoslistNext64(
178124:   const u8 *a, int n,             /* Buffer containing poslist */
178125:   int *pi,                        /* IN/OUT: Offset within a[] */
178126:   i64 *piOff                      /* IN/OUT: Current offset */
178127: );
178128: 
178129: /* Malloc utility */
178130: static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
178131: static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
178132: 
178133: /* Character set tests (like isspace(), isalpha() etc.) */
178134: static int sqlite3Fts5IsBareword(char t);
178135: 
178136: 
178137: /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
178138: typedef struct Fts5Termset Fts5Termset;
178139: static int sqlite3Fts5TermsetNew(Fts5Termset**);
178140: static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
178141: static void sqlite3Fts5TermsetFree(Fts5Termset*);
178142: 
178143: /*
178144: ** End of interface to code in fts5_buffer.c.
178145: **************************************************************************/
178146: 
178147: /**************************************************************************
178148: ** Interface to code in fts5_index.c. fts5_index.c contains contains code
178149: ** to access the data stored in the %_data table.
178150: */
178151: 
178152: typedef struct Fts5Index Fts5Index;
178153: typedef struct Fts5IndexIter Fts5IndexIter;
178154: 
178155: struct Fts5IndexIter {
178156:   i64 iRowid;
178157:   const u8 *pData;
178158:   int nData;
178159:   u8 bEof;
178160: };
178161: 
178162: #define sqlite3Fts5IterEof(x) ((x)->bEof)
178163: 
178164: /*
178165: ** Values used as part of the flags argument passed to IndexQuery().
178166: */
178167: #define FTS5INDEX_QUERY_PREFIX     0x0001   /* Prefix query */
178168: #define FTS5INDEX_QUERY_DESC       0x0002   /* Docs in descending rowid order */
178169: #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004   /* Do not use prefix index */
178170: #define FTS5INDEX_QUERY_SCAN       0x0008   /* Scan query (fts5vocab) */
178171: 
178172: /* The following are used internally by the fts5_index.c module. They are
178173: ** defined here only to make it easier to avoid clashes with the flags
178174: ** above. */
178175: #define FTS5INDEX_QUERY_SKIPEMPTY  0x0010
178176: #define FTS5INDEX_QUERY_NOOUTPUT   0x0020
178177: 
178178: /*
178179: ** Create/destroy an Fts5Index object.
178180: */
178181: static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
178182: static int sqlite3Fts5IndexClose(Fts5Index *p);
178183: 
178184: /*
178185: ** Return a simple checksum value based on the arguments.
178186: */
178187: static u64 sqlite3Fts5IndexEntryCksum(
178188:   i64 iRowid, 
178189:   int iCol, 
178190:   int iPos, 
178191:   int iIdx,
178192:   const char *pTerm,
178193:   int nTerm
178194: );
178195: 
178196: /*
178197: ** Argument p points to a buffer containing utf-8 text that is n bytes in 
178198: ** size. Return the number of bytes in the nChar character prefix of the
178199: ** buffer, or 0 if there are less than nChar characters in total.
178200: */
178201: static int sqlite3Fts5IndexCharlenToBytelen(
178202:   const char *p, 
178203:   int nByte, 
178204:   int nChar
178205: );
178206: 
178207: /*
178208: ** Open a new iterator to iterate though all rowids that match the 
178209: ** specified token or token prefix.
178210: */
178211: static int sqlite3Fts5IndexQuery(
178212:   Fts5Index *p,                   /* FTS index to query */
178213:   const char *pToken, int nToken, /* Token (or prefix) to query for */
178214:   int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
178215:   Fts5Colset *pColset,            /* Match these columns only */
178216:   Fts5IndexIter **ppIter          /* OUT: New iterator object */
178217: );
178218: 
178219: /*
178220: ** The various operations on open token or token prefix iterators opened
178221: ** using sqlite3Fts5IndexQuery().
178222: */
178223: static int sqlite3Fts5IterNext(Fts5IndexIter*);
178224: static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
178225: 
178226: /*
178227: ** Close an iterator opened by sqlite3Fts5IndexQuery().
178228: */
178229: static void sqlite3Fts5IterClose(Fts5IndexIter*);
178230: 
178231: /*
178232: ** This interface is used by the fts5vocab module.
178233: */
178234: static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
178235: static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
178236: 
178237: 
178238: /*
178239: ** Insert or remove data to or from the index. Each time a document is 
178240: ** added to or removed from the index, this function is called one or more
178241: ** times.
178242: **
178243: ** For an insert, it must be called once for each token in the new document.
178244: ** If the operation is a delete, it must be called (at least) once for each
178245: ** unique token in the document with an iCol value less than zero. The iPos
178246: ** argument is ignored for a delete.
178247: */
178248: static int sqlite3Fts5IndexWrite(
178249:   Fts5Index *p,                   /* Index to write to */
178250:   int iCol,                       /* Column token appears in (-ve -> delete) */
178251:   int iPos,                       /* Position of token within column */
178252:   const char *pToken, int nToken  /* Token to add or remove to or from index */
178253: );
178254: 
178255: /*
178256: ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
178257: ** document iDocid.
178258: */
178259: static int sqlite3Fts5IndexBeginWrite(
178260:   Fts5Index *p,                   /* Index to write to */
178261:   int bDelete,                    /* True if current operation is a delete */
178262:   i64 iDocid                      /* Docid to add or remove data from */
178263: );
178264: 
178265: /*
178266: ** Flush any data stored in the in-memory hash tables to the database.
178267: ** If the bCommit flag is true, also close any open blob handles.
178268: */
178269: static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
178270: 
178271: /*
178272: ** Discard any data stored in the in-memory hash tables. Do not write it
178273: ** to the database. Additionally, assume that the contents of the %_data
178274: ** table may have changed on disk. So any in-memory caches of %_data 
178275: ** records must be invalidated.
178276: */
178277: static int sqlite3Fts5IndexRollback(Fts5Index *p);
178278: 
178279: /*
178280: ** Get or set the "averages" values.
178281: */
178282: static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
178283: static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
178284: 
178285: /*
178286: ** Functions called by the storage module as part of integrity-check.
178287: */
178288: static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
178289: 
178290: /* 
178291: ** Called during virtual module initialization to register UDF 
178292: ** fts5_decode() with SQLite 
178293: */
178294: static int sqlite3Fts5IndexInit(sqlite3*);
178295: 
178296: static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
178297: 
178298: /*
178299: ** Return the total number of entries read from the %_data table by 
178300: ** this connection since it was created.
178301: */
178302: static int sqlite3Fts5IndexReads(Fts5Index *p);
178303: 
178304: static int sqlite3Fts5IndexReinit(Fts5Index *p);
178305: static int sqlite3Fts5IndexOptimize(Fts5Index *p);
178306: static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
178307: static int sqlite3Fts5IndexReset(Fts5Index *p);
178308: 
178309: static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
178310: 
178311: /*
178312: ** End of interface to code in fts5_index.c.
178313: **************************************************************************/
178314: 
178315: /**************************************************************************
178316: ** Interface to code in fts5_varint.c. 
178317: */
178318: static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
178319: static int sqlite3Fts5GetVarintLen(u32 iVal);
178320: static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
178321: static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
178322: 
178323: #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
178324: #define fts5GetVarint    sqlite3Fts5GetVarint
178325: 
178326: #define fts5FastGetVarint32(a, iOff, nVal) {      \
178327:   nVal = (a)[iOff++];                             \
178328:   if( nVal & 0x80 ){                              \
178329:     iOff--;                                       \
178330:     iOff += fts5GetVarint32(&(a)[iOff], nVal);    \
178331:   }                                               \
178332: }
178333: 
178334: 
178335: /*
178336: ** End of interface to code in fts5_varint.c.
178337: **************************************************************************/
178338: 
178339: 
178340: /**************************************************************************
178341: ** Interface to code in fts5.c. 
178342: */
178343: 
178344: static int sqlite3Fts5GetTokenizer(
178345:   Fts5Global*, 
178346:   const char **azArg,
178347:   int nArg,
178348:   Fts5Tokenizer**,
178349:   fts5_tokenizer**,
178350:   char **pzErr
178351: );
178352: 
178353: static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
178354: 
178355: /*
178356: ** End of interface to code in fts5.c.
178357: **************************************************************************/
178358: 
178359: /**************************************************************************
178360: ** Interface to code in fts5_hash.c. 
178361: */
178362: typedef struct Fts5Hash Fts5Hash;
178363: 
178364: /*
178365: ** Create a hash table, free a hash table.
178366: */
178367: static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
178368: static void sqlite3Fts5HashFree(Fts5Hash*);
178369: 
178370: static int sqlite3Fts5HashWrite(
178371:   Fts5Hash*,
178372:   i64 iRowid,                     /* Rowid for this entry */
178373:   int iCol,                       /* Column token appears in (-ve -> delete) */
178374:   int iPos,                       /* Position of token within column */
178375:   char bByte,
178376:   const char *pToken, int nToken  /* Token to add or remove to or from index */
178377: );
178378: 
178379: /*
178380: ** Empty (but do not delete) a hash table.
178381: */
178382: static void sqlite3Fts5HashClear(Fts5Hash*);
178383: 
178384: static int sqlite3Fts5HashQuery(
178385:   Fts5Hash*,                      /* Hash table to query */
178386:   const char *pTerm, int nTerm,   /* Query term */
178387:   const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
178388:   int *pnDoclist                  /* OUT: Size of doclist in bytes */
178389: );
178390: 
178391: static int sqlite3Fts5HashScanInit(
178392:   Fts5Hash*,                      /* Hash table to query */
178393:   const char *pTerm, int nTerm    /* Query prefix */
178394: );
178395: static void sqlite3Fts5HashScanNext(Fts5Hash*);
178396: static int sqlite3Fts5HashScanEof(Fts5Hash*);
178397: static void sqlite3Fts5HashScanEntry(Fts5Hash *,
178398:   const char **pzTerm,            /* OUT: term (nul-terminated) */
178399:   const u8 **ppDoclist,           /* OUT: pointer to doclist */
178400:   int *pnDoclist                  /* OUT: size of doclist in bytes */
178401: );
178402: 
178403: 
178404: /*
178405: ** End of interface to code in fts5_hash.c.
178406: **************************************************************************/
178407: 
178408: /**************************************************************************
178409: ** Interface to code in fts5_storage.c. fts5_storage.c contains contains 
178410: ** code to access the data stored in the %_content and %_docsize tables.
178411: */
178412: 
178413: #define FTS5_STMT_SCAN_ASC  0     /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
178414: #define FTS5_STMT_SCAN_DESC 1     /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
178415: #define FTS5_STMT_LOOKUP    2     /* SELECT rowid, * FROM ... WHERE rowid=? */
178416: 
178417: typedef struct Fts5Storage Fts5Storage;
178418: 
178419: static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
178420: static int sqlite3Fts5StorageClose(Fts5Storage *p);
178421: static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
178422: 
178423: static int sqlite3Fts5DropAll(Fts5Config*);
178424: static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
178425: 
178426: static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
178427: static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
178428: static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
178429: 
178430: static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
178431: 
178432: static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
178433: static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
178434: 
178435: static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
178436: static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
178437: static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
178438: 
178439: static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
178440: static int sqlite3Fts5StorageRollback(Fts5Storage *p);
178441: 
178442: static int sqlite3Fts5StorageConfigValue(
178443:     Fts5Storage *p, const char*, sqlite3_value*, int
178444: );
178445: 
178446: static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
178447: static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
178448: static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
178449: static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
178450: static int sqlite3Fts5StorageReset(Fts5Storage *p);
178451: 
178452: /*
178453: ** End of interface to code in fts5_storage.c.
178454: **************************************************************************/
178455: 
178456: 
178457: /**************************************************************************
178458: ** Interface to code in fts5_expr.c. 
178459: */
178460: typedef struct Fts5Expr Fts5Expr;
178461: typedef struct Fts5ExprNode Fts5ExprNode;
178462: typedef struct Fts5Parse Fts5Parse;
178463: typedef struct Fts5Token Fts5Token;
178464: typedef struct Fts5ExprPhrase Fts5ExprPhrase;
178465: typedef struct Fts5ExprNearset Fts5ExprNearset;
178466: 
178467: struct Fts5Token {
178468:   const char *p;                  /* Token text (not NULL terminated) */
178469:   int n;                          /* Size of buffer p in bytes */
178470: };
178471: 
178472: /* Parse a MATCH expression. */
178473: static int sqlite3Fts5ExprNew(
178474:   Fts5Config *pConfig, 
178475:   const char *zExpr,
178476:   Fts5Expr **ppNew, 
178477:   char **pzErr
178478: );
178479: 
178480: /*
178481: ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
178482: **     rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
178483: **     rc = sqlite3Fts5ExprNext(pExpr)
178484: ** ){
178485: **   // The document with rowid iRowid matches the expression!
178486: **   i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
178487: ** }
178488: */
178489: static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
178490: static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
178491: static int sqlite3Fts5ExprEof(Fts5Expr*);
178492: static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
178493: 
178494: static void sqlite3Fts5ExprFree(Fts5Expr*);
178495: 
178496: /* Called during startup to register a UDF with SQLite */
178497: static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
178498: 
178499: static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
178500: static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
178501: static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
178502: 
178503: typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
178504: static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
178505: static int sqlite3Fts5ExprPopulatePoslists(
178506:     Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
178507: );
178508: static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
178509: 
178510: static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
178511: 
178512: static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
178513: 
178514: /*******************************************
178515: ** The fts5_expr.c API above this point is used by the other hand-written
178516: ** C code in this module. The interfaces below this point are called by
178517: ** the parser code in fts5parse.y.  */
178518: 
178519: static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
178520: 
178521: static Fts5ExprNode *sqlite3Fts5ParseNode(
178522:   Fts5Parse *pParse,
178523:   int eType,
178524:   Fts5ExprNode *pLeft,
178525:   Fts5ExprNode *pRight,
178526:   Fts5ExprNearset *pNear
178527: );
178528: 
178529: static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
178530:   Fts5Parse *pParse,
178531:   Fts5ExprNode *pLeft,
178532:   Fts5ExprNode *pRight
178533: );
178534: 
178535: static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
178536:   Fts5Parse *pParse, 
178537:   Fts5ExprPhrase *pPhrase, 
178538:   Fts5Token *pToken,
178539:   int bPrefix
178540: );
178541: 
178542: static Fts5ExprNearset *sqlite3Fts5ParseNearset(
178543:   Fts5Parse*, 
178544:   Fts5ExprNearset*,
178545:   Fts5ExprPhrase* 
178546: );
178547: 
178548: static Fts5Colset *sqlite3Fts5ParseColset(
178549:   Fts5Parse*, 
178550:   Fts5Colset*, 
178551:   Fts5Token *
178552: );
178553: 
178554: static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
178555: static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
178556: static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
178557: 
178558: static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
178559: static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
178560: static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
178561: static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
178562: 
178563: /*
178564: ** End of interface to code in fts5_expr.c.
178565: **************************************************************************/
178566: 
178567: 
178568: 
178569: /**************************************************************************
178570: ** Interface to code in fts5_aux.c. 
178571: */
178572: 
178573: static int sqlite3Fts5AuxInit(fts5_api*);
178574: /*
178575: ** End of interface to code in fts5_aux.c.
178576: **************************************************************************/
178577: 
178578: /**************************************************************************
178579: ** Interface to code in fts5_tokenizer.c. 
178580: */
178581: 
178582: static int sqlite3Fts5TokenizerInit(fts5_api*);
178583: /*
178584: ** End of interface to code in fts5_tokenizer.c.
178585: **************************************************************************/
178586: 
178587: /**************************************************************************
178588: ** Interface to code in fts5_vocab.c. 
178589: */
178590: 
178591: static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
178592: 
178593: /*
178594: ** End of interface to code in fts5_vocab.c.
178595: **************************************************************************/
178596: 
178597: 
178598: /**************************************************************************
178599: ** Interface to automatically generated code in fts5_unicode2.c. 
178600: */
178601: static int sqlite3Fts5UnicodeIsalnum(int c);
178602: static int sqlite3Fts5UnicodeIsdiacritic(int c);
178603: static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
178604: /*
178605: ** End of interface to code in fts5_unicode2.c.
178606: **************************************************************************/
178607: 
178608: #endif
178609: 
178610: #define FTS5_OR                               1
178611: #define FTS5_AND                              2
178612: #define FTS5_NOT                              3
178613: #define FTS5_TERM                             4
178614: #define FTS5_COLON                            5
178615: #define FTS5_LP                               6
178616: #define FTS5_RP                               7
178617: #define FTS5_LCP                              8
178618: #define FTS5_RCP                              9
178619: #define FTS5_STRING                          10
178620: #define FTS5_COMMA                           11
178621: #define FTS5_PLUS                            12
178622: #define FTS5_STAR                            13
178623: 
178624: /*
178625: ** 2000-05-29
178626: **
178627: ** The author disclaims copyright to this source code.  In place of
178628: ** a legal notice, here is a blessing:
178629: **
178630: **    May you do good and not evil.
178631: **    May you find forgiveness for yourself and forgive others.
178632: **    May you share freely, never taking more than you give.
178633: **
178634: *************************************************************************
178635: ** Driver template for the LEMON parser generator.
178636: **
178637: ** The "lemon" program processes an LALR(1) input grammar file, then uses
178638: ** this template to construct a parser.  The "lemon" program inserts text
178639: ** at each "%%" line.  Also, any "P-a-r-s-e" identifer prefix (without the
178640: ** interstitial "-" characters) contained in this template is changed into
178641: ** the value of the %name directive from the grammar.  Otherwise, the content
178642: ** of this template is copied straight through into the generate parser
178643: ** source file.
178644: **
178645: ** The following is the concatenation of all %include directives from the
178646: ** input grammar file:
178647: */
178648: /* #include <stdio.h> */
178649: /************ Begin %include sections from the grammar ************************/
178650: 
178651: /* #include "fts5Int.h" */
178652: /* #include "fts5parse.h" */
178653: 
178654: /*
178655: ** Disable all error recovery processing in the parser push-down
178656: ** automaton.
178657: */
178658: #define fts5YYNOERRORRECOVERY 1
178659: 
178660: /*
178661: ** Make fts5yytestcase() the same as testcase()
178662: */
178663: #define fts5yytestcase(X) testcase(X)
178664: 
178665: /*
178666: ** Indicate that sqlite3ParserFree() will never be called with a null
178667: ** pointer.
178668: */
178669: #define fts5YYPARSEFREENOTNULL 1
178670: 
178671: /*
178672: ** Alternative datatype for the argument to the malloc() routine passed
178673: ** into sqlite3ParserAlloc().  The default is size_t.
178674: */
178675: #define fts5YYMALLOCARGTYPE  u64
178676: 
178677: /**************** End of %include directives **********************************/
178678: /* These constants specify the various numeric values for terminal symbols
178679: ** in a format understandable to "makeheaders".  This section is blank unless
178680: ** "lemon" is run with the "-m" command-line option.
178681: ***************** Begin makeheaders token definitions *************************/
178682: /**************** End makeheaders token definitions ***************************/
178683: 
178684: /* The next sections is a series of control #defines.
178685: ** various aspects of the generated parser.
178686: **    fts5YYCODETYPE         is the data type used to store the integer codes
178687: **                       that represent terminal and non-terminal symbols.
178688: **                       "unsigned char" is used if there are fewer than
178689: **                       256 symbols.  Larger types otherwise.
178690: **    fts5YYNOCODE           is a number of type fts5YYCODETYPE that is not used for
178691: **                       any terminal or nonterminal symbol.
178692: **    fts5YYFALLBACK         If defined, this indicates that one or more tokens
178693: **                       (also known as: "terminal symbols") have fall-back
178694: **                       values which should be used if the original symbol
178695: **                       would not parse.  This permits keywords to sometimes
178696: **                       be used as identifiers, for example.
178697: **    fts5YYACTIONTYPE       is the data type used for "action codes" - numbers
178698: **                       that indicate what to do in response to the next
178699: **                       token.
178700: **    sqlite3Fts5ParserFTS5TOKENTYPE     is the data type used for minor type for terminal
178701: **                       symbols.  Background: A "minor type" is a semantic
178702: **                       value associated with a terminal or non-terminal
178703: **                       symbols.  For example, for an "ID" terminal symbol,
178704: **                       the minor type might be the name of the identifier.
178705: **                       Each non-terminal can have a different minor type.
178706: **                       Terminal symbols all have the same minor type, though.
178707: **                       This macros defines the minor type for terminal 
178708: **                       symbols.
178709: **    fts5YYMINORTYPE        is the data type used for all minor types.
178710: **                       This is typically a union of many types, one of
178711: **                       which is sqlite3Fts5ParserFTS5TOKENTYPE.  The entry in the union
178712: **                       for terminal symbols is called "fts5yy0".
178713: **    fts5YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
178714: **                       zero the stack is dynamically sized using realloc()
178715: **    sqlite3Fts5ParserARG_SDECL     A static variable declaration for the %extra_argument
178716: **    sqlite3Fts5ParserARG_PDECL     A parameter declaration for the %extra_argument
178717: **    sqlite3Fts5ParserARG_STORE     Code to store %extra_argument into fts5yypParser
178718: **    sqlite3Fts5ParserARG_FETCH     Code to extract %extra_argument from fts5yypParser
178719: **    fts5YYERRORSYMBOL      is the code number of the error symbol.  If not
178720: **                       defined, then do no error processing.
178721: **    fts5YYNSTATE           the combined number of states.
178722: **    fts5YYNRULE            the number of rules in the grammar
178723: **    fts5YY_MAX_SHIFT       Maximum value for shift actions
178724: **    fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
178725: **    fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
178726: **    fts5YY_MIN_REDUCE      Maximum value for reduce actions
178727: **    fts5YY_ERROR_ACTION    The fts5yy_action[] code for syntax error
178728: **    fts5YY_ACCEPT_ACTION   The fts5yy_action[] code for accept
178729: **    fts5YY_NO_ACTION       The fts5yy_action[] code for no-op
178730: */
178731: #ifndef INTERFACE
178732: # define INTERFACE 1
178733: #endif
178734: /************* Begin control #defines *****************************************/
178735: #define fts5YYCODETYPE unsigned char
178736: #define fts5YYNOCODE 27
178737: #define fts5YYACTIONTYPE unsigned char
178738: #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
178739: typedef union {
178740:   int fts5yyinit;
178741:   sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
178742:   Fts5Colset* fts5yy3;
178743:   Fts5ExprPhrase* fts5yy11;
178744:   Fts5ExprNode* fts5yy18;
178745:   int fts5yy20;
178746:   Fts5ExprNearset* fts5yy26;
178747: } fts5YYMINORTYPE;
178748: #ifndef fts5YYSTACKDEPTH
178749: #define fts5YYSTACKDEPTH 100
178750: #endif
178751: #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
178752: #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
178753: #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
178754: #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
178755: #define fts5YYNSTATE             26
178756: #define fts5YYNRULE              24
178757: #define fts5YY_MAX_SHIFT         25
178758: #define fts5YY_MIN_SHIFTREDUCE   40
178759: #define fts5YY_MAX_SHIFTREDUCE   63
178760: #define fts5YY_MIN_REDUCE        64
178761: #define fts5YY_MAX_REDUCE        87
178762: #define fts5YY_ERROR_ACTION      88
178763: #define fts5YY_ACCEPT_ACTION     89
178764: #define fts5YY_NO_ACTION         90
178765: /************* End control #defines *******************************************/
178766: 
178767: /* Define the fts5yytestcase() macro to be a no-op if is not already defined
178768: ** otherwise.
178769: **
178770: ** Applications can choose to define fts5yytestcase() in the %include section
178771: ** to a macro that can assist in verifying code coverage.  For production
178772: ** code the fts5yytestcase() macro should be turned off.  But it is useful
178773: ** for testing.
178774: */
178775: #ifndef fts5yytestcase
178776: # define fts5yytestcase(X)
178777: #endif
178778: 
178779: 
178780: /* Next are the tables used to determine what action to take based on the
178781: ** current state and lookahead token.  These tables are used to implement
178782: ** functions that take a state number and lookahead value and return an
178783: ** action integer.  
178784: **
178785: ** Suppose the action integer is N.  Then the action is determined as
178786: ** follows
178787: **
178788: **   0 <= N <= fts5YY_MAX_SHIFT             Shift N.  That is, push the lookahead
178789: **                                      token onto the stack and goto state N.
178790: **
178791: **   N between fts5YY_MIN_SHIFTREDUCE       Shift to an arbitrary state then
178792: **     and fts5YY_MAX_SHIFTREDUCE           reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
178793: **
178794: **   N between fts5YY_MIN_REDUCE            Reduce by rule N-fts5YY_MIN_REDUCE
178795: **     and fts5YY_MAX_REDUCE
178796: 
178797: **   N == fts5YY_ERROR_ACTION               A syntax error has occurred.
178798: **
178799: **   N == fts5YY_ACCEPT_ACTION              The parser accepts its input.
178800: **
178801: **   N == fts5YY_NO_ACTION                  No such action.  Denotes unused
178802: **                                      slots in the fts5yy_action[] table.
178803: **
178804: ** The action table is constructed as a single large table named fts5yy_action[].
178805: ** Given state S and lookahead X, the action is computed as
178806: **
178807: **      fts5yy_action[ fts5yy_shift_ofst[S] + X ]
178808: **
178809: ** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
178810: ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
178811: ** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
178812: ** and that fts5yy_default[S] should be used instead.  
178813: **
178814: ** The formula above is for computing the action when the lookahead is
178815: ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
178816: ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
178817: ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
178818: ** fts5YY_SHIFT_USE_DFLT.
178819: **
178820: ** The following are the tables generated in this section:
178821: **
178822: **  fts5yy_action[]        A single table containing all actions.
178823: **  fts5yy_lookahead[]     A table containing the lookahead for each entry in
178824: **                     fts5yy_action.  Used to detect hash collisions.
178825: **  fts5yy_shift_ofst[]    For each state, the offset into fts5yy_action for
178826: **                     shifting terminals.
178827: **  fts5yy_reduce_ofst[]   For each state, the offset into fts5yy_action for
178828: **                     shifting non-terminals after a reduce.
178829: **  fts5yy_default[]       Default action for each state.
178830: **
178831: *********** Begin parsing tables **********************************************/
178832: #define fts5YY_ACTTAB_COUNT (78)
178833: static const fts5YYACTIONTYPE fts5yy_action[] = {
178834:  /*     0 */    89,   15,   46,    5,   48,   24,   12,   19,   23,   14,
178835:  /*    10 */    46,    5,   48,   24,   20,   21,   23,   43,   46,    5,
178836:  /*    20 */    48,   24,    6,   18,   23,   17,   46,    5,   48,   24,
178837:  /*    30 */    75,    7,   23,   25,   46,    5,   48,   24,   62,   47,
178838:  /*    40 */    23,   48,   24,    7,   11,   23,    9,    3,    4,    2,
178839:  /*    50 */    62,   50,   52,   44,   64,    3,    4,    2,   49,    4,
178840:  /*    60 */     2,    1,   23,   11,   16,    9,   12,    2,   10,   61,
178841:  /*    70 */    53,   59,   62,   60,   22,   13,   55,    8,
178842: };
178843: static const fts5YYCODETYPE fts5yy_lookahead[] = {
178844:  /*     0 */    15,   16,   17,   18,   19,   20,   10,   11,   23,   16,
178845:  /*    10 */    17,   18,   19,   20,   23,   24,   23,   16,   17,   18,
178846:  /*    20 */    19,   20,   22,   23,   23,   16,   17,   18,   19,   20,
178847:  /*    30 */     5,    6,   23,   16,   17,   18,   19,   20,   13,   17,
178848:  /*    40 */    23,   19,   20,    6,    8,   23,   10,    1,    2,    3,
178849:  /*    50 */    13,    9,   10,    7,    0,    1,    2,    3,   19,    2,
178850:  /*    60 */     3,    6,   23,    8,   21,   10,   10,    3,   10,   25,
178851:  /*    70 */    10,   10,   13,   25,   12,   10,    7,    5,
178852: };
178853: #define fts5YY_SHIFT_USE_DFLT (-5)
178854: #define fts5YY_SHIFT_COUNT (25)
178855: #define fts5YY_SHIFT_MIN   (-4)
178856: #define fts5YY_SHIFT_MAX   (72)
178857: static const signed char fts5yy_shift_ofst[] = {
178858:  /*     0 */    55,   55,   55,   55,   55,   36,   -4,   56,   58,   25,
178859:  /*    10 */    37,   60,   59,   59,   46,   54,   42,   57,   62,   61,
178860:  /*    20 */    62,   69,   65,   62,   72,   64,
178861: };
178862: #define fts5YY_REDUCE_USE_DFLT (-16)
178863: #define fts5YY_REDUCE_COUNT (13)
178864: #define fts5YY_REDUCE_MIN   (-15)
178865: #define fts5YY_REDUCE_MAX   (48)
178866: static const signed char fts5yy_reduce_ofst[] = {
178867:  /*     0 */   -15,   -7,    1,    9,   17,   22,   -9,    0,   39,   44,
178868:  /*    10 */    44,   43,   44,   48,
178869: };
178870: static const fts5YYACTIONTYPE fts5yy_default[] = {
178871:  /*     0 */    88,   88,   88,   88,   88,   69,   82,   88,   88,   87,
178872:  /*    10 */    87,   88,   87,   87,   88,   88,   88,   66,   80,   88,
178873:  /*    20 */    81,   88,   88,   78,   88,   65,
178874: };
178875: /********** End of lemon-generated parsing tables *****************************/
178876: 
178877: /* The next table maps tokens (terminal symbols) into fallback tokens.  
178878: ** If a construct like the following:
178879: ** 
178880: **      %fallback ID X Y Z.
178881: **
178882: ** appears in the grammar, then ID becomes a fallback token for X, Y,
178883: ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
178884: ** but it does not parse, the type of the token is changed to ID and
178885: ** the parse is retried before an error is thrown.
178886: **
178887: ** This feature can be used, for example, to cause some keywords in a language
178888: ** to revert to identifiers if they keyword does not apply in the context where
178889: ** it appears.
178890: */
178891: #ifdef fts5YYFALLBACK
178892: static const fts5YYCODETYPE fts5yyFallback[] = {
178893: };
178894: #endif /* fts5YYFALLBACK */
178895: 
178896: /* The following structure represents a single element of the
178897: ** parser's stack.  Information stored includes:
178898: **
178899: **   +  The state number for the parser at this level of the stack.
178900: **
178901: **   +  The value of the token stored at this level of the stack.
178902: **      (In other words, the "major" token.)
178903: **
178904: **   +  The semantic value stored at this level of the stack.  This is
178905: **      the information used by the action routines in the grammar.
178906: **      It is sometimes called the "minor" token.
178907: **
178908: ** After the "shift" half of a SHIFTREDUCE action, the stateno field
178909: ** actually contains the reduce action for the second half of the
178910: ** SHIFTREDUCE.
178911: */
178912: struct fts5yyStackEntry {
178913:   fts5YYACTIONTYPE stateno;  /* The state-number, or reduce action in SHIFTREDUCE */
178914:   fts5YYCODETYPE major;      /* The major token value.  This is the code
178915:                          ** number for the token at this stack level */
178916:   fts5YYMINORTYPE minor;     /* The user-supplied minor token value.  This
178917:                          ** is the value of the token  */
178918: };
178919: typedef struct fts5yyStackEntry fts5yyStackEntry;
178920: 
178921: /* The state of the parser is completely contained in an instance of
178922: ** the following structure */
178923: struct fts5yyParser {
178924:   fts5yyStackEntry *fts5yytos;          /* Pointer to top element of the stack */
178925: #ifdef fts5YYTRACKMAXSTACKDEPTH
178926:   int fts5yyhwm;                    /* High-water mark of the stack */
178927: #endif
178928: #ifndef fts5YYNOERRORRECOVERY
178929:   int fts5yyerrcnt;                 /* Shifts left before out of the error */
178930: #endif
178931:   sqlite3Fts5ParserARG_SDECL                /* A place to hold %extra_argument */
178932: #if fts5YYSTACKDEPTH<=0
178933:   int fts5yystksz;                  /* Current side of the stack */
178934:   fts5yyStackEntry *fts5yystack;        /* The parser's stack */
178935:   fts5yyStackEntry fts5yystk0;          /* First stack entry */
178936: #else
178937:   fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH];  /* The parser's stack */
178938: #endif
178939: };
178940: typedef struct fts5yyParser fts5yyParser;
178941: 
178942: #ifndef NDEBUG
178943: /* #include <stdio.h> */
178944: static FILE *fts5yyTraceFILE = 0;
178945: static char *fts5yyTracePrompt = 0;
178946: #endif /* NDEBUG */
178947: 
178948: #ifndef NDEBUG
178949: /* 
178950: ** Turn parser tracing on by giving a stream to which to write the trace
178951: ** and a prompt to preface each trace message.  Tracing is turned off
178952: ** by making either argument NULL 
178953: **
178954: ** Inputs:
178955: ** <ul>
178956: ** <li> A FILE* to which trace output should be written.
178957: **      If NULL, then tracing is turned off.
178958: ** <li> A prefix string written at the beginning of every
178959: **      line of trace output.  If NULL, then tracing is
178960: **      turned off.
178961: ** </ul>
178962: **
178963: ** Outputs:
178964: ** None.
178965: */
178966: static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
178967:   fts5yyTraceFILE = TraceFILE;
178968:   fts5yyTracePrompt = zTracePrompt;
178969:   if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
178970:   else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
178971: }
178972: #endif /* NDEBUG */
178973: 
178974: #ifndef NDEBUG
178975: /* For tracing shifts, the names of all terminals and nonterminals
178976: ** are required.  The following table supplies these names */
178977: static const char *const fts5yyTokenName[] = { 
178978:   "$",             "OR",            "AND",           "NOT",         
178979:   "TERM",          "COLON",         "LP",            "RP",          
178980:   "LCP",           "RCP",           "STRING",        "COMMA",       
178981:   "PLUS",          "STAR",          "error",         "input",       
178982:   "expr",          "cnearset",      "exprlist",      "nearset",     
178983:   "colset",        "colsetlist",    "nearphrases",   "phrase",      
178984:   "neardist_opt",  "star_opt",    
178985: };
178986: #endif /* NDEBUG */
178987: 
178988: #ifndef NDEBUG
178989: /* For tracing reduce actions, the names of all rules are required.
178990: */
178991: static const char *const fts5yyRuleName[] = {
178992:  /*   0 */ "input ::= expr",
178993:  /*   1 */ "expr ::= expr AND expr",
178994:  /*   2 */ "expr ::= expr OR expr",
178995:  /*   3 */ "expr ::= expr NOT expr",
178996:  /*   4 */ "expr ::= LP expr RP",
178997:  /*   5 */ "expr ::= exprlist",
178998:  /*   6 */ "exprlist ::= cnearset",
178999:  /*   7 */ "exprlist ::= exprlist cnearset",
179000:  /*   8 */ "cnearset ::= nearset",
179001:  /*   9 */ "cnearset ::= colset COLON nearset",
179002:  /*  10 */ "colset ::= LCP colsetlist RCP",
179003:  /*  11 */ "colset ::= STRING",
179004:  /*  12 */ "colsetlist ::= colsetlist STRING",
179005:  /*  13 */ "colsetlist ::= STRING",
179006:  /*  14 */ "nearset ::= phrase",
179007:  /*  15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
179008:  /*  16 */ "nearphrases ::= phrase",
179009:  /*  17 */ "nearphrases ::= nearphrases phrase",
179010:  /*  18 */ "neardist_opt ::=",
179011:  /*  19 */ "neardist_opt ::= COMMA STRING",
179012:  /*  20 */ "phrase ::= phrase PLUS STRING star_opt",
179013:  /*  21 */ "phrase ::= STRING star_opt",
179014:  /*  22 */ "star_opt ::= STAR",
179015:  /*  23 */ "star_opt ::=",
179016: };
179017: #endif /* NDEBUG */
179018: 
179019: 
179020: #if fts5YYSTACKDEPTH<=0
179021: /*
179022: ** Try to increase the size of the parser stack.  Return the number
179023: ** of errors.  Return 0 on success.
179024: */
179025: static int fts5yyGrowStack(fts5yyParser *p){
179026:   int newSize;
179027:   int idx;
179028:   fts5yyStackEntry *pNew;
179029: 
179030:   newSize = p->fts5yystksz*2 + 100;
179031:   idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
179032:   if( p->fts5yystack==&p->fts5yystk0 ){
179033:     pNew = malloc(newSize*sizeof(pNew[0]));
179034:     if( pNew ) pNew[0] = p->fts5yystk0;
179035:   }else{
179036:     pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
179037:   }
179038:   if( pNew ){
179039:     p->fts5yystack = pNew;
179040:     p->fts5yytos = &p->fts5yystack[idx];
179041: #ifndef NDEBUG
179042:     if( fts5yyTraceFILE ){
179043:       fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
179044:               fts5yyTracePrompt, p->fts5yystksz, newSize);
179045:     }
179046: #endif
179047:     p->fts5yystksz = newSize;
179048:   }
179049:   return pNew==0; 
179050: }
179051: #endif
179052: 
179053: /* Datatype of the argument to the memory allocated passed as the
179054: ** second argument to sqlite3Fts5ParserAlloc() below.  This can be changed by
179055: ** putting an appropriate #define in the %include section of the input
179056: ** grammar.
179057: */
179058: #ifndef fts5YYMALLOCARGTYPE
179059: # define fts5YYMALLOCARGTYPE size_t
179060: #endif
179061: 
179062: /* 
179063: ** This function allocates a new parser.
179064: ** The only argument is a pointer to a function which works like
179065: ** malloc.
179066: **
179067: ** Inputs:
179068: ** A pointer to the function used to allocate memory.
179069: **
179070: ** Outputs:
179071: ** A pointer to a parser.  This pointer is used in subsequent calls
179072: ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
179073: */
179074: static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
179075:   fts5yyParser *pParser;
179076:   pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
179077:   if( pParser ){
179078: #ifdef fts5YYTRACKMAXSTACKDEPTH
179079:     pParser->fts5yyhwm = 0;
179080: #endif
179081: #if fts5YYSTACKDEPTH<=0
179082:     pParser->fts5yytos = NULL;
179083:     pParser->fts5yystack = NULL;
179084:     pParser->fts5yystksz = 0;
179085:     if( fts5yyGrowStack(pParser) ){
179086:       pParser->fts5yystack = &pParser->fts5yystk0;
179087:       pParser->fts5yystksz = 1;
179088:     }
179089: #endif
179090: #ifndef fts5YYNOERRORRECOVERY
179091:     pParser->fts5yyerrcnt = -1;
179092: #endif
179093:     pParser->fts5yytos = pParser->fts5yystack;
179094:     pParser->fts5yystack[0].stateno = 0;
179095:     pParser->fts5yystack[0].major = 0;
179096:   }
179097:   return pParser;
179098: }
179099: 
179100: /* The following function deletes the "minor type" or semantic value
179101: ** associated with a symbol.  The symbol can be either a terminal
179102: ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
179103: ** a pointer to the value to be deleted.  The code used to do the 
179104: ** deletions is derived from the %destructor and/or %token_destructor
179105: ** directives of the input grammar.
179106: */
179107: static void fts5yy_destructor(
179108:   fts5yyParser *fts5yypParser,    /* The parser */
179109:   fts5YYCODETYPE fts5yymajor,     /* Type code for object to destroy */
179110:   fts5YYMINORTYPE *fts5yypminor   /* The object to be destroyed */
179111: ){
179112:   sqlite3Fts5ParserARG_FETCH;
179113:   switch( fts5yymajor ){
179114:     /* Here is inserted the actions which take place when a
179115:     ** terminal or non-terminal is destroyed.  This can happen
179116:     ** when the symbol is popped from the stack during a
179117:     ** reduce or during error processing or when a parser is 
179118:     ** being destroyed before it is finished parsing.
179119:     **
179120:     ** Note: during a reduce, the only symbols destroyed are those
179121:     ** which appear on the RHS of the rule, but which are *not* used
179122:     ** inside the C code.
179123:     */
179124: /********* Begin destructor definitions ***************************************/
179125:     case 15: /* input */
179126: {
179127:  (void)pParse; 
179128: }
179129:       break;
179130:     case 16: /* expr */
179131:     case 17: /* cnearset */
179132:     case 18: /* exprlist */
179133: {
179134:  sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18)); 
179135: }
179136:       break;
179137:     case 19: /* nearset */
179138:     case 22: /* nearphrases */
179139: {
179140:  sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26)); 
179141: }
179142:       break;
179143:     case 20: /* colset */
179144:     case 21: /* colsetlist */
179145: {
179146:  sqlite3_free((fts5yypminor->fts5yy3)); 
179147: }
179148:       break;
179149:     case 23: /* phrase */
179150: {
179151:  sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11)); 
179152: }
179153:       break;
179154: /********* End destructor definitions *****************************************/
179155:     default:  break;   /* If no destructor action specified: do nothing */
179156:   }
179157: }
179158: 
179159: /*
179160: ** Pop the parser's stack once.
179161: **
179162: ** If there is a destructor routine associated with the token which
179163: ** is popped from the stack, then call it.
179164: */
179165: static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
179166:   fts5yyStackEntry *fts5yytos;
179167:   assert( pParser->fts5yytos!=0 );
179168:   assert( pParser->fts5yytos > pParser->fts5yystack );
179169:   fts5yytos = pParser->fts5yytos--;
179170: #ifndef NDEBUG
179171:   if( fts5yyTraceFILE ){
179172:     fprintf(fts5yyTraceFILE,"%sPopping %s\n",
179173:       fts5yyTracePrompt,
179174:       fts5yyTokenName[fts5yytos->major]);
179175:   }
179176: #endif
179177:   fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
179178: }
179179: 
179180: /* 
179181: ** Deallocate and destroy a parser.  Destructors are called for
179182: ** all stack elements before shutting the parser down.
179183: **
179184: ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
179185: ** is defined in a %include section of the input grammar) then it is
179186: ** assumed that the input pointer is never NULL.
179187: */
179188: static void sqlite3Fts5ParserFree(
179189:   void *p,                    /* The parser to be deleted */
179190:   void (*freeProc)(void*)     /* Function used to reclaim memory */
179191: ){
179192:   fts5yyParser *pParser = (fts5yyParser*)p;
179193: #ifndef fts5YYPARSEFREENEVERNULL
179194:   if( pParser==0 ) return;
179195: #endif
179196:   while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
179197: #if fts5YYSTACKDEPTH<=0
179198:   if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
179199: #endif
179200:   (*freeProc)((void*)pParser);
179201: }
179202: 
179203: /*
179204: ** Return the peak depth of the stack for a parser.
179205: */
179206: #ifdef fts5YYTRACKMAXSTACKDEPTH
179207: static int sqlite3Fts5ParserStackPeak(void *p){
179208:   fts5yyParser *pParser = (fts5yyParser*)p;
179209:   return pParser->fts5yyhwm;
179210: }
179211: #endif
179212: 
179213: /*
179214: ** Find the appropriate action for a parser given the terminal
179215: ** look-ahead token iLookAhead.
179216: */
179217: static unsigned int fts5yy_find_shift_action(
179218:   fts5yyParser *pParser,        /* The parser */
179219:   fts5YYCODETYPE iLookAhead     /* The look-ahead token */
179220: ){
179221:   int i;
179222:   int stateno = pParser->fts5yytos->stateno;
179223:  
179224:   if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
179225:   assert( stateno <= fts5YY_SHIFT_COUNT );
179226:   do{
179227:     i = fts5yy_shift_ofst[stateno];
179228:     if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
179229:     assert( iLookAhead!=fts5YYNOCODE );
179230:     i += iLookAhead;
179231:     if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
179232:       if( iLookAhead>0 ){
179233: #ifdef fts5YYFALLBACK
179234:         fts5YYCODETYPE iFallback;            /* Fallback token */
179235:         if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
179236:                && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
179237: #ifndef NDEBUG
179238:           if( fts5yyTraceFILE ){
179239:             fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
179240:                fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
179241:           }
179242: #endif
179243:           assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
179244:           iLookAhead = iFallback;
179245:           continue;
179246:         }
179247: #endif
179248: #ifdef fts5YYWILDCARD
179249:         {
179250:           int j = i - iLookAhead + fts5YYWILDCARD;
179251:           if( 
179252: #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
179253:             j>=0 &&
179254: #endif
179255: #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
179256:             j<fts5YY_ACTTAB_COUNT &&
179257: #endif
179258:             fts5yy_lookahead[j]==fts5YYWILDCARD
179259:           ){
179260: #ifndef NDEBUG
179261:             if( fts5yyTraceFILE ){
179262:               fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
179263:                  fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
179264:                  fts5yyTokenName[fts5YYWILDCARD]);
179265:             }
179266: #endif /* NDEBUG */
179267:             return fts5yy_action[j];
179268:           }
179269:         }
179270: #endif /* fts5YYWILDCARD */
179271:       }
179272:       return fts5yy_default[stateno];
179273:     }else{
179274:       return fts5yy_action[i];
179275:     }
179276:   }while(1);
179277: }
179278: 
179279: /*
179280: ** Find the appropriate action for a parser given the non-terminal
179281: ** look-ahead token iLookAhead.
179282: */
179283: static int fts5yy_find_reduce_action(
179284:   int stateno,              /* Current state number */
179285:   fts5YYCODETYPE iLookAhead     /* The look-ahead token */
179286: ){
179287:   int i;
179288: #ifdef fts5YYERRORSYMBOL
179289:   if( stateno>fts5YY_REDUCE_COUNT ){
179290:     return fts5yy_default[stateno];
179291:   }
179292: #else
179293:   assert( stateno<=fts5YY_REDUCE_COUNT );
179294: #endif
179295:   i = fts5yy_reduce_ofst[stateno];
179296:   assert( i!=fts5YY_REDUCE_USE_DFLT );
179297:   assert( iLookAhead!=fts5YYNOCODE );
179298:   i += iLookAhead;
179299: #ifdef fts5YYERRORSYMBOL
179300:   if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
179301:     return fts5yy_default[stateno];
179302:   }
179303: #else
179304:   assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
179305:   assert( fts5yy_lookahead[i]==iLookAhead );
179306: #endif
179307:   return fts5yy_action[i];
179308: }
179309: 
179310: /*
179311: ** The following routine is called if the stack overflows.
179312: */
179313: static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
179314:    sqlite3Fts5ParserARG_FETCH;
179315:    fts5yypParser->fts5yytos--;
179316: #ifndef NDEBUG
179317:    if( fts5yyTraceFILE ){
179318:      fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
179319:    }
179320: #endif
179321:    while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
179322:    /* Here code is inserted which will execute if the parser
179323:    ** stack every overflows */
179324: /******** Begin %stack_overflow code ******************************************/
179325: 
179326:   sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
179327: /******** End %stack_overflow code ********************************************/
179328:    sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
179329: }
179330: 
179331: /*
179332: ** Print tracing information for a SHIFT action
179333: */
179334: #ifndef NDEBUG
179335: static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
179336:   if( fts5yyTraceFILE ){
179337:     if( fts5yyNewState<fts5YYNSTATE ){
179338:       fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
179339:          fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
179340:          fts5yyNewState);
179341:     }else{
179342:       fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
179343:          fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
179344:     }
179345:   }
179346: }
179347: #else
179348: # define fts5yyTraceShift(X,Y)
179349: #endif
179350: 
179351: /*
179352: ** Perform a shift action.
179353: */
179354: static void fts5yy_shift(
179355:   fts5yyParser *fts5yypParser,          /* The parser to be shifted */
179356:   int fts5yyNewState,               /* The new state to shift in */
179357:   int fts5yyMajor,                  /* The major token to shift in */
179358:   sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor        /* The minor token to shift in */
179359: ){
179360:   fts5yyStackEntry *fts5yytos;
179361:   fts5yypParser->fts5yytos++;
179362: #ifdef fts5YYTRACKMAXSTACKDEPTH
179363:   if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
179364:     fts5yypParser->fts5yyhwm++;
179365:     assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
179366:   }
179367: #endif
179368: #if fts5YYSTACKDEPTH>0 
179369:   if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
179370:     fts5yyStackOverflow(fts5yypParser);
179371:     return;
179372:   }
179373: #else
179374:   if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
179375:     if( fts5yyGrowStack(fts5yypParser) ){
179376:       fts5yyStackOverflow(fts5yypParser);
179377:       return;
179378:     }
179379:   }
179380: #endif
179381:   if( fts5yyNewState > fts5YY_MAX_SHIFT ){
179382:     fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
179383:   }
179384:   fts5yytos = fts5yypParser->fts5yytos;
179385:   fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
179386:   fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
179387:   fts5yytos->minor.fts5yy0 = fts5yyMinor;
179388:   fts5yyTraceShift(fts5yypParser, fts5yyNewState);
179389: }
179390: 
179391: /* The following table contains information about every rule that
179392: ** is used during the reduce.
179393: */
179394: static const struct {
179395:   fts5YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
179396:   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
179397: } fts5yyRuleInfo[] = {
179398:   { 15, 1 },
179399:   { 16, 3 },
179400:   { 16, 3 },
179401:   { 16, 3 },
179402:   { 16, 3 },
179403:   { 16, 1 },
179404:   { 18, 1 },
179405:   { 18, 2 },
179406:   { 17, 1 },
179407:   { 17, 3 },
179408:   { 20, 3 },
179409:   { 20, 1 },
179410:   { 21, 2 },
179411:   { 21, 1 },
179412:   { 19, 1 },
179413:   { 19, 5 },
179414:   { 22, 1 },
179415:   { 22, 2 },
179416:   { 24, 0 },
179417:   { 24, 2 },
179418:   { 23, 4 },
179419:   { 23, 2 },
179420:   { 25, 1 },
179421:   { 25, 0 },
179422: };
179423: 
179424: static void fts5yy_accept(fts5yyParser*);  /* Forward Declaration */
179425: 
179426: /*
179427: ** Perform a reduce action and the shift that must immediately
179428: ** follow the reduce.
179429: */
179430: static void fts5yy_reduce(
179431:   fts5yyParser *fts5yypParser,         /* The parser */
179432:   unsigned int fts5yyruleno        /* Number of the rule by which to reduce */
179433: ){
179434:   int fts5yygoto;                     /* The next state */
179435:   int fts5yyact;                      /* The next action */
179436:   fts5yyStackEntry *fts5yymsp;            /* The top of the parser's stack */
179437:   int fts5yysize;                     /* Amount to pop the stack */
179438:   sqlite3Fts5ParserARG_FETCH;
179439:   fts5yymsp = fts5yypParser->fts5yytos;
179440: #ifndef NDEBUG
179441:   if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
179442:     fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
179443:     fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
179444:       fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
179445:   }
179446: #endif /* NDEBUG */
179447: 
179448:   /* Check that the stack is large enough to grow by a single entry
179449:   ** if the RHS of the rule is empty.  This ensures that there is room
179450:   ** enough on the stack to push the LHS value */
179451:   if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
179452: #ifdef fts5YYTRACKMAXSTACKDEPTH
179453:     if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
179454:       fts5yypParser->fts5yyhwm++;
179455:       assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
179456:     }
179457: #endif
179458: #if fts5YYSTACKDEPTH>0 
179459:     if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
179460:       fts5yyStackOverflow(fts5yypParser);
179461:       return;
179462:     }
179463: #else
179464:     if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
179465:       if( fts5yyGrowStack(fts5yypParser) ){
179466:         fts5yyStackOverflow(fts5yypParser);
179467:         return;
179468:       }
179469:       fts5yymsp = fts5yypParser->fts5yytos;
179470:     }
179471: #endif
179472:   }
179473: 
179474:   switch( fts5yyruleno ){
179475:   /* Beginning here are the reduction cases.  A typical example
179476:   ** follows:
179477:   **   case 0:
179478:   **  #line <lineno> <grammarfile>
179479:   **     { ... }           // User supplied code
179480:   **  #line <lineno> <thisfile>
179481:   **     break;
179482:   */
179483: /********** Begin reduce actions **********************************************/
179484:         fts5YYMINORTYPE fts5yylhsminor;
179485:       case 0: /* input ::= expr */
179486: { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
179487:         break;
179488:       case 1: /* expr ::= expr AND expr */
179489: {
179490:   fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179491: }
179492:   fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179493:         break;
179494:       case 2: /* expr ::= expr OR expr */
179495: {
179496:   fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179497: }
179498:   fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179499:         break;
179500:       case 3: /* expr ::= expr NOT expr */
179501: {
179502:   fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
179503: }
179504:   fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179505:         break;
179506:       case 4: /* expr ::= LP expr RP */
179507: {fts5yymsp[-2].minor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
179508:         break;
179509:       case 5: /* expr ::= exprlist */
179510:       case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
179511: {fts5yylhsminor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
179512:   fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179513:         break;
179514:       case 7: /* exprlist ::= exprlist cnearset */
179515: {
179516:   fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18);
179517: }
179518:   fts5yymsp[-1].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179519:         break;
179520:       case 8: /* cnearset ::= nearset */
179521: { 
179522:   fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26); 
179523: }
179524:   fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179525:         break;
179526:       case 9: /* cnearset ::= colset COLON nearset */
179527: { 
179528:   sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
179529:   fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26); 
179530: }
179531:   fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
179532:         break;
179533:       case 10: /* colset ::= LCP colsetlist RCP */
179534: { fts5yymsp[-2].minor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
179535:         break;
179536:       case 11: /* colset ::= STRING */
179537: {
179538:   fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
179539: }
179540:   fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179541:         break;
179542:       case 12: /* colsetlist ::= colsetlist STRING */
179543: { 
179544:   fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
179545:   fts5yymsp[-1].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179546:         break;
179547:       case 13: /* colsetlist ::= STRING */
179548: { 
179549:   fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0); 
179550: }
179551:   fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
179552:         break;
179553:       case 14: /* nearset ::= phrase */
179554: { fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
179555:   fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179556:         break;
179557:       case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
179558: {
179559:   sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
179560:   sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
179561:   fts5yylhsminor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
179562: }
179563:   fts5yymsp[-4].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179564:         break;
179565:       case 16: /* nearphrases ::= phrase */
179566: { 
179567:   fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); 
179568: }
179569:   fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179570:         break;
179571:       case 17: /* nearphrases ::= nearphrases phrase */
179572: {
179573:   fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
179574: }
179575:   fts5yymsp[-1].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
179576:         break;
179577:       case 18: /* neardist_opt ::= */
179578: { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
179579:         break;
179580:       case 19: /* neardist_opt ::= COMMA STRING */
179581: { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
179582:         break;
179583:       case 20: /* phrase ::= phrase PLUS STRING star_opt */
179584: { 
179585:   fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
179586: }
179587:   fts5yymsp[-3].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
179588:         break;
179589:       case 21: /* phrase ::= STRING star_opt */
179590: { 
179591:   fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
179592: }
179593:   fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
179594:         break;
179595:       case 22: /* star_opt ::= STAR */
179596: { fts5yymsp[0].minor.fts5yy20 = 1; }
179597:         break;
179598:       case 23: /* star_opt ::= */
179599: { fts5yymsp[1].minor.fts5yy20 = 0; }
179600:         break;
179601:       default:
179602:         break;
179603: /********** End reduce actions ************************************************/
179604:   };
179605:   assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
179606:   fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
179607:   fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
179608:   fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
179609:   if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
179610:     if( fts5yyact>fts5YY_MAX_SHIFT ){
179611:       fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
179612:     }
179613:     fts5yymsp -= fts5yysize-1;
179614:     fts5yypParser->fts5yytos = fts5yymsp;
179615:     fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
179616:     fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
179617:     fts5yyTraceShift(fts5yypParser, fts5yyact);
179618:   }else{
179619:     assert( fts5yyact == fts5YY_ACCEPT_ACTION );
179620:     fts5yypParser->fts5yytos -= fts5yysize;
179621:     fts5yy_accept(fts5yypParser);
179622:   }
179623: }
179624: 
179625: /*
179626: ** The following code executes when the parse fails
179627: */
179628: #ifndef fts5YYNOERRORRECOVERY
179629: static void fts5yy_parse_failed(
179630:   fts5yyParser *fts5yypParser           /* The parser */
179631: ){
179632:   sqlite3Fts5ParserARG_FETCH;
179633: #ifndef NDEBUG
179634:   if( fts5yyTraceFILE ){
179635:     fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
179636:   }
179637: #endif
179638:   while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
179639:   /* Here code is inserted which will be executed whenever the
179640:   ** parser fails */
179641: /************ Begin %parse_failure code ***************************************/
179642: /************ End %parse_failure code *****************************************/
179643:   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179644: }
179645: #endif /* fts5YYNOERRORRECOVERY */
179646: 
179647: /*
179648: ** The following code executes when a syntax error first occurs.
179649: */
179650: static void fts5yy_syntax_error(
179651:   fts5yyParser *fts5yypParser,           /* The parser */
179652:   int fts5yymajor,                   /* The major type of the error token */
179653:   sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor         /* The minor type of the error token */
179654: ){
179655:   sqlite3Fts5ParserARG_FETCH;
179656: #define FTS5TOKEN fts5yyminor
179657: /************ Begin %syntax_error code ****************************************/
179658: 
179659:   UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
179660:   sqlite3Fts5ParseError(
179661:     pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
179662:   );
179663: /************ End %syntax_error code ******************************************/
179664:   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179665: }
179666: 
179667: /*
179668: ** The following is executed when the parser accepts
179669: */
179670: static void fts5yy_accept(
179671:   fts5yyParser *fts5yypParser           /* The parser */
179672: ){
179673:   sqlite3Fts5ParserARG_FETCH;
179674: #ifndef NDEBUG
179675:   if( fts5yyTraceFILE ){
179676:     fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
179677:   }
179678: #endif
179679: #ifndef fts5YYNOERRORRECOVERY
179680:   fts5yypParser->fts5yyerrcnt = -1;
179681: #endif
179682:   assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
179683:   /* Here code is inserted which will be executed whenever the
179684:   ** parser accepts */
179685: /*********** Begin %parse_accept code *****************************************/
179686: /*********** End %parse_accept code *******************************************/
179687:   sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
179688: }
179689: 
179690: /* The main parser program.
179691: ** The first argument is a pointer to a structure obtained from
179692: ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
179693: ** The second argument is the major token number.  The third is
179694: ** the minor token.  The fourth optional argument is whatever the
179695: ** user wants (and specified in the grammar) and is available for
179696: ** use by the action routines.
179697: **
179698: ** Inputs:
179699: ** <ul>
179700: ** <li> A pointer to the parser (an opaque structure.)
179701: ** <li> The major token number.
179702: ** <li> The minor token number.
179703: ** <li> An option argument of a grammar-specified type.
179704: ** </ul>
179705: **
179706: ** Outputs:
179707: ** None.
179708: */
179709: static void sqlite3Fts5Parser(
179710:   void *fts5yyp,                   /* The parser */
179711:   int fts5yymajor,                 /* The major token code number */
179712:   sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor       /* The value for the token */
179713:   sqlite3Fts5ParserARG_PDECL               /* Optional %extra_argument parameter */
179714: ){
179715:   fts5YYMINORTYPE fts5yyminorunion;
179716:   unsigned int fts5yyact;   /* The parser action. */
179717: #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
179718:   int fts5yyendofinput;     /* True if we are at the end of input */
179719: #endif
179720: #ifdef fts5YYERRORSYMBOL
179721:   int fts5yyerrorhit = 0;   /* True if fts5yymajor has invoked an error */
179722: #endif
179723:   fts5yyParser *fts5yypParser;  /* The parser */
179724: 
179725:   fts5yypParser = (fts5yyParser*)fts5yyp;
179726:   assert( fts5yypParser->fts5yytos!=0 );
179727: #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
179728:   fts5yyendofinput = (fts5yymajor==0);
179729: #endif
179730:   sqlite3Fts5ParserARG_STORE;
179731: 
179732: #ifndef NDEBUG
179733:   if( fts5yyTraceFILE ){
179734:     fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
179735:   }
179736: #endif
179737: 
179738:   do{
179739:     fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
179740:     if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
179741:       fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
179742: #ifndef fts5YYNOERRORRECOVERY
179743:       fts5yypParser->fts5yyerrcnt--;
179744: #endif
179745:       fts5yymajor = fts5YYNOCODE;
179746:     }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
179747:       fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
179748:     }else{
179749:       assert( fts5yyact == fts5YY_ERROR_ACTION );
179750:       fts5yyminorunion.fts5yy0 = fts5yyminor;
179751: #ifdef fts5YYERRORSYMBOL
179752:       int fts5yymx;
179753: #endif
179754: #ifndef NDEBUG
179755:       if( fts5yyTraceFILE ){
179756:         fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
179757:       }
179758: #endif
179759: #ifdef fts5YYERRORSYMBOL
179760:       /* A syntax error has occurred.
179761:       ** The response to an error depends upon whether or not the
179762:       ** grammar defines an error token "ERROR".  
179763:       **
179764:       ** This is what we do if the grammar does define ERROR:
179765:       **
179766:       **  * Call the %syntax_error function.
179767:       **
179768:       **  * Begin popping the stack until we enter a state where
179769:       **    it is legal to shift the error symbol, then shift
179770:       **    the error symbol.
179771:       **
179772:       **  * Set the error count to three.
179773:       **
179774:       **  * Begin accepting and shifting new tokens.  No new error
179775:       **    processing will occur until three tokens have been
179776:       **    shifted successfully.
179777:       **
179778:       */
179779:       if( fts5yypParser->fts5yyerrcnt<0 ){
179780:         fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
179781:       }
179782:       fts5yymx = fts5yypParser->fts5yytos->major;
179783:       if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
179784: #ifndef NDEBUG
179785:         if( fts5yyTraceFILE ){
179786:           fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
179787:              fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
179788:         }
179789: #endif
179790:         fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
179791:         fts5yymajor = fts5YYNOCODE;
179792:       }else{
179793:         while( fts5yypParser->fts5yytos >= &fts5yypParser->fts5yystack
179794:             && fts5yymx != fts5YYERRORSYMBOL
179795:             && (fts5yyact = fts5yy_find_reduce_action(
179796:                         fts5yypParser->fts5yytos->stateno,
179797:                         fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
179798:         ){
179799:           fts5yy_pop_parser_stack(fts5yypParser);
179800:         }
179801:         if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
179802:           fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179803:           fts5yy_parse_failed(fts5yypParser);
179804: #ifndef fts5YYNOERRORRECOVERY
179805:           fts5yypParser->fts5yyerrcnt = -1;
179806: #endif
179807:           fts5yymajor = fts5YYNOCODE;
179808:         }else if( fts5yymx!=fts5YYERRORSYMBOL ){
179809:           fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
179810:         }
179811:       }
179812:       fts5yypParser->fts5yyerrcnt = 3;
179813:       fts5yyerrorhit = 1;
179814: #elif defined(fts5YYNOERRORRECOVERY)
179815:       /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
179816:       ** do any kind of error recovery.  Instead, simply invoke the syntax
179817:       ** error routine and continue going as if nothing had happened.
179818:       **
179819:       ** Applications can set this macro (for example inside %include) if
179820:       ** they intend to abandon the parse upon the first syntax error seen.
179821:       */
179822:       fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
179823:       fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179824:       fts5yymajor = fts5YYNOCODE;
179825:       
179826: #else  /* fts5YYERRORSYMBOL is not defined */
179827:       /* This is what we do if the grammar does not define ERROR:
179828:       **
179829:       **  * Report an error message, and throw away the input token.
179830:       **
179831:       **  * If the input token is $, then fail the parse.
179832:       **
179833:       ** As before, subsequent error messages are suppressed until
179834:       ** three input tokens have been successfully shifted.
179835:       */
179836:       if( fts5yypParser->fts5yyerrcnt<=0 ){
179837:         fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
179838:       }
179839:       fts5yypParser->fts5yyerrcnt = 3;
179840:       fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
179841:       if( fts5yyendofinput ){
179842:         fts5yy_parse_failed(fts5yypParser);
179843: #ifndef fts5YYNOERRORRECOVERY
179844:         fts5yypParser->fts5yyerrcnt = -1;
179845: #endif
179846:       }
179847:       fts5yymajor = fts5YYNOCODE;
179848: #endif
179849:     }
179850:   }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
179851: #ifndef NDEBUG
179852:   if( fts5yyTraceFILE ){
179853:     fts5yyStackEntry *i;
179854:     char cDiv = '[';
179855:     fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
179856:     for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
179857:       fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
179858:       cDiv = ' ';
179859:     }
179860:     fprintf(fts5yyTraceFILE,"]\n");
179861:   }
179862: #endif
179863:   return;
179864: }
179865: 
179866: /*
179867: ** 2014 May 31
179868: **
179869: ** The author disclaims copyright to this source code.  In place of
179870: ** a legal notice, here is a blessing:
179871: **
179872: **    May you do good and not evil.
179873: **    May you find forgiveness for yourself and forgive others.
179874: **    May you share freely, never taking more than you give.
179875: **
179876: ******************************************************************************
179877: */
179878: 
179879: 
179880: /* #include "fts5Int.h" */
179881: #include <math.h>                 /* amalgamator: keep */
179882: 
179883: /*
179884: ** Object used to iterate through all "coalesced phrase instances" in 
179885: ** a single column of the current row. If the phrase instances in the
179886: ** column being considered do not overlap, this object simply iterates
179887: ** through them. Or, if they do overlap (share one or more tokens in
179888: ** common), each set of overlapping instances is treated as a single
179889: ** match. See documentation for the highlight() auxiliary function for
179890: ** details.
179891: **
179892: ** Usage is:
179893: **
179894: **   for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
179895: **      (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
179896: **      rc = fts5CInstIterNext(&iter)
179897: **   ){
179898: **     printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
179899: **   }
179900: **
179901: */
179902: typedef struct CInstIter CInstIter;
179903: struct CInstIter {
179904:   const Fts5ExtensionApi *pApi;   /* API offered by current FTS version */
179905:   Fts5Context *pFts;              /* First arg to pass to pApi functions */
179906:   int iCol;                       /* Column to search */
179907:   int iInst;                      /* Next phrase instance index */
179908:   int nInst;                      /* Total number of phrase instances */
179909: 
179910:   /* Output variables */
179911:   int iStart;                     /* First token in coalesced phrase instance */
179912:   int iEnd;                       /* Last token in coalesced phrase instance */
179913: };
179914: 
179915: /*
179916: ** Advance the iterator to the next coalesced phrase instance. Return
179917: ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
179918: */
179919: static int fts5CInstIterNext(CInstIter *pIter){
179920:   int rc = SQLITE_OK;
179921:   pIter->iStart = -1;
179922:   pIter->iEnd = -1;
179923: 
179924:   while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
179925:     int ip; int ic; int io;
179926:     rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
179927:     if( rc==SQLITE_OK ){
179928:       if( ic==pIter->iCol ){
179929:         int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
179930:         if( pIter->iStart<0 ){
179931:           pIter->iStart = io;
179932:           pIter->iEnd = iEnd;
179933:         }else if( io<=pIter->iEnd ){
179934:           if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
179935:         }else{
179936:           break;
179937:         }
179938:       }
179939:       pIter->iInst++;
179940:     }
179941:   }
179942: 
179943:   return rc;
179944: }
179945: 
179946: /*
179947: ** Initialize the iterator object indicated by the final parameter to 
179948: ** iterate through coalesced phrase instances in column iCol.
179949: */
179950: static int fts5CInstIterInit(
179951:   const Fts5ExtensionApi *pApi,
179952:   Fts5Context *pFts,
179953:   int iCol,
179954:   CInstIter *pIter
179955: ){
179956:   int rc;
179957: 
179958:   memset(pIter, 0, sizeof(CInstIter));
179959:   pIter->pApi = pApi;
179960:   pIter->pFts = pFts;
179961:   pIter->iCol = iCol;
179962:   rc = pApi->xInstCount(pFts, &pIter->nInst);
179963: 
179964:   if( rc==SQLITE_OK ){
179965:     rc = fts5CInstIterNext(pIter);
179966:   }
179967: 
179968:   return rc;
179969: }
179970: 
179971: 
179972: 
179973: /*************************************************************************
179974: ** Start of highlight() implementation.
179975: */
179976: typedef struct HighlightContext HighlightContext;
179977: struct HighlightContext {
179978:   CInstIter iter;                 /* Coalesced Instance Iterator */
179979:   int iPos;                       /* Current token offset in zIn[] */
179980:   int iRangeStart;                /* First token to include */
179981:   int iRangeEnd;                  /* If non-zero, last token to include */
179982:   const char *zOpen;              /* Opening highlight */
179983:   const char *zClose;             /* Closing highlight */
179984:   const char *zIn;                /* Input text */
179985:   int nIn;                        /* Size of input text in bytes */
179986:   int iOff;                       /* Current offset within zIn[] */
179987:   char *zOut;                     /* Output value */
179988: };
179989: 
179990: /*
179991: ** Append text to the HighlightContext output string - p->zOut. Argument
179992: ** z points to a buffer containing n bytes of text to append. If n is 
179993: ** negative, everything up until the first '\0' is appended to the output.
179994: **
179995: ** If *pRc is set to any value other than SQLITE_OK when this function is 
179996: ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered, 
179997: ** *pRc is set to an error code before returning. 
179998: */
179999: static void fts5HighlightAppend(
180000:   int *pRc, 
180001:   HighlightContext *p, 
180002:   const char *z, int n
180003: ){
180004:   if( *pRc==SQLITE_OK ){
180005:     if( n<0 ) n = (int)strlen(z);
180006:     p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
180007:     if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
180008:   }
180009: }
180010: 
180011: /*
180012: ** Tokenizer callback used by implementation of highlight() function.
180013: */
180014: static int fts5HighlightCb(
180015:   void *pContext,                 /* Pointer to HighlightContext object */
180016:   int tflags,                     /* Mask of FTS5_TOKEN_* flags */
180017:   const char *pToken,             /* Buffer containing token */
180018:   int nToken,                     /* Size of token in bytes */
180019:   int iStartOff,                  /* Start offset of token */
180020:   int iEndOff                     /* End offset of token */
180021: ){
180022:   HighlightContext *p = (HighlightContext*)pContext;
180023:   int rc = SQLITE_OK;
180024:   int iPos;
180025: 
180026:   UNUSED_PARAM2(pToken, nToken);
180027: 
180028:   if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
180029:   iPos = p->iPos++;
180030: 
180031:   if( p->iRangeEnd>0 ){
180032:     if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
180033:     if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
180034:   }
180035: 
180036:   if( iPos==p->iter.iStart ){
180037:     fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
180038:     fts5HighlightAppend(&rc, p, p->zOpen, -1);
180039:     p->iOff = iStartOff;
180040:   }
180041: 
180042:   if( iPos==p->iter.iEnd ){
180043:     if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
180044:       fts5HighlightAppend(&rc, p, p->zOpen, -1);
180045:     }
180046:     fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
180047:     fts5HighlightAppend(&rc, p, p->zClose, -1);
180048:     p->iOff = iEndOff;
180049:     if( rc==SQLITE_OK ){
180050:       rc = fts5CInstIterNext(&p->iter);
180051:     }
180052:   }
180053: 
180054:   if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
180055:     fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
180056:     p->iOff = iEndOff;
180057:     if( iPos<p->iter.iEnd ){
180058:       fts5HighlightAppend(&rc, p, p->zClose, -1);
180059:     }
180060:   }
180061: 
180062:   return rc;
180063: }
180064: 
180065: /*
180066: ** Implementation of highlight() function.
180067: */
180068: static void fts5HighlightFunction(
180069:   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180070:   Fts5Context *pFts,              /* First arg to pass to pApi functions */
180071:   sqlite3_context *pCtx,          /* Context for returning result/error */
180072:   int nVal,                       /* Number of values in apVal[] array */
180073:   sqlite3_value **apVal           /* Array of trailing arguments */
180074: ){
180075:   HighlightContext ctx;
180076:   int rc;
180077:   int iCol;
180078: 
180079:   if( nVal!=3 ){
180080:     const char *zErr = "wrong number of arguments to function highlight()";
180081:     sqlite3_result_error(pCtx, zErr, -1);
180082:     return;
180083:   }
180084: 
180085:   iCol = sqlite3_value_int(apVal[0]);
180086:   memset(&ctx, 0, sizeof(HighlightContext));
180087:   ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
180088:   ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
180089:   rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
180090: 
180091:   if( ctx.zIn ){
180092:     if( rc==SQLITE_OK ){
180093:       rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
180094:     }
180095: 
180096:     if( rc==SQLITE_OK ){
180097:       rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
180098:     }
180099:     fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
180100: 
180101:     if( rc==SQLITE_OK ){
180102:       sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
180103:     }
180104:     sqlite3_free(ctx.zOut);
180105:   }
180106:   if( rc!=SQLITE_OK ){
180107:     sqlite3_result_error_code(pCtx, rc);
180108:   }
180109: }
180110: /*
180111: ** End of highlight() implementation.
180112: **************************************************************************/
180113: 
180114: /*
180115: ** Implementation of snippet() function.
180116: */
180117: static void fts5SnippetFunction(
180118:   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180119:   Fts5Context *pFts,              /* First arg to pass to pApi functions */
180120:   sqlite3_context *pCtx,          /* Context for returning result/error */
180121:   int nVal,                       /* Number of values in apVal[] array */
180122:   sqlite3_value **apVal           /* Array of trailing arguments */
180123: ){
180124:   HighlightContext ctx;
180125:   int rc = SQLITE_OK;             /* Return code */
180126:   int iCol;                       /* 1st argument to snippet() */
180127:   const char *zEllips;            /* 4th argument to snippet() */
180128:   int nToken;                     /* 5th argument to snippet() */
180129:   int nInst = 0;                  /* Number of instance matches this row */
180130:   int i;                          /* Used to iterate through instances */
180131:   int nPhrase;                    /* Number of phrases in query */
180132:   unsigned char *aSeen;           /* Array of "seen instance" flags */
180133:   int iBestCol;                   /* Column containing best snippet */
180134:   int iBestStart = 0;             /* First token of best snippet */
180135:   int iBestLast;                  /* Last token of best snippet */
180136:   int nBestScore = 0;             /* Score of best snippet */
180137:   int nColSize = 0;               /* Total size of iBestCol in tokens */
180138: 
180139:   if( nVal!=5 ){
180140:     const char *zErr = "wrong number of arguments to function snippet()";
180141:     sqlite3_result_error(pCtx, zErr, -1);
180142:     return;
180143:   }
180144: 
180145:   memset(&ctx, 0, sizeof(HighlightContext));
180146:   iCol = sqlite3_value_int(apVal[0]);
180147:   ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
180148:   ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
180149:   zEllips = (const char*)sqlite3_value_text(apVal[3]);
180150:   nToken = sqlite3_value_int(apVal[4]);
180151:   iBestLast = nToken-1;
180152: 
180153:   iBestCol = (iCol>=0 ? iCol : 0);
180154:   nPhrase = pApi->xPhraseCount(pFts);
180155:   aSeen = sqlite3_malloc(nPhrase);
180156:   if( aSeen==0 ){
180157:     rc = SQLITE_NOMEM;
180158:   }
180159: 
180160:   if( rc==SQLITE_OK ){
180161:     rc = pApi->xInstCount(pFts, &nInst);
180162:   }
180163:   for(i=0; rc==SQLITE_OK && i<nInst; i++){
180164:     int ip, iSnippetCol, iStart;
180165:     memset(aSeen, 0, nPhrase);
180166:     rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
180167:     if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
180168:       int nScore = 1000;
180169:       int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
180170:       int j;
180171:       aSeen[ip] = 1;
180172: 
180173:       for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
180174:         int ic; int io; int iFinal;
180175:         rc = pApi->xInst(pFts, j, &ip, &ic, &io);
180176:         iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
180177:         if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
180178:           nScore += aSeen[ip] ? 1000 : 1;
180179:           aSeen[ip] = 1;
180180:           if( iFinal>iLast ) iLast = iFinal;
180181:         }
180182:       }
180183: 
180184:       if( rc==SQLITE_OK && nScore>nBestScore ){
180185:         iBestCol = iSnippetCol;
180186:         iBestStart = iStart;
180187:         iBestLast = iLast;
180188:         nBestScore = nScore;
180189:       }
180190:     }
180191:   }
180192: 
180193:   if( rc==SQLITE_OK ){
180194:     rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
180195:   }
180196:   if( rc==SQLITE_OK ){
180197:     rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
180198:   }
180199:   if( ctx.zIn ){
180200:     if( rc==SQLITE_OK ){
180201:       rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
180202:     }
180203: 
180204:     if( (iBestStart+nToken-1)>iBestLast ){
180205:       iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
180206:     }
180207:     if( iBestStart+nToken>nColSize ){
180208:       iBestStart = nColSize - nToken;
180209:     }
180210:     if( iBestStart<0 ) iBestStart = 0;
180211: 
180212:     ctx.iRangeStart = iBestStart;
180213:     ctx.iRangeEnd = iBestStart + nToken - 1;
180214: 
180215:     if( iBestStart>0 ){
180216:       fts5HighlightAppend(&rc, &ctx, zEllips, -1);
180217:     }
180218:     if( rc==SQLITE_OK ){
180219:       rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
180220:     }
180221:     if( ctx.iRangeEnd>=(nColSize-1) ){
180222:       fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
180223:     }else{
180224:       fts5HighlightAppend(&rc, &ctx, zEllips, -1);
180225:     }
180226: 
180227:     if( rc==SQLITE_OK ){
180228:       sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
180229:     }else{
180230:       sqlite3_result_error_code(pCtx, rc);
180231:     }
180232:     sqlite3_free(ctx.zOut);
180233:   }
180234:   sqlite3_free(aSeen);
180235: }
180236: 
180237: /************************************************************************/
180238: 
180239: /*
180240: ** The first time the bm25() function is called for a query, an instance
180241: ** of the following structure is allocated and populated.
180242: */
180243: typedef struct Fts5Bm25Data Fts5Bm25Data;
180244: struct Fts5Bm25Data {
180245:   int nPhrase;                    /* Number of phrases in query */
180246:   double avgdl;                   /* Average number of tokens in each row */
180247:   double *aIDF;                   /* IDF for each phrase */
180248:   double *aFreq;                  /* Array used to calculate phrase freq. */
180249: };
180250: 
180251: /*
180252: ** Callback used by fts5Bm25GetData() to count the number of rows in the
180253: ** table matched by each individual phrase within the query.
180254: */
180255: static int fts5CountCb(
180256:   const Fts5ExtensionApi *pApi, 
180257:   Fts5Context *pFts,
180258:   void *pUserData                 /* Pointer to sqlite3_int64 variable */
180259: ){
180260:   sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
180261:   UNUSED_PARAM2(pApi, pFts);
180262:   (*pn)++;
180263:   return SQLITE_OK;
180264: }
180265: 
180266: /*
180267: ** Set *ppData to point to the Fts5Bm25Data object for the current query. 
180268: ** If the object has not already been allocated, allocate and populate it
180269: ** now.
180270: */
180271: static int fts5Bm25GetData(
180272:   const Fts5ExtensionApi *pApi, 
180273:   Fts5Context *pFts,
180274:   Fts5Bm25Data **ppData           /* OUT: bm25-data object for this query */
180275: ){
180276:   int rc = SQLITE_OK;             /* Return code */
180277:   Fts5Bm25Data *p;                /* Object to return */
180278: 
180279:   p = pApi->xGetAuxdata(pFts, 0);
180280:   if( p==0 ){
180281:     int nPhrase;                  /* Number of phrases in query */
180282:     sqlite3_int64 nRow = 0;       /* Number of rows in table */
180283:     sqlite3_int64 nToken = 0;     /* Number of tokens in table */
180284:     int nByte;                    /* Bytes of space to allocate */
180285:     int i;
180286: 
180287:     /* Allocate the Fts5Bm25Data object */
180288:     nPhrase = pApi->xPhraseCount(pFts);
180289:     nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
180290:     p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
180291:     if( p==0 ){
180292:       rc = SQLITE_NOMEM;
180293:     }else{
180294:       memset(p, 0, nByte);
180295:       p->nPhrase = nPhrase;
180296:       p->aIDF = (double*)&p[1];
180297:       p->aFreq = &p->aIDF[nPhrase];
180298:     }
180299: 
180300:     /* Calculate the average document length for this FTS5 table */
180301:     if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
180302:     if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
180303:     if( rc==SQLITE_OK ) p->avgdl = (double)nToken  / (double)nRow;
180304: 
180305:     /* Calculate an IDF for each phrase in the query */
180306:     for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
180307:       sqlite3_int64 nHit = 0;
180308:       rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
180309:       if( rc==SQLITE_OK ){
180310:         /* Calculate the IDF (Inverse Document Frequency) for phrase i.
180311:         ** This is done using the standard BM25 formula as found on wikipedia:
180312:         **
180313:         **   IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
180314:         **
180315:         ** where "N" is the total number of documents in the set and nHit
180316:         ** is the number that contain at least one instance of the phrase
180317:         ** under consideration.
180318:         **
180319:         ** The problem with this is that if (N < 2*nHit), the IDF is 
180320:         ** negative. Which is undesirable. So the mimimum allowable IDF is
180321:         ** (1e-6) - roughly the same as a term that appears in just over
180322:         ** half of set of 5,000,000 documents.  */
180323:         double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
180324:         if( idf<=0.0 ) idf = 1e-6;
180325:         p->aIDF[i] = idf;
180326:       }
180327:     }
180328: 
180329:     if( rc!=SQLITE_OK ){
180330:       sqlite3_free(p);
180331:     }else{
180332:       rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
180333:     }
180334:     if( rc!=SQLITE_OK ) p = 0;
180335:   }
180336:   *ppData = p;
180337:   return rc;
180338: }
180339: 
180340: /*
180341: ** Implementation of bm25() function.
180342: */
180343: static void fts5Bm25Function(
180344:   const Fts5ExtensionApi *pApi,   /* API offered by current FTS version */
180345:   Fts5Context *pFts,              /* First arg to pass to pApi functions */
180346:   sqlite3_context *pCtx,          /* Context for returning result/error */
180347:   int nVal,                       /* Number of values in apVal[] array */
180348:   sqlite3_value **apVal           /* Array of trailing arguments */
180349: ){
180350:   const double k1 = 1.2;          /* Constant "k1" from BM25 formula */
180351:   const double b = 0.75;          /* Constant "b" from BM25 formula */
180352:   int rc = SQLITE_OK;             /* Error code */
180353:   double score = 0.0;             /* SQL function return value */
180354:   Fts5Bm25Data *pData;            /* Values allocated/calculated once only */
180355:   int i;                          /* Iterator variable */
180356:   int nInst = 0;                  /* Value returned by xInstCount() */
180357:   double D = 0.0;                 /* Total number of tokens in row */
180358:   double *aFreq = 0;              /* Array of phrase freq. for current row */
180359: 
180360:   /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
180361:   ** for each phrase in the query for the current row. */
180362:   rc = fts5Bm25GetData(pApi, pFts, &pData);
180363:   if( rc==SQLITE_OK ){
180364:     aFreq = pData->aFreq;
180365:     memset(aFreq, 0, sizeof(double) * pData->nPhrase);
180366:     rc = pApi->xInstCount(pFts, &nInst);
180367:   }
180368:   for(i=0; rc==SQLITE_OK && i<nInst; i++){
180369:     int ip; int ic; int io;
180370:     rc = pApi->xInst(pFts, i, &ip, &ic, &io);
180371:     if( rc==SQLITE_OK ){
180372:       double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
180373:       aFreq[ip] += w;
180374:     }
180375:   }
180376: 
180377:   /* Figure out the total size of the current row in tokens. */
180378:   if( rc==SQLITE_OK ){
180379:     int nTok;
180380:     rc = pApi->xColumnSize(pFts, -1, &nTok);
180381:     D = (double)nTok;
180382:   }
180383: 
180384:   /* Determine the BM25 score for the current row. */
180385:   for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
180386:     score += pData->aIDF[i] * (
180387:       ( aFreq[i] * (k1 + 1.0) ) / 
180388:       ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
180389:     );
180390:   }
180391:   
180392:   /* If no error has occurred, return the calculated score. Otherwise,
180393:   ** throw an SQL exception.  */
180394:   if( rc==SQLITE_OK ){
180395:     sqlite3_result_double(pCtx, -1.0 * score);
180396:   }else{
180397:     sqlite3_result_error_code(pCtx, rc);
180398:   }
180399: }
180400: 
180401: static int sqlite3Fts5AuxInit(fts5_api *pApi){
180402:   struct Builtin {
180403:     const char *zFunc;            /* Function name (nul-terminated) */
180404:     void *pUserData;              /* User-data pointer */
180405:     fts5_extension_function xFunc;/* Callback function */
180406:     void (*xDestroy)(void*);      /* Destructor function */
180407:   } aBuiltin [] = {
180408:     { "snippet",   0, fts5SnippetFunction, 0 },
180409:     { "highlight", 0, fts5HighlightFunction, 0 },
180410:     { "bm25",      0, fts5Bm25Function,    0 },
180411:   };
180412:   int rc = SQLITE_OK;             /* Return code */
180413:   int i;                          /* To iterate through builtin functions */
180414: 
180415:   for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
180416:     rc = pApi->xCreateFunction(pApi,
180417:         aBuiltin[i].zFunc,
180418:         aBuiltin[i].pUserData,
180419:         aBuiltin[i].xFunc,
180420:         aBuiltin[i].xDestroy
180421:     );
180422:   }
180423: 
180424:   return rc;
180425: }
180426: 
180427: 
180428: 
180429: /*
180430: ** 2014 May 31
180431: **
180432: ** The author disclaims copyright to this source code.  In place of
180433: ** a legal notice, here is a blessing:
180434: **
180435: **    May you do good and not evil.
180436: **    May you find forgiveness for yourself and forgive others.
180437: **    May you share freely, never taking more than you give.
180438: **
180439: ******************************************************************************
180440: */
180441: 
180442: 
180443: 
180444: /* #include "fts5Int.h" */
180445: 
180446: static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
180447:   if( (u32)pBuf->nSpace<nByte ){
180448:     u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
180449:     u8 *pNew;
180450:     while( nNew<nByte ){
180451:       nNew = nNew * 2;
180452:     }
180453:     pNew = sqlite3_realloc(pBuf->p, nNew);
180454:     if( pNew==0 ){
180455:       *pRc = SQLITE_NOMEM;
180456:       return 1;
180457:     }else{
180458:       pBuf->nSpace = nNew;
180459:       pBuf->p = pNew;
180460:     }
180461:   }
180462:   return 0;
180463: }
180464: 
180465: 
180466: /*
180467: ** Encode value iVal as an SQLite varint and append it to the buffer object
180468: ** pBuf. If an OOM error occurs, set the error code in p.
180469: */
180470: static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
180471:   if( fts5BufferGrow(pRc, pBuf, 9) ) return;
180472:   pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
180473: }
180474: 
180475: static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
180476:   aBuf[0] = (iVal>>24) & 0x00FF;
180477:   aBuf[1] = (iVal>>16) & 0x00FF;
180478:   aBuf[2] = (iVal>> 8) & 0x00FF;
180479:   aBuf[3] = (iVal>> 0) & 0x00FF;
180480: }
180481: 
180482: static int sqlite3Fts5Get32(const u8 *aBuf){
180483:   return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
180484: }
180485: 
180486: /*
180487: ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set 
180488: ** the error code in p. If an error has already occurred when this function
180489: ** is called, it is a no-op.
180490: */
180491: static void sqlite3Fts5BufferAppendBlob(
180492:   int *pRc,
180493:   Fts5Buffer *pBuf, 
180494:   u32 nData, 
180495:   const u8 *pData
180496: ){
180497:   assert_nc( *pRc || nData>=0 );
180498:   if( fts5BufferGrow(pRc, pBuf, nData) ) return;
180499:   memcpy(&pBuf->p[pBuf->n], pData, nData);
180500:   pBuf->n += nData;
180501: }
180502: 
180503: /*
180504: ** Append the nul-terminated string zStr to the buffer pBuf. This function
180505: ** ensures that the byte following the buffer data is set to 0x00, even 
180506: ** though this byte is not included in the pBuf->n count.
180507: */
180508: static void sqlite3Fts5BufferAppendString(
180509:   int *pRc,
180510:   Fts5Buffer *pBuf, 
180511:   const char *zStr
180512: ){
180513:   int nStr = (int)strlen(zStr);
180514:   sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
180515:   pBuf->n--;
180516: }
180517: 
180518: /*
180519: ** Argument zFmt is a printf() style format string. This function performs
180520: ** the printf() style processing, then appends the results to buffer pBuf.
180521: **
180522: ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte 
180523: ** following the buffer data is set to 0x00, even though this byte is not
180524: ** included in the pBuf->n count.
180525: */ 
180526: static void sqlite3Fts5BufferAppendPrintf(
180527:   int *pRc,
180528:   Fts5Buffer *pBuf, 
180529:   char *zFmt, ...
180530: ){
180531:   if( *pRc==SQLITE_OK ){
180532:     char *zTmp;
180533:     va_list ap;
180534:     va_start(ap, zFmt);
180535:     zTmp = sqlite3_vmprintf(zFmt, ap);
180536:     va_end(ap);
180537: 
180538:     if( zTmp==0 ){
180539:       *pRc = SQLITE_NOMEM;
180540:     }else{
180541:       sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
180542:       sqlite3_free(zTmp);
180543:     }
180544:   }
180545: }
180546: 
180547: static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
180548:   char *zRet = 0;
180549:   if( *pRc==SQLITE_OK ){
180550:     va_list ap;
180551:     va_start(ap, zFmt);
180552:     zRet = sqlite3_vmprintf(zFmt, ap);
180553:     va_end(ap);
180554:     if( zRet==0 ){
180555:       *pRc = SQLITE_NOMEM; 
180556:     }
180557:   }
180558:   return zRet;
180559: }
180560:  
180561: 
180562: /*
180563: ** Free any buffer allocated by pBuf. Zero the structure before returning.
180564: */
180565: static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
180566:   sqlite3_free(pBuf->p);
180567:   memset(pBuf, 0, sizeof(Fts5Buffer));
180568: }
180569: 
180570: /*
180571: ** Zero the contents of the buffer object. But do not free the associated 
180572: ** memory allocation.
180573: */
180574: static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
180575:   pBuf->n = 0;
180576: }
180577: 
180578: /*
180579: ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
180580: ** the error code in p. If an error has already occurred when this function
180581: ** is called, it is a no-op.
180582: */
180583: static void sqlite3Fts5BufferSet(
180584:   int *pRc,
180585:   Fts5Buffer *pBuf, 
180586:   int nData, 
180587:   const u8 *pData
180588: ){
180589:   pBuf->n = 0;
180590:   sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
180591: }
180592: 
180593: static int sqlite3Fts5PoslistNext64(
180594:   const u8 *a, int n,             /* Buffer containing poslist */
180595:   int *pi,                        /* IN/OUT: Offset within a[] */
180596:   i64 *piOff                      /* IN/OUT: Current offset */
180597: ){
180598:   int i = *pi;
180599:   if( i>=n ){
180600:     /* EOF */
180601:     *piOff = -1;
180602:     return 1;  
180603:   }else{
180604:     i64 iOff = *piOff;
180605:     int iVal;
180606:     fts5FastGetVarint32(a, i, iVal);
180607:     if( iVal==1 ){
180608:       fts5FastGetVarint32(a, i, iVal);
180609:       iOff = ((i64)iVal) << 32;
180610:       fts5FastGetVarint32(a, i, iVal);
180611:     }
180612:     *piOff = iOff + (iVal-2);
180613:     *pi = i;
180614:     return 0;
180615:   }
180616: }
180617: 
180618: 
180619: /*
180620: ** Advance the iterator object passed as the only argument. Return true
180621: ** if the iterator reaches EOF, or false otherwise.
180622: */
180623: static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
180624:   if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
180625:     pIter->bEof = 1;
180626:   }
180627:   return pIter->bEof;
180628: }
180629: 
180630: static int sqlite3Fts5PoslistReaderInit(
180631:   const u8 *a, int n,             /* Poslist buffer to iterate through */
180632:   Fts5PoslistReader *pIter        /* Iterator object to initialize */
180633: ){
180634:   memset(pIter, 0, sizeof(*pIter));
180635:   pIter->a = a;
180636:   pIter->n = n;
180637:   sqlite3Fts5PoslistReaderNext(pIter);
180638:   return pIter->bEof;
180639: }
180640: 
180641: /*
180642: ** Append position iPos to the position list being accumulated in buffer
180643: ** pBuf, which must be already be large enough to hold the new data.
180644: ** The previous position written to this list is *piPrev. *piPrev is set
180645: ** to iPos before returning.
180646: */
180647: static void sqlite3Fts5PoslistSafeAppend(
180648:   Fts5Buffer *pBuf, 
180649:   i64 *piPrev, 
180650:   i64 iPos
180651: ){
180652:   static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
180653:   if( (iPos & colmask) != (*piPrev & colmask) ){
180654:     pBuf->p[pBuf->n++] = 1;
180655:     pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
180656:     *piPrev = (iPos & colmask);
180657:   }
180658:   pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
180659:   *piPrev = iPos;
180660: }
180661: 
180662: static int sqlite3Fts5PoslistWriterAppend(
180663:   Fts5Buffer *pBuf, 
180664:   Fts5PoslistWriter *pWriter,
180665:   i64 iPos
180666: ){
180667:   int rc = 0;   /* Initialized only to suppress erroneous warning from Clang */
180668:   if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
180669:   sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
180670:   return SQLITE_OK;
180671: }
180672: 
180673: static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
180674:   void *pRet = 0;
180675:   if( *pRc==SQLITE_OK ){
180676:     pRet = sqlite3_malloc(nByte);
180677:     if( pRet==0 && nByte>0 ){
180678:       *pRc = SQLITE_NOMEM;
180679:     }else{
180680:       memset(pRet, 0, nByte);
180681:     }
180682:   }
180683:   return pRet;
180684: }
180685: 
180686: /*
180687: ** Return a nul-terminated copy of the string indicated by pIn. If nIn
180688: ** is non-negative, then it is the length of the string in bytes. Otherwise,
180689: ** the length of the string is determined using strlen().
180690: **
180691: ** It is the responsibility of the caller to eventually free the returned
180692: ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned. 
180693: */
180694: static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
180695:   char *zRet = 0;
180696:   if( *pRc==SQLITE_OK ){
180697:     if( nIn<0 ){
180698:       nIn = (int)strlen(pIn);
180699:     }
180700:     zRet = (char*)sqlite3_malloc(nIn+1);
180701:     if( zRet ){
180702:       memcpy(zRet, pIn, nIn);
180703:       zRet[nIn] = '\0';
180704:     }else{
180705:       *pRc = SQLITE_NOMEM;
180706:     }
180707:   }
180708:   return zRet;
180709: }
180710: 
180711: 
180712: /*
180713: ** Return true if character 't' may be part of an FTS5 bareword, or false
180714: ** otherwise. Characters that may be part of barewords:
180715: **
180716: **   * All non-ASCII characters,
180717: **   * The 52 upper and lower case ASCII characters, and
180718: **   * The 10 integer ASCII characters.
180719: **   * The underscore character "_" (0x5F).
180720: **   * The unicode "subsitute" character (0x1A).
180721: */
180722: static int sqlite3Fts5IsBareword(char t){
180723:   u8 aBareword[128] = {
180724:     0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00 .. 0x0F */
180725:     0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 1, 0, 0, 0, 0, 0,   /* 0x10 .. 0x1F */
180726:     0, 0, 0, 0, 0, 0, 0, 0,    0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20 .. 0x2F */
180727:     1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30 .. 0x3F */
180728:     0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40 .. 0x4F */
180729:     1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 1,   /* 0x50 .. 0x5F */
180730:     0, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60 .. 0x6F */
180731:     1, 1, 1, 1, 1, 1, 1, 1,    1, 1, 1, 0, 0, 0, 0, 0    /* 0x70 .. 0x7F */
180732:   };
180733: 
180734:   return (t & 0x80) || aBareword[(int)t];
180735: }
180736: 
180737: 
180738: /*************************************************************************
180739: */
180740: typedef struct Fts5TermsetEntry Fts5TermsetEntry;
180741: struct Fts5TermsetEntry {
180742:   char *pTerm;
180743:   int nTerm;
180744:   int iIdx;                       /* Index (main or aPrefix[] entry) */
180745:   Fts5TermsetEntry *pNext;
180746: };
180747: 
180748: struct Fts5Termset {
180749:   Fts5TermsetEntry *apHash[512];
180750: };
180751: 
180752: static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
180753:   int rc = SQLITE_OK;
180754:   *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
180755:   return rc;
180756: }
180757: 
180758: static int sqlite3Fts5TermsetAdd(
180759:   Fts5Termset *p, 
180760:   int iIdx,
180761:   const char *pTerm, int nTerm, 
180762:   int *pbPresent
180763: ){
180764:   int rc = SQLITE_OK;
180765:   *pbPresent = 0;
180766:   if( p ){
180767:     int i;
180768:     u32 hash = 13;
180769:     Fts5TermsetEntry *pEntry;
180770: 
180771:     /* Calculate a hash value for this term. This is the same hash checksum
180772:     ** used by the fts5_hash.c module. This is not important for correct
180773:     ** operation of the module, but is necessary to ensure that some tests
180774:     ** designed to produce hash table collisions really do work.  */
180775:     for(i=nTerm-1; i>=0; i--){
180776:       hash = (hash << 3) ^ hash ^ pTerm[i];
180777:     }
180778:     hash = (hash << 3) ^ hash ^ iIdx;
180779:     hash = hash % ArraySize(p->apHash);
180780: 
180781:     for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
180782:       if( pEntry->iIdx==iIdx 
180783:           && pEntry->nTerm==nTerm 
180784:           && memcmp(pEntry->pTerm, pTerm, nTerm)==0 
180785:       ){
180786:         *pbPresent = 1;
180787:         break;
180788:       }
180789:     }
180790: 
180791:     if( pEntry==0 ){
180792:       pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
180793:       if( pEntry ){
180794:         pEntry->pTerm = (char*)&pEntry[1];
180795:         pEntry->nTerm = nTerm;
180796:         pEntry->iIdx = iIdx;
180797:         memcpy(pEntry->pTerm, pTerm, nTerm);
180798:         pEntry->pNext = p->apHash[hash];
180799:         p->apHash[hash] = pEntry;
180800:       }
180801:     }
180802:   }
180803: 
180804:   return rc;
180805: }
180806: 
180807: static void sqlite3Fts5TermsetFree(Fts5Termset *p){
180808:   if( p ){
180809:     u32 i;
180810:     for(i=0; i<ArraySize(p->apHash); i++){
180811:       Fts5TermsetEntry *pEntry = p->apHash[i];
180812:       while( pEntry ){
180813:         Fts5TermsetEntry *pDel = pEntry;
180814:         pEntry = pEntry->pNext;
180815:         sqlite3_free(pDel);
180816:       }
180817:     }
180818:     sqlite3_free(p);
180819:   }
180820: }
180821: 
180822: /*
180823: ** 2014 Jun 09
180824: **
180825: ** The author disclaims copyright to this source code.  In place of
180826: ** a legal notice, here is a blessing:
180827: **
180828: **    May you do good and not evil.
180829: **    May you find forgiveness for yourself and forgive others.
180830: **    May you share freely, never taking more than you give.
180831: **
180832: ******************************************************************************
180833: **
180834: ** This is an SQLite module implementing full-text search.
180835: */
180836: 
180837: 
180838: /* #include "fts5Int.h" */
180839: 
180840: #define FTS5_DEFAULT_PAGE_SIZE   4050
180841: #define FTS5_DEFAULT_AUTOMERGE      4
180842: #define FTS5_DEFAULT_USERMERGE      4
180843: #define FTS5_DEFAULT_CRISISMERGE   16
180844: #define FTS5_DEFAULT_HASHSIZE    (1024*1024)
180845: 
180846: /* Maximum allowed page size */
180847: #define FTS5_MAX_PAGE_SIZE (128*1024)
180848: 
180849: static int fts5_iswhitespace(char x){
180850:   return (x==' ');
180851: }
180852: 
180853: static int fts5_isopenquote(char x){
180854:   return (x=='"' || x=='\'' || x=='[' || x=='`');
180855: }
180856: 
180857: /*
180858: ** Argument pIn points to a character that is part of a nul-terminated 
180859: ** string. Return a pointer to the first character following *pIn in 
180860: ** the string that is not a white-space character.
180861: */
180862: static const char *fts5ConfigSkipWhitespace(const char *pIn){
180863:   const char *p = pIn;
180864:   if( p ){
180865:     while( fts5_iswhitespace(*p) ){ p++; }
180866:   }
180867:   return p;
180868: }
180869: 
180870: /*
180871: ** Argument pIn points to a character that is part of a nul-terminated 
180872: ** string. Return a pointer to the first character following *pIn in 
180873: ** the string that is not a "bareword" character.
180874: */
180875: static const char *fts5ConfigSkipBareword(const char *pIn){
180876:   const char *p = pIn;
180877:   while ( sqlite3Fts5IsBareword(*p) ) p++;
180878:   if( p==pIn ) p = 0;
180879:   return p;
180880: }
180881: 
180882: static int fts5_isdigit(char a){
180883:   return (a>='0' && a<='9');
180884: }
180885: 
180886: 
180887: 
180888: static const char *fts5ConfigSkipLiteral(const char *pIn){
180889:   const char *p = pIn;
180890:   switch( *p ){
180891:     case 'n': case 'N':
180892:       if( sqlite3_strnicmp("null", p, 4)==0 ){
180893:         p = &p[4];
180894:       }else{
180895:         p = 0;
180896:       }
180897:       break;
180898: 
180899:     case 'x': case 'X':
180900:       p++;
180901:       if( *p=='\'' ){
180902:         p++;
180903:         while( (*p>='a' && *p<='f') 
180904:             || (*p>='A' && *p<='F') 
180905:             || (*p>='0' && *p<='9') 
180906:             ){
180907:           p++;
180908:         }
180909:         if( *p=='\'' && 0==((p-pIn)%2) ){
180910:           p++;
180911:         }else{
180912:           p = 0;
180913:         }
180914:       }else{
180915:         p = 0;
180916:       }
180917:       break;
180918: 
180919:     case '\'':
180920:       p++;
180921:       while( p ){
180922:         if( *p=='\'' ){
180923:           p++;
180924:           if( *p!='\'' ) break;
180925:         }
180926:         p++;
180927:         if( *p==0 ) p = 0;
180928:       }
180929:       break;
180930: 
180931:     default:
180932:       /* maybe a number */
180933:       if( *p=='+' || *p=='-' ) p++;
180934:       while( fts5_isdigit(*p) ) p++;
180935: 
180936:       /* At this point, if the literal was an integer, the parse is 
180937:       ** finished. Or, if it is a floating point value, it may continue
180938:       ** with either a decimal point or an 'E' character. */
180939:       if( *p=='.' && fts5_isdigit(p[1]) ){
180940:         p += 2;
180941:         while( fts5_isdigit(*p) ) p++;
180942:       }
180943:       if( p==pIn ) p = 0;
180944: 
180945:       break;
180946:   }
180947: 
180948:   return p;
180949: }
180950: 
180951: /*
180952: ** The first character of the string pointed to by argument z is guaranteed
180953: ** to be an open-quote character (see function fts5_isopenquote()).
180954: **
180955: ** This function searches for the corresponding close-quote character within
180956: ** the string and, if found, dequotes the string in place and adds a new
180957: ** nul-terminator byte.
180958: **
180959: ** If the close-quote is found, the value returned is the byte offset of
180960: ** the character immediately following it. Or, if the close-quote is not 
180961: ** found, -1 is returned. If -1 is returned, the buffer is left in an 
180962: ** undefined state.
180963: */
180964: static int fts5Dequote(char *z){
180965:   char q;
180966:   int iIn = 1;
180967:   int iOut = 0;
180968:   q = z[0];
180969: 
180970:   /* Set stack variable q to the close-quote character */
180971:   assert( q=='[' || q=='\'' || q=='"' || q=='`' );
180972:   if( q=='[' ) q = ']';  
180973: 
180974:   while( ALWAYS(z[iIn]) ){
180975:     if( z[iIn]==q ){
180976:       if( z[iIn+1]!=q ){
180977:         /* Character iIn was the close quote. */
180978:         iIn++;
180979:         break;
180980:       }else{
180981:         /* Character iIn and iIn+1 form an escaped quote character. Skip
180982:         ** the input cursor past both and copy a single quote character 
180983:         ** to the output buffer. */
180984:         iIn += 2;
180985:         z[iOut++] = q;
180986:       }
180987:     }else{
180988:       z[iOut++] = z[iIn++];
180989:     }
180990:   }
180991: 
180992:   z[iOut] = '\0';
180993:   return iIn;
180994: }
180995: 
180996: /*
180997: ** Convert an SQL-style quoted string into a normal string by removing
180998: ** the quote characters.  The conversion is done in-place.  If the
180999: ** input does not begin with a quote character, then this routine
181000: ** is a no-op.
181001: **
181002: ** Examples:
181003: **
181004: **     "abc"   becomes   abc
181005: **     'xyz'   becomes   xyz
181006: **     [pqr]   becomes   pqr
181007: **     `mno`   becomes   mno
181008: */
181009: static void sqlite3Fts5Dequote(char *z){
181010:   char quote;                     /* Quote character (if any ) */
181011: 
181012:   assert( 0==fts5_iswhitespace(z[0]) );
181013:   quote = z[0];
181014:   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
181015:     fts5Dequote(z);
181016:   }
181017: }
181018: 
181019: 
181020: struct Fts5Enum {
181021:   const char *zName;
181022:   int eVal;
181023: };
181024: typedef struct Fts5Enum Fts5Enum;
181025: 
181026: static int fts5ConfigSetEnum(
181027:   const Fts5Enum *aEnum, 
181028:   const char *zEnum, 
181029:   int *peVal
181030: ){
181031:   int nEnum = (int)strlen(zEnum);
181032:   int i;
181033:   int iVal = -1;
181034: 
181035:   for(i=0; aEnum[i].zName; i++){
181036:     if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
181037:       if( iVal>=0 ) return SQLITE_ERROR;
181038:       iVal = aEnum[i].eVal;
181039:     }
181040:   }
181041: 
181042:   *peVal = iVal;
181043:   return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
181044: }
181045: 
181046: /*
181047: ** Parse a "special" CREATE VIRTUAL TABLE directive and update
181048: ** configuration object pConfig as appropriate.
181049: **
181050: ** If successful, object pConfig is updated and SQLITE_OK returned. If
181051: ** an error occurs, an SQLite error code is returned and an error message
181052: ** may be left in *pzErr. It is the responsibility of the caller to
181053: ** eventually free any such error message using sqlite3_free().
181054: */
181055: static int fts5ConfigParseSpecial(
181056:   Fts5Global *pGlobal,
181057:   Fts5Config *pConfig,            /* Configuration object to update */
181058:   const char *zCmd,               /* Special command to parse */
181059:   const char *zArg,               /* Argument to parse */
181060:   char **pzErr                    /* OUT: Error message */
181061: ){
181062:   int rc = SQLITE_OK;
181063:   int nCmd = (int)strlen(zCmd);
181064:   if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
181065:     const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
181066:     const char *p;
181067:     int bFirst = 1;
181068:     if( pConfig->aPrefix==0 ){
181069:       pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
181070:       if( rc ) return rc;
181071:     }
181072: 
181073:     p = zArg;
181074:     while( 1 ){
181075:       int nPre = 0;
181076: 
181077:       while( p[0]==' ' ) p++;
181078:       if( bFirst==0 && p[0]==',' ){
181079:         p++;
181080:         while( p[0]==' ' ) p++;
181081:       }else if( p[0]=='\0' ){
181082:         break;
181083:       }
181084:       if( p[0]<'0' || p[0]>'9' ){
181085:         *pzErr = sqlite3_mprintf("malformed prefix=... directive");
181086:         rc = SQLITE_ERROR;
181087:         break;
181088:       }
181089: 
181090:       if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
181091:         *pzErr = sqlite3_mprintf(
181092:             "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
181093:         );
181094:         rc = SQLITE_ERROR;
181095:         break;
181096:       }
181097: 
181098:       while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
181099:         nPre = nPre*10 + (p[0] - '0');
181100:         p++;
181101:       }
181102: 
181103:       if( nPre<=0 || nPre>=1000 ){
181104:         *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
181105:         rc = SQLITE_ERROR;
181106:         break;
181107:       }
181108: 
181109:       pConfig->aPrefix[pConfig->nPrefix] = nPre;
181110:       pConfig->nPrefix++;
181111:       bFirst = 0;
181112:     }
181113:     assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
181114:     return rc;
181115:   }
181116: 
181117:   if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
181118:     const char *p = (const char*)zArg;
181119:     int nArg = (int)strlen(zArg) + 1;
181120:     char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
181121:     char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
181122:     char *pSpace = pDel;
181123: 
181124:     if( azArg && pSpace ){
181125:       if( pConfig->pTok ){
181126:         *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
181127:         rc = SQLITE_ERROR;
181128:       }else{
181129:         for(nArg=0; p && *p; nArg++){
181130:           const char *p2 = fts5ConfigSkipWhitespace(p);
181131:           if( *p2=='\'' ){
181132:             p = fts5ConfigSkipLiteral(p2);
181133:           }else{
181134:             p = fts5ConfigSkipBareword(p2);
181135:           }
181136:           if( p ){
181137:             memcpy(pSpace, p2, p-p2);
181138:             azArg[nArg] = pSpace;
181139:             sqlite3Fts5Dequote(pSpace);
181140:             pSpace += (p - p2) + 1;
181141:             p = fts5ConfigSkipWhitespace(p);
181142:           }
181143:         }
181144:         if( p==0 ){
181145:           *pzErr = sqlite3_mprintf("parse error in tokenize directive");
181146:           rc = SQLITE_ERROR;
181147:         }else{
181148:           rc = sqlite3Fts5GetTokenizer(pGlobal, 
181149:               (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
181150:               pzErr
181151:           );
181152:         }
181153:       }
181154:     }
181155: 
181156:     sqlite3_free(azArg);
181157:     sqlite3_free(pDel);
181158:     return rc;
181159:   }
181160: 
181161:   if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
181162:     if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
181163:       *pzErr = sqlite3_mprintf("multiple content=... directives");
181164:       rc = SQLITE_ERROR;
181165:     }else{
181166:       if( zArg[0] ){
181167:         pConfig->eContent = FTS5_CONTENT_EXTERNAL;
181168:         pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
181169:       }else{
181170:         pConfig->eContent = FTS5_CONTENT_NONE;
181171:       }
181172:     }
181173:     return rc;
181174:   }
181175: 
181176:   if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
181177:     if( pConfig->zContentRowid ){
181178:       *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
181179:       rc = SQLITE_ERROR;
181180:     }else{
181181:       pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
181182:     }
181183:     return rc;
181184:   }
181185: 
181186:   if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
181187:     if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
181188:       *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
181189:       rc = SQLITE_ERROR;
181190:     }else{
181191:       pConfig->bColumnsize = (zArg[0]=='1');
181192:     }
181193:     return rc;
181194:   }
181195: 
181196:   if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
181197:     const Fts5Enum aDetail[] = {
181198:       { "none", FTS5_DETAIL_NONE },
181199:       { "full", FTS5_DETAIL_FULL },
181200:       { "columns", FTS5_DETAIL_COLUMNS },
181201:       { 0, 0 }
181202:     };
181203: 
181204:     if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
181205:       *pzErr = sqlite3_mprintf("malformed detail=... directive");
181206:     }
181207:     return rc;
181208:   }
181209: 
181210:   *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
181211:   return SQLITE_ERROR;
181212: }
181213: 
181214: /*
181215: ** Allocate an instance of the default tokenizer ("simple") at 
181216: ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
181217: ** code if an error occurs.
181218: */
181219: static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
181220:   assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
181221:   return sqlite3Fts5GetTokenizer(
181222:       pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
181223:   );
181224: }
181225: 
181226: /*
181227: ** Gobble up the first bareword or quoted word from the input buffer zIn.
181228: ** Return a pointer to the character immediately following the last in
181229: ** the gobbled word if successful, or a NULL pointer otherwise (failed
181230: ** to find close-quote character).
181231: **
181232: ** Before returning, set pzOut to point to a new buffer containing a
181233: ** nul-terminated, dequoted copy of the gobbled word. If the word was
181234: ** quoted, *pbQuoted is also set to 1 before returning.
181235: **
181236: ** If *pRc is other than SQLITE_OK when this function is called, it is
181237: ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
181238: ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
181239: ** set if a parse error (failed to find close quote) occurs.
181240: */
181241: static const char *fts5ConfigGobbleWord(
181242:   int *pRc,                       /* IN/OUT: Error code */
181243:   const char *zIn,                /* Buffer to gobble string/bareword from */
181244:   char **pzOut,                   /* OUT: malloc'd buffer containing str/bw */
181245:   int *pbQuoted                   /* OUT: Set to true if dequoting required */
181246: ){
181247:   const char *zRet = 0;
181248: 
181249:   int nIn = (int)strlen(zIn);
181250:   char *zOut = sqlite3_malloc(nIn+1);
181251: 
181252:   assert( *pRc==SQLITE_OK );
181253:   *pbQuoted = 0;
181254:   *pzOut = 0;
181255: 
181256:   if( zOut==0 ){
181257:     *pRc = SQLITE_NOMEM;
181258:   }else{
181259:     memcpy(zOut, zIn, nIn+1);
181260:     if( fts5_isopenquote(zOut[0]) ){
181261:       int ii = fts5Dequote(zOut);
181262:       zRet = &zIn[ii];
181263:       *pbQuoted = 1;
181264:     }else{
181265:       zRet = fts5ConfigSkipBareword(zIn);
181266:       if( zRet ){
181267:         zOut[zRet-zIn] = '\0';
181268:       }
181269:     }
181270:   }
181271: 
181272:   if( zRet==0 ){
181273:     sqlite3_free(zOut);
181274:   }else{
181275:     *pzOut = zOut;
181276:   }
181277: 
181278:   return zRet;
181279: }
181280: 
181281: static int fts5ConfigParseColumn(
181282:   Fts5Config *p, 
181283:   char *zCol, 
181284:   char *zArg, 
181285:   char **pzErr
181286: ){
181287:   int rc = SQLITE_OK;
181288:   if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME) 
181289:    || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME) 
181290:   ){
181291:     *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
181292:     rc = SQLITE_ERROR;
181293:   }else if( zArg ){
181294:     if( 0==sqlite3_stricmp(zArg, "unindexed") ){
181295:       p->abUnindexed[p->nCol] = 1;
181296:     }else{
181297:       *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
181298:       rc = SQLITE_ERROR;
181299:     }
181300:   }
181301: 
181302:   p->azCol[p->nCol++] = zCol;
181303:   return rc;
181304: }
181305: 
181306: /*
181307: ** Populate the Fts5Config.zContentExprlist string.
181308: */
181309: static int fts5ConfigMakeExprlist(Fts5Config *p){
181310:   int i;
181311:   int rc = SQLITE_OK;
181312:   Fts5Buffer buf = {0, 0, 0};
181313: 
181314:   sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
181315:   if( p->eContent!=FTS5_CONTENT_NONE ){
181316:     for(i=0; i<p->nCol; i++){
181317:       if( p->eContent==FTS5_CONTENT_EXTERNAL ){
181318:         sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
181319:       }else{
181320:         sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
181321:       }
181322:     }
181323:   }
181324: 
181325:   assert( p->zContentExprlist==0 );
181326:   p->zContentExprlist = (char*)buf.p;
181327:   return rc;
181328: }
181329: 
181330: /*
181331: ** Arguments nArg/azArg contain the string arguments passed to the xCreate
181332: ** or xConnect method of the virtual table. This function attempts to 
181333: ** allocate an instance of Fts5Config containing the results of parsing
181334: ** those arguments.
181335: **
181336: ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
181337: ** new Fts5Config object. If an error occurs, an SQLite error code is 
181338: ** returned, *ppOut is set to NULL and an error message may be left in
181339: ** *pzErr. It is the responsibility of the caller to eventually free any 
181340: ** such error message using sqlite3_free().
181341: */
181342: static int sqlite3Fts5ConfigParse(
181343:   Fts5Global *pGlobal,
181344:   sqlite3 *db,
181345:   int nArg,                       /* Number of arguments */
181346:   const char **azArg,             /* Array of nArg CREATE VIRTUAL TABLE args */
181347:   Fts5Config **ppOut,             /* OUT: Results of parse */
181348:   char **pzErr                    /* OUT: Error message */
181349: ){
181350:   int rc = SQLITE_OK;             /* Return code */
181351:   Fts5Config *pRet;               /* New object to return */
181352:   int i;
181353:   int nByte;
181354: 
181355:   *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
181356:   if( pRet==0 ) return SQLITE_NOMEM;
181357:   memset(pRet, 0, sizeof(Fts5Config));
181358:   pRet->db = db;
181359:   pRet->iCookie = -1;
181360: 
181361:   nByte = nArg * (sizeof(char*) + sizeof(u8));
181362:   pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
181363:   pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
181364:   pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
181365:   pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
181366:   pRet->bColumnsize = 1;
181367:   pRet->eDetail = FTS5_DETAIL_FULL;
181368: #ifdef SQLITE_DEBUG
181369:   pRet->bPrefixIndex = 1;
181370: #endif
181371:   if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
181372:     *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
181373:     rc = SQLITE_ERROR;
181374:   }
181375: 
181376:   for(i=3; rc==SQLITE_OK && i<nArg; i++){
181377:     const char *zOrig = azArg[i];
181378:     const char *z;
181379:     char *zOne = 0;
181380:     char *zTwo = 0;
181381:     int bOption = 0;
181382:     int bMustBeCol = 0;
181383: 
181384:     z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
181385:     z = fts5ConfigSkipWhitespace(z);
181386:     if( z && *z=='=' ){
181387:       bOption = 1;
181388:       z++;
181389:       if( bMustBeCol ) z = 0;
181390:     }
181391:     z = fts5ConfigSkipWhitespace(z);
181392:     if( z && z[0] ){
181393:       int bDummy;
181394:       z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
181395:       if( z && z[0] ) z = 0;
181396:     }
181397: 
181398:     if( rc==SQLITE_OK ){
181399:       if( z==0 ){
181400:         *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
181401:         rc = SQLITE_ERROR;
181402:       }else{
181403:         if( bOption ){
181404:           rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
181405:         }else{
181406:           rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
181407:           zOne = 0;
181408:         }
181409:       }
181410:     }
181411: 
181412:     sqlite3_free(zOne);
181413:     sqlite3_free(zTwo);
181414:   }
181415: 
181416:   /* If a tokenizer= option was successfully parsed, the tokenizer has
181417:   ** already been allocated. Otherwise, allocate an instance of the default
181418:   ** tokenizer (unicode61) now.  */
181419:   if( rc==SQLITE_OK && pRet->pTok==0 ){
181420:     rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
181421:   }
181422: 
181423:   /* If no zContent option was specified, fill in the default values. */
181424:   if( rc==SQLITE_OK && pRet->zContent==0 ){
181425:     const char *zTail = 0;
181426:     assert( pRet->eContent==FTS5_CONTENT_NORMAL 
181427:          || pRet->eContent==FTS5_CONTENT_NONE 
181428:     );
181429:     if( pRet->eContent==FTS5_CONTENT_NORMAL ){
181430:       zTail = "content";
181431:     }else if( pRet->bColumnsize ){
181432:       zTail = "docsize";
181433:     }
181434: 
181435:     if( zTail ){
181436:       pRet->zContent = sqlite3Fts5Mprintf(
181437:           &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
181438:       );
181439:     }
181440:   }
181441: 
181442:   if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
181443:     pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
181444:   }
181445: 
181446:   /* Formulate the zContentExprlist text */
181447:   if( rc==SQLITE_OK ){
181448:     rc = fts5ConfigMakeExprlist(pRet);
181449:   }
181450: 
181451:   if( rc!=SQLITE_OK ){
181452:     sqlite3Fts5ConfigFree(pRet);
181453:     *ppOut = 0;
181454:   }
181455:   return rc;
181456: }
181457: 
181458: /*
181459: ** Free the configuration object passed as the only argument.
181460: */
181461: static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
181462:   if( pConfig ){
181463:     int i;
181464:     if( pConfig->pTok ){
181465:       pConfig->pTokApi->xDelete(pConfig->pTok);
181466:     }
181467:     sqlite3_free(pConfig->zDb);
181468:     sqlite3_free(pConfig->zName);
181469:     for(i=0; i<pConfig->nCol; i++){
181470:       sqlite3_free(pConfig->azCol[i]);
181471:     }
181472:     sqlite3_free(pConfig->azCol);
181473:     sqlite3_free(pConfig->aPrefix);
181474:     sqlite3_free(pConfig->zRank);
181475:     sqlite3_free(pConfig->zRankArgs);
181476:     sqlite3_free(pConfig->zContent);
181477:     sqlite3_free(pConfig->zContentRowid);
181478:     sqlite3_free(pConfig->zContentExprlist);
181479:     sqlite3_free(pConfig);
181480:   }
181481: }
181482: 
181483: /*
181484: ** Call sqlite3_declare_vtab() based on the contents of the configuration
181485: ** object passed as the only argument. Return SQLITE_OK if successful, or
181486: ** an SQLite error code if an error occurs.
181487: */
181488: static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
181489:   int i;
181490:   int rc = SQLITE_OK;
181491:   char *zSql;
181492: 
181493:   zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
181494:   for(i=0; zSql && i<pConfig->nCol; i++){
181495:     const char *zSep = (i==0?"":", ");
181496:     zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
181497:   }
181498:   zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)", 
181499:       zSql, pConfig->zName, FTS5_RANK_NAME
181500:   );
181501: 
181502:   assert( zSql || rc==SQLITE_NOMEM );
181503:   if( zSql ){
181504:     rc = sqlite3_declare_vtab(pConfig->db, zSql);
181505:     sqlite3_free(zSql);
181506:   }
181507:   
181508:   return rc;
181509: }
181510: 
181511: /*
181512: ** Tokenize the text passed via the second and third arguments.
181513: **
181514: ** The callback is invoked once for each token in the input text. The
181515: ** arguments passed to it are, in order:
181516: **
181517: **     void *pCtx          // Copy of 4th argument to sqlite3Fts5Tokenize()
181518: **     const char *pToken  // Pointer to buffer containing token
181519: **     int nToken          // Size of token in bytes
181520: **     int iStart          // Byte offset of start of token within input text
181521: **     int iEnd            // Byte offset of end of token within input text
181522: **     int iPos            // Position of token in input (first token is 0)
181523: **
181524: ** If the callback returns a non-zero value the tokenization is abandoned
181525: ** and no further callbacks are issued. 
181526: **
181527: ** This function returns SQLITE_OK if successful or an SQLite error code
181528: ** if an error occurs. If the tokenization was abandoned early because
181529: ** the callback returned SQLITE_DONE, this is not an error and this function
181530: ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
181531: ** because the callback returned another non-zero value, it is assumed
181532: ** to be an SQLite error code and returned to the caller.
181533: */
181534: static int sqlite3Fts5Tokenize(
181535:   Fts5Config *pConfig,            /* FTS5 Configuration object */
181536:   int flags,                      /* FTS5_TOKENIZE_* flags */
181537:   const char *pText, int nText,   /* Text to tokenize */
181538:   void *pCtx,                     /* Context passed to xToken() */
181539:   int (*xToken)(void*, int, const char*, int, int, int)    /* Callback */
181540: ){
181541:   if( pText==0 ) return SQLITE_OK;
181542:   return pConfig->pTokApi->xTokenize(
181543:       pConfig->pTok, pCtx, flags, pText, nText, xToken
181544:   );
181545: }
181546: 
181547: /*
181548: ** Argument pIn points to the first character in what is expected to be
181549: ** a comma-separated list of SQL literals followed by a ')' character.
181550: ** If it actually is this, return a pointer to the ')'. Otherwise, return
181551: ** NULL to indicate a parse error.
181552: */
181553: static const char *fts5ConfigSkipArgs(const char *pIn){
181554:   const char *p = pIn;
181555:   
181556:   while( 1 ){
181557:     p = fts5ConfigSkipWhitespace(p);
181558:     p = fts5ConfigSkipLiteral(p);
181559:     p = fts5ConfigSkipWhitespace(p);
181560:     if( p==0 || *p==')' ) break;
181561:     if( *p!=',' ){
181562:       p = 0;
181563:       break;
181564:     }
181565:     p++;
181566:   }
181567: 
181568:   return p;
181569: }
181570: 
181571: /*
181572: ** Parameter zIn contains a rank() function specification. The format of 
181573: ** this is:
181574: **
181575: **   + Bareword (function name)
181576: **   + Open parenthesis - "("
181577: **   + Zero or more SQL literals in a comma separated list
181578: **   + Close parenthesis - ")"
181579: */
181580: static int sqlite3Fts5ConfigParseRank(
181581:   const char *zIn,                /* Input string */
181582:   char **pzRank,                  /* OUT: Rank function name */
181583:   char **pzRankArgs               /* OUT: Rank function arguments */
181584: ){
181585:   const char *p = zIn;
181586:   const char *pRank;
181587:   char *zRank = 0;
181588:   char *zRankArgs = 0;
181589:   int rc = SQLITE_OK;
181590: 
181591:   *pzRank = 0;
181592:   *pzRankArgs = 0;
181593: 
181594:   if( p==0 ){
181595:     rc = SQLITE_ERROR;
181596:   }else{
181597:     p = fts5ConfigSkipWhitespace(p);
181598:     pRank = p;
181599:     p = fts5ConfigSkipBareword(p);
181600: 
181601:     if( p ){
181602:       zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
181603:       if( zRank ) memcpy(zRank, pRank, p-pRank);
181604:     }else{
181605:       rc = SQLITE_ERROR;
181606:     }
181607: 
181608:     if( rc==SQLITE_OK ){
181609:       p = fts5ConfigSkipWhitespace(p);
181610:       if( *p!='(' ) rc = SQLITE_ERROR;
181611:       p++;
181612:     }
181613:     if( rc==SQLITE_OK ){
181614:       const char *pArgs; 
181615:       p = fts5ConfigSkipWhitespace(p);
181616:       pArgs = p;
181617:       if( *p!=')' ){
181618:         p = fts5ConfigSkipArgs(p);
181619:         if( p==0 ){
181620:           rc = SQLITE_ERROR;
181621:         }else{
181622:           zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
181623:           if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
181624:         }
181625:       }
181626:     }
181627:   }
181628: 
181629:   if( rc!=SQLITE_OK ){
181630:     sqlite3_free(zRank);
181631:     assert( zRankArgs==0 );
181632:   }else{
181633:     *pzRank = zRank;
181634:     *pzRankArgs = zRankArgs;
181635:   }
181636:   return rc;
181637: }
181638: 
181639: static int sqlite3Fts5ConfigSetValue(
181640:   Fts5Config *pConfig, 
181641:   const char *zKey, 
181642:   sqlite3_value *pVal,
181643:   int *pbBadkey
181644: ){
181645:   int rc = SQLITE_OK;
181646: 
181647:   if( 0==sqlite3_stricmp(zKey, "pgsz") ){
181648:     int pgsz = 0;
181649:     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181650:       pgsz = sqlite3_value_int(pVal);
181651:     }
181652:     if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
181653:       *pbBadkey = 1;
181654:     }else{
181655:       pConfig->pgsz = pgsz;
181656:     }
181657:   }
181658: 
181659:   else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
181660:     int nHashSize = -1;
181661:     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181662:       nHashSize = sqlite3_value_int(pVal);
181663:     }
181664:     if( nHashSize<=0 ){
181665:       *pbBadkey = 1;
181666:     }else{
181667:       pConfig->nHashSize = nHashSize;
181668:     }
181669:   }
181670: 
181671:   else if( 0==sqlite3_stricmp(zKey, "automerge") ){
181672:     int nAutomerge = -1;
181673:     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181674:       nAutomerge = sqlite3_value_int(pVal);
181675:     }
181676:     if( nAutomerge<0 || nAutomerge>64 ){
181677:       *pbBadkey = 1;
181678:     }else{
181679:       if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
181680:       pConfig->nAutomerge = nAutomerge;
181681:     }
181682:   }
181683: 
181684:   else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
181685:     int nUsermerge = -1;
181686:     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181687:       nUsermerge = sqlite3_value_int(pVal);
181688:     }
181689:     if( nUsermerge<2 || nUsermerge>16 ){
181690:       *pbBadkey = 1;
181691:     }else{
181692:       pConfig->nUsermerge = nUsermerge;
181693:     }
181694:   }
181695: 
181696:   else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
181697:     int nCrisisMerge = -1;
181698:     if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
181699:       nCrisisMerge = sqlite3_value_int(pVal);
181700:     }
181701:     if( nCrisisMerge<0 ){
181702:       *pbBadkey = 1;
181703:     }else{
181704:       if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
181705:       pConfig->nCrisisMerge = nCrisisMerge;
181706:     }
181707:   }
181708: 
181709:   else if( 0==sqlite3_stricmp(zKey, "rank") ){
181710:     const char *zIn = (const char*)sqlite3_value_text(pVal);
181711:     char *zRank;
181712:     char *zRankArgs;
181713:     rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
181714:     if( rc==SQLITE_OK ){
181715:       sqlite3_free(pConfig->zRank);
181716:       sqlite3_free(pConfig->zRankArgs);
181717:       pConfig->zRank = zRank;
181718:       pConfig->zRankArgs = zRankArgs;
181719:     }else if( rc==SQLITE_ERROR ){
181720:       rc = SQLITE_OK;
181721:       *pbBadkey = 1;
181722:     }
181723:   }else{
181724:     *pbBadkey = 1;
181725:   }
181726:   return rc;
181727: }
181728: 
181729: /*
181730: ** Load the contents of the %_config table into memory.
181731: */
181732: static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
181733:   const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
181734:   char *zSql;
181735:   sqlite3_stmt *p = 0;
181736:   int rc = SQLITE_OK;
181737:   int iVersion = 0;
181738: 
181739:   /* Set default values */
181740:   pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
181741:   pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
181742:   pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
181743:   pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
181744:   pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
181745: 
181746:   zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
181747:   if( zSql ){
181748:     rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
181749:     sqlite3_free(zSql);
181750:   }
181751: 
181752:   assert( rc==SQLITE_OK || p==0 );
181753:   if( rc==SQLITE_OK ){
181754:     while( SQLITE_ROW==sqlite3_step(p) ){
181755:       const char *zK = (const char*)sqlite3_column_text(p, 0);
181756:       sqlite3_value *pVal = sqlite3_column_value(p, 1);
181757:       if( 0==sqlite3_stricmp(zK, "version") ){
181758:         iVersion = sqlite3_value_int(pVal);
181759:       }else{
181760:         int bDummy = 0;
181761:         sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
181762:       }
181763:     }
181764:     rc = sqlite3_finalize(p);
181765:   }
181766:   
181767:   if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
181768:     rc = SQLITE_ERROR;
181769:     if( pConfig->pzErrmsg ){
181770:       assert( 0==*pConfig->pzErrmsg );
181771:       *pConfig->pzErrmsg = sqlite3_mprintf(
181772:           "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
181773:           iVersion, FTS5_CURRENT_VERSION
181774:       );
181775:     }
181776:   }
181777: 
181778:   if( rc==SQLITE_OK ){
181779:     pConfig->iCookie = iCookie;
181780:   }
181781:   return rc;
181782: }
181783: 
181784: /*
181785: ** 2014 May 31
181786: **
181787: ** The author disclaims copyright to this source code.  In place of
181788: ** a legal notice, here is a blessing:
181789: **
181790: **    May you do good and not evil.
181791: **    May you find forgiveness for yourself and forgive others.
181792: **    May you share freely, never taking more than you give.
181793: **
181794: ******************************************************************************
181795: **
181796: */
181797: 
181798: 
181799: 
181800: /* #include "fts5Int.h" */
181801: /* #include "fts5parse.h" */
181802: 
181803: /*
181804: ** All token types in the generated fts5parse.h file are greater than 0.
181805: */
181806: #define FTS5_EOF 0
181807: 
181808: #define FTS5_LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
181809: 
181810: typedef struct Fts5ExprTerm Fts5ExprTerm;
181811: 
181812: /*
181813: ** Functions generated by lemon from fts5parse.y.
181814: */
181815: static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
181816: static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
181817: static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
181818: #ifndef NDEBUG
181819: /* #include <stdio.h> */
181820: static void sqlite3Fts5ParserTrace(FILE*, char*);
181821: #endif
181822: 
181823: 
181824: struct Fts5Expr {
181825:   Fts5Index *pIndex;
181826:   Fts5Config *pConfig;
181827:   Fts5ExprNode *pRoot;
181828:   int bDesc;                      /* Iterate in descending rowid order */
181829:   int nPhrase;                    /* Number of phrases in expression */
181830:   Fts5ExprPhrase **apExprPhrase;  /* Pointers to phrase objects */
181831: };
181832: 
181833: /*
181834: ** eType:
181835: **   Expression node type. Always one of:
181836: **
181837: **       FTS5_AND                 (nChild, apChild valid)
181838: **       FTS5_OR                  (nChild, apChild valid)
181839: **       FTS5_NOT                 (nChild, apChild valid)
181840: **       FTS5_STRING              (pNear valid)
181841: **       FTS5_TERM                (pNear valid)
181842: */
181843: struct Fts5ExprNode {
181844:   int eType;                      /* Node type */
181845:   int bEof;                       /* True at EOF */
181846:   int bNomatch;                   /* True if entry is not a match */
181847: 
181848:   /* Next method for this node. */
181849:   int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
181850: 
181851:   i64 iRowid;                     /* Current rowid */
181852:   Fts5ExprNearset *pNear;         /* For FTS5_STRING - cluster of phrases */
181853: 
181854:   /* Child nodes. For a NOT node, this array always contains 2 entries. For 
181855:   ** AND or OR nodes, it contains 2 or more entries.  */
181856:   int nChild;                     /* Number of child nodes */
181857:   Fts5ExprNode *apChild[1];       /* Array of child nodes */
181858: };
181859: 
181860: #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
181861: 
181862: /*
181863: ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
181864: ** used as if it has the same signature as the xNext() methods themselves.
181865: */
181866: #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
181867: 
181868: /*
181869: ** An instance of the following structure represents a single search term
181870: ** or term prefix.
181871: */
181872: struct Fts5ExprTerm {
181873:   int bPrefix;                    /* True for a prefix term */
181874:   char *zTerm;                    /* nul-terminated term */
181875:   Fts5IndexIter *pIter;           /* Iterator for this term */
181876:   Fts5ExprTerm *pSynonym;         /* Pointer to first in list of synonyms */
181877: };
181878: 
181879: /*
181880: ** A phrase. One or more terms that must appear in a contiguous sequence
181881: ** within a document for it to match.
181882: */
181883: struct Fts5ExprPhrase {
181884:   Fts5ExprNode *pNode;            /* FTS5_STRING node this phrase is part of */
181885:   Fts5Buffer poslist;             /* Current position list */
181886:   int nTerm;                      /* Number of entries in aTerm[] */
181887:   Fts5ExprTerm aTerm[1];          /* Terms that make up this phrase */
181888: };
181889: 
181890: /*
181891: ** One or more phrases that must appear within a certain token distance of
181892: ** each other within each matching document.
181893: */
181894: struct Fts5ExprNearset {
181895:   int nNear;                      /* NEAR parameter */
181896:   Fts5Colset *pColset;            /* Columns to search (NULL -> all columns) */
181897:   int nPhrase;                    /* Number of entries in aPhrase[] array */
181898:   Fts5ExprPhrase *apPhrase[1];    /* Array of phrase pointers */
181899: };
181900: 
181901: 
181902: /*
181903: ** Parse context.
181904: */
181905: struct Fts5Parse {
181906:   Fts5Config *pConfig;
181907:   char *zErr;
181908:   int rc;
181909:   int nPhrase;                    /* Size of apPhrase array */
181910:   Fts5ExprPhrase **apPhrase;      /* Array of all phrases */
181911:   Fts5ExprNode *pExpr;            /* Result of a successful parse */
181912: };
181913: 
181914: static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
181915:   va_list ap;
181916:   va_start(ap, zFmt);
181917:   if( pParse->rc==SQLITE_OK ){
181918:     pParse->zErr = sqlite3_vmprintf(zFmt, ap);
181919:     pParse->rc = SQLITE_ERROR;
181920:   }
181921:   va_end(ap);
181922: }
181923: 
181924: static int fts5ExprIsspace(char t){
181925:   return t==' ' || t=='\t' || t=='\n' || t=='\r';
181926: }
181927: 
181928: /*
181929: ** Read the first token from the nul-terminated string at *pz.
181930: */
181931: static int fts5ExprGetToken(
181932:   Fts5Parse *pParse, 
181933:   const char **pz,                /* IN/OUT: Pointer into buffer */
181934:   Fts5Token *pToken
181935: ){
181936:   const char *z = *pz;
181937:   int tok;
181938: 
181939:   /* Skip past any whitespace */
181940:   while( fts5ExprIsspace(*z) ) z++;
181941: 
181942:   pToken->p = z;
181943:   pToken->n = 1;
181944:   switch( *z ){
181945:     case '(':  tok = FTS5_LP;    break;
181946:     case ')':  tok = FTS5_RP;    break;
181947:     case '{':  tok = FTS5_LCP;   break;
181948:     case '}':  tok = FTS5_RCP;   break;
181949:     case ':':  tok = FTS5_COLON; break;
181950:     case ',':  tok = FTS5_COMMA; break;
181951:     case '+':  tok = FTS5_PLUS;  break;
181952:     case '*':  tok = FTS5_STAR;  break;
181953:     case '\0': tok = FTS5_EOF;   break;
181954: 
181955:     case '"': {
181956:       const char *z2;
181957:       tok = FTS5_STRING;
181958: 
181959:       for(z2=&z[1]; 1; z2++){
181960:         if( z2[0]=='"' ){
181961:           z2++;
181962:           if( z2[0]!='"' ) break;
181963:         }
181964:         if( z2[0]=='\0' ){
181965:           sqlite3Fts5ParseError(pParse, "unterminated string");
181966:           return FTS5_EOF;
181967:         }
181968:       }
181969:       pToken->n = (z2 - z);
181970:       break;
181971:     }
181972: 
181973:     default: {
181974:       const char *z2;
181975:       if( sqlite3Fts5IsBareword(z[0])==0 ){
181976:         sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
181977:         return FTS5_EOF;
181978:       }
181979:       tok = FTS5_STRING;
181980:       for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
181981:       pToken->n = (z2 - z);
181982:       if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 )  tok = FTS5_OR;
181983:       if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
181984:       if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
181985:       break;
181986:     }
181987:   }
181988: 
181989:   *pz = &pToken->p[pToken->n];
181990:   return tok;
181991: }
181992: 
181993: static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
181994: static void fts5ParseFree(void *p){ sqlite3_free(p); }
181995: 
181996: static int sqlite3Fts5ExprNew(
181997:   Fts5Config *pConfig,            /* FTS5 Configuration */
181998:   const char *zExpr,              /* Expression text */
181999:   Fts5Expr **ppNew, 
182000:   char **pzErr
182001: ){
182002:   Fts5Parse sParse;
182003:   Fts5Token token;
182004:   const char *z = zExpr;
182005:   int t;                          /* Next token type */
182006:   void *pEngine;
182007:   Fts5Expr *pNew;
182008: 
182009:   *ppNew = 0;
182010:   *pzErr = 0;
182011:   memset(&sParse, 0, sizeof(sParse));
182012:   pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
182013:   if( pEngine==0 ){ return SQLITE_NOMEM; }
182014:   sParse.pConfig = pConfig;
182015: 
182016:   do {
182017:     t = fts5ExprGetToken(&sParse, &z, &token);
182018:     sqlite3Fts5Parser(pEngine, t, token, &sParse);
182019:   }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
182020:   sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
182021: 
182022:   assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
182023:   if( sParse.rc==SQLITE_OK ){
182024:     *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
182025:     if( pNew==0 ){
182026:       sParse.rc = SQLITE_NOMEM;
182027:       sqlite3Fts5ParseNodeFree(sParse.pExpr);
182028:     }else{
182029:       if( !sParse.pExpr ){
182030:         const int nByte = sizeof(Fts5ExprNode);
182031:         pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
182032:         if( pNew->pRoot ){
182033:           pNew->pRoot->bEof = 1;
182034:         }
182035:       }else{
182036:         pNew->pRoot = sParse.pExpr;
182037:       }
182038:       pNew->pIndex = 0;
182039:       pNew->pConfig = pConfig;
182040:       pNew->apExprPhrase = sParse.apPhrase;
182041:       pNew->nPhrase = sParse.nPhrase;
182042:       sParse.apPhrase = 0;
182043:     }
182044:   }else{
182045:     sqlite3Fts5ParseNodeFree(sParse.pExpr);
182046:   }
182047: 
182048:   sqlite3_free(sParse.apPhrase);
182049:   *pzErr = sParse.zErr;
182050:   return sParse.rc;
182051: }
182052: 
182053: /*
182054: ** Free the expression node object passed as the only argument.
182055: */
182056: static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
182057:   if( p ){
182058:     int i;
182059:     for(i=0; i<p->nChild; i++){
182060:       sqlite3Fts5ParseNodeFree(p->apChild[i]);
182061:     }
182062:     sqlite3Fts5ParseNearsetFree(p->pNear);
182063:     sqlite3_free(p);
182064:   }
182065: }
182066: 
182067: /*
182068: ** Free the expression object passed as the only argument.
182069: */
182070: static void sqlite3Fts5ExprFree(Fts5Expr *p){
182071:   if( p ){
182072:     sqlite3Fts5ParseNodeFree(p->pRoot);
182073:     sqlite3_free(p->apExprPhrase);
182074:     sqlite3_free(p);
182075:   }
182076: }
182077: 
182078: /*
182079: ** Argument pTerm must be a synonym iterator. Return the current rowid
182080: ** that it points to.
182081: */
182082: static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
182083:   i64 iRet = 0;
182084:   int bRetValid = 0;
182085:   Fts5ExprTerm *p;
182086: 
182087:   assert( pTerm->pSynonym );
182088:   assert( bDesc==0 || bDesc==1 );
182089:   for(p=pTerm; p; p=p->pSynonym){
182090:     if( 0==sqlite3Fts5IterEof(p->pIter) ){
182091:       i64 iRowid = p->pIter->iRowid;
182092:       if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
182093:         iRet = iRowid;
182094:         bRetValid = 1;
182095:       }
182096:     }
182097:   }
182098: 
182099:   if( pbEof && bRetValid==0 ) *pbEof = 1;
182100:   return iRet;
182101: }
182102: 
182103: /*
182104: ** Argument pTerm must be a synonym iterator.
182105: */
182106: static int fts5ExprSynonymList(
182107:   Fts5ExprTerm *pTerm, 
182108:   i64 iRowid,
182109:   Fts5Buffer *pBuf,               /* Use this buffer for space if required */
182110:   u8 **pa, int *pn
182111: ){
182112:   Fts5PoslistReader aStatic[4];
182113:   Fts5PoslistReader *aIter = aStatic;
182114:   int nIter = 0;
182115:   int nAlloc = 4;
182116:   int rc = SQLITE_OK;
182117:   Fts5ExprTerm *p;
182118: 
182119:   assert( pTerm->pSynonym );
182120:   for(p=pTerm; p; p=p->pSynonym){
182121:     Fts5IndexIter *pIter = p->pIter;
182122:     if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
182123:       if( pIter->nData==0 ) continue;
182124:       if( nIter==nAlloc ){
182125:         int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
182126:         Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
182127:         if( aNew==0 ){
182128:           rc = SQLITE_NOMEM;
182129:           goto synonym_poslist_out;
182130:         }
182131:         memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
182132:         nAlloc = nAlloc*2;
182133:         if( aIter!=aStatic ) sqlite3_free(aIter);
182134:         aIter = aNew;
182135:       }
182136:       sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
182137:       assert( aIter[nIter].bEof==0 );
182138:       nIter++;
182139:     }
182140:   }
182141: 
182142:   if( nIter==1 ){
182143:     *pa = (u8*)aIter[0].a;
182144:     *pn = aIter[0].n;
182145:   }else{
182146:     Fts5PoslistWriter writer = {0};
182147:     i64 iPrev = -1;
182148:     fts5BufferZero(pBuf);
182149:     while( 1 ){
182150:       int i;
182151:       i64 iMin = FTS5_LARGEST_INT64;
182152:       for(i=0; i<nIter; i++){
182153:         if( aIter[i].bEof==0 ){
182154:           if( aIter[i].iPos==iPrev ){
182155:             if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
182156:           }
182157:           if( aIter[i].iPos<iMin ){
182158:             iMin = aIter[i].iPos;
182159:           }
182160:         }
182161:       }
182162:       if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
182163:       rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
182164:       iPrev = iMin;
182165:     }
182166:     if( rc==SQLITE_OK ){
182167:       *pa = pBuf->p;
182168:       *pn = pBuf->n;
182169:     }
182170:   }
182171: 
182172:  synonym_poslist_out:
182173:   if( aIter!=aStatic ) sqlite3_free(aIter);
182174:   return rc;
182175: }
182176: 
182177: 
182178: /*
182179: ** All individual term iterators in pPhrase are guaranteed to be valid and
182180: ** pointing to the same rowid when this function is called. This function 
182181: ** checks if the current rowid really is a match, and if so populates
182182: ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
182183: ** is set to true if this is really a match, or false otherwise.
182184: **
182185: ** SQLITE_OK is returned if an error occurs, or an SQLite error code 
182186: ** otherwise. It is not considered an error code if the current rowid is 
182187: ** not a match.
182188: */
182189: static int fts5ExprPhraseIsMatch(
182190:   Fts5ExprNode *pNode,            /* Node pPhrase belongs to */
182191:   Fts5ExprPhrase *pPhrase,        /* Phrase object to initialize */
182192:   int *pbMatch                    /* OUT: Set to true if really a match */
182193: ){
182194:   Fts5PoslistWriter writer = {0};
182195:   Fts5PoslistReader aStatic[4];
182196:   Fts5PoslistReader *aIter = aStatic;
182197:   int i;
182198:   int rc = SQLITE_OK;
182199:   
182200:   fts5BufferZero(&pPhrase->poslist);
182201: 
182202:   /* If the aStatic[] array is not large enough, allocate a large array
182203:   ** using sqlite3_malloc(). This approach could be improved upon. */
182204:   if( pPhrase->nTerm>ArraySize(aStatic) ){
182205:     int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
182206:     aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
182207:     if( !aIter ) return SQLITE_NOMEM;
182208:   }
182209:   memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
182210: 
182211:   /* Initialize a term iterator for each term in the phrase */
182212:   for(i=0; i<pPhrase->nTerm; i++){
182213:     Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
182214:     int n = 0;
182215:     int bFlag = 0;
182216:     u8 *a = 0;
182217:     if( pTerm->pSynonym ){
182218:       Fts5Buffer buf = {0, 0, 0};
182219:       rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
182220:       if( rc ){
182221:         sqlite3_free(a);
182222:         goto ismatch_out;
182223:       }
182224:       if( a==buf.p ) bFlag = 1;
182225:     }else{
182226:       a = (u8*)pTerm->pIter->pData;
182227:       n = pTerm->pIter->nData;
182228:     }
182229:     sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
182230:     aIter[i].bFlag = (u8)bFlag;
182231:     if( aIter[i].bEof ) goto ismatch_out;
182232:   }
182233: 
182234:   while( 1 ){
182235:     int bMatch;
182236:     i64 iPos = aIter[0].iPos;
182237:     do {
182238:       bMatch = 1;
182239:       for(i=0; i<pPhrase->nTerm; i++){
182240:         Fts5PoslistReader *pPos = &aIter[i];
182241:         i64 iAdj = iPos + i;
182242:         if( pPos->iPos!=iAdj ){
182243:           bMatch = 0;
182244:           while( pPos->iPos<iAdj ){
182245:             if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
182246:           }
182247:           if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
182248:         }
182249:       }
182250:     }while( bMatch==0 );
182251: 
182252:     /* Append position iPos to the output */
182253:     rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
182254:     if( rc!=SQLITE_OK ) goto ismatch_out;
182255: 
182256:     for(i=0; i<pPhrase->nTerm; i++){
182257:       if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
182258:     }
182259:   }
182260: 
182261:  ismatch_out:
182262:   *pbMatch = (pPhrase->poslist.n>0);
182263:   for(i=0; i<pPhrase->nTerm; i++){
182264:     if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
182265:   }
182266:   if( aIter!=aStatic ) sqlite3_free(aIter);
182267:   return rc;
182268: }
182269: 
182270: typedef struct Fts5LookaheadReader Fts5LookaheadReader;
182271: struct Fts5LookaheadReader {
182272:   const u8 *a;                    /* Buffer containing position list */
182273:   int n;                          /* Size of buffer a[] in bytes */
182274:   int i;                          /* Current offset in position list */
182275:   i64 iPos;                       /* Current position */
182276:   i64 iLookahead;                 /* Next position */
182277: };
182278: 
182279: #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
182280: 
182281: static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
182282:   p->iPos = p->iLookahead;
182283:   if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
182284:     p->iLookahead = FTS5_LOOKAHEAD_EOF;
182285:   }
182286:   return (p->iPos==FTS5_LOOKAHEAD_EOF);
182287: }
182288: 
182289: static int fts5LookaheadReaderInit(
182290:   const u8 *a, int n,             /* Buffer to read position list from */
182291:   Fts5LookaheadReader *p          /* Iterator object to initialize */
182292: ){
182293:   memset(p, 0, sizeof(Fts5LookaheadReader));
182294:   p->a = a;
182295:   p->n = n;
182296:   fts5LookaheadReaderNext(p);
182297:   return fts5LookaheadReaderNext(p);
182298: }
182299: 
182300: typedef struct Fts5NearTrimmer Fts5NearTrimmer;
182301: struct Fts5NearTrimmer {
182302:   Fts5LookaheadReader reader;     /* Input iterator */
182303:   Fts5PoslistWriter writer;       /* Writer context */
182304:   Fts5Buffer *pOut;               /* Output poslist */
182305: };
182306: 
182307: /*
182308: ** The near-set object passed as the first argument contains more than
182309: ** one phrase. All phrases currently point to the same row. The
182310: ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
182311: ** tests if the current row contains instances of each phrase sufficiently
182312: ** close together to meet the NEAR constraint. Non-zero is returned if it
182313: ** does, or zero otherwise.
182314: **
182315: ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
182316: ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
182317: ** occurs within this function (*pRc) is set accordingly before returning.
182318: ** The return value is undefined in both these cases.
182319: ** 
182320: ** If no error occurs and non-zero (a match) is returned, the position-list
182321: ** of each phrase object is edited to contain only those entries that
182322: ** meet the constraint before returning.
182323: */
182324: static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
182325:   Fts5NearTrimmer aStatic[4];
182326:   Fts5NearTrimmer *a = aStatic;
182327:   Fts5ExprPhrase **apPhrase = pNear->apPhrase;
182328: 
182329:   int i;
182330:   int rc = *pRc;
182331:   int bMatch;
182332: 
182333:   assert( pNear->nPhrase>1 );
182334: 
182335:   /* If the aStatic[] array is not large enough, allocate a large array
182336:   ** using sqlite3_malloc(). This approach could be improved upon. */
182337:   if( pNear->nPhrase>ArraySize(aStatic) ){
182338:     int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
182339:     a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
182340:   }else{
182341:     memset(aStatic, 0, sizeof(aStatic));
182342:   }
182343:   if( rc!=SQLITE_OK ){
182344:     *pRc = rc;
182345:     return 0;
182346:   }
182347: 
182348:   /* Initialize a lookahead iterator for each phrase. After passing the
182349:   ** buffer and buffer size to the lookaside-reader init function, zero
182350:   ** the phrase poslist buffer. The new poslist for the phrase (containing
182351:   ** the same entries as the original with some entries removed on account 
182352:   ** of the NEAR constraint) is written over the original even as it is
182353:   ** being read. This is safe as the entries for the new poslist are a
182354:   ** subset of the old, so it is not possible for data yet to be read to
182355:   ** be overwritten.  */
182356:   for(i=0; i<pNear->nPhrase; i++){
182357:     Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
182358:     fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
182359:     pPoslist->n = 0;
182360:     a[i].pOut = pPoslist;
182361:   }
182362: 
182363:   while( 1 ){
182364:     int iAdv;
182365:     i64 iMin;
182366:     i64 iMax;
182367: 
182368:     /* This block advances the phrase iterators until they point to a set of
182369:     ** entries that together comprise a match.  */
182370:     iMax = a[0].reader.iPos;
182371:     do {
182372:       bMatch = 1;
182373:       for(i=0; i<pNear->nPhrase; i++){
182374:         Fts5LookaheadReader *pPos = &a[i].reader;
182375:         iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
182376:         if( pPos->iPos<iMin || pPos->iPos>iMax ){
182377:           bMatch = 0;
182378:           while( pPos->iPos<iMin ){
182379:             if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
182380:           }
182381:           if( pPos->iPos>iMax ) iMax = pPos->iPos;
182382:         }
182383:       }
182384:     }while( bMatch==0 );
182385: 
182386:     /* Add an entry to each output position list */
182387:     for(i=0; i<pNear->nPhrase; i++){
182388:       i64 iPos = a[i].reader.iPos;
182389:       Fts5PoslistWriter *pWriter = &a[i].writer;
182390:       if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
182391:         sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
182392:       }
182393:     }
182394: 
182395:     iAdv = 0;
182396:     iMin = a[0].reader.iLookahead;
182397:     for(i=0; i<pNear->nPhrase; i++){
182398:       if( a[i].reader.iLookahead < iMin ){
182399:         iMin = a[i].reader.iLookahead;
182400:         iAdv = i;
182401:       }
182402:     }
182403:     if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
182404:   }
182405: 
182406:   ismatch_out: {
182407:     int bRet = a[0].pOut->n>0;
182408:     *pRc = rc;
182409:     if( a!=aStatic ) sqlite3_free(a);
182410:     return bRet;
182411:   }
182412: }
182413: 
182414: /*
182415: ** Advance iterator pIter until it points to a value equal to or laster
182416: ** than the initial value of *piLast. If this means the iterator points
182417: ** to a value laster than *piLast, update *piLast to the new lastest value.
182418: **
182419: ** If the iterator reaches EOF, set *pbEof to true before returning. If
182420: ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
182421: ** are set, return a non-zero value. Otherwise, return zero.
182422: */
182423: static int fts5ExprAdvanceto(
182424:   Fts5IndexIter *pIter,           /* Iterator to advance */
182425:   int bDesc,                      /* True if iterator is "rowid DESC" */
182426:   i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
182427:   int *pRc,                       /* OUT: Error code */
182428:   int *pbEof                      /* OUT: Set to true if EOF */
182429: ){
182430:   i64 iLast = *piLast;
182431:   i64 iRowid;
182432: 
182433:   iRowid = pIter->iRowid;
182434:   if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
182435:     int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
182436:     if( rc || sqlite3Fts5IterEof(pIter) ){
182437:       *pRc = rc;
182438:       *pbEof = 1;
182439:       return 1;
182440:     }
182441:     iRowid = pIter->iRowid;
182442:     assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
182443:   }
182444:   *piLast = iRowid;
182445: 
182446:   return 0;
182447: }
182448: 
182449: static int fts5ExprSynonymAdvanceto(
182450:   Fts5ExprTerm *pTerm,            /* Term iterator to advance */
182451:   int bDesc,                      /* True if iterator is "rowid DESC" */
182452:   i64 *piLast,                    /* IN/OUT: Lastest rowid seen so far */
182453:   int *pRc                        /* OUT: Error code */
182454: ){
182455:   int rc = SQLITE_OK;
182456:   i64 iLast = *piLast;
182457:   Fts5ExprTerm *p;
182458:   int bEof = 0;
182459: 
182460:   for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
182461:     if( sqlite3Fts5IterEof(p->pIter)==0 ){
182462:       i64 iRowid = p->pIter->iRowid;
182463:       if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
182464:         rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
182465:       }
182466:     }
182467:   }
182468: 
182469:   if( rc!=SQLITE_OK ){
182470:     *pRc = rc;
182471:     bEof = 1;
182472:   }else{
182473:     *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
182474:   }
182475:   return bEof;
182476: }
182477: 
182478: 
182479: static int fts5ExprNearTest(
182480:   int *pRc,
182481:   Fts5Expr *pExpr,                /* Expression that pNear is a part of */
182482:   Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_STRING) */
182483: ){
182484:   Fts5ExprNearset *pNear = pNode->pNear;
182485:   int rc = *pRc;
182486: 
182487:   if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
182488:     Fts5ExprTerm *pTerm;
182489:     Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
182490:     pPhrase->poslist.n = 0;
182491:     for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
182492:       Fts5IndexIter *pIter = pTerm->pIter;
182493:       if( sqlite3Fts5IterEof(pIter)==0 ){
182494:         if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
182495:           pPhrase->poslist.n = 1;
182496:         }
182497:       }
182498:     }
182499:     return pPhrase->poslist.n;
182500:   }else{
182501:     int i;
182502: 
182503:     /* Check that each phrase in the nearset matches the current row.
182504:     ** Populate the pPhrase->poslist buffers at the same time. If any
182505:     ** phrase is not a match, break out of the loop early.  */
182506:     for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
182507:       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182508:       if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
182509:         int bMatch = 0;
182510:         rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
182511:         if( bMatch==0 ) break;
182512:       }else{
182513:         Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
182514:         fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
182515:       }
182516:     }
182517: 
182518:     *pRc = rc;
182519:     if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
182520:       return 1;
182521:     }
182522:     return 0;
182523:   }
182524: }
182525: 
182526: 
182527: /*
182528: ** Initialize all term iterators in the pNear object. If any term is found
182529: ** to match no documents at all, return immediately without initializing any
182530: ** further iterators.
182531: */
182532: static int fts5ExprNearInitAll(
182533:   Fts5Expr *pExpr,
182534:   Fts5ExprNode *pNode
182535: ){
182536:   Fts5ExprNearset *pNear = pNode->pNear;
182537:   int i, j;
182538:   int rc = SQLITE_OK;
182539: 
182540:   assert( pNode->bNomatch==0 );
182541:   for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
182542:     Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182543:     for(j=0; j<pPhrase->nTerm; j++){
182544:       Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
182545:       Fts5ExprTerm *p;
182546:       int bEof = 1;
182547: 
182548:       for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
182549:         if( p->pIter ){
182550:           sqlite3Fts5IterClose(p->pIter);
182551:           p->pIter = 0;
182552:         }
182553:         rc = sqlite3Fts5IndexQuery(
182554:             pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
182555:             (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
182556:             (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
182557:             pNear->pColset,
182558:             &p->pIter
182559:         );
182560:         assert( rc==SQLITE_OK || p->pIter==0 );
182561:         if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
182562:           bEof = 0;
182563:         }
182564:       }
182565: 
182566:       if( bEof ){
182567:         pNode->bEof = 1;
182568:         return rc;
182569:       }
182570:     }
182571:   }
182572: 
182573:   return rc;
182574: }
182575: 
182576: /*
182577: ** If pExpr is an ASC iterator, this function returns a value with the
182578: ** same sign as:
182579: **
182580: **   (iLhs - iRhs)
182581: **
182582: ** Otherwise, if this is a DESC iterator, the opposite is returned:
182583: **
182584: **   (iRhs - iLhs)
182585: */
182586: static int fts5RowidCmp(
182587:   Fts5Expr *pExpr,
182588:   i64 iLhs,
182589:   i64 iRhs
182590: ){
182591:   assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
182592:   if( pExpr->bDesc==0 ){
182593:     if( iLhs<iRhs ) return -1;
182594:     return (iLhs > iRhs);
182595:   }else{
182596:     if( iLhs>iRhs ) return -1;
182597:     return (iLhs < iRhs);
182598:   }
182599: }
182600: 
182601: static void fts5ExprSetEof(Fts5ExprNode *pNode){
182602:   int i;
182603:   pNode->bEof = 1;
182604:   pNode->bNomatch = 0;
182605:   for(i=0; i<pNode->nChild; i++){
182606:     fts5ExprSetEof(pNode->apChild[i]);
182607:   }
182608: }
182609: 
182610: static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
182611:   if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
182612:     Fts5ExprNearset *pNear = pNode->pNear;
182613:     int i;
182614:     for(i=0; i<pNear->nPhrase; i++){
182615:       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182616:       pPhrase->poslist.n = 0;
182617:     }
182618:   }else{
182619:     int i;
182620:     for(i=0; i<pNode->nChild; i++){
182621:       fts5ExprNodeZeroPoslist(pNode->apChild[i]);
182622:     }
182623:   }
182624: }
182625: 
182626: 
182627: 
182628: /*
182629: ** Compare the values currently indicated by the two nodes as follows:
182630: **
182631: **    res = (*p1) - (*p2)
182632: **
182633: ** Nodes that point to values that come later in the iteration order are
182634: ** considered to be larger. Nodes at EOF are the largest of all.
182635: **
182636: ** This means that if the iteration order is ASC, then numerically larger
182637: ** rowids are considered larger. Or if it is the default DESC, numerically
182638: ** smaller rowids are larger.
182639: */
182640: static int fts5NodeCompare(
182641:   Fts5Expr *pExpr,
182642:   Fts5ExprNode *p1, 
182643:   Fts5ExprNode *p2
182644: ){
182645:   if( p2->bEof ) return -1;
182646:   if( p1->bEof ) return +1;
182647:   return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
182648: }
182649: 
182650: /*
182651: ** All individual term iterators in pNear are guaranteed to be valid when
182652: ** this function is called. This function checks if all term iterators
182653: ** point to the same rowid, and if not, advances them until they do.
182654: ** If an EOF is reached before this happens, *pbEof is set to true before
182655: ** returning.
182656: **
182657: ** SQLITE_OK is returned if an error occurs, or an SQLite error code 
182658: ** otherwise. It is not considered an error code if an iterator reaches
182659: ** EOF.
182660: */
182661: static int fts5ExprNodeTest_STRING(
182662:   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182663:   Fts5ExprNode *pNode
182664: ){
182665:   Fts5ExprNearset *pNear = pNode->pNear;
182666:   Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
182667:   int rc = SQLITE_OK;
182668:   i64 iLast;                      /* Lastest rowid any iterator points to */
182669:   int i, j;                       /* Phrase and token index, respectively */
182670:   int bMatch;                     /* True if all terms are at the same rowid */
182671:   const int bDesc = pExpr->bDesc;
182672: 
182673:   /* Check that this node should not be FTS5_TERM */
182674:   assert( pNear->nPhrase>1 
182675:        || pNear->apPhrase[0]->nTerm>1 
182676:        || pNear->apPhrase[0]->aTerm[0].pSynonym
182677:   );
182678: 
182679:   /* Initialize iLast, the "lastest" rowid any iterator points to. If the
182680:   ** iterator skips through rowids in the default ascending order, this means
182681:   ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
182682:   ** means the minimum rowid.  */
182683:   if( pLeft->aTerm[0].pSynonym ){
182684:     iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
182685:   }else{
182686:     iLast = pLeft->aTerm[0].pIter->iRowid;
182687:   }
182688: 
182689:   do {
182690:     bMatch = 1;
182691:     for(i=0; i<pNear->nPhrase; i++){
182692:       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182693:       for(j=0; j<pPhrase->nTerm; j++){
182694:         Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
182695:         if( pTerm->pSynonym ){
182696:           i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
182697:           if( iRowid==iLast ) continue;
182698:           bMatch = 0;
182699:           if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
182700:             pNode->bNomatch = 0;
182701:             pNode->bEof = 1;
182702:             return rc;
182703:           }
182704:         }else{
182705:           Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
182706:           if( pIter->iRowid==iLast ) continue;
182707:           bMatch = 0;
182708:           if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
182709:             return rc;
182710:           }
182711:         }
182712:       }
182713:     }
182714:   }while( bMatch==0 );
182715: 
182716:   pNode->iRowid = iLast;
182717:   pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
182718:   assert( pNode->bEof==0 || pNode->bNomatch==0 );
182719: 
182720:   return rc;
182721: }
182722: 
182723: /*
182724: ** Advance the first term iterator in the first phrase of pNear. Set output
182725: ** variable *pbEof to true if it reaches EOF or if an error occurs.
182726: **
182727: ** Return SQLITE_OK if successful, or an SQLite error code if an error
182728: ** occurs.
182729: */
182730: static int fts5ExprNodeNext_STRING(
182731:   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182732:   Fts5ExprNode *pNode,            /* FTS5_STRING or FTS5_TERM node */
182733:   int bFromValid,
182734:   i64 iFrom 
182735: ){
182736:   Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
182737:   int rc = SQLITE_OK;
182738: 
182739:   pNode->bNomatch = 0;
182740:   if( pTerm->pSynonym ){
182741:     int bEof = 1;
182742:     Fts5ExprTerm *p;
182743: 
182744:     /* Find the firstest rowid any synonym points to. */
182745:     i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
182746: 
182747:     /* Advance each iterator that currently points to iRowid. Or, if iFrom
182748:     ** is valid - each iterator that points to a rowid before iFrom.  */
182749:     for(p=pTerm; p; p=p->pSynonym){
182750:       if( sqlite3Fts5IterEof(p->pIter)==0 ){
182751:         i64 ii = p->pIter->iRowid;
182752:         if( ii==iRowid 
182753:          || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc) 
182754:         ){
182755:           if( bFromValid ){
182756:             rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
182757:           }else{
182758:             rc = sqlite3Fts5IterNext(p->pIter);
182759:           }
182760:           if( rc!=SQLITE_OK ) break;
182761:           if( sqlite3Fts5IterEof(p->pIter)==0 ){
182762:             bEof = 0;
182763:           }
182764:         }else{
182765:           bEof = 0;
182766:         }
182767:       }
182768:     }
182769: 
182770:     /* Set the EOF flag if either all synonym iterators are at EOF or an
182771:     ** error has occurred.  */
182772:     pNode->bEof = (rc || bEof);
182773:   }else{
182774:     Fts5IndexIter *pIter = pTerm->pIter;
182775: 
182776:     assert( Fts5NodeIsString(pNode) );
182777:     if( bFromValid ){
182778:       rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
182779:     }else{
182780:       rc = sqlite3Fts5IterNext(pIter);
182781:     }
182782: 
182783:     pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
182784:   }
182785: 
182786:   if( pNode->bEof==0 ){
182787:     assert( rc==SQLITE_OK );
182788:     rc = fts5ExprNodeTest_STRING(pExpr, pNode);
182789:   }
182790: 
182791:   return rc;
182792: }
182793: 
182794: 
182795: static int fts5ExprNodeTest_TERM(
182796:   Fts5Expr *pExpr,                /* Expression that pNear is a part of */
182797:   Fts5ExprNode *pNode             /* The "NEAR" node (FTS5_TERM) */
182798: ){
182799:   /* As this "NEAR" object is actually a single phrase that consists 
182800:   ** of a single term only, grab pointers into the poslist managed by the
182801:   ** fts5_index.c iterator object. This is much faster than synthesizing 
182802:   ** a new poslist the way we have to for more complicated phrase or NEAR
182803:   ** expressions.  */
182804:   Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
182805:   Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
182806: 
182807:   assert( pNode->eType==FTS5_TERM );
182808:   assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
182809:   assert( pPhrase->aTerm[0].pSynonym==0 );
182810: 
182811:   pPhrase->poslist.n = pIter->nData;
182812:   if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
182813:     pPhrase->poslist.p = (u8*)pIter->pData;
182814:   }
182815:   pNode->iRowid = pIter->iRowid;
182816:   pNode->bNomatch = (pPhrase->poslist.n==0);
182817:   return SQLITE_OK;
182818: }
182819: 
182820: /*
182821: ** xNext() method for a node of type FTS5_TERM.
182822: */
182823: static int fts5ExprNodeNext_TERM(
182824:   Fts5Expr *pExpr, 
182825:   Fts5ExprNode *pNode,
182826:   int bFromValid,
182827:   i64 iFrom
182828: ){
182829:   int rc;
182830:   Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
182831: 
182832:   assert( pNode->bEof==0 );
182833:   if( bFromValid ){
182834:     rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
182835:   }else{
182836:     rc = sqlite3Fts5IterNext(pIter);
182837:   }
182838:   if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
182839:     rc = fts5ExprNodeTest_TERM(pExpr, pNode);
182840:   }else{
182841:     pNode->bEof = 1;
182842:     pNode->bNomatch = 0;
182843:   }
182844:   return rc;
182845: }
182846: 
182847: static void fts5ExprNodeTest_OR(
182848:   Fts5Expr *pExpr,                /* Expression of which pNode is a part */
182849:   Fts5ExprNode *pNode             /* Expression node to test */
182850: ){
182851:   Fts5ExprNode *pNext = pNode->apChild[0];
182852:   int i;
182853: 
182854:   for(i=1; i<pNode->nChild; i++){
182855:     Fts5ExprNode *pChild = pNode->apChild[i];
182856:     int cmp = fts5NodeCompare(pExpr, pNext, pChild);
182857:     if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
182858:       pNext = pChild;
182859:     }
182860:   }
182861:   pNode->iRowid = pNext->iRowid;
182862:   pNode->bEof = pNext->bEof;
182863:   pNode->bNomatch = pNext->bNomatch;
182864: }
182865: 
182866: static int fts5ExprNodeNext_OR(
182867:   Fts5Expr *pExpr, 
182868:   Fts5ExprNode *pNode,
182869:   int bFromValid,
182870:   i64 iFrom
182871: ){
182872:   int i;
182873:   i64 iLast = pNode->iRowid;
182874: 
182875:   for(i=0; i<pNode->nChild; i++){
182876:     Fts5ExprNode *p1 = pNode->apChild[i];
182877:     assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
182878:     if( p1->bEof==0 ){
182879:       if( (p1->iRowid==iLast) 
182880:        || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
182881:       ){
182882:         int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
182883:         if( rc!=SQLITE_OK ) return rc;
182884:       }
182885:     }
182886:   }
182887: 
182888:   fts5ExprNodeTest_OR(pExpr, pNode);
182889:   return SQLITE_OK;
182890: }
182891: 
182892: /*
182893: ** Argument pNode is an FTS5_AND node.
182894: */
182895: static int fts5ExprNodeTest_AND(
182896:   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182897:   Fts5ExprNode *pAnd              /* FTS5_AND node to advance */
182898: ){
182899:   int iChild;
182900:   i64 iLast = pAnd->iRowid;
182901:   int rc = SQLITE_OK;
182902:   int bMatch;
182903: 
182904:   assert( pAnd->bEof==0 );
182905:   do {
182906:     pAnd->bNomatch = 0;
182907:     bMatch = 1;
182908:     for(iChild=0; iChild<pAnd->nChild; iChild++){
182909:       Fts5ExprNode *pChild = pAnd->apChild[iChild];
182910:       int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
182911:       if( cmp>0 ){
182912:         /* Advance pChild until it points to iLast or laster */
182913:         rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
182914:         if( rc!=SQLITE_OK ) return rc;
182915:       }
182916: 
182917:       /* If the child node is now at EOF, so is the parent AND node. Otherwise,
182918:       ** the child node is guaranteed to have advanced at least as far as
182919:       ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
182920:       ** new lastest rowid seen so far.  */
182921:       assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
182922:       if( pChild->bEof ){
182923:         fts5ExprSetEof(pAnd);
182924:         bMatch = 1;
182925:         break;
182926:       }else if( iLast!=pChild->iRowid ){
182927:         bMatch = 0;
182928:         iLast = pChild->iRowid;
182929:       }
182930: 
182931:       if( pChild->bNomatch ){
182932:         pAnd->bNomatch = 1;
182933:       }
182934:     }
182935:   }while( bMatch==0 );
182936: 
182937:   if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
182938:     fts5ExprNodeZeroPoslist(pAnd);
182939:   }
182940:   pAnd->iRowid = iLast;
182941:   return SQLITE_OK;
182942: }
182943: 
182944: static int fts5ExprNodeNext_AND(
182945:   Fts5Expr *pExpr, 
182946:   Fts5ExprNode *pNode,
182947:   int bFromValid,
182948:   i64 iFrom
182949: ){
182950:   int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
182951:   if( rc==SQLITE_OK ){
182952:     rc = fts5ExprNodeTest_AND(pExpr, pNode);
182953:   }
182954:   return rc;
182955: }
182956: 
182957: static int fts5ExprNodeTest_NOT(
182958:   Fts5Expr *pExpr,                /* Expression pPhrase belongs to */
182959:   Fts5ExprNode *pNode             /* FTS5_NOT node to advance */
182960: ){
182961:   int rc = SQLITE_OK;
182962:   Fts5ExprNode *p1 = pNode->apChild[0];
182963:   Fts5ExprNode *p2 = pNode->apChild[1];
182964:   assert( pNode->nChild==2 );
182965: 
182966:   while( rc==SQLITE_OK && p1->bEof==0 ){
182967:     int cmp = fts5NodeCompare(pExpr, p1, p2);
182968:     if( cmp>0 ){
182969:       rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
182970:       cmp = fts5NodeCompare(pExpr, p1, p2);
182971:     }
182972:     assert( rc!=SQLITE_OK || cmp<=0 );
182973:     if( cmp || p2->bNomatch ) break;
182974:     rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
182975:   }
182976:   pNode->bEof = p1->bEof;
182977:   pNode->bNomatch = p1->bNomatch;
182978:   pNode->iRowid = p1->iRowid;
182979:   if( p1->bEof ){
182980:     fts5ExprNodeZeroPoslist(p2);
182981:   }
182982:   return rc;
182983: }
182984: 
182985: static int fts5ExprNodeNext_NOT(
182986:   Fts5Expr *pExpr, 
182987:   Fts5ExprNode *pNode,
182988:   int bFromValid,
182989:   i64 iFrom
182990: ){
182991:   int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
182992:   if( rc==SQLITE_OK ){
182993:     rc = fts5ExprNodeTest_NOT(pExpr, pNode);
182994:   }
182995:   return rc;
182996: }
182997: 
182998: /*
182999: ** If pNode currently points to a match, this function returns SQLITE_OK
183000: ** without modifying it. Otherwise, pNode is advanced until it does point
183001: ** to a match or EOF is reached.
183002: */
183003: static int fts5ExprNodeTest(
183004:   Fts5Expr *pExpr,                /* Expression of which pNode is a part */
183005:   Fts5ExprNode *pNode             /* Expression node to test */
183006: ){
183007:   int rc = SQLITE_OK;
183008:   if( pNode->bEof==0 ){
183009:     switch( pNode->eType ){
183010: 
183011:       case FTS5_STRING: {
183012:         rc = fts5ExprNodeTest_STRING(pExpr, pNode);
183013:         break;
183014:       }
183015: 
183016:       case FTS5_TERM: {
183017:         rc = fts5ExprNodeTest_TERM(pExpr, pNode);
183018:         break;
183019:       }
183020: 
183021:       case FTS5_AND: {
183022:         rc = fts5ExprNodeTest_AND(pExpr, pNode);
183023:         break;
183024:       }
183025: 
183026:       case FTS5_OR: {
183027:         fts5ExprNodeTest_OR(pExpr, pNode);
183028:         break;
183029:       }
183030: 
183031:       default: assert( pNode->eType==FTS5_NOT ); {
183032:         rc = fts5ExprNodeTest_NOT(pExpr, pNode);
183033:         break;
183034:       }
183035:     }
183036:   }
183037:   return rc;
183038: }
183039: 
183040:  
183041: /*
183042: ** Set node pNode, which is part of expression pExpr, to point to the first
183043: ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
183044: **
183045: ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
183046: ** It is not an error if there are no matches.
183047: */
183048: static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
183049:   int rc = SQLITE_OK;
183050:   pNode->bEof = 0;
183051:   pNode->bNomatch = 0;
183052: 
183053:   if( Fts5NodeIsString(pNode) ){
183054:     /* Initialize all term iterators in the NEAR object. */
183055:     rc = fts5ExprNearInitAll(pExpr, pNode);
183056:   }else if( pNode->xNext==0 ){
183057:     pNode->bEof = 1;
183058:   }else{
183059:     int i;
183060:     int nEof = 0;
183061:     for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
183062:       Fts5ExprNode *pChild = pNode->apChild[i];
183063:       rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
183064:       assert( pChild->bEof==0 || pChild->bEof==1 );
183065:       nEof += pChild->bEof;
183066:     }
183067:     pNode->iRowid = pNode->apChild[0]->iRowid;
183068: 
183069:     switch( pNode->eType ){
183070:       case FTS5_AND:
183071:         if( nEof>0 ) fts5ExprSetEof(pNode);
183072:         break;
183073: 
183074:       case FTS5_OR:
183075:         if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
183076:         break;
183077: 
183078:       default:
183079:         assert( pNode->eType==FTS5_NOT );
183080:         pNode->bEof = pNode->apChild[0]->bEof;
183081:         break;
183082:     }
183083:   }
183084: 
183085:   if( rc==SQLITE_OK ){
183086:     rc = fts5ExprNodeTest(pExpr, pNode);
183087:   }
183088:   return rc;
183089: }
183090: 
183091: 
183092: /*
183093: ** Begin iterating through the set of documents in index pIdx matched by
183094: ** the MATCH expression passed as the first argument. If the "bDesc" 
183095: ** parameter is passed a non-zero value, iteration is in descending rowid 
183096: ** order. Or, if it is zero, in ascending order.
183097: **
183098: ** If iterating in ascending rowid order (bDesc==0), the first document
183099: ** visited is that with the smallest rowid that is larger than or equal
183100: ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
183101: ** then the first document visited must have a rowid smaller than or
183102: ** equal to iFirst.
183103: **
183104: ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
183105: ** is not considered an error if the query does not match any documents.
183106: */
183107: static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
183108:   Fts5ExprNode *pRoot = p->pRoot;
183109:   int rc;                         /* Return code */
183110: 
183111:   p->pIndex = pIdx;
183112:   p->bDesc = bDesc;
183113:   rc = fts5ExprNodeFirst(p, pRoot);
183114: 
183115:   /* If not at EOF but the current rowid occurs earlier than iFirst in
183116:   ** the iteration order, move to document iFirst or later. */
183117:   if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
183118:     rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
183119:   }
183120: 
183121:   /* If the iterator is not at a real match, skip forward until it is. */
183122:   while( pRoot->bNomatch ){
183123:     assert( pRoot->bEof==0 && rc==SQLITE_OK );
183124:     rc = fts5ExprNodeNext(p, pRoot, 0, 0);
183125:   }
183126:   return rc;
183127: }
183128: 
183129: /*
183130: ** Move to the next document 
183131: **
183132: ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
183133: ** is not considered an error if the query does not match any documents.
183134: */
183135: static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
183136:   int rc;
183137:   Fts5ExprNode *pRoot = p->pRoot;
183138:   assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
183139:   do {
183140:     rc = fts5ExprNodeNext(p, pRoot, 0, 0);
183141:     assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
183142:   }while( pRoot->bNomatch );
183143:   if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
183144:     pRoot->bEof = 1;
183145:   }
183146:   return rc;
183147: }
183148: 
183149: static int sqlite3Fts5ExprEof(Fts5Expr *p){
183150:   return p->pRoot->bEof;
183151: }
183152: 
183153: static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
183154:   return p->pRoot->iRowid;
183155: }
183156: 
183157: static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
183158:   int rc = SQLITE_OK;
183159:   *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
183160:   return rc;
183161: }
183162: 
183163: /*
183164: ** Free the phrase object passed as the only argument.
183165: */
183166: static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
183167:   if( pPhrase ){
183168:     int i;
183169:     for(i=0; i<pPhrase->nTerm; i++){
183170:       Fts5ExprTerm *pSyn;
183171:       Fts5ExprTerm *pNext;
183172:       Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
183173:       sqlite3_free(pTerm->zTerm);
183174:       sqlite3Fts5IterClose(pTerm->pIter);
183175:       for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
183176:         pNext = pSyn->pSynonym;
183177:         sqlite3Fts5IterClose(pSyn->pIter);
183178:         fts5BufferFree((Fts5Buffer*)&pSyn[1]);
183179:         sqlite3_free(pSyn);
183180:       }
183181:     }
183182:     if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
183183:     sqlite3_free(pPhrase);
183184:   }
183185: }
183186: 
183187: /*
183188: ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
183189: ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
183190: ** appended to it and the results returned.
183191: **
183192: ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
183193: ** NULL returned.
183194: */
183195: static Fts5ExprNearset *sqlite3Fts5ParseNearset(
183196:   Fts5Parse *pParse,              /* Parse context */
183197:   Fts5ExprNearset *pNear,         /* Existing nearset, or NULL */
183198:   Fts5ExprPhrase *pPhrase         /* Recently parsed phrase */
183199: ){
183200:   const int SZALLOC = 8;
183201:   Fts5ExprNearset *pRet = 0;
183202: 
183203:   if( pParse->rc==SQLITE_OK ){
183204:     if( pPhrase==0 ){
183205:       return pNear;
183206:     }
183207:     if( pNear==0 ){
183208:       int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
183209:       pRet = sqlite3_malloc(nByte);
183210:       if( pRet==0 ){
183211:         pParse->rc = SQLITE_NOMEM;
183212:       }else{
183213:         memset(pRet, 0, nByte);
183214:       }
183215:     }else if( (pNear->nPhrase % SZALLOC)==0 ){
183216:       int nNew = pNear->nPhrase + SZALLOC;
183217:       int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
183218: 
183219:       pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
183220:       if( pRet==0 ){
183221:         pParse->rc = SQLITE_NOMEM;
183222:       }
183223:     }else{
183224:       pRet = pNear;
183225:     }
183226:   }
183227: 
183228:   if( pRet==0 ){
183229:     assert( pParse->rc!=SQLITE_OK );
183230:     sqlite3Fts5ParseNearsetFree(pNear);
183231:     sqlite3Fts5ParsePhraseFree(pPhrase);
183232:   }else{
183233:     if( pRet->nPhrase>0 ){
183234:       Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
183235:       assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
183236:       if( pPhrase->nTerm==0 ){
183237:         fts5ExprPhraseFree(pPhrase);
183238:         pRet->nPhrase--;
183239:         pParse->nPhrase--;
183240:         pPhrase = pLast;
183241:       }else if( pLast->nTerm==0 ){
183242:         fts5ExprPhraseFree(pLast);
183243:         pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
183244:         pParse->nPhrase--;
183245:         pRet->nPhrase--;
183246:       }
183247:     }
183248:     pRet->apPhrase[pRet->nPhrase++] = pPhrase;
183249:   }
183250:   return pRet;
183251: }
183252: 
183253: typedef struct TokenCtx TokenCtx;
183254: struct TokenCtx {
183255:   Fts5ExprPhrase *pPhrase;
183256:   int rc;
183257: };
183258: 
183259: /*
183260: ** Callback for tokenizing terms used by ParseTerm().
183261: */
183262: static int fts5ParseTokenize(
183263:   void *pContext,                 /* Pointer to Fts5InsertCtx object */
183264:   int tflags,                     /* Mask of FTS5_TOKEN_* flags */
183265:   const char *pToken,             /* Buffer containing token */
183266:   int nToken,                     /* Size of token in bytes */
183267:   int iUnused1,                   /* Start offset of token */
183268:   int iUnused2                    /* End offset of token */
183269: ){
183270:   int rc = SQLITE_OK;
183271:   const int SZALLOC = 8;
183272:   TokenCtx *pCtx = (TokenCtx*)pContext;
183273:   Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
183274: 
183275:   UNUSED_PARAM2(iUnused1, iUnused2);
183276: 
183277:   /* If an error has already occurred, this is a no-op */
183278:   if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
183279:   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
183280: 
183281:   if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
183282:     Fts5ExprTerm *pSyn;
183283:     int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
183284:     pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
183285:     if( pSyn==0 ){
183286:       rc = SQLITE_NOMEM;
183287:     }else{
183288:       memset(pSyn, 0, nByte);
183289:       pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
183290:       memcpy(pSyn->zTerm, pToken, nToken);
183291:       pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
183292:       pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
183293:     }
183294:   }else{
183295:     Fts5ExprTerm *pTerm;
183296:     if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
183297:       Fts5ExprPhrase *pNew;
183298:       int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
183299: 
183300:       pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase, 
183301:           sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
183302:       );
183303:       if( pNew==0 ){
183304:         rc = SQLITE_NOMEM;
183305:       }else{
183306:         if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
183307:         pCtx->pPhrase = pPhrase = pNew;
183308:         pNew->nTerm = nNew - SZALLOC;
183309:       }
183310:     }
183311: 
183312:     if( rc==SQLITE_OK ){
183313:       pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
183314:       memset(pTerm, 0, sizeof(Fts5ExprTerm));
183315:       pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
183316:     }
183317:   }
183318: 
183319:   pCtx->rc = rc;
183320:   return rc;
183321: }
183322: 
183323: 
183324: /*
183325: ** Free the phrase object passed as the only argument.
183326: */
183327: static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
183328:   fts5ExprPhraseFree(pPhrase);
183329: }
183330: 
183331: /*
183332: ** Free the phrase object passed as the second argument.
183333: */
183334: static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
183335:   if( pNear ){
183336:     int i;
183337:     for(i=0; i<pNear->nPhrase; i++){
183338:       fts5ExprPhraseFree(pNear->apPhrase[i]);
183339:     }
183340:     sqlite3_free(pNear->pColset);
183341:     sqlite3_free(pNear);
183342:   }
183343: }
183344: 
183345: static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
183346:   assert( pParse->pExpr==0 );
183347:   pParse->pExpr = p;
183348: }
183349: 
183350: /*
183351: ** This function is called by the parser to process a string token. The
183352: ** string may or may not be quoted. In any case it is tokenized and a
183353: ** phrase object consisting of all tokens returned.
183354: */
183355: static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
183356:   Fts5Parse *pParse,              /* Parse context */
183357:   Fts5ExprPhrase *pAppend,        /* Phrase to append to */
183358:   Fts5Token *pToken,              /* String to tokenize */
183359:   int bPrefix                     /* True if there is a trailing "*" */
183360: ){
183361:   Fts5Config *pConfig = pParse->pConfig;
183362:   TokenCtx sCtx;                  /* Context object passed to callback */
183363:   int rc;                         /* Tokenize return code */
183364:   char *z = 0;
183365: 
183366:   memset(&sCtx, 0, sizeof(TokenCtx));
183367:   sCtx.pPhrase = pAppend;
183368: 
183369:   rc = fts5ParseStringFromToken(pToken, &z);
183370:   if( rc==SQLITE_OK ){
183371:     int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
183372:     int n;
183373:     sqlite3Fts5Dequote(z);
183374:     n = (int)strlen(z);
183375:     rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
183376:   }
183377:   sqlite3_free(z);
183378:   if( rc || (rc = sCtx.rc) ){
183379:     pParse->rc = rc;
183380:     fts5ExprPhraseFree(sCtx.pPhrase);
183381:     sCtx.pPhrase = 0;
183382:   }else{
183383: 
183384:     if( pAppend==0 ){
183385:       if( (pParse->nPhrase % 8)==0 ){
183386:         int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
183387:         Fts5ExprPhrase **apNew;
183388:         apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
183389:         if( apNew==0 ){
183390:           pParse->rc = SQLITE_NOMEM;
183391:           fts5ExprPhraseFree(sCtx.pPhrase);
183392:           return 0;
183393:         }
183394:         pParse->apPhrase = apNew;
183395:       }
183396:       pParse->nPhrase++;
183397:     }
183398: 
183399:     if( sCtx.pPhrase==0 ){
183400:       /* This happens when parsing a token or quoted phrase that contains
183401:       ** no token characters at all. (e.g ... MATCH '""'). */
183402:       sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
183403:     }else if( sCtx.pPhrase->nTerm ){
183404:       sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
183405:     }
183406:     pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
183407:   }
183408: 
183409:   return sCtx.pPhrase;
183410: }
183411: 
183412: /*
183413: ** Create a new FTS5 expression by cloning phrase iPhrase of the
183414: ** expression passed as the second argument.
183415: */
183416: static int sqlite3Fts5ExprClonePhrase(
183417:   Fts5Expr *pExpr, 
183418:   int iPhrase, 
183419:   Fts5Expr **ppNew
183420: ){
183421:   int rc = SQLITE_OK;             /* Return code */
183422:   Fts5ExprPhrase *pOrig;          /* The phrase extracted from pExpr */
183423:   int i;                          /* Used to iterate through phrase terms */
183424:   Fts5Expr *pNew = 0;             /* Expression to return via *ppNew */
183425:   TokenCtx sCtx = {0,0};          /* Context object for fts5ParseTokenize */
183426: 
183427:   pOrig = pExpr->apExprPhrase[iPhrase];
183428:   pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
183429:   if( rc==SQLITE_OK ){
183430:     pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc, 
183431:         sizeof(Fts5ExprPhrase*));
183432:   }
183433:   if( rc==SQLITE_OK ){
183434:     pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc, 
183435:         sizeof(Fts5ExprNode));
183436:   }
183437:   if( rc==SQLITE_OK ){
183438:     pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc, 
183439:         sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
183440:   }
183441:   if( rc==SQLITE_OK ){
183442:     Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
183443:     if( pColsetOrig ){
183444:       int nByte = sizeof(Fts5Colset) + pColsetOrig->nCol * sizeof(int);
183445:       Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
183446:       if( pColset ){ 
183447:         memcpy(pColset, pColsetOrig, nByte);
183448:       }
183449:       pNew->pRoot->pNear->pColset = pColset;
183450:     }
183451:   }
183452: 
183453:   for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
183454:     int tflags = 0;
183455:     Fts5ExprTerm *p;
183456:     for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
183457:       const char *zTerm = p->zTerm;
183458:       rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
183459:           0, 0);
183460:       tflags = FTS5_TOKEN_COLOCATED;
183461:     }
183462:     if( rc==SQLITE_OK ){
183463:       sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
183464:     }
183465:   }
183466: 
183467:   if( rc==SQLITE_OK ){
183468:     /* All the allocations succeeded. Put the expression object together. */
183469:     pNew->pIndex = pExpr->pIndex;
183470:     pNew->pConfig = pExpr->pConfig;
183471:     pNew->nPhrase = 1;
183472:     pNew->apExprPhrase[0] = sCtx.pPhrase;
183473:     pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
183474:     pNew->pRoot->pNear->nPhrase = 1;
183475:     sCtx.pPhrase->pNode = pNew->pRoot;
183476: 
183477:     if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
183478:       pNew->pRoot->eType = FTS5_TERM;
183479:       pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
183480:     }else{
183481:       pNew->pRoot->eType = FTS5_STRING;
183482:       pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
183483:     }
183484:   }else{
183485:     sqlite3Fts5ExprFree(pNew);
183486:     fts5ExprPhraseFree(sCtx.pPhrase);
183487:     pNew = 0;
183488:   }
183489: 
183490:   *ppNew = pNew;
183491:   return rc;
183492: }
183493: 
183494: 
183495: /*
183496: ** Token pTok has appeared in a MATCH expression where the NEAR operator
183497: ** is expected. If token pTok does not contain "NEAR", store an error
183498: ** in the pParse object.
183499: */
183500: static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
183501:   if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
183502:     sqlite3Fts5ParseError(
183503:         pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
183504:     );
183505:   }
183506: }
183507: 
183508: static void sqlite3Fts5ParseSetDistance(
183509:   Fts5Parse *pParse, 
183510:   Fts5ExprNearset *pNear,
183511:   Fts5Token *p
183512: ){
183513:   if( pNear ){
183514:     int nNear = 0;
183515:     int i;
183516:     if( p->n ){
183517:       for(i=0; i<p->n; i++){
183518:         char c = (char)p->p[i];
183519:         if( c<'0' || c>'9' ){
183520:           sqlite3Fts5ParseError(
183521:               pParse, "expected integer, got \"%.*s\"", p->n, p->p
183522:               );
183523:           return;
183524:         }
183525:         nNear = nNear * 10 + (p->p[i] - '0');
183526:       }
183527:     }else{
183528:       nNear = FTS5_DEFAULT_NEARDIST;
183529:     }
183530:     pNear->nNear = nNear;
183531:   }
183532: }
183533: 
183534: /*
183535: ** The second argument passed to this function may be NULL, or it may be
183536: ** an existing Fts5Colset object. This function returns a pointer to
183537: ** a new colset object containing the contents of (p) with new value column
183538: ** number iCol appended. 
183539: **
183540: ** If an OOM error occurs, store an error code in pParse and return NULL.
183541: ** The old colset object (if any) is not freed in this case.
183542: */
183543: static Fts5Colset *fts5ParseColset(
183544:   Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
183545:   Fts5Colset *p,                  /* Existing colset object */
183546:   int iCol                        /* New column to add to colset object */
183547: ){
183548:   int nCol = p ? p->nCol : 0;     /* Num. columns already in colset object */
183549:   Fts5Colset *pNew;               /* New colset object to return */
183550: 
183551:   assert( pParse->rc==SQLITE_OK );
183552:   assert( iCol>=0 && iCol<pParse->pConfig->nCol );
183553: 
183554:   pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
183555:   if( pNew==0 ){
183556:     pParse->rc = SQLITE_NOMEM;
183557:   }else{
183558:     int *aiCol = pNew->aiCol;
183559:     int i, j;
183560:     for(i=0; i<nCol; i++){
183561:       if( aiCol[i]==iCol ) return pNew;
183562:       if( aiCol[i]>iCol ) break;
183563:     }
183564:     for(j=nCol; j>i; j--){
183565:       aiCol[j] = aiCol[j-1];
183566:     }
183567:     aiCol[i] = iCol;
183568:     pNew->nCol = nCol+1;
183569: 
183570: #ifndef NDEBUG
183571:     /* Check that the array is in order and contains no duplicate entries. */
183572:     for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
183573: #endif
183574:   }
183575: 
183576:   return pNew;
183577: }
183578: 
183579: static Fts5Colset *sqlite3Fts5ParseColset(
183580:   Fts5Parse *pParse,              /* Store SQLITE_NOMEM here if required */
183581:   Fts5Colset *pColset,            /* Existing colset object */
183582:   Fts5Token *p
183583: ){
183584:   Fts5Colset *pRet = 0;
183585:   int iCol;
183586:   char *z;                        /* Dequoted copy of token p */
183587: 
183588:   z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
183589:   if( pParse->rc==SQLITE_OK ){
183590:     Fts5Config *pConfig = pParse->pConfig;
183591:     sqlite3Fts5Dequote(z);
183592:     for(iCol=0; iCol<pConfig->nCol; iCol++){
183593:       if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
183594:     }
183595:     if( iCol==pConfig->nCol ){
183596:       sqlite3Fts5ParseError(pParse, "no such column: %s", z);
183597:     }else{
183598:       pRet = fts5ParseColset(pParse, pColset, iCol);
183599:     }
183600:     sqlite3_free(z);
183601:   }
183602: 
183603:   if( pRet==0 ){
183604:     assert( pParse->rc!=SQLITE_OK );
183605:     sqlite3_free(pColset);
183606:   }
183607: 
183608:   return pRet;
183609: }
183610: 
183611: static void sqlite3Fts5ParseSetColset(
183612:   Fts5Parse *pParse, 
183613:   Fts5ExprNearset *pNear, 
183614:   Fts5Colset *pColset 
183615: ){
183616:   if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
183617:     pParse->rc = SQLITE_ERROR;
183618:     pParse->zErr = sqlite3_mprintf(
183619:       "fts5: column queries are not supported (detail=none)"
183620:     );
183621:     sqlite3_free(pColset);
183622:     return;
183623:   }
183624: 
183625:   if( pNear ){
183626:     pNear->pColset = pColset;
183627:   }else{
183628:     sqlite3_free(pColset);
183629:   }
183630: }
183631: 
183632: static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
183633:   switch( pNode->eType ){
183634:     case FTS5_STRING: {
183635:       Fts5ExprNearset *pNear = pNode->pNear;
183636:       if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1 
183637:        && pNear->apPhrase[0]->aTerm[0].pSynonym==0
183638:       ){
183639:         pNode->eType = FTS5_TERM;
183640:         pNode->xNext = fts5ExprNodeNext_TERM;
183641:       }else{
183642:         pNode->xNext = fts5ExprNodeNext_STRING;
183643:       }
183644:       break;
183645:     };
183646: 
183647:     case FTS5_OR: {
183648:       pNode->xNext = fts5ExprNodeNext_OR;
183649:       break;
183650:     };
183651: 
183652:     case FTS5_AND: {
183653:       pNode->xNext = fts5ExprNodeNext_AND;
183654:       break;
183655:     };
183656: 
183657:     default: assert( pNode->eType==FTS5_NOT ); {
183658:       pNode->xNext = fts5ExprNodeNext_NOT;
183659:       break;
183660:     };
183661:   }
183662: }
183663: 
183664: static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
183665:   if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
183666:     int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
183667:     memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
183668:     p->nChild += pSub->nChild;
183669:     sqlite3_free(pSub);
183670:   }else{
183671:     p->apChild[p->nChild++] = pSub;
183672:   }
183673: }
183674: 
183675: /*
183676: ** Allocate and return a new expression object. If anything goes wrong (i.e.
183677: ** OOM error), leave an error code in pParse and return NULL.
183678: */
183679: static Fts5ExprNode *sqlite3Fts5ParseNode(
183680:   Fts5Parse *pParse,              /* Parse context */
183681:   int eType,                      /* FTS5_STRING, AND, OR or NOT */
183682:   Fts5ExprNode *pLeft,            /* Left hand child expression */
183683:   Fts5ExprNode *pRight,           /* Right hand child expression */
183684:   Fts5ExprNearset *pNear          /* For STRING expressions, the near cluster */
183685: ){
183686:   Fts5ExprNode *pRet = 0;
183687: 
183688:   if( pParse->rc==SQLITE_OK ){
183689:     int nChild = 0;               /* Number of children of returned node */
183690:     int nByte;                    /* Bytes of space to allocate for this node */
183691:  
183692:     assert( (eType!=FTS5_STRING && !pNear)
183693:          || (eType==FTS5_STRING && !pLeft && !pRight)
183694:     );
183695:     if( eType==FTS5_STRING && pNear==0 ) return 0;
183696:     if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
183697:     if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
183698: 
183699:     if( eType==FTS5_NOT ){
183700:       nChild = 2;
183701:     }else if( eType==FTS5_AND || eType==FTS5_OR ){
183702:       nChild = 2;
183703:       if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
183704:       if( pRight->eType==eType ) nChild += pRight->nChild-1;
183705:     }
183706: 
183707:     nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
183708:     pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
183709: 
183710:     if( pRet ){
183711:       pRet->eType = eType;
183712:       pRet->pNear = pNear;
183713:       fts5ExprAssignXNext(pRet);
183714:       if( eType==FTS5_STRING ){
183715:         int iPhrase;
183716:         for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
183717:           pNear->apPhrase[iPhrase]->pNode = pRet;
183718:           if( pNear->apPhrase[iPhrase]->nTerm==0 ){
183719:             pRet->xNext = 0;
183720:             pRet->eType = FTS5_EOF;
183721:           }
183722:         }
183723: 
183724:         if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL 
183725:          && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
183726:         ){
183727:           assert( pParse->rc==SQLITE_OK );
183728:           pParse->rc = SQLITE_ERROR;
183729:           assert( pParse->zErr==0 );
183730:           pParse->zErr = sqlite3_mprintf(
183731:               "fts5: %s queries are not supported (detail!=full)", 
183732:               pNear->nPhrase==1 ? "phrase": "NEAR"
183733:           );
183734:           sqlite3_free(pRet);
183735:           pRet = 0;
183736:         }
183737: 
183738:       }else{
183739:         fts5ExprAddChildren(pRet, pLeft);
183740:         fts5ExprAddChildren(pRet, pRight);
183741:       }
183742:     }
183743:   }
183744: 
183745:   if( pRet==0 ){
183746:     assert( pParse->rc!=SQLITE_OK );
183747:     sqlite3Fts5ParseNodeFree(pLeft);
183748:     sqlite3Fts5ParseNodeFree(pRight);
183749:     sqlite3Fts5ParseNearsetFree(pNear);
183750:   }
183751:   return pRet;
183752: }
183753: 
183754: static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
183755:   Fts5Parse *pParse,              /* Parse context */
183756:   Fts5ExprNode *pLeft,            /* Left hand child expression */
183757:   Fts5ExprNode *pRight            /* Right hand child expression */
183758: ){
183759:   Fts5ExprNode *pRet = 0;
183760:   Fts5ExprNode *pPrev;
183761: 
183762:   if( pParse->rc ){
183763:     sqlite3Fts5ParseNodeFree(pLeft);
183764:     sqlite3Fts5ParseNodeFree(pRight);
183765:   }else{
183766: 
183767:     assert( pLeft->eType==FTS5_STRING 
183768:         || pLeft->eType==FTS5_TERM
183769:         || pLeft->eType==FTS5_EOF
183770:         || pLeft->eType==FTS5_AND
183771:     );
183772:     assert( pRight->eType==FTS5_STRING 
183773:         || pRight->eType==FTS5_TERM 
183774:         || pRight->eType==FTS5_EOF 
183775:     );
183776: 
183777:     if( pLeft->eType==FTS5_AND ){
183778:       pPrev = pLeft->apChild[pLeft->nChild-1];
183779:     }else{
183780:       pPrev = pLeft;
183781:     }
183782:     assert( pPrev->eType==FTS5_STRING 
183783:         || pPrev->eType==FTS5_TERM 
183784:         || pPrev->eType==FTS5_EOF 
183785:         );
183786: 
183787:     if( pRight->eType==FTS5_EOF ){
183788:       assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
183789:       sqlite3Fts5ParseNodeFree(pRight);
183790:       pRet = pLeft;
183791:       pParse->nPhrase--;
183792:     }
183793:     else if( pPrev->eType==FTS5_EOF ){
183794:       Fts5ExprPhrase **ap;
183795: 
183796:       if( pPrev==pLeft ){
183797:         pRet = pRight;
183798:       }else{
183799:         pLeft->apChild[pLeft->nChild-1] = pRight;
183800:         pRet = pLeft;
183801:       }
183802: 
183803:       ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
183804:       assert( ap[0]==pPrev->pNear->apPhrase[0] );
183805:       memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
183806:       pParse->nPhrase--;
183807: 
183808:       sqlite3Fts5ParseNodeFree(pPrev);
183809:     }
183810:     else{
183811:       pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
183812:     }
183813:   }
183814: 
183815:   return pRet;
183816: }
183817: 
183818: static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
183819:   int nByte = 0;
183820:   Fts5ExprTerm *p;
183821:   char *zQuoted;
183822: 
183823:   /* Determine the maximum amount of space required. */
183824:   for(p=pTerm; p; p=p->pSynonym){
183825:     nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
183826:   }
183827:   zQuoted = sqlite3_malloc(nByte);
183828: 
183829:   if( zQuoted ){
183830:     int i = 0;
183831:     for(p=pTerm; p; p=p->pSynonym){
183832:       char *zIn = p->zTerm;
183833:       zQuoted[i++] = '"';
183834:       while( *zIn ){
183835:         if( *zIn=='"' ) zQuoted[i++] = '"';
183836:         zQuoted[i++] = *zIn++;
183837:       }
183838:       zQuoted[i++] = '"';
183839:       if( p->pSynonym ) zQuoted[i++] = '|';
183840:     }
183841:     if( pTerm->bPrefix ){
183842:       zQuoted[i++] = ' ';
183843:       zQuoted[i++] = '*';
183844:     }
183845:     zQuoted[i++] = '\0';
183846:   }
183847:   return zQuoted;
183848: }
183849: 
183850: static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
183851:   char *zNew;
183852:   va_list ap;
183853:   va_start(ap, zFmt);
183854:   zNew = sqlite3_vmprintf(zFmt, ap);
183855:   va_end(ap);
183856:   if( zApp && zNew ){
183857:     char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
183858:     sqlite3_free(zNew);
183859:     zNew = zNew2;
183860:   }
183861:   sqlite3_free(zApp);
183862:   return zNew;
183863: }
183864: 
183865: /*
183866: ** Compose a tcl-readable representation of expression pExpr. Return a 
183867: ** pointer to a buffer containing that representation. It is the 
183868: ** responsibility of the caller to at some point free the buffer using 
183869: ** sqlite3_free().
183870: */
183871: static char *fts5ExprPrintTcl(
183872:   Fts5Config *pConfig, 
183873:   const char *zNearsetCmd,
183874:   Fts5ExprNode *pExpr
183875: ){
183876:   char *zRet = 0;
183877:   if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
183878:     Fts5ExprNearset *pNear = pExpr->pNear;
183879:     int i; 
183880:     int iTerm;
183881: 
183882:     zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
183883:     if( zRet==0 ) return 0;
183884:     if( pNear->pColset ){
183885:       int *aiCol = pNear->pColset->aiCol;
183886:       int nCol = pNear->pColset->nCol;
183887:       if( nCol==1 ){
183888:         zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
183889:       }else{
183890:         zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
183891:         for(i=1; i<pNear->pColset->nCol; i++){
183892:           zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
183893:         }
183894:         zRet = fts5PrintfAppend(zRet, "} ");
183895:       }
183896:       if( zRet==0 ) return 0;
183897:     }
183898: 
183899:     if( pNear->nPhrase>1 ){
183900:       zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
183901:       if( zRet==0 ) return 0;
183902:     }
183903: 
183904:     zRet = fts5PrintfAppend(zRet, "--");
183905:     if( zRet==0 ) return 0;
183906: 
183907:     for(i=0; i<pNear->nPhrase; i++){
183908:       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
183909: 
183910:       zRet = fts5PrintfAppend(zRet, " {");
183911:       for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
183912:         char *zTerm = pPhrase->aTerm[iTerm].zTerm;
183913:         zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
183914:         if( pPhrase->aTerm[iTerm].bPrefix ){
183915:           zRet = fts5PrintfAppend(zRet, "*");
183916:         }
183917:       }
183918: 
183919:       if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
183920:       if( zRet==0 ) return 0;
183921:     }
183922: 
183923:   }else{
183924:     char const *zOp = 0;
183925:     int i;
183926:     switch( pExpr->eType ){
183927:       case FTS5_AND: zOp = "AND"; break;
183928:       case FTS5_NOT: zOp = "NOT"; break;
183929:       default: 
183930:         assert( pExpr->eType==FTS5_OR );
183931:         zOp = "OR"; 
183932:         break;
183933:     }
183934: 
183935:     zRet = sqlite3_mprintf("%s", zOp);
183936:     for(i=0; zRet && i<pExpr->nChild; i++){
183937:       char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
183938:       if( !z ){
183939:         sqlite3_free(zRet);
183940:         zRet = 0;
183941:       }else{
183942:         zRet = fts5PrintfAppend(zRet, " [%z]", z);
183943:       }
183944:     }
183945:   }
183946: 
183947:   return zRet;
183948: }
183949: 
183950: static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
183951:   char *zRet = 0;
183952:   if( pExpr->eType==0 ){
183953:     return sqlite3_mprintf("\"\"");
183954:   }else
183955:   if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
183956:     Fts5ExprNearset *pNear = pExpr->pNear;
183957:     int i; 
183958:     int iTerm;
183959: 
183960:     if( pNear->pColset ){
183961:       int iCol = pNear->pColset->aiCol[0];
183962:       zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
183963:       if( zRet==0 ) return 0;
183964:     }
183965: 
183966:     if( pNear->nPhrase>1 ){
183967:       zRet = fts5PrintfAppend(zRet, "NEAR(");
183968:       if( zRet==0 ) return 0;
183969:     }
183970: 
183971:     for(i=0; i<pNear->nPhrase; i++){
183972:       Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
183973:       if( i!=0 ){
183974:         zRet = fts5PrintfAppend(zRet, " ");
183975:         if( zRet==0 ) return 0;
183976:       }
183977:       for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
183978:         char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
183979:         if( zTerm ){
183980:           zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
183981:           sqlite3_free(zTerm);
183982:         }
183983:         if( zTerm==0 || zRet==0 ){
183984:           sqlite3_free(zRet);
183985:           return 0;
183986:         }
183987:       }
183988:     }
183989: 
183990:     if( pNear->nPhrase>1 ){
183991:       zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
183992:       if( zRet==0 ) return 0;
183993:     }
183994: 
183995:   }else{
183996:     char const *zOp = 0;
183997:     int i;
183998: 
183999:     switch( pExpr->eType ){
184000:       case FTS5_AND: zOp = " AND "; break;
184001:       case FTS5_NOT: zOp = " NOT "; break;
184002:       default:  
184003:         assert( pExpr->eType==FTS5_OR );
184004:         zOp = " OR "; 
184005:         break;
184006:     }
184007: 
184008:     for(i=0; i<pExpr->nChild; i++){
184009:       char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
184010:       if( z==0 ){
184011:         sqlite3_free(zRet);
184012:         zRet = 0;
184013:       }else{
184014:         int e = pExpr->apChild[i]->eType;
184015:         int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
184016:         zRet = fts5PrintfAppend(zRet, "%s%s%z%s", 
184017:             (i==0 ? "" : zOp),
184018:             (b?"(":""), z, (b?")":"")
184019:         );
184020:       }
184021:       if( zRet==0 ) break;
184022:     }
184023:   }
184024: 
184025:   return zRet;
184026: }
184027: 
184028: /*
184029: ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
184030: ** and fts5_expr_tcl() (bTcl!=0).
184031: */
184032: static void fts5ExprFunction(
184033:   sqlite3_context *pCtx,          /* Function call context */
184034:   int nArg,                       /* Number of args */
184035:   sqlite3_value **apVal,          /* Function arguments */
184036:   int bTcl
184037: ){
184038:   Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
184039:   sqlite3 *db = sqlite3_context_db_handle(pCtx);
184040:   const char *zExpr = 0;
184041:   char *zErr = 0;
184042:   Fts5Expr *pExpr = 0;
184043:   int rc;
184044:   int i;
184045: 
184046:   const char **azConfig;          /* Array of arguments for Fts5Config */
184047:   const char *zNearsetCmd = "nearset";
184048:   int nConfig;                    /* Size of azConfig[] */
184049:   Fts5Config *pConfig = 0;
184050:   int iArg = 1;
184051: 
184052:   if( nArg<1 ){
184053:     zErr = sqlite3_mprintf("wrong number of arguments to function %s",
184054:         bTcl ? "fts5_expr_tcl" : "fts5_expr"
184055:     );
184056:     sqlite3_result_error(pCtx, zErr, -1);
184057:     sqlite3_free(zErr);
184058:     return;
184059:   }
184060: 
184061:   if( bTcl && nArg>1 ){
184062:     zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
184063:     iArg = 2;
184064:   }
184065: 
184066:   nConfig = 3 + (nArg-iArg);
184067:   azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
184068:   if( azConfig==0 ){
184069:     sqlite3_result_error_nomem(pCtx);
184070:     return;
184071:   }
184072:   azConfig[0] = 0;
184073:   azConfig[1] = "main";
184074:   azConfig[2] = "tbl";
184075:   for(i=3; iArg<nArg; iArg++){
184076:     azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
184077:   }
184078: 
184079:   zExpr = (const char*)sqlite3_value_text(apVal[0]);
184080: 
184081:   rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
184082:   if( rc==SQLITE_OK ){
184083:     rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
184084:   }
184085:   if( rc==SQLITE_OK ){
184086:     char *zText;
184087:     if( pExpr->pRoot->xNext==0 ){
184088:       zText = sqlite3_mprintf("");
184089:     }else if( bTcl ){
184090:       zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
184091:     }else{
184092:       zText = fts5ExprPrint(pConfig, pExpr->pRoot);
184093:     }
184094:     if( zText==0 ){
184095:       rc = SQLITE_NOMEM;
184096:     }else{
184097:       sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
184098:       sqlite3_free(zText);
184099:     }
184100:   }
184101: 
184102:   if( rc!=SQLITE_OK ){
184103:     if( zErr ){
184104:       sqlite3_result_error(pCtx, zErr, -1);
184105:       sqlite3_free(zErr);
184106:     }else{
184107:       sqlite3_result_error_code(pCtx, rc);
184108:     }
184109:   }
184110:   sqlite3_free((void *)azConfig);
184111:   sqlite3Fts5ConfigFree(pConfig);
184112:   sqlite3Fts5ExprFree(pExpr);
184113: }
184114: 
184115: static void fts5ExprFunctionHr(
184116:   sqlite3_context *pCtx,          /* Function call context */
184117:   int nArg,                       /* Number of args */
184118:   sqlite3_value **apVal           /* Function arguments */
184119: ){
184120:   fts5ExprFunction(pCtx, nArg, apVal, 0);
184121: }
184122: static void fts5ExprFunctionTcl(
184123:   sqlite3_context *pCtx,          /* Function call context */
184124:   int nArg,                       /* Number of args */
184125:   sqlite3_value **apVal           /* Function arguments */
184126: ){
184127:   fts5ExprFunction(pCtx, nArg, apVal, 1);
184128: }
184129: 
184130: /*
184131: ** The implementation of an SQLite user-defined-function that accepts a
184132: ** single integer as an argument. If the integer is an alpha-numeric 
184133: ** unicode code point, 1 is returned. Otherwise 0.
184134: */
184135: static void fts5ExprIsAlnum(
184136:   sqlite3_context *pCtx,          /* Function call context */
184137:   int nArg,                       /* Number of args */
184138:   sqlite3_value **apVal           /* Function arguments */
184139: ){
184140:   int iCode;
184141:   if( nArg!=1 ){
184142:     sqlite3_result_error(pCtx, 
184143:         "wrong number of arguments to function fts5_isalnum", -1
184144:     );
184145:     return;
184146:   }
184147:   iCode = sqlite3_value_int(apVal[0]);
184148:   sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
184149: }
184150: 
184151: static void fts5ExprFold(
184152:   sqlite3_context *pCtx,          /* Function call context */
184153:   int nArg,                       /* Number of args */
184154:   sqlite3_value **apVal           /* Function arguments */
184155: ){
184156:   if( nArg!=1 && nArg!=2 ){
184157:     sqlite3_result_error(pCtx, 
184158:         "wrong number of arguments to function fts5_fold", -1
184159:     );
184160:   }else{
184161:     int iCode;
184162:     int bRemoveDiacritics = 0;
184163:     iCode = sqlite3_value_int(apVal[0]);
184164:     if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
184165:     sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
184166:   }
184167: }
184168: 
184169: /*
184170: ** This is called during initialization to register the fts5_expr() scalar
184171: ** UDF with the SQLite handle passed as the only argument.
184172: */
184173: static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
184174:   struct Fts5ExprFunc {
184175:     const char *z;
184176:     void (*x)(sqlite3_context*,int,sqlite3_value**);
184177:   } aFunc[] = {
184178:     { "fts5_expr",     fts5ExprFunctionHr },
184179:     { "fts5_expr_tcl", fts5ExprFunctionTcl },
184180:     { "fts5_isalnum",  fts5ExprIsAlnum },
184181:     { "fts5_fold",     fts5ExprFold },
184182:   };
184183:   int i;
184184:   int rc = SQLITE_OK;
184185:   void *pCtx = (void*)pGlobal;
184186: 
184187:   for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
184188:     struct Fts5ExprFunc *p = &aFunc[i];
184189:     rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
184190:   }
184191: 
184192:   /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
184193: #ifndef NDEBUG
184194:   (void)sqlite3Fts5ParserTrace;
184195: #endif
184196: 
184197:   return rc;
184198: }
184199: 
184200: /*
184201: ** Return the number of phrases in expression pExpr.
184202: */
184203: static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
184204:   return (pExpr ? pExpr->nPhrase : 0);
184205: }
184206: 
184207: /*
184208: ** Return the number of terms in the iPhrase'th phrase in pExpr.
184209: */
184210: static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
184211:   if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
184212:   return pExpr->apExprPhrase[iPhrase]->nTerm;
184213: }
184214: 
184215: /*
184216: ** This function is used to access the current position list for phrase
184217: ** iPhrase.
184218: */
184219: static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
184220:   int nRet;
184221:   Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
184222:   Fts5ExprNode *pNode = pPhrase->pNode;
184223:   if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
184224:     *pa = pPhrase->poslist.p;
184225:     nRet = pPhrase->poslist.n;
184226:   }else{
184227:     *pa = 0;
184228:     nRet = 0;
184229:   }
184230:   return nRet;
184231: }
184232: 
184233: struct Fts5PoslistPopulator {
184234:   Fts5PoslistWriter writer;
184235:   int bOk;                        /* True if ok to populate */
184236:   int bMiss;
184237: };
184238: 
184239: static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
184240:   Fts5PoslistPopulator *pRet;
184241:   pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
184242:   if( pRet ){
184243:     int i;
184244:     memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
184245:     for(i=0; i<pExpr->nPhrase; i++){
184246:       Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
184247:       Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
184248:       assert( pExpr->apExprPhrase[i]->nTerm==1 );
184249:       if( bLive && 
184250:           (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
184251:       ){
184252:         pRet[i].bMiss = 1;
184253:       }else{
184254:         pBuf->n = 0;
184255:       }
184256:     }
184257:   }
184258:   return pRet;
184259: }
184260: 
184261: struct Fts5ExprCtx {
184262:   Fts5Expr *pExpr;
184263:   Fts5PoslistPopulator *aPopulator;
184264:   i64 iOff;
184265: };
184266: typedef struct Fts5ExprCtx Fts5ExprCtx;
184267: 
184268: /*
184269: ** TODO: Make this more efficient!
184270: */
184271: static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
184272:   int i;
184273:   for(i=0; i<pColset->nCol; i++){
184274:     if( pColset->aiCol[i]==iCol ) return 1;
184275:   }
184276:   return 0;
184277: }
184278: 
184279: static int fts5ExprPopulatePoslistsCb(
184280:   void *pCtx,                /* Copy of 2nd argument to xTokenize() */
184281:   int tflags,                /* Mask of FTS5_TOKEN_* flags */
184282:   const char *pToken,        /* Pointer to buffer containing token */
184283:   int nToken,                /* Size of token in bytes */
184284:   int iUnused1,              /* Byte offset of token within input text */
184285:   int iUnused2               /* Byte offset of end of token within input text */
184286: ){
184287:   Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
184288:   Fts5Expr *pExpr = p->pExpr;
184289:   int i;
184290: 
184291:   UNUSED_PARAM2(iUnused1, iUnused2);
184292: 
184293:   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
184294:   if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
184295:   for(i=0; i<pExpr->nPhrase; i++){
184296:     Fts5ExprTerm *pTerm;
184297:     if( p->aPopulator[i].bOk==0 ) continue;
184298:     for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
184299:       int nTerm = (int)strlen(pTerm->zTerm);
184300:       if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
184301:        && memcmp(pTerm->zTerm, pToken, nTerm)==0
184302:       ){
184303:         int rc = sqlite3Fts5PoslistWriterAppend(
184304:             &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
184305:         );
184306:         if( rc ) return rc;
184307:         break;
184308:       }
184309:     }
184310:   }
184311:   return SQLITE_OK;
184312: }
184313: 
184314: static int sqlite3Fts5ExprPopulatePoslists(
184315:   Fts5Config *pConfig,
184316:   Fts5Expr *pExpr, 
184317:   Fts5PoslistPopulator *aPopulator,
184318:   int iCol, 
184319:   const char *z, int n
184320: ){
184321:   int i;
184322:   Fts5ExprCtx sCtx;
184323:   sCtx.pExpr = pExpr;
184324:   sCtx.aPopulator = aPopulator;
184325:   sCtx.iOff = (((i64)iCol) << 32) - 1;
184326: 
184327:   for(i=0; i<pExpr->nPhrase; i++){
184328:     Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
184329:     Fts5Colset *pColset = pNode->pNear->pColset;
184330:     if( (pColset && 0==fts5ExprColsetTest(pColset, iCol)) 
184331:      || aPopulator[i].bMiss
184332:     ){
184333:       aPopulator[i].bOk = 0;
184334:     }else{
184335:       aPopulator[i].bOk = 1;
184336:     }
184337:   }
184338: 
184339:   return sqlite3Fts5Tokenize(pConfig, 
184340:       FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
184341:   );
184342: }
184343: 
184344: static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
184345:   if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
184346:     pNode->pNear->apPhrase[0]->poslist.n = 0;
184347:   }else{
184348:     int i;
184349:     for(i=0; i<pNode->nChild; i++){
184350:       fts5ExprClearPoslists(pNode->apChild[i]);
184351:     }
184352:   }
184353: }
184354: 
184355: static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
184356:   pNode->iRowid = iRowid;
184357:   pNode->bEof = 0;
184358:   switch( pNode->eType ){
184359:     case FTS5_TERM:
184360:     case FTS5_STRING:
184361:       return (pNode->pNear->apPhrase[0]->poslist.n>0);
184362: 
184363:     case FTS5_AND: {
184364:       int i;
184365:       for(i=0; i<pNode->nChild; i++){
184366:         if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
184367:           fts5ExprClearPoslists(pNode);
184368:           return 0;
184369:         }
184370:       }
184371:       break;
184372:     }
184373: 
184374:     case FTS5_OR: {
184375:       int i;
184376:       int bRet = 0;
184377:       for(i=0; i<pNode->nChild; i++){
184378:         if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
184379:           bRet = 1;
184380:         }
184381:       }
184382:       return bRet;
184383:     }
184384: 
184385:     default: {
184386:       assert( pNode->eType==FTS5_NOT );
184387:       if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
184388:           || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
184389:         ){
184390:         fts5ExprClearPoslists(pNode);
184391:         return 0;
184392:       }
184393:       break;
184394:     }
184395:   }
184396:   return 1;
184397: }
184398: 
184399: static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
184400:   fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
184401: }
184402: 
184403: /*
184404: ** This function is only called for detail=columns tables. 
184405: */
184406: static int sqlite3Fts5ExprPhraseCollist(
184407:   Fts5Expr *pExpr, 
184408:   int iPhrase, 
184409:   const u8 **ppCollist, 
184410:   int *pnCollist
184411: ){
184412:   Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
184413:   Fts5ExprNode *pNode = pPhrase->pNode;
184414:   int rc = SQLITE_OK;
184415: 
184416:   assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
184417:   assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
184418: 
184419:   if( pNode->bEof==0 
184420:    && pNode->iRowid==pExpr->pRoot->iRowid 
184421:    && pPhrase->poslist.n>0
184422:   ){
184423:     Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
184424:     if( pTerm->pSynonym ){
184425:       Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
184426:       rc = fts5ExprSynonymList(
184427:           pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
184428:       );
184429:     }else{
184430:       *ppCollist = pPhrase->aTerm[0].pIter->pData;
184431:       *pnCollist = pPhrase->aTerm[0].pIter->nData;
184432:     }
184433:   }else{
184434:     *ppCollist = 0;
184435:     *pnCollist = 0;
184436:   }
184437: 
184438:   return rc;
184439: }
184440: 
184441: 
184442: /*
184443: ** 2014 August 11
184444: **
184445: ** The author disclaims copyright to this source code.  In place of
184446: ** a legal notice, here is a blessing:
184447: **
184448: **    May you do good and not evil.
184449: **    May you find forgiveness for yourself and forgive others.
184450: **    May you share freely, never taking more than you give.
184451: **
184452: ******************************************************************************
184453: **
184454: */
184455: 
184456: 
184457: 
184458: /* #include "fts5Int.h" */
184459: 
184460: typedef struct Fts5HashEntry Fts5HashEntry;
184461: 
184462: /*
184463: ** This file contains the implementation of an in-memory hash table used
184464: ** to accumuluate "term -> doclist" content before it is flused to a level-0
184465: ** segment.
184466: */
184467: 
184468: 
184469: struct Fts5Hash {
184470:   int eDetail;                    /* Copy of Fts5Config.eDetail */
184471:   int *pnByte;                    /* Pointer to bytes counter */
184472:   int nEntry;                     /* Number of entries currently in hash */
184473:   int nSlot;                      /* Size of aSlot[] array */
184474:   Fts5HashEntry *pScan;           /* Current ordered scan item */
184475:   Fts5HashEntry **aSlot;          /* Array of hash slots */
184476: };
184477: 
184478: /*
184479: ** Each entry in the hash table is represented by an object of the 
184480: ** following type. Each object, its key (zKey[]) and its current data
184481: ** are stored in a single memory allocation. The position list data 
184482: ** immediately follows the key data in memory.
184483: **
184484: ** The data that follows the key is in a similar, but not identical format
184485: ** to the doclist data stored in the database. It is:
184486: **
184487: **   * Rowid, as a varint
184488: **   * Position list, without 0x00 terminator.
184489: **   * Size of previous position list and rowid, as a 4 byte
184490: **     big-endian integer.
184491: **
184492: ** iRowidOff:
184493: **   Offset of last rowid written to data area. Relative to first byte of
184494: **   structure.
184495: **
184496: ** nData:
184497: **   Bytes of data written since iRowidOff.
184498: */
184499: struct Fts5HashEntry {
184500:   Fts5HashEntry *pHashNext;       /* Next hash entry with same hash-key */
184501:   Fts5HashEntry *pScanNext;       /* Next entry in sorted order */
184502:   
184503:   int nAlloc;                     /* Total size of allocation */
184504:   int iSzPoslist;                 /* Offset of space for 4-byte poslist size */
184505:   int nData;                      /* Total bytes of data (incl. structure) */
184506:   int nKey;                       /* Length of zKey[] in bytes */
184507:   u8 bDel;                        /* Set delete-flag @ iSzPoslist */
184508:   u8 bContent;                    /* Set content-flag (detail=none mode) */
184509:   i16 iCol;                       /* Column of last value written */
184510:   int iPos;                       /* Position of last value written */
184511:   i64 iRowid;                     /* Rowid of last value written */
184512:   char zKey[8];                   /* Nul-terminated entry key */
184513: };
184514: 
184515: /*
184516: ** Size of Fts5HashEntry without the zKey[] array.
184517: */
184518: #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
184519: 
184520: 
184521: 
184522: /*
184523: ** Allocate a new hash table.
184524: */
184525: static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
184526:   int rc = SQLITE_OK;
184527:   Fts5Hash *pNew;
184528: 
184529:   *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
184530:   if( pNew==0 ){
184531:     rc = SQLITE_NOMEM;
184532:   }else{
184533:     int nByte;
184534:     memset(pNew, 0, sizeof(Fts5Hash));
184535:     pNew->pnByte = pnByte;
184536:     pNew->eDetail = pConfig->eDetail;
184537: 
184538:     pNew->nSlot = 1024;
184539:     nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
184540:     pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
184541:     if( pNew->aSlot==0 ){
184542:       sqlite3_free(pNew);
184543:       *ppNew = 0;
184544:       rc = SQLITE_NOMEM;
184545:     }else{
184546:       memset(pNew->aSlot, 0, nByte);
184547:     }
184548:   }
184549:   return rc;
184550: }
184551: 
184552: /*
184553: ** Free a hash table object.
184554: */
184555: static void sqlite3Fts5HashFree(Fts5Hash *pHash){
184556:   if( pHash ){
184557:     sqlite3Fts5HashClear(pHash);
184558:     sqlite3_free(pHash->aSlot);
184559:     sqlite3_free(pHash);
184560:   }
184561: }
184562: 
184563: /*
184564: ** Empty (but do not delete) a hash table.
184565: */
184566: static void sqlite3Fts5HashClear(Fts5Hash *pHash){
184567:   int i;
184568:   for(i=0; i<pHash->nSlot; i++){
184569:     Fts5HashEntry *pNext;
184570:     Fts5HashEntry *pSlot;
184571:     for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
184572:       pNext = pSlot->pHashNext;
184573:       sqlite3_free(pSlot);
184574:     }
184575:   }
184576:   memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
184577:   pHash->nEntry = 0;
184578: }
184579: 
184580: static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
184581:   int i;
184582:   unsigned int h = 13;
184583:   for(i=n-1; i>=0; i--){
184584:     h = (h << 3) ^ h ^ p[i];
184585:   }
184586:   return (h % nSlot);
184587: }
184588: 
184589: static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
184590:   int i;
184591:   unsigned int h = 13;
184592:   for(i=n-1; i>=0; i--){
184593:     h = (h << 3) ^ h ^ p[i];
184594:   }
184595:   h = (h << 3) ^ h ^ b;
184596:   return (h % nSlot);
184597: }
184598: 
184599: /*
184600: ** Resize the hash table by doubling the number of slots.
184601: */
184602: static int fts5HashResize(Fts5Hash *pHash){
184603:   int nNew = pHash->nSlot*2;
184604:   int i;
184605:   Fts5HashEntry **apNew;
184606:   Fts5HashEntry **apOld = pHash->aSlot;
184607: 
184608:   apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
184609:   if( !apNew ) return SQLITE_NOMEM;
184610:   memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
184611: 
184612:   for(i=0; i<pHash->nSlot; i++){
184613:     while( apOld[i] ){
184614:       int iHash;
184615:       Fts5HashEntry *p = apOld[i];
184616:       apOld[i] = p->pHashNext;
184617:       iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
184618:       p->pHashNext = apNew[iHash];
184619:       apNew[iHash] = p;
184620:     }
184621:   }
184622: 
184623:   sqlite3_free(apOld);
184624:   pHash->nSlot = nNew;
184625:   pHash->aSlot = apNew;
184626:   return SQLITE_OK;
184627: }
184628: 
184629: static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
184630:   if( p->iSzPoslist ){
184631:     u8 *pPtr = (u8*)p;
184632:     if( pHash->eDetail==FTS5_DETAIL_NONE ){
184633:       assert( p->nData==p->iSzPoslist );
184634:       if( p->bDel ){
184635:         pPtr[p->nData++] = 0x00;
184636:         if( p->bContent ){
184637:           pPtr[p->nData++] = 0x00;
184638:         }
184639:       }
184640:     }else{
184641:       int nSz = (p->nData - p->iSzPoslist - 1);       /* Size in bytes */
184642:       int nPos = nSz*2 + p->bDel;                     /* Value of nPos field */
184643: 
184644:       assert( p->bDel==0 || p->bDel==1 );
184645:       if( nPos<=127 ){
184646:         pPtr[p->iSzPoslist] = (u8)nPos;
184647:       }else{
184648:         int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
184649:         memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
184650:         sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
184651:         p->nData += (nByte-1);
184652:       }
184653:     }
184654: 
184655:     p->iSzPoslist = 0;
184656:     p->bDel = 0;
184657:     p->bContent = 0;
184658:   }
184659: }
184660: 
184661: /*
184662: ** Add an entry to the in-memory hash table. The key is the concatenation
184663: ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
184664: **
184665: **     (bByte || pToken) -> (iRowid,iCol,iPos)
184666: **
184667: ** Or, if iCol is negative, then the value is a delete marker.
184668: */
184669: static int sqlite3Fts5HashWrite(
184670:   Fts5Hash *pHash,
184671:   i64 iRowid,                     /* Rowid for this entry */
184672:   int iCol,                       /* Column token appears in (-ve -> delete) */
184673:   int iPos,                       /* Position of token within column */
184674:   char bByte,                     /* First byte of token */
184675:   const char *pToken, int nToken  /* Token to add or remove to or from index */
184676: ){
184677:   unsigned int iHash;
184678:   Fts5HashEntry *p;
184679:   u8 *pPtr;
184680:   int nIncr = 0;                  /* Amount to increment (*pHash->pnByte) by */
184681:   int bNew;                       /* If non-delete entry should be written */
184682:   
184683:   bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
184684: 
184685:   /* Attempt to locate an existing hash entry */
184686:   iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
184687:   for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
184688:     if( p->zKey[0]==bByte 
184689:      && p->nKey==nToken
184690:      && memcmp(&p->zKey[1], pToken, nToken)==0 
184691:     ){
184692:       break;
184693:     }
184694:   }
184695: 
184696:   /* If an existing hash entry cannot be found, create a new one. */
184697:   if( p==0 ){
184698:     /* Figure out how much space to allocate */
184699:     int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
184700:     if( nByte<128 ) nByte = 128;
184701: 
184702:     /* Grow the Fts5Hash.aSlot[] array if necessary. */
184703:     if( (pHash->nEntry*2)>=pHash->nSlot ){
184704:       int rc = fts5HashResize(pHash);
184705:       if( rc!=SQLITE_OK ) return rc;
184706:       iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
184707:     }
184708: 
184709:     /* Allocate new Fts5HashEntry and add it to the hash table. */
184710:     p = (Fts5HashEntry*)sqlite3_malloc(nByte);
184711:     if( !p ) return SQLITE_NOMEM;
184712:     memset(p, 0, FTS5_HASHENTRYSIZE);
184713:     p->nAlloc = nByte;
184714:     p->zKey[0] = bByte;
184715:     memcpy(&p->zKey[1], pToken, nToken);
184716:     assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
184717:     p->nKey = nToken;
184718:     p->zKey[nToken+1] = '\0';
184719:     p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
184720:     p->pHashNext = pHash->aSlot[iHash];
184721:     pHash->aSlot[iHash] = p;
184722:     pHash->nEntry++;
184723: 
184724:     /* Add the first rowid field to the hash-entry */
184725:     p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
184726:     p->iRowid = iRowid;
184727: 
184728:     p->iSzPoslist = p->nData;
184729:     if( pHash->eDetail!=FTS5_DETAIL_NONE ){
184730:       p->nData += 1;
184731:       p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
184732:     }
184733: 
184734:     nIncr += p->nData;
184735:   }else{
184736: 
184737:     /* Appending to an existing hash-entry. Check that there is enough 
184738:     ** space to append the largest possible new entry. Worst case scenario 
184739:     ** is:
184740:     **
184741:     **     + 9 bytes for a new rowid,
184742:     **     + 4 byte reserved for the "poslist size" varint.
184743:     **     + 1 byte for a "new column" byte,
184744:     **     + 3 bytes for a new column number (16-bit max) as a varint,
184745:     **     + 5 bytes for the new position offset (32-bit max).
184746:     */
184747:     if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
184748:       int nNew = p->nAlloc * 2;
184749:       Fts5HashEntry *pNew;
184750:       Fts5HashEntry **pp;
184751:       pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
184752:       if( pNew==0 ) return SQLITE_NOMEM;
184753:       pNew->nAlloc = nNew;
184754:       for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
184755:       *pp = pNew;
184756:       p = pNew;
184757:     }
184758:     nIncr -= p->nData;
184759:   }
184760:   assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
184761: 
184762:   pPtr = (u8*)p;
184763: 
184764:   /* If this is a new rowid, append the 4-byte size field for the previous
184765:   ** entry, and the new rowid for this entry.  */
184766:   if( iRowid!=p->iRowid ){
184767:     fts5HashAddPoslistSize(pHash, p);
184768:     p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
184769:     p->iRowid = iRowid;
184770:     bNew = 1;
184771:     p->iSzPoslist = p->nData;
184772:     if( pHash->eDetail!=FTS5_DETAIL_NONE ){
184773:       p->nData += 1;
184774:       p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
184775:       p->iPos = 0;
184776:     }
184777:   }
184778: 
184779:   if( iCol>=0 ){
184780:     if( pHash->eDetail==FTS5_DETAIL_NONE ){
184781:       p->bContent = 1;
184782:     }else{
184783:       /* Append a new column value, if necessary */
184784:       assert( iCol>=p->iCol );
184785:       if( iCol!=p->iCol ){
184786:         if( pHash->eDetail==FTS5_DETAIL_FULL ){
184787:           pPtr[p->nData++] = 0x01;
184788:           p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
184789:           p->iCol = (i16)iCol;
184790:           p->iPos = 0;
184791:         }else{
184792:           bNew = 1;
184793:           p->iCol = (i16)(iPos = iCol);
184794:         }
184795:       }
184796: 
184797:       /* Append the new position offset, if necessary */
184798:       if( bNew ){
184799:         p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
184800:         p->iPos = iPos;
184801:       }
184802:     }
184803:   }else{
184804:     /* This is a delete. Set the delete flag. */
184805:     p->bDel = 1;
184806:   }
184807: 
184808:   nIncr += p->nData;
184809:   *pHash->pnByte += nIncr;
184810:   return SQLITE_OK;
184811: }
184812: 
184813: 
184814: /*
184815: ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
184816: ** each sorted in key order. This function merges the two lists into a
184817: ** single list and returns a pointer to its first element.
184818: */
184819: static Fts5HashEntry *fts5HashEntryMerge(
184820:   Fts5HashEntry *pLeft,
184821:   Fts5HashEntry *pRight
184822: ){
184823:   Fts5HashEntry *p1 = pLeft;
184824:   Fts5HashEntry *p2 = pRight;
184825:   Fts5HashEntry *pRet = 0;
184826:   Fts5HashEntry **ppOut = &pRet;
184827: 
184828:   while( p1 || p2 ){
184829:     if( p1==0 ){
184830:       *ppOut = p2;
184831:       p2 = 0;
184832:     }else if( p2==0 ){
184833:       *ppOut = p1;
184834:       p1 = 0;
184835:     }else{
184836:       int i = 0;
184837:       while( p1->zKey[i]==p2->zKey[i] ) i++;
184838: 
184839:       if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
184840:         /* p2 is smaller */
184841:         *ppOut = p2;
184842:         ppOut = &p2->pScanNext;
184843:         p2 = p2->pScanNext;
184844:       }else{
184845:         /* p1 is smaller */
184846:         *ppOut = p1;
184847:         ppOut = &p1->pScanNext;
184848:         p1 = p1->pScanNext;
184849:       }
184850:       *ppOut = 0;
184851:     }
184852:   }
184853: 
184854:   return pRet;
184855: }
184856: 
184857: /*
184858: ** Extract all tokens from hash table iHash and link them into a list
184859: ** in sorted order. The hash table is cleared before returning. It is
184860: ** the responsibility of the caller to free the elements of the returned
184861: ** list.
184862: */
184863: static int fts5HashEntrySort(
184864:   Fts5Hash *pHash, 
184865:   const char *pTerm, int nTerm,   /* Query prefix, if any */
184866:   Fts5HashEntry **ppSorted
184867: ){
184868:   const int nMergeSlot = 32;
184869:   Fts5HashEntry **ap;
184870:   Fts5HashEntry *pList;
184871:   int iSlot;
184872:   int i;
184873: 
184874:   *ppSorted = 0;
184875:   ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
184876:   if( !ap ) return SQLITE_NOMEM;
184877:   memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
184878: 
184879:   for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
184880:     Fts5HashEntry *pIter;
184881:     for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
184882:       if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
184883:         Fts5HashEntry *pEntry = pIter;
184884:         pEntry->pScanNext = 0;
184885:         for(i=0; ap[i]; i++){
184886:           pEntry = fts5HashEntryMerge(pEntry, ap[i]);
184887:           ap[i] = 0;
184888:         }
184889:         ap[i] = pEntry;
184890:       }
184891:     }
184892:   }
184893: 
184894:   pList = 0;
184895:   for(i=0; i<nMergeSlot; i++){
184896:     pList = fts5HashEntryMerge(pList, ap[i]);
184897:   }
184898: 
184899:   pHash->nEntry = 0;
184900:   sqlite3_free(ap);
184901:   *ppSorted = pList;
184902:   return SQLITE_OK;
184903: }
184904: 
184905: /*
184906: ** Query the hash table for a doclist associated with term pTerm/nTerm.
184907: */
184908: static int sqlite3Fts5HashQuery(
184909:   Fts5Hash *pHash,                /* Hash table to query */
184910:   const char *pTerm, int nTerm,   /* Query term */
184911:   const u8 **ppDoclist,           /* OUT: Pointer to doclist for pTerm */
184912:   int *pnDoclist                  /* OUT: Size of doclist in bytes */
184913: ){
184914:   unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
184915:   Fts5HashEntry *p;
184916: 
184917:   for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
184918:     if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
184919:   }
184920: 
184921:   if( p ){
184922:     fts5HashAddPoslistSize(pHash, p);
184923:     *ppDoclist = (const u8*)&p->zKey[nTerm+1];
184924:     *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
184925:   }else{
184926:     *ppDoclist = 0;
184927:     *pnDoclist = 0;
184928:   }
184929: 
184930:   return SQLITE_OK;
184931: }
184932: 
184933: static int sqlite3Fts5HashScanInit(
184934:   Fts5Hash *p,                    /* Hash table to query */
184935:   const char *pTerm, int nTerm    /* Query prefix */
184936: ){
184937:   return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
184938: }
184939: 
184940: static void sqlite3Fts5HashScanNext(Fts5Hash *p){
184941:   assert( !sqlite3Fts5HashScanEof(p) );
184942:   p->pScan = p->pScan->pScanNext;
184943: }
184944: 
184945: static int sqlite3Fts5HashScanEof(Fts5Hash *p){
184946:   return (p->pScan==0);
184947: }
184948: 
184949: static void sqlite3Fts5HashScanEntry(
184950:   Fts5Hash *pHash,
184951:   const char **pzTerm,            /* OUT: term (nul-terminated) */
184952:   const u8 **ppDoclist,           /* OUT: pointer to doclist */
184953:   int *pnDoclist                  /* OUT: size of doclist in bytes */
184954: ){
184955:   Fts5HashEntry *p;
184956:   if( (p = pHash->pScan) ){
184957:     int nTerm = (int)strlen(p->zKey);
184958:     fts5HashAddPoslistSize(pHash, p);
184959:     *pzTerm = p->zKey;
184960:     *ppDoclist = (const u8*)&p->zKey[nTerm+1];
184961:     *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
184962:   }else{
184963:     *pzTerm = 0;
184964:     *ppDoclist = 0;
184965:     *pnDoclist = 0;
184966:   }
184967: }
184968: 
184969: 
184970: /*
184971: ** 2014 May 31
184972: **
184973: ** The author disclaims copyright to this source code.  In place of
184974: ** a legal notice, here is a blessing:
184975: **
184976: **    May you do good and not evil.
184977: **    May you find forgiveness for yourself and forgive others.
184978: **    May you share freely, never taking more than you give.
184979: **
184980: ******************************************************************************
184981: **
184982: ** Low level access to the FTS index stored in the database file. The 
184983: ** routines in this file file implement all read and write access to the
184984: ** %_data table. Other parts of the system access this functionality via
184985: ** the interface defined in fts5Int.h.
184986: */
184987: 
184988: 
184989: /* #include "fts5Int.h" */
184990: 
184991: /*
184992: ** Overview:
184993: **
184994: ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
184995: ** As well as the main term index, there may be up to 31 prefix indexes.
184996: ** The format is similar to FTS3/4, except that:
184997: **
184998: **   * all segment b-tree leaf data is stored in fixed size page records 
184999: **     (e.g. 1000 bytes). A single doclist may span multiple pages. Care is 
185000: **     taken to ensure it is possible to iterate in either direction through 
185001: **     the entries in a doclist, or to seek to a specific entry within a 
185002: **     doclist, without loading it into memory.
185003: **
185004: **   * large doclists that span many pages have associated "doclist index"
185005: **     records that contain a copy of the first rowid on each page spanned by
185006: **     the doclist. This is used to speed up seek operations, and merges of
185007: **     large doclists with very small doclists.
185008: **
185009: **   * extra fields in the "structure record" record the state of ongoing
185010: **     incremental merge operations.
185011: **
185012: */
185013: 
185014: 
185015: #define FTS5_OPT_WORK_UNIT  1000  /* Number of leaf pages per optimize step */
185016: #define FTS5_WORK_UNIT      64    /* Number of leaf pages in unit of work */
185017: 
185018: #define FTS5_MIN_DLIDX_SIZE 4     /* Add dlidx if this many empty pages */
185019: 
185020: #define FTS5_MAIN_PREFIX '0'
185021: 
185022: #if FTS5_MAX_PREFIX_INDEXES > 31
185023: # error "FTS5_MAX_PREFIX_INDEXES is too large"
185024: #endif
185025: 
185026: /*
185027: ** Details:
185028: **
185029: ** The %_data table managed by this module,
185030: **
185031: **     CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
185032: **
185033: ** , contains the following 5 types of records. See the comments surrounding
185034: ** the FTS5_*_ROWID macros below for a description of how %_data rowids are 
185035: ** assigned to each fo them.
185036: **
185037: ** 1. Structure Records:
185038: **
185039: **   The set of segments that make up an index - the index structure - are
185040: **   recorded in a single record within the %_data table. The record consists
185041: **   of a single 32-bit configuration cookie value followed by a list of 
185042: **   SQLite varints. If the FTS table features more than one index (because
185043: **   there are one or more prefix indexes), it is guaranteed that all share
185044: **   the same cookie value.
185045: **
185046: **   Immediately following the configuration cookie, the record begins with
185047: **   three varints:
185048: **
185049: **     + number of levels,
185050: **     + total number of segments on all levels,
185051: **     + value of write counter.
185052: **
185053: **   Then, for each level from 0 to nMax:
185054: **
185055: **     + number of input segments in ongoing merge.
185056: **     + total number of segments in level.
185057: **     + for each segment from oldest to newest:
185058: **         + segment id (always > 0)
185059: **         + first leaf page number (often 1, always greater than 0)
185060: **         + final leaf page number
185061: **
185062: ** 2. The Averages Record:
185063: **
185064: **   A single record within the %_data table. The data is a list of varints.
185065: **   The first value is the number of rows in the index. Then, for each column
185066: **   from left to right, the total number of tokens in the column for all
185067: **   rows of the table.
185068: **
185069: ** 3. Segment leaves:
185070: **
185071: **   TERM/DOCLIST FORMAT:
185072: **
185073: **     Most of each segment leaf is taken up by term/doclist data. The 
185074: **     general format of term/doclist, starting with the first term
185075: **     on the leaf page, is:
185076: **
185077: **         varint : size of first term
185078: **         blob:    first term data
185079: **         doclist: first doclist
185080: **         zero-or-more {
185081: **           varint:  number of bytes in common with previous term
185082: **           varint:  number of bytes of new term data (nNew)
185083: **           blob:    nNew bytes of new term data
185084: **           doclist: next doclist
185085: **         }
185086: **
185087: **     doclist format:
185088: **
185089: **         varint:  first rowid
185090: **         poslist: first poslist
185091: **         zero-or-more {
185092: **           varint:  rowid delta (always > 0)
185093: **           poslist: next poslist
185094: **         }
185095: **
185096: **     poslist format:
185097: **
185098: **         varint: size of poslist in bytes multiplied by 2, not including
185099: **                 this field. Plus 1 if this entry carries the "delete" flag.
185100: **         collist: collist for column 0
185101: **         zero-or-more {
185102: **           0x01 byte
185103: **           varint: column number (I)
185104: **           collist: collist for column I
185105: **         }
185106: **
185107: **     collist format:
185108: **
185109: **         varint: first offset + 2
185110: **         zero-or-more {
185111: **           varint: offset delta + 2
185112: **         }
185113: **
185114: **   PAGE FORMAT
185115: **
185116: **     Each leaf page begins with a 4-byte header containing 2 16-bit 
185117: **     unsigned integer fields in big-endian format. They are:
185118: **
185119: **       * The byte offset of the first rowid on the page, if it exists
185120: **         and occurs before the first term (otherwise 0).
185121: **
185122: **       * The byte offset of the start of the page footer. If the page
185123: **         footer is 0 bytes in size, then this field is the same as the
185124: **         size of the leaf page in bytes.
185125: **
185126: **     The page footer consists of a single varint for each term located
185127: **     on the page. Each varint is the byte offset of the current term
185128: **     within the page, delta-compressed against the previous value. In
185129: **     other words, the first varint in the footer is the byte offset of
185130: **     the first term, the second is the byte offset of the second less that
185131: **     of the first, and so on.
185132: **
185133: **     The term/doclist format described above is accurate if the entire
185134: **     term/doclist data fits on a single leaf page. If this is not the case,
185135: **     the format is changed in two ways:
185136: **
185137: **       + if the first rowid on a page occurs before the first term, it
185138: **         is stored as a literal value:
185139: **
185140: **             varint:  first rowid
185141: **
185142: **       + the first term on each page is stored in the same way as the
185143: **         very first term of the segment:
185144: **
185145: **             varint : size of first term
185146: **             blob:    first term data
185147: **
185148: ** 5. Segment doclist indexes:
185149: **
185150: **   Doclist indexes are themselves b-trees, however they usually consist of
185151: **   a single leaf record only. The format of each doclist index leaf page 
185152: **   is:
185153: **
185154: **     * Flags byte. Bits are:
185155: **         0x01: Clear if leaf is also the root page, otherwise set.
185156: **
185157: **     * Page number of fts index leaf page. As a varint.
185158: **
185159: **     * First rowid on page indicated by previous field. As a varint.
185160: **
185161: **     * A list of varints, one for each subsequent termless page. A 
185162: **       positive delta if the termless page contains at least one rowid, 
185163: **       or an 0x00 byte otherwise.
185164: **
185165: **   Internal doclist index nodes are:
185166: **
185167: **     * Flags byte. Bits are:
185168: **         0x01: Clear for root page, otherwise set.
185169: **
185170: **     * Page number of first child page. As a varint.
185171: **
185172: **     * Copy of first rowid on page indicated by previous field. As a varint.
185173: **
185174: **     * A list of delta-encoded varints - the first rowid on each subsequent
185175: **       child page. 
185176: **
185177: */
185178: 
185179: /*
185180: ** Rowids for the averages and structure records in the %_data table.
185181: */
185182: #define FTS5_AVERAGES_ROWID     1    /* Rowid used for the averages record */
185183: #define FTS5_STRUCTURE_ROWID   10    /* The structure record */
185184: 
185185: /*
185186: ** Macros determining the rowids used by segment leaves and dlidx leaves
185187: ** and nodes. All nodes and leaves are stored in the %_data table with large
185188: ** positive rowids.
185189: **
185190: ** Each segment has a unique non-zero 16-bit id.
185191: **
185192: ** The rowid for each segment leaf is found by passing the segment id and 
185193: ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
185194: ** sequentially starting from 1.
185195: */
185196: #define FTS5_DATA_ID_B     16     /* Max seg id number 65535 */
185197: #define FTS5_DATA_DLI_B     1     /* Doclist-index flag (1 bit) */
185198: #define FTS5_DATA_HEIGHT_B  5     /* Max dlidx tree height of 32 */
185199: #define FTS5_DATA_PAGE_B   31     /* Max page number of 2147483648 */
185200: 
185201: #define fts5_dri(segid, dlidx, height, pgno) (                                 \
185202:  ((i64)(segid)  << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) +    \
185203:  ((i64)(dlidx)  << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) +                  \
185204:  ((i64)(height) << (FTS5_DATA_PAGE_B)) +                                       \
185205:  ((i64)(pgno))                                                                 \
185206: )
185207: 
185208: #define FTS5_SEGMENT_ROWID(segid, pgno)       fts5_dri(segid, 0, 0, pgno)
185209: #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
185210: 
185211: /*
185212: ** Maximum segments permitted in a single index 
185213: */
185214: #define FTS5_MAX_SEGMENT 2000
185215: 
185216: #ifdef SQLITE_DEBUG
185217: static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
185218: #endif
185219: 
185220: 
185221: /*
185222: ** Each time a blob is read from the %_data table, it is padded with this
185223: ** many zero bytes. This makes it easier to decode the various record formats
185224: ** without overreading if the records are corrupt.
185225: */
185226: #define FTS5_DATA_ZERO_PADDING 8
185227: #define FTS5_DATA_PADDING 20
185228: 
185229: typedef struct Fts5Data Fts5Data;
185230: typedef struct Fts5DlidxIter Fts5DlidxIter;
185231: typedef struct Fts5DlidxLvl Fts5DlidxLvl;
185232: typedef struct Fts5DlidxWriter Fts5DlidxWriter;
185233: typedef struct Fts5Iter Fts5Iter;
185234: typedef struct Fts5PageWriter Fts5PageWriter;
185235: typedef struct Fts5SegIter Fts5SegIter;
185236: typedef struct Fts5DoclistIter Fts5DoclistIter;
185237: typedef struct Fts5SegWriter Fts5SegWriter;
185238: typedef struct Fts5Structure Fts5Structure;
185239: typedef struct Fts5StructureLevel Fts5StructureLevel;
185240: typedef struct Fts5StructureSegment Fts5StructureSegment;
185241: 
185242: struct Fts5Data {
185243:   u8 *p;                          /* Pointer to buffer containing record */
185244:   int nn;                         /* Size of record in bytes */
185245:   int szLeaf;                     /* Size of leaf without page-index */
185246: };
185247: 
185248: /*
185249: ** One object per %_data table.
185250: */
185251: struct Fts5Index {
185252:   Fts5Config *pConfig;            /* Virtual table configuration */
185253:   char *zDataTbl;                 /* Name of %_data table */
185254:   int nWorkUnit;                  /* Leaf pages in a "unit" of work */
185255: 
185256:   /*
185257:   ** Variables related to the accumulation of tokens and doclists within the
185258:   ** in-memory hash tables before they are flushed to disk.
185259:   */
185260:   Fts5Hash *pHash;                /* Hash table for in-memory data */
185261:   int nPendingData;               /* Current bytes of pending data */
185262:   i64 iWriteRowid;                /* Rowid for current doc being written */
185263:   int bDelete;                    /* Current write is a delete */
185264: 
185265:   /* Error state. */
185266:   int rc;                         /* Current error code */
185267: 
185268:   /* State used by the fts5DataXXX() functions. */
185269:   sqlite3_blob *pReader;          /* RO incr-blob open on %_data table */
185270:   sqlite3_stmt *pWriter;          /* "INSERT ... %_data VALUES(?,?)" */
185271:   sqlite3_stmt *pDeleter;         /* "DELETE FROM %_data ... id>=? AND id<=?" */
185272:   sqlite3_stmt *pIdxWriter;       /* "INSERT ... %_idx VALUES(?,?,?,?)" */
185273:   sqlite3_stmt *pIdxDeleter;      /* "DELETE FROM %_idx WHERE segid=? */
185274:   sqlite3_stmt *pIdxSelect;
185275:   int nRead;                      /* Total number of blocks read */
185276: 
185277:   sqlite3_stmt *pDataVersion;
185278:   i64 iStructVersion;             /* data_version when pStruct read */
185279:   Fts5Structure *pStruct;         /* Current db structure (or NULL) */
185280: };
185281: 
185282: struct Fts5DoclistIter {
185283:   u8 *aEof;                       /* Pointer to 1 byte past end of doclist */
185284: 
185285:   /* Output variables. aPoslist==0 at EOF */
185286:   i64 iRowid;
185287:   u8 *aPoslist;
185288:   int nPoslist;
185289:   int nSize;
185290: };
185291: 
185292: /*
185293: ** The contents of the "structure" record for each index are represented
185294: ** using an Fts5Structure record in memory. Which uses instances of the 
185295: ** other Fts5StructureXXX types as components.
185296: */
185297: struct Fts5StructureSegment {
185298:   int iSegid;                     /* Segment id */
185299:   int pgnoFirst;                  /* First leaf page number in segment */
185300:   int pgnoLast;                   /* Last leaf page number in segment */
185301: };
185302: struct Fts5StructureLevel {
185303:   int nMerge;                     /* Number of segments in incr-merge */
185304:   int nSeg;                       /* Total number of segments on level */
185305:   Fts5StructureSegment *aSeg;     /* Array of segments. aSeg[0] is oldest. */
185306: };
185307: struct Fts5Structure {
185308:   int nRef;                       /* Object reference count */
185309:   u64 nWriteCounter;              /* Total leaves written to level 0 */
185310:   int nSegment;                   /* Total segments in this structure */
185311:   int nLevel;                     /* Number of levels in this index */
185312:   Fts5StructureLevel aLevel[1];   /* Array of nLevel level objects */
185313: };
185314: 
185315: /*
185316: ** An object of type Fts5SegWriter is used to write to segments.
185317: */
185318: struct Fts5PageWriter {
185319:   int pgno;                       /* Page number for this page */
185320:   int iPrevPgidx;                 /* Previous value written into pgidx */
185321:   Fts5Buffer buf;                 /* Buffer containing leaf data */
185322:   Fts5Buffer pgidx;               /* Buffer containing page-index */
185323:   Fts5Buffer term;                /* Buffer containing previous term on page */
185324: };
185325: struct Fts5DlidxWriter {
185326:   int pgno;                       /* Page number for this page */
185327:   int bPrevValid;                 /* True if iPrev is valid */
185328:   i64 iPrev;                      /* Previous rowid value written to page */
185329:   Fts5Buffer buf;                 /* Buffer containing page data */
185330: };
185331: struct Fts5SegWriter {
185332:   int iSegid;                     /* Segid to write to */
185333:   Fts5PageWriter writer;          /* PageWriter object */
185334:   i64 iPrevRowid;                 /* Previous rowid written to current leaf */
185335:   u8 bFirstRowidInDoclist;        /* True if next rowid is first in doclist */
185336:   u8 bFirstRowidInPage;           /* True if next rowid is first in page */
185337:   /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
185338:   u8 bFirstTermInPage;            /* True if next term will be first in leaf */
185339:   int nLeafWritten;               /* Number of leaf pages written */
185340:   int nEmpty;                     /* Number of contiguous term-less nodes */
185341: 
185342:   int nDlidx;                     /* Allocated size of aDlidx[] array */
185343:   Fts5DlidxWriter *aDlidx;        /* Array of Fts5DlidxWriter objects */
185344: 
185345:   /* Values to insert into the %_idx table */
185346:   Fts5Buffer btterm;              /* Next term to insert into %_idx table */
185347:   int iBtPage;                    /* Page number corresponding to btterm */
185348: };
185349: 
185350: typedef struct Fts5CResult Fts5CResult;
185351: struct Fts5CResult {
185352:   u16 iFirst;                     /* aSeg[] index of firstest iterator */
185353:   u8 bTermEq;                     /* True if the terms are equal */
185354: };
185355: 
185356: /*
185357: ** Object for iterating through a single segment, visiting each term/rowid
185358: ** pair in the segment.
185359: **
185360: ** pSeg:
185361: **   The segment to iterate through.
185362: **
185363: ** iLeafPgno:
185364: **   Current leaf page number within segment.
185365: **
185366: ** iLeafOffset:
185367: **   Byte offset within the current leaf that is the first byte of the 
185368: **   position list data (one byte passed the position-list size field).
185369: **   rowid field of the current entry. Usually this is the size field of the
185370: **   position list data. The exception is if the rowid for the current entry 
185371: **   is the last thing on the leaf page.
185372: **
185373: ** pLeaf:
185374: **   Buffer containing current leaf page data. Set to NULL at EOF.
185375: **
185376: ** iTermLeafPgno, iTermLeafOffset:
185377: **   Leaf page number containing the last term read from the segment. And
185378: **   the offset immediately following the term data.
185379: **
185380: ** flags:
185381: **   Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
185382: **
185383: **   FTS5_SEGITER_ONETERM:
185384: **     If set, set the iterator to point to EOF after the current doclist 
185385: **     has been exhausted. Do not proceed to the next term in the segment.
185386: **
185387: **   FTS5_SEGITER_REVERSE:
185388: **     This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
185389: **     it is set, iterate through rowid in descending order instead of the
185390: **     default ascending order.
185391: **
185392: ** iRowidOffset/nRowidOffset/aRowidOffset:
185393: **     These are used if the FTS5_SEGITER_REVERSE flag is set.
185394: **
185395: **     For each rowid on the page corresponding to the current term, the
185396: **     corresponding aRowidOffset[] entry is set to the byte offset of the
185397: **     start of the "position-list-size" field within the page.
185398: **
185399: ** iTermIdx:
185400: **     Index of current term on iTermLeafPgno.
185401: */
185402: struct Fts5SegIter {
185403:   Fts5StructureSegment *pSeg;     /* Segment to iterate through */
185404:   int flags;                      /* Mask of configuration flags */
185405:   int iLeafPgno;                  /* Current leaf page number */
185406:   Fts5Data *pLeaf;                /* Current leaf data */
185407:   Fts5Data *pNextLeaf;            /* Leaf page (iLeafPgno+1) */
185408:   int iLeafOffset;                /* Byte offset within current leaf */
185409: 
185410:   /* Next method */
185411:   void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
185412: 
185413:   /* The page and offset from which the current term was read. The offset 
185414:   ** is the offset of the first rowid in the current doclist.  */
185415:   int iTermLeafPgno;
185416:   int iTermLeafOffset;
185417: 
185418:   int iPgidxOff;                  /* Next offset in pgidx */
185419:   int iEndofDoclist;
185420: 
185421:   /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
185422:   int iRowidOffset;               /* Current entry in aRowidOffset[] */
185423:   int nRowidOffset;               /* Allocated size of aRowidOffset[] array */
185424:   int *aRowidOffset;              /* Array of offset to rowid fields */
185425: 
185426:   Fts5DlidxIter *pDlidx;          /* If there is a doclist-index */
185427: 
185428:   /* Variables populated based on current entry. */
185429:   Fts5Buffer term;                /* Current term */
185430:   i64 iRowid;                     /* Current rowid */
185431:   int nPos;                       /* Number of bytes in current position list */
185432:   u8 bDel;                        /* True if the delete flag is set */
185433: };
185434: 
185435: /*
185436: ** Argument is a pointer to an Fts5Data structure that contains a 
185437: ** leaf page.
185438: */
185439: #define ASSERT_SZLEAF_OK(x) assert( \
185440:     (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
185441: )
185442: 
185443: #define FTS5_SEGITER_ONETERM 0x01
185444: #define FTS5_SEGITER_REVERSE 0x02
185445: 
185446: /* 
185447: ** Argument is a pointer to an Fts5Data structure that contains a leaf
185448: ** page. This macro evaluates to true if the leaf contains no terms, or
185449: ** false if it contains at least one term.
185450: */
185451: #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
185452: 
185453: #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
185454: 
185455: #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
185456: 
185457: /*
185458: ** Object for iterating through the merged results of one or more segments,
185459: ** visiting each term/rowid pair in the merged data.
185460: **
185461: ** nSeg is always a power of two greater than or equal to the number of
185462: ** segments that this object is merging data from. Both the aSeg[] and
185463: ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
185464: ** with zeroed objects - these are handled as if they were iterators opened
185465: ** on empty segments.
185466: **
185467: ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
185468: ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the 
185469: ** comparison in this context is the index of the iterator that currently
185470: ** points to the smaller term/rowid combination. Iterators at EOF are
185471: ** considered to be greater than all other iterators.
185472: **
185473: ** aFirst[1] contains the index in aSeg[] of the iterator that points to
185474: ** the smallest key overall. aFirst[0] is unused. 
185475: **
185476: ** poslist:
185477: **   Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
185478: **   There is no way to tell if this is populated or not.
185479: */
185480: struct Fts5Iter {
185481:   Fts5IndexIter base;             /* Base class containing output vars */
185482: 
185483:   Fts5Index *pIndex;              /* Index that owns this iterator */
185484:   Fts5Structure *pStruct;         /* Database structure for this iterator */
185485:   Fts5Buffer poslist;             /* Buffer containing current poslist */
185486:   Fts5Colset *pColset;            /* Restrict matches to these columns */
185487: 
185488:   /* Invoked to set output variables. */
185489:   void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
185490: 
185491:   int nSeg;                       /* Size of aSeg[] array */
185492:   int bRev;                       /* True to iterate in reverse order */
185493:   u8 bSkipEmpty;                  /* True to skip deleted entries */
185494: 
185495:   i64 iSwitchRowid;               /* Firstest rowid of other than aFirst[1] */
185496:   Fts5CResult *aFirst;            /* Current merge state (see above) */
185497:   Fts5SegIter aSeg[1];            /* Array of segment iterators */
185498: };
185499: 
185500: 
185501: /*
185502: ** An instance of the following type is used to iterate through the contents
185503: ** of a doclist-index record.
185504: **
185505: ** pData:
185506: **   Record containing the doclist-index data.
185507: **
185508: ** bEof:
185509: **   Set to true once iterator has reached EOF.
185510: **
185511: ** iOff:
185512: **   Set to the current offset within record pData.
185513: */
185514: struct Fts5DlidxLvl {
185515:   Fts5Data *pData;              /* Data for current page of this level */
185516:   int iOff;                     /* Current offset into pData */
185517:   int bEof;                     /* At EOF already */
185518:   int iFirstOff;                /* Used by reverse iterators */
185519: 
185520:   /* Output variables */
185521:   int iLeafPgno;                /* Page number of current leaf page */
185522:   i64 iRowid;                   /* First rowid on leaf iLeafPgno */
185523: };
185524: struct Fts5DlidxIter {
185525:   int nLvl;
185526:   int iSegid;
185527:   Fts5DlidxLvl aLvl[1];
185528: };
185529: 
185530: static void fts5PutU16(u8 *aOut, u16 iVal){
185531:   aOut[0] = (iVal>>8);
185532:   aOut[1] = (iVal&0xFF);
185533: }
185534: 
185535: static u16 fts5GetU16(const u8 *aIn){
185536:   return ((u16)aIn[0] << 8) + aIn[1];
185537: } 
185538: 
185539: /*
185540: ** Allocate and return a buffer at least nByte bytes in size.
185541: **
185542: ** If an OOM error is encountered, return NULL and set the error code in
185543: ** the Fts5Index handle passed as the first argument.
185544: */
185545: static void *fts5IdxMalloc(Fts5Index *p, int nByte){
185546:   return sqlite3Fts5MallocZero(&p->rc, nByte);
185547: }
185548: 
185549: /*
185550: ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
185551: **
185552: ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
185553: ** +ve if pRight is smaller than pLeft. In other words:
185554: **
185555: **     res = *pLeft - *pRight
185556: */
185557: #ifdef SQLITE_DEBUG
185558: static int fts5BufferCompareBlob(
185559:   Fts5Buffer *pLeft,              /* Left hand side of comparison */
185560:   const u8 *pRight, int nRight    /* Right hand side of comparison */
185561: ){
185562:   int nCmp = MIN(pLeft->n, nRight);
185563:   int res = memcmp(pLeft->p, pRight, nCmp);
185564:   return (res==0 ? (pLeft->n - nRight) : res);
185565: }
185566: #endif
185567: 
185568: /*
185569: ** Compare the contents of the two buffers using memcmp(). If one buffer
185570: ** is a prefix of the other, it is considered the lesser.
185571: **
185572: ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
185573: ** +ve if pRight is smaller than pLeft. In other words:
185574: **
185575: **     res = *pLeft - *pRight
185576: */
185577: static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
185578:   int nCmp = MIN(pLeft->n, pRight->n);
185579:   int res = memcmp(pLeft->p, pRight->p, nCmp);
185580:   return (res==0 ? (pLeft->n - pRight->n) : res);
185581: }
185582: 
185583: static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
185584:   int ret;
185585:   fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
185586:   return ret;
185587: }
185588: 
185589: /*
185590: ** Close the read-only blob handle, if it is open.
185591: */
185592: static void fts5CloseReader(Fts5Index *p){
185593:   if( p->pReader ){
185594:     sqlite3_blob *pReader = p->pReader;
185595:     p->pReader = 0;
185596:     sqlite3_blob_close(pReader);
185597:   }
185598: }
185599: 
185600: 
185601: /*
185602: ** Retrieve a record from the %_data table.
185603: **
185604: ** If an error occurs, NULL is returned and an error left in the 
185605: ** Fts5Index object.
185606: */
185607: static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
185608:   Fts5Data *pRet = 0;
185609:   if( p->rc==SQLITE_OK ){
185610:     int rc = SQLITE_OK;
185611: 
185612:     if( p->pReader ){
185613:       /* This call may return SQLITE_ABORT if there has been a savepoint
185614:       ** rollback since it was last used. In this case a new blob handle
185615:       ** is required.  */
185616:       sqlite3_blob *pBlob = p->pReader;
185617:       p->pReader = 0;
185618:       rc = sqlite3_blob_reopen(pBlob, iRowid);
185619:       assert( p->pReader==0 );
185620:       p->pReader = pBlob;
185621:       if( rc!=SQLITE_OK ){
185622:         fts5CloseReader(p);
185623:       }
185624:       if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
185625:     }
185626: 
185627:     /* If the blob handle is not open at this point, open it and seek 
185628:     ** to the requested entry.  */
185629:     if( p->pReader==0 && rc==SQLITE_OK ){
185630:       Fts5Config *pConfig = p->pConfig;
185631:       rc = sqlite3_blob_open(pConfig->db, 
185632:           pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
185633:       );
185634:     }
185635: 
185636:     /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
185637:     ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
185638:     ** All the reasons those functions might return SQLITE_ERROR - missing
185639:     ** table, missing row, non-blob/text in block column - indicate 
185640:     ** backing store corruption.  */
185641:     if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
185642: 
185643:     if( rc==SQLITE_OK ){
185644:       u8 *aOut = 0;               /* Read blob data into this buffer */
185645:       int nByte = sqlite3_blob_bytes(p->pReader);
185646:       int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
185647:       pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
185648:       if( pRet ){
185649:         pRet->nn = nByte;
185650:         aOut = pRet->p = (u8*)&pRet[1];
185651:       }else{
185652:         rc = SQLITE_NOMEM;
185653:       }
185654: 
185655:       if( rc==SQLITE_OK ){
185656:         rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
185657:       }
185658:       if( rc!=SQLITE_OK ){
185659:         sqlite3_free(pRet);
185660:         pRet = 0;
185661:       }else{
185662:         /* TODO1: Fix this */
185663:         pRet->szLeaf = fts5GetU16(&pRet->p[2]);
185664:       }
185665:     }
185666:     p->rc = rc;
185667:     p->nRead++;
185668:   }
185669: 
185670:   assert( (pRet==0)==(p->rc!=SQLITE_OK) );
185671:   return pRet;
185672: }
185673: 
185674: 
185675: /*
185676: ** Release a reference to data record returned by an earlier call to
185677: ** fts5DataRead().
185678: */
185679: static void fts5DataRelease(Fts5Data *pData){
185680:   sqlite3_free(pData);
185681: }
185682: 
185683: static int fts5IndexPrepareStmt(
185684:   Fts5Index *p,
185685:   sqlite3_stmt **ppStmt,
185686:   char *zSql
185687: ){
185688:   if( p->rc==SQLITE_OK ){
185689:     if( zSql ){
185690:       p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
185691:     }else{
185692:       p->rc = SQLITE_NOMEM;
185693:     }
185694:   }
185695:   sqlite3_free(zSql);
185696:   return p->rc;
185697: }
185698: 
185699: 
185700: /*
185701: ** INSERT OR REPLACE a record into the %_data table.
185702: */
185703: static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
185704:   if( p->rc!=SQLITE_OK ) return;
185705: 
185706:   if( p->pWriter==0 ){
185707:     Fts5Config *pConfig = p->pConfig;
185708:     fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
185709:           "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)", 
185710:           pConfig->zDb, pConfig->zName
185711:     ));
185712:     if( p->rc ) return;
185713:   }
185714: 
185715:   sqlite3_bind_int64(p->pWriter, 1, iRowid);
185716:   sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
185717:   sqlite3_step(p->pWriter);
185718:   p->rc = sqlite3_reset(p->pWriter);
185719: }
185720: 
185721: /*
185722: ** Execute the following SQL:
185723: **
185724: **     DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
185725: */
185726: static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
185727:   if( p->rc!=SQLITE_OK ) return;
185728: 
185729:   if( p->pDeleter==0 ){
185730:     int rc;
185731:     Fts5Config *pConfig = p->pConfig;
185732:     char *zSql = sqlite3_mprintf(
185733:         "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?", 
185734:           pConfig->zDb, pConfig->zName
185735:     );
185736:     if( zSql==0 ){
185737:       rc = SQLITE_NOMEM;
185738:     }else{
185739:       rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
185740:       sqlite3_free(zSql);
185741:     }
185742:     if( rc!=SQLITE_OK ){
185743:       p->rc = rc;
185744:       return;
185745:     }
185746:   }
185747: 
185748:   sqlite3_bind_int64(p->pDeleter, 1, iFirst);
185749:   sqlite3_bind_int64(p->pDeleter, 2, iLast);
185750:   sqlite3_step(p->pDeleter);
185751:   p->rc = sqlite3_reset(p->pDeleter);
185752: }
185753: 
185754: /*
185755: ** Remove all records associated with segment iSegid.
185756: */
185757: static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
185758:   i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
185759:   i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
185760:   fts5DataDelete(p, iFirst, iLast);
185761:   if( p->pIdxDeleter==0 ){
185762:     Fts5Config *pConfig = p->pConfig;
185763:     fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
185764:           "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
185765:           pConfig->zDb, pConfig->zName
185766:     ));
185767:   }
185768:   if( p->rc==SQLITE_OK ){
185769:     sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
185770:     sqlite3_step(p->pIdxDeleter);
185771:     p->rc = sqlite3_reset(p->pIdxDeleter);
185772:   }
185773: }
185774: 
185775: /*
185776: ** Release a reference to an Fts5Structure object returned by an earlier 
185777: ** call to fts5StructureRead() or fts5StructureDecode().
185778: */
185779: static void fts5StructureRelease(Fts5Structure *pStruct){
185780:   if( pStruct && 0>=(--pStruct->nRef) ){
185781:     int i;
185782:     assert( pStruct->nRef==0 );
185783:     for(i=0; i<pStruct->nLevel; i++){
185784:       sqlite3_free(pStruct->aLevel[i].aSeg);
185785:     }
185786:     sqlite3_free(pStruct);
185787:   }
185788: }
185789: 
185790: static void fts5StructureRef(Fts5Structure *pStruct){
185791:   pStruct->nRef++;
185792: }
185793: 
185794: /*
185795: ** Deserialize and return the structure record currently stored in serialized
185796: ** form within buffer pData/nData.
185797: **
185798: ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
185799: ** are over-allocated by one slot. This allows the structure contents
185800: ** to be more easily edited.
185801: **
185802: ** If an error occurs, *ppOut is set to NULL and an SQLite error code
185803: ** returned. Otherwise, *ppOut is set to point to the new object and
185804: ** SQLITE_OK returned.
185805: */
185806: static int fts5StructureDecode(
185807:   const u8 *pData,                /* Buffer containing serialized structure */
185808:   int nData,                      /* Size of buffer pData in bytes */
185809:   int *piCookie,                  /* Configuration cookie value */
185810:   Fts5Structure **ppOut           /* OUT: Deserialized object */
185811: ){
185812:   int rc = SQLITE_OK;
185813:   int i = 0;
185814:   int iLvl;
185815:   int nLevel = 0;
185816:   int nSegment = 0;
185817:   int nByte;                      /* Bytes of space to allocate at pRet */
185818:   Fts5Structure *pRet = 0;        /* Structure object to return */
185819: 
185820:   /* Grab the cookie value */
185821:   if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
185822:   i = 4;
185823: 
185824:   /* Read the total number of levels and segments from the start of the
185825:   ** structure record.  */
185826:   i += fts5GetVarint32(&pData[i], nLevel);
185827:   i += fts5GetVarint32(&pData[i], nSegment);
185828:   nByte = (
185829:       sizeof(Fts5Structure) +                    /* Main structure */
185830:       sizeof(Fts5StructureLevel) * (nLevel-1)    /* aLevel[] array */
185831:   );
185832:   pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
185833: 
185834:   if( pRet ){
185835:     pRet->nRef = 1;
185836:     pRet->nLevel = nLevel;
185837:     pRet->nSegment = nSegment;
185838:     i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
185839: 
185840:     for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
185841:       Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
185842:       int nTotal = 0;
185843:       int iSeg;
185844: 
185845:       if( i>=nData ){
185846:         rc = FTS5_CORRUPT;
185847:       }else{
185848:         i += fts5GetVarint32(&pData[i], pLvl->nMerge);
185849:         i += fts5GetVarint32(&pData[i], nTotal);
185850:         assert( nTotal>=pLvl->nMerge );
185851:         pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc, 
185852:             nTotal * sizeof(Fts5StructureSegment)
185853:         );
185854:       }
185855: 
185856:       if( rc==SQLITE_OK ){
185857:         pLvl->nSeg = nTotal;
185858:         for(iSeg=0; iSeg<nTotal; iSeg++){
185859:           if( i>=nData ){
185860:             rc = FTS5_CORRUPT;
185861:             break;
185862:           }
185863:           i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
185864:           i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
185865:           i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
185866:         }
185867:       }
185868:     }
185869:     if( rc!=SQLITE_OK ){
185870:       fts5StructureRelease(pRet);
185871:       pRet = 0;
185872:     }
185873:   }
185874: 
185875:   *ppOut = pRet;
185876:   return rc;
185877: }
185878: 
185879: /*
185880: **
185881: */
185882: static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
185883:   if( *pRc==SQLITE_OK ){
185884:     Fts5Structure *pStruct = *ppStruct;
185885:     int nLevel = pStruct->nLevel;
185886:     int nByte = (
185887:         sizeof(Fts5Structure) +                  /* Main structure */
185888:         sizeof(Fts5StructureLevel) * (nLevel+1)  /* aLevel[] array */
185889:     );
185890: 
185891:     pStruct = sqlite3_realloc(pStruct, nByte);
185892:     if( pStruct ){
185893:       memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
185894:       pStruct->nLevel++;
185895:       *ppStruct = pStruct;
185896:     }else{
185897:       *pRc = SQLITE_NOMEM;
185898:     }
185899:   }
185900: }
185901: 
185902: /*
185903: ** Extend level iLvl so that there is room for at least nExtra more
185904: ** segments.
185905: */
185906: static void fts5StructureExtendLevel(
185907:   int *pRc, 
185908:   Fts5Structure *pStruct, 
185909:   int iLvl, 
185910:   int nExtra, 
185911:   int bInsert
185912: ){
185913:   if( *pRc==SQLITE_OK ){
185914:     Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
185915:     Fts5StructureSegment *aNew;
185916:     int nByte;
185917: 
185918:     nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
185919:     aNew = sqlite3_realloc(pLvl->aSeg, nByte);
185920:     if( aNew ){
185921:       if( bInsert==0 ){
185922:         memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
185923:       }else{
185924:         int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
185925:         memmove(&aNew[nExtra], aNew, nMove);
185926:         memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
185927:       }
185928:       pLvl->aSeg = aNew;
185929:     }else{
185930:       *pRc = SQLITE_NOMEM;
185931:     }
185932:   }
185933: }
185934: 
185935: static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
185936:   Fts5Structure *pRet = 0;
185937:   Fts5Config *pConfig = p->pConfig;
185938:   int iCookie;                    /* Configuration cookie */
185939:   Fts5Data *pData;
185940: 
185941:   pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
185942:   if( p->rc==SQLITE_OK ){
185943:     /* TODO: Do we need this if the leaf-index is appended? Probably... */
185944:     memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
185945:     p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
185946:     if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
185947:       p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
185948:     }
185949:     fts5DataRelease(pData);
185950:     if( p->rc!=SQLITE_OK ){
185951:       fts5StructureRelease(pRet);
185952:       pRet = 0;
185953:     }
185954:   }
185955: 
185956:   return pRet;
185957: }
185958: 
185959: static i64 fts5IndexDataVersion(Fts5Index *p){
185960:   i64 iVersion = 0;
185961: 
185962:   if( p->rc==SQLITE_OK ){
185963:     if( p->pDataVersion==0 ){
185964:       p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion, 
185965:           sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
185966:           );
185967:       if( p->rc ) return 0;
185968:     }
185969: 
185970:     if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
185971:       iVersion = sqlite3_column_int64(p->pDataVersion, 0);
185972:     }
185973:     p->rc = sqlite3_reset(p->pDataVersion);
185974:   }
185975: 
185976:   return iVersion;
185977: }
185978: 
185979: /*
185980: ** Read, deserialize and return the structure record.
185981: **
185982: ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
185983: ** are over-allocated as described for function fts5StructureDecode() 
185984: ** above.
185985: **
185986: ** If an error occurs, NULL is returned and an error code left in the
185987: ** Fts5Index handle. If an error has already occurred when this function
185988: ** is called, it is a no-op.
185989: */
185990: static Fts5Structure *fts5StructureRead(Fts5Index *p){
185991: 
185992:   if( p->pStruct==0 ){
185993:     p->iStructVersion = fts5IndexDataVersion(p);
185994:     if( p->rc==SQLITE_OK ){
185995:       p->pStruct = fts5StructureReadUncached(p);
185996:     }
185997:   }
185998: 
185999: #if 0
186000:   else{
186001:     Fts5Structure *pTest = fts5StructureReadUncached(p);
186002:     if( pTest ){
186003:       int i, j;
186004:       assert_nc( p->pStruct->nSegment==pTest->nSegment );
186005:       assert_nc( p->pStruct->nLevel==pTest->nLevel );
186006:       for(i=0; i<pTest->nLevel; i++){
186007:         assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
186008:         assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
186009:         for(j=0; j<pTest->aLevel[i].nSeg; j++){
186010:           Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
186011:           Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
186012:           assert_nc( p1->iSegid==p2->iSegid );
186013:           assert_nc( p1->pgnoFirst==p2->pgnoFirst );
186014:           assert_nc( p1->pgnoLast==p2->pgnoLast );
186015:         }
186016:       }
186017:       fts5StructureRelease(pTest);
186018:     }
186019:   }
186020: #endif
186021: 
186022:   if( p->rc!=SQLITE_OK ) return 0;
186023:   assert( p->iStructVersion!=0 );
186024:   assert( p->pStruct!=0 );
186025:   fts5StructureRef(p->pStruct);
186026:   return p->pStruct;
186027: }
186028: 
186029: static void fts5StructureInvalidate(Fts5Index *p){
186030:   if( p->pStruct ){
186031:     fts5StructureRelease(p->pStruct);
186032:     p->pStruct = 0;
186033:   }
186034: }
186035: 
186036: /*
186037: ** Return the total number of segments in index structure pStruct. This
186038: ** function is only ever used as part of assert() conditions.
186039: */
186040: #ifdef SQLITE_DEBUG
186041: static int fts5StructureCountSegments(Fts5Structure *pStruct){
186042:   int nSegment = 0;               /* Total number of segments */
186043:   if( pStruct ){
186044:     int iLvl;                     /* Used to iterate through levels */
186045:     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
186046:       nSegment += pStruct->aLevel[iLvl].nSeg;
186047:     }
186048:   }
186049: 
186050:   return nSegment;
186051: }
186052: #endif
186053: 
186054: #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) {     \
186055:   assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) );             \
186056:   memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob);             \
186057:   (pBuf)->n += nBlob;                                      \
186058: }
186059: 
186060: #define fts5BufferSafeAppendVarint(pBuf, iVal) {                \
186061:   (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal));  \
186062:   assert( (pBuf)->nSpace>=(pBuf)->n );                          \
186063: }
186064: 
186065: 
186066: /*
186067: ** Serialize and store the "structure" record.
186068: **
186069: ** If an error occurs, leave an error code in the Fts5Index object. If an
186070: ** error has already occurred, this function is a no-op.
186071: */
186072: static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
186073:   if( p->rc==SQLITE_OK ){
186074:     Fts5Buffer buf;               /* Buffer to serialize record into */
186075:     int iLvl;                     /* Used to iterate through levels */
186076:     int iCookie;                  /* Cookie value to store */
186077: 
186078:     assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
186079:     memset(&buf, 0, sizeof(Fts5Buffer));
186080: 
186081:     /* Append the current configuration cookie */
186082:     iCookie = p->pConfig->iCookie;
186083:     if( iCookie<0 ) iCookie = 0;
186084: 
186085:     if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
186086:       sqlite3Fts5Put32(buf.p, iCookie);
186087:       buf.n = 4;
186088:       fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
186089:       fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
186090:       fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
186091:     }
186092: 
186093:     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
186094:       int iSeg;                     /* Used to iterate through segments */
186095:       Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
186096:       fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
186097:       fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
186098:       assert( pLvl->nMerge<=pLvl->nSeg );
186099: 
186100:       for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
186101:         fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
186102:         fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
186103:         fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
186104:       }
186105:     }
186106: 
186107:     fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
186108:     fts5BufferFree(&buf);
186109:   }
186110: }
186111: 
186112: #if 0
186113: static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
186114: static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
186115:   int rc = SQLITE_OK;
186116:   Fts5Buffer buf;
186117:   memset(&buf, 0, sizeof(buf));
186118:   fts5DebugStructure(&rc, &buf, pStruct);
186119:   fprintf(stdout, "%s: %s\n", zCaption, buf.p);
186120:   fflush(stdout);
186121:   fts5BufferFree(&buf);
186122: }
186123: #else
186124: # define fts5PrintStructure(x,y)
186125: #endif
186126: 
186127: static int fts5SegmentSize(Fts5StructureSegment *pSeg){
186128:   return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
186129: }
186130: 
186131: /*
186132: ** Return a copy of index structure pStruct. Except, promote as many 
186133: ** segments as possible to level iPromote. If an OOM occurs, NULL is 
186134: ** returned.
186135: */
186136: static void fts5StructurePromoteTo(
186137:   Fts5Index *p,
186138:   int iPromote,
186139:   int szPromote,
186140:   Fts5Structure *pStruct
186141: ){
186142:   int il, is;
186143:   Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
186144: 
186145:   if( pOut->nMerge==0 ){
186146:     for(il=iPromote+1; il<pStruct->nLevel; il++){
186147:       Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
186148:       if( pLvl->nMerge ) return;
186149:       for(is=pLvl->nSeg-1; is>=0; is--){
186150:         int sz = fts5SegmentSize(&pLvl->aSeg[is]);
186151:         if( sz>szPromote ) return;
186152:         fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
186153:         if( p->rc ) return;
186154:         memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
186155:         pOut->nSeg++;
186156:         pLvl->nSeg--;
186157:       }
186158:     }
186159:   }
186160: }
186161: 
186162: /*
186163: ** A new segment has just been written to level iLvl of index structure
186164: ** pStruct. This function determines if any segments should be promoted
186165: ** as a result. Segments are promoted in two scenarios:
186166: **
186167: **   a) If the segment just written is smaller than one or more segments
186168: **      within the previous populated level, it is promoted to the previous
186169: **      populated level.
186170: **
186171: **   b) If the segment just written is larger than the newest segment on
186172: **      the next populated level, then that segment, and any other adjacent
186173: **      segments that are also smaller than the one just written, are 
186174: **      promoted. 
186175: **
186176: ** If one or more segments are promoted, the structure object is updated
186177: ** to reflect this.
186178: */
186179: static void fts5StructurePromote(
186180:   Fts5Index *p,                   /* FTS5 backend object */
186181:   int iLvl,                       /* Index level just updated */
186182:   Fts5Structure *pStruct          /* Index structure */
186183: ){
186184:   if( p->rc==SQLITE_OK ){
186185:     int iTst;
186186:     int iPromote = -1;
186187:     int szPromote = 0;            /* Promote anything this size or smaller */
186188:     Fts5StructureSegment *pSeg;   /* Segment just written */
186189:     int szSeg;                    /* Size of segment just written */
186190:     int nSeg = pStruct->aLevel[iLvl].nSeg;
186191: 
186192:     if( nSeg==0 ) return;
186193:     pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
186194:     szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
186195: 
186196:     /* Check for condition (a) */
186197:     for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
186198:     if( iTst>=0 ){
186199:       int i;
186200:       int szMax = 0;
186201:       Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
186202:       assert( pTst->nMerge==0 );
186203:       for(i=0; i<pTst->nSeg; i++){
186204:         int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
186205:         if( sz>szMax ) szMax = sz;
186206:       }
186207:       if( szMax>=szSeg ){
186208:         /* Condition (a) is true. Promote the newest segment on level 
186209:         ** iLvl to level iTst.  */
186210:         iPromote = iTst;
186211:         szPromote = szMax;
186212:       }
186213:     }
186214: 
186215:     /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
186216:     ** is a no-op if it is not.  */
186217:     if( iPromote<0 ){
186218:       iPromote = iLvl;
186219:       szPromote = szSeg;
186220:     }
186221:     fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
186222:   }
186223: }
186224: 
186225: 
186226: /*
186227: ** Advance the iterator passed as the only argument. If the end of the 
186228: ** doclist-index page is reached, return non-zero.
186229: */
186230: static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
186231:   Fts5Data *pData = pLvl->pData;
186232: 
186233:   if( pLvl->iOff==0 ){
186234:     assert( pLvl->bEof==0 );
186235:     pLvl->iOff = 1;
186236:     pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
186237:     pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
186238:     pLvl->iFirstOff = pLvl->iOff;
186239:   }else{
186240:     int iOff;
186241:     for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
186242:       if( pData->p[iOff] ) break; 
186243:     }
186244: 
186245:     if( iOff<pData->nn ){
186246:       i64 iVal;
186247:       pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
186248:       iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
186249:       pLvl->iRowid += iVal;
186250:       pLvl->iOff = iOff;
186251:     }else{
186252:       pLvl->bEof = 1;
186253:     }
186254:   }
186255: 
186256:   return pLvl->bEof;
186257: }
186258: 
186259: /*
186260: ** Advance the iterator passed as the only argument.
186261: */
186262: static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
186263:   Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
186264: 
186265:   assert( iLvl<pIter->nLvl );
186266:   if( fts5DlidxLvlNext(pLvl) ){
186267:     if( (iLvl+1) < pIter->nLvl ){
186268:       fts5DlidxIterNextR(p, pIter, iLvl+1);
186269:       if( pLvl[1].bEof==0 ){
186270:         fts5DataRelease(pLvl->pData);
186271:         memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186272:         pLvl->pData = fts5DataRead(p, 
186273:             FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
186274:         );
186275:         if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
186276:       }
186277:     }
186278:   }
186279: 
186280:   return pIter->aLvl[0].bEof;
186281: }
186282: static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
186283:   return fts5DlidxIterNextR(p, pIter, 0);
186284: }
186285: 
186286: /*
186287: ** The iterator passed as the first argument has the following fields set
186288: ** as follows. This function sets up the rest of the iterator so that it
186289: ** points to the first rowid in the doclist-index.
186290: **
186291: **   pData:
186292: **     pointer to doclist-index record, 
186293: **
186294: ** When this function is called pIter->iLeafPgno is the page number the
186295: ** doclist is associated with (the one featuring the term).
186296: */
186297: static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
186298:   int i;
186299:   for(i=0; i<pIter->nLvl; i++){
186300:     fts5DlidxLvlNext(&pIter->aLvl[i]);
186301:   }
186302:   return pIter->aLvl[0].bEof;
186303: }
186304: 
186305: 
186306: static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
186307:   return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
186308: }
186309: 
186310: static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
186311:   int i;
186312: 
186313:   /* Advance each level to the last entry on the last page */
186314:   for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
186315:     Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
186316:     while( fts5DlidxLvlNext(pLvl)==0 );
186317:     pLvl->bEof = 0;
186318: 
186319:     if( i>0 ){
186320:       Fts5DlidxLvl *pChild = &pLvl[-1];
186321:       fts5DataRelease(pChild->pData);
186322:       memset(pChild, 0, sizeof(Fts5DlidxLvl));
186323:       pChild->pData = fts5DataRead(p, 
186324:           FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
186325:       );
186326:     }
186327:   }
186328: }
186329: 
186330: /*
186331: ** Move the iterator passed as the only argument to the previous entry.
186332: */
186333: static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
186334:   int iOff = pLvl->iOff;
186335: 
186336:   assert( pLvl->bEof==0 );
186337:   if( iOff<=pLvl->iFirstOff ){
186338:     pLvl->bEof = 1;
186339:   }else{
186340:     u8 *a = pLvl->pData->p;
186341:     i64 iVal;
186342:     int iLimit;
186343:     int ii;
186344:     int nZero = 0;
186345: 
186346:     /* Currently iOff points to the first byte of a varint. This block 
186347:     ** decrements iOff until it points to the first byte of the previous 
186348:     ** varint. Taking care not to read any memory locations that occur
186349:     ** before the buffer in memory.  */
186350:     iLimit = (iOff>9 ? iOff-9 : 0);
186351:     for(iOff--; iOff>iLimit; iOff--){
186352:       if( (a[iOff-1] & 0x80)==0 ) break;
186353:     }
186354: 
186355:     fts5GetVarint(&a[iOff], (u64*)&iVal);
186356:     pLvl->iRowid -= iVal;
186357:     pLvl->iLeafPgno--;
186358: 
186359:     /* Skip backwards past any 0x00 varints. */
186360:     for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
186361:       nZero++;
186362:     }
186363:     if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
186364:       /* The byte immediately before the last 0x00 byte has the 0x80 bit
186365:       ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
186366:       ** bytes before a[ii]. */
186367:       int bZero = 0;              /* True if last 0x00 counts */
186368:       if( (ii-8)>=pLvl->iFirstOff ){
186369:         int j;
186370:         for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
186371:         bZero = (j>8);
186372:       }
186373:       if( bZero==0 ) nZero--;
186374:     }
186375:     pLvl->iLeafPgno -= nZero;
186376:     pLvl->iOff = iOff - nZero;
186377:   }
186378: 
186379:   return pLvl->bEof;
186380: }
186381: 
186382: static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
186383:   Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
186384: 
186385:   assert( iLvl<pIter->nLvl );
186386:   if( fts5DlidxLvlPrev(pLvl) ){
186387:     if( (iLvl+1) < pIter->nLvl ){
186388:       fts5DlidxIterPrevR(p, pIter, iLvl+1);
186389:       if( pLvl[1].bEof==0 ){
186390:         fts5DataRelease(pLvl->pData);
186391:         memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186392:         pLvl->pData = fts5DataRead(p, 
186393:             FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
186394:         );
186395:         if( pLvl->pData ){
186396:           while( fts5DlidxLvlNext(pLvl)==0 );
186397:           pLvl->bEof = 0;
186398:         }
186399:       }
186400:     }
186401:   }
186402: 
186403:   return pIter->aLvl[0].bEof;
186404: }
186405: static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
186406:   return fts5DlidxIterPrevR(p, pIter, 0);
186407: }
186408: 
186409: /*
186410: ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
186411: */
186412: static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
186413:   if( pIter ){
186414:     int i;
186415:     for(i=0; i<pIter->nLvl; i++){
186416:       fts5DataRelease(pIter->aLvl[i].pData);
186417:     }
186418:     sqlite3_free(pIter);
186419:   }
186420: }
186421: 
186422: static Fts5DlidxIter *fts5DlidxIterInit(
186423:   Fts5Index *p,                   /* Fts5 Backend to iterate within */
186424:   int bRev,                       /* True for ORDER BY ASC */
186425:   int iSegid,                     /* Segment id */
186426:   int iLeafPg                     /* Leaf page number to load dlidx for */
186427: ){
186428:   Fts5DlidxIter *pIter = 0;
186429:   int i;
186430:   int bDone = 0;
186431: 
186432:   for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
186433:     int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
186434:     Fts5DlidxIter *pNew;
186435: 
186436:     pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
186437:     if( pNew==0 ){
186438:       p->rc = SQLITE_NOMEM;
186439:     }else{
186440:       i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
186441:       Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
186442:       pIter = pNew;
186443:       memset(pLvl, 0, sizeof(Fts5DlidxLvl));
186444:       pLvl->pData = fts5DataRead(p, iRowid);
186445:       if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
186446:         bDone = 1;
186447:       }
186448:       pIter->nLvl = i+1;
186449:     }
186450:   }
186451: 
186452:   if( p->rc==SQLITE_OK ){
186453:     pIter->iSegid = iSegid;
186454:     if( bRev==0 ){
186455:       fts5DlidxIterFirst(pIter);
186456:     }else{
186457:       fts5DlidxIterLast(p, pIter);
186458:     }
186459:   }
186460: 
186461:   if( p->rc!=SQLITE_OK ){
186462:     fts5DlidxIterFree(pIter);
186463:     pIter = 0;
186464:   }
186465: 
186466:   return pIter;
186467: }
186468: 
186469: static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
186470:   return pIter->aLvl[0].iRowid;
186471: }
186472: static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
186473:   return pIter->aLvl[0].iLeafPgno;
186474: }
186475: 
186476: /*
186477: ** Load the next leaf page into the segment iterator.
186478: */
186479: static void fts5SegIterNextPage(
186480:   Fts5Index *p,                   /* FTS5 backend object */
186481:   Fts5SegIter *pIter              /* Iterator to advance to next page */
186482: ){
186483:   Fts5Data *pLeaf;
186484:   Fts5StructureSegment *pSeg = pIter->pSeg;
186485:   fts5DataRelease(pIter->pLeaf);
186486:   pIter->iLeafPgno++;
186487:   if( pIter->pNextLeaf ){
186488:     pIter->pLeaf = pIter->pNextLeaf;
186489:     pIter->pNextLeaf = 0;
186490:   }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
186491:     pIter->pLeaf = fts5DataRead(p, 
186492:         FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
186493:     );
186494:   }else{
186495:     pIter->pLeaf = 0;
186496:   }
186497:   pLeaf = pIter->pLeaf;
186498: 
186499:   if( pLeaf ){
186500:     pIter->iPgidxOff = pLeaf->szLeaf;
186501:     if( fts5LeafIsTermless(pLeaf) ){
186502:       pIter->iEndofDoclist = pLeaf->nn+1;
186503:     }else{
186504:       pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
186505:           pIter->iEndofDoclist
186506:       );
186507:     }
186508:   }
186509: }
186510: 
186511: /*
186512: ** Argument p points to a buffer containing a varint to be interpreted as a
186513: ** position list size field. Read the varint and return the number of bytes
186514: ** read. Before returning, set *pnSz to the number of bytes in the position
186515: ** list, and *pbDel to true if the delete flag is set, or false otherwise.
186516: */
186517: static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
186518:   int nSz;
186519:   int n = 0;
186520:   fts5FastGetVarint32(p, n, nSz);
186521:   assert_nc( nSz>=0 );
186522:   *pnSz = nSz/2;
186523:   *pbDel = nSz & 0x0001;
186524:   return n;
186525: }
186526: 
186527: /*
186528: ** Fts5SegIter.iLeafOffset currently points to the first byte of a
186529: ** position-list size field. Read the value of the field and store it
186530: ** in the following variables:
186531: **
186532: **   Fts5SegIter.nPos
186533: **   Fts5SegIter.bDel
186534: **
186535: ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the 
186536: ** position list content (if any).
186537: */
186538: static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
186539:   if( p->rc==SQLITE_OK ){
186540:     int iOff = pIter->iLeafOffset;  /* Offset to read at */
186541:     ASSERT_SZLEAF_OK(pIter->pLeaf);
186542:     if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
186543:       int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
186544:       pIter->bDel = 0;
186545:       pIter->nPos = 1;
186546:       if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
186547:         pIter->bDel = 1;
186548:         iOff++;
186549:         if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
186550:           pIter->nPos = 1;
186551:           iOff++;
186552:         }else{
186553:           pIter->nPos = 0;
186554:         }
186555:       }
186556:     }else{
186557:       int nSz;
186558:       fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
186559:       pIter->bDel = (nSz & 0x0001);
186560:       pIter->nPos = nSz>>1;
186561:       assert_nc( pIter->nPos>=0 );
186562:     }
186563:     pIter->iLeafOffset = iOff;
186564:   }
186565: }
186566: 
186567: static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
186568:   u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
186569:   int iOff = pIter->iLeafOffset;
186570: 
186571:   ASSERT_SZLEAF_OK(pIter->pLeaf);
186572:   if( iOff>=pIter->pLeaf->szLeaf ){
186573:     fts5SegIterNextPage(p, pIter);
186574:     if( pIter->pLeaf==0 ){
186575:       if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
186576:       return;
186577:     }
186578:     iOff = 4;
186579:     a = pIter->pLeaf->p;
186580:   }
186581:   iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
186582:   pIter->iLeafOffset = iOff;
186583: }
186584: 
186585: /*
186586: ** Fts5SegIter.iLeafOffset currently points to the first byte of the 
186587: ** "nSuffix" field of a term. Function parameter nKeep contains the value
186588: ** of the "nPrefix" field (if there was one - it is passed 0 if this is
186589: ** the first term in the segment).
186590: **
186591: ** This function populates:
186592: **
186593: **   Fts5SegIter.term
186594: **   Fts5SegIter.rowid
186595: **
186596: ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
186597: ** the first position list. The position list belonging to document 
186598: ** (Fts5SegIter.iRowid).
186599: */
186600: static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
186601:   u8 *a = pIter->pLeaf->p;        /* Buffer to read data from */
186602:   int iOff = pIter->iLeafOffset;  /* Offset to read at */
186603:   int nNew;                       /* Bytes of new data */
186604: 
186605:   iOff += fts5GetVarint32(&a[iOff], nNew);
186606:   if( iOff+nNew>pIter->pLeaf->nn ){
186607:     p->rc = FTS5_CORRUPT;
186608:     return;
186609:   }
186610:   pIter->term.n = nKeep;
186611:   fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
186612:   iOff += nNew;
186613:   pIter->iTermLeafOffset = iOff;
186614:   pIter->iTermLeafPgno = pIter->iLeafPgno;
186615:   pIter->iLeafOffset = iOff;
186616: 
186617:   if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
186618:     pIter->iEndofDoclist = pIter->pLeaf->nn+1;
186619:   }else{
186620:     int nExtra;
186621:     pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
186622:     pIter->iEndofDoclist += nExtra;
186623:   }
186624: 
186625:   fts5SegIterLoadRowid(p, pIter);
186626: }
186627: 
186628: static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
186629: static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
186630: static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
186631: 
186632: static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
186633:   if( pIter->flags & FTS5_SEGITER_REVERSE ){
186634:     pIter->xNext = fts5SegIterNext_Reverse;
186635:   }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
186636:     pIter->xNext = fts5SegIterNext_None;
186637:   }else{
186638:     pIter->xNext = fts5SegIterNext;
186639:   }
186640: }
186641: 
186642: /*
186643: ** Initialize the iterator object pIter to iterate through the entries in
186644: ** segment pSeg. The iterator is left pointing to the first entry when 
186645: ** this function returns.
186646: **
186647: ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
186648: ** an error has already occurred when this function is called, it is a no-op.
186649: */
186650: static void fts5SegIterInit(
186651:   Fts5Index *p,                   /* FTS index object */
186652:   Fts5StructureSegment *pSeg,     /* Description of segment */
186653:   Fts5SegIter *pIter              /* Object to populate */
186654: ){
186655:   if( pSeg->pgnoFirst==0 ){
186656:     /* This happens if the segment is being used as an input to an incremental
186657:     ** merge and all data has already been "trimmed". See function
186658:     ** fts5TrimSegments() for details. In this case leave the iterator empty.
186659:     ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
186660:     ** at EOF already. */
186661:     assert( pIter->pLeaf==0 );
186662:     return;
186663:   }
186664: 
186665:   if( p->rc==SQLITE_OK ){
186666:     memset(pIter, 0, sizeof(*pIter));
186667:     fts5SegIterSetNext(p, pIter);
186668:     pIter->pSeg = pSeg;
186669:     pIter->iLeafPgno = pSeg->pgnoFirst-1;
186670:     fts5SegIterNextPage(p, pIter);
186671:   }
186672: 
186673:   if( p->rc==SQLITE_OK ){
186674:     pIter->iLeafOffset = 4;
186675:     assert_nc( pIter->pLeaf->nn>4 );
186676:     assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
186677:     pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
186678:     fts5SegIterLoadTerm(p, pIter, 0);
186679:     fts5SegIterLoadNPos(p, pIter);
186680:   }
186681: }
186682: 
186683: /*
186684: ** This function is only ever called on iterators created by calls to
186685: ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
186686: **
186687: ** The iterator is in an unusual state when this function is called: the
186688: ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
186689: ** the position-list size field for the first relevant rowid on the page.
186690: ** Fts5SegIter.rowid is set, but nPos and bDel are not.
186691: **
186692: ** This function advances the iterator so that it points to the last 
186693: ** relevant rowid on the page and, if necessary, initializes the 
186694: ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
186695: ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
186696: ** byte of the position list content associated with said rowid.
186697: */
186698: static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
186699:   int eDetail = p->pConfig->eDetail;
186700:   int n = pIter->pLeaf->szLeaf;
186701:   int i = pIter->iLeafOffset;
186702:   u8 *a = pIter->pLeaf->p;
186703:   int iRowidOffset = 0;
186704: 
186705:   if( n>pIter->iEndofDoclist ){
186706:     n = pIter->iEndofDoclist;
186707:   }
186708: 
186709:   ASSERT_SZLEAF_OK(pIter->pLeaf);
186710:   while( 1 ){
186711:     i64 iDelta = 0;
186712: 
186713:     if( eDetail==FTS5_DETAIL_NONE ){
186714:       /* todo */
186715:       if( i<n && a[i]==0 ){
186716:         i++;
186717:         if( i<n && a[i]==0 ) i++;
186718:       }
186719:     }else{
186720:       int nPos;
186721:       int bDummy;
186722:       i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
186723:       i += nPos;
186724:     }
186725:     if( i>=n ) break;
186726:     i += fts5GetVarint(&a[i], (u64*)&iDelta);
186727:     pIter->iRowid += iDelta;
186728: 
186729:     /* If necessary, grow the pIter->aRowidOffset[] array. */
186730:     if( iRowidOffset>=pIter->nRowidOffset ){
186731:       int nNew = pIter->nRowidOffset + 8;
186732:       int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
186733:       if( aNew==0 ){
186734:         p->rc = SQLITE_NOMEM;
186735:         break;
186736:       }
186737:       pIter->aRowidOffset = aNew;
186738:       pIter->nRowidOffset = nNew;
186739:     }
186740: 
186741:     pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
186742:     pIter->iLeafOffset = i;
186743:   }
186744:   pIter->iRowidOffset = iRowidOffset;
186745:   fts5SegIterLoadNPos(p, pIter);
186746: }
186747: 
186748: /*
186749: **
186750: */
186751: static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
186752:   assert( pIter->flags & FTS5_SEGITER_REVERSE );
186753:   assert( pIter->flags & FTS5_SEGITER_ONETERM );
186754: 
186755:   fts5DataRelease(pIter->pLeaf);
186756:   pIter->pLeaf = 0;
186757:   while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
186758:     Fts5Data *pNew;
186759:     pIter->iLeafPgno--;
186760:     pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
186761:           pIter->pSeg->iSegid, pIter->iLeafPgno
186762:     ));
186763:     if( pNew ){
186764:       /* iTermLeafOffset may be equal to szLeaf if the term is the last
186765:       ** thing on the page - i.e. the first rowid is on the following page.
186766:       ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
186767:       if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
186768:         assert( pIter->pLeaf==0 );
186769:         if( pIter->iTermLeafOffset<pNew->szLeaf ){
186770:           pIter->pLeaf = pNew;
186771:           pIter->iLeafOffset = pIter->iTermLeafOffset;
186772:         }
186773:       }else{
186774:         int iRowidOff;
186775:         iRowidOff = fts5LeafFirstRowidOff(pNew);
186776:         if( iRowidOff ){
186777:           pIter->pLeaf = pNew;
186778:           pIter->iLeafOffset = iRowidOff;
186779:         }
186780:       }
186781: 
186782:       if( pIter->pLeaf ){
186783:         u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
186784:         pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
186785:         break;
186786:       }else{
186787:         fts5DataRelease(pNew);
186788:       }
186789:     }
186790:   }
186791: 
186792:   if( pIter->pLeaf ){
186793:     pIter->iEndofDoclist = pIter->pLeaf->nn+1;
186794:     fts5SegIterReverseInitPage(p, pIter);
186795:   }
186796: }
186797: 
186798: /*
186799: ** Return true if the iterator passed as the second argument currently
186800: ** points to a delete marker. A delete marker is an entry with a 0 byte
186801: ** position-list.
186802: */
186803: static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
186804:   Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
186805:   return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
186806: }
186807: 
186808: /*
186809: ** Advance iterator pIter to the next entry.
186810: **
186811: ** This version of fts5SegIterNext() is only used by reverse iterators.
186812: */
186813: static void fts5SegIterNext_Reverse(
186814:   Fts5Index *p,                   /* FTS5 backend object */
186815:   Fts5SegIter *pIter,             /* Iterator to advance */
186816:   int *pbUnused                   /* Unused */
186817: ){
186818:   assert( pIter->flags & FTS5_SEGITER_REVERSE );
186819:   assert( pIter->pNextLeaf==0 );
186820:   UNUSED_PARAM(pbUnused);
186821: 
186822:   if( pIter->iRowidOffset>0 ){
186823:     u8 *a = pIter->pLeaf->p;
186824:     int iOff;
186825:     i64 iDelta;
186826: 
186827:     pIter->iRowidOffset--;
186828:     pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
186829:     fts5SegIterLoadNPos(p, pIter);
186830:     iOff = pIter->iLeafOffset;
186831:     if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
186832:       iOff += pIter->nPos;
186833:     }
186834:     fts5GetVarint(&a[iOff], (u64*)&iDelta);
186835:     pIter->iRowid -= iDelta;
186836:   }else{
186837:     fts5SegIterReverseNewPage(p, pIter);
186838:   }
186839: }
186840: 
186841: /*
186842: ** Advance iterator pIter to the next entry.
186843: **
186844: ** This version of fts5SegIterNext() is only used if detail=none and the
186845: ** iterator is not a reverse direction iterator.
186846: */
186847: static void fts5SegIterNext_None(
186848:   Fts5Index *p,                   /* FTS5 backend object */
186849:   Fts5SegIter *pIter,             /* Iterator to advance */
186850:   int *pbNewTerm                  /* OUT: Set for new term */
186851: ){
186852:   int iOff;
186853: 
186854:   assert( p->rc==SQLITE_OK );
186855:   assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
186856:   assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
186857: 
186858:   ASSERT_SZLEAF_OK(pIter->pLeaf);
186859:   iOff = pIter->iLeafOffset;
186860: 
186861:   /* Next entry is on the next page */
186862:   if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
186863:     fts5SegIterNextPage(p, pIter);
186864:     if( p->rc || pIter->pLeaf==0 ) return;
186865:     pIter->iRowid = 0;
186866:     iOff = 4;
186867:   }
186868: 
186869:   if( iOff<pIter->iEndofDoclist ){
186870:     /* Next entry is on the current page */
186871:     i64 iDelta;
186872:     iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
186873:     pIter->iLeafOffset = iOff;
186874:     pIter->iRowid += iDelta;
186875:   }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
186876:     if( pIter->pSeg ){
186877:       int nKeep = 0;
186878:       if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
186879:         iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
186880:       }
186881:       pIter->iLeafOffset = iOff;
186882:       fts5SegIterLoadTerm(p, pIter, nKeep);
186883:     }else{
186884:       const u8 *pList = 0;
186885:       const char *zTerm = 0;
186886:       int nList;
186887:       sqlite3Fts5HashScanNext(p->pHash);
186888:       sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
186889:       if( pList==0 ) goto next_none_eof;
186890:       pIter->pLeaf->p = (u8*)pList;
186891:       pIter->pLeaf->nn = nList;
186892:       pIter->pLeaf->szLeaf = nList;
186893:       pIter->iEndofDoclist = nList;
186894:       sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
186895:       pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
186896:     }
186897: 
186898:     if( pbNewTerm ) *pbNewTerm = 1;
186899:   }else{
186900:     goto next_none_eof;
186901:   }
186902: 
186903:   fts5SegIterLoadNPos(p, pIter);
186904: 
186905:   return;
186906:  next_none_eof:
186907:   fts5DataRelease(pIter->pLeaf);
186908:   pIter->pLeaf = 0;
186909: }
186910: 
186911: 
186912: /*
186913: ** Advance iterator pIter to the next entry. 
186914: **
186915: ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It 
186916: ** is not considered an error if the iterator reaches EOF. If an error has 
186917: ** already occurred when this function is called, it is a no-op.
186918: */
186919: static void fts5SegIterNext(
186920:   Fts5Index *p,                   /* FTS5 backend object */
186921:   Fts5SegIter *pIter,             /* Iterator to advance */
186922:   int *pbNewTerm                  /* OUT: Set for new term */
186923: ){
186924:   Fts5Data *pLeaf = pIter->pLeaf;
186925:   int iOff;
186926:   int bNewTerm = 0;
186927:   int nKeep = 0;
186928:   u8 *a;
186929:   int n;
186930: 
186931:   assert( pbNewTerm==0 || *pbNewTerm==0 );
186932:   assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
186933: 
186934:   /* Search for the end of the position list within the current page. */
186935:   a = pLeaf->p;
186936:   n = pLeaf->szLeaf;
186937: 
186938:   ASSERT_SZLEAF_OK(pLeaf);
186939:   iOff = pIter->iLeafOffset + pIter->nPos;
186940: 
186941:   if( iOff<n ){
186942:     /* The next entry is on the current page. */
186943:     assert_nc( iOff<=pIter->iEndofDoclist );
186944:     if( iOff>=pIter->iEndofDoclist ){
186945:       bNewTerm = 1;
186946:       if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
186947:         iOff += fts5GetVarint32(&a[iOff], nKeep);
186948:       }
186949:     }else{
186950:       u64 iDelta;
186951:       iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
186952:       pIter->iRowid += iDelta;
186953:       assert_nc( iDelta>0 );
186954:     }
186955:     pIter->iLeafOffset = iOff;
186956: 
186957:   }else if( pIter->pSeg==0 ){
186958:     const u8 *pList = 0;
186959:     const char *zTerm = 0;
186960:     int nList = 0;
186961:     assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
186962:     if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
186963:       sqlite3Fts5HashScanNext(p->pHash);
186964:       sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
186965:     }
186966:     if( pList==0 ){
186967:       fts5DataRelease(pIter->pLeaf);
186968:       pIter->pLeaf = 0;
186969:     }else{
186970:       pIter->pLeaf->p = (u8*)pList;
186971:       pIter->pLeaf->nn = nList;
186972:       pIter->pLeaf->szLeaf = nList;
186973:       pIter->iEndofDoclist = nList+1;
186974:       sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
186975:           (u8*)zTerm);
186976:       pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
186977:       *pbNewTerm = 1;
186978:     }
186979:   }else{
186980:     iOff = 0;
186981:     /* Next entry is not on the current page */
186982:     while( iOff==0 ){
186983:       fts5SegIterNextPage(p, pIter);
186984:       pLeaf = pIter->pLeaf;
186985:       if( pLeaf==0 ) break;
186986:       ASSERT_SZLEAF_OK(pLeaf);
186987:       if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
186988:         iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
186989:         pIter->iLeafOffset = iOff;
186990: 
186991:         if( pLeaf->nn>pLeaf->szLeaf ){
186992:           pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
186993:               &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
186994:               );
186995:         }
186996: 
186997:       }
186998:       else if( pLeaf->nn>pLeaf->szLeaf ){
186999:         pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
187000:             &pLeaf->p[pLeaf->szLeaf], iOff
187001:             );
187002:         pIter->iLeafOffset = iOff;
187003:         pIter->iEndofDoclist = iOff;
187004:         bNewTerm = 1;
187005:       }
187006:       assert_nc( iOff<pLeaf->szLeaf );
187007:       if( iOff>pLeaf->szLeaf ){
187008:         p->rc = FTS5_CORRUPT;
187009:         return;
187010:       }
187011:     }
187012:   }
187013: 
187014:   /* Check if the iterator is now at EOF. If so, return early. */
187015:   if( pIter->pLeaf ){
187016:     if( bNewTerm ){
187017:       if( pIter->flags & FTS5_SEGITER_ONETERM ){
187018:         fts5DataRelease(pIter->pLeaf);
187019:         pIter->pLeaf = 0;
187020:       }else{
187021:         fts5SegIterLoadTerm(p, pIter, nKeep);
187022:         fts5SegIterLoadNPos(p, pIter);
187023:         if( pbNewTerm ) *pbNewTerm = 1;
187024:       }
187025:     }else{
187026:       /* The following could be done by calling fts5SegIterLoadNPos(). But
187027:       ** this block is particularly performance critical, so equivalent
187028:       ** code is inlined. 
187029:       **
187030:       ** Later: Switched back to fts5SegIterLoadNPos() because it supports
187031:       ** detail=none mode. Not ideal.
187032:       */
187033:       int nSz;
187034:       assert( p->rc==SQLITE_OK );
187035:       fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
187036:       pIter->bDel = (nSz & 0x0001);
187037:       pIter->nPos = nSz>>1;
187038:       assert_nc( pIter->nPos>=0 );
187039:     }
187040:   }
187041: }
187042: 
187043: #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
187044: 
187045: #define fts5IndexSkipVarint(a, iOff) {            \
187046:   int iEnd = iOff+9;                              \
187047:   while( (a[iOff++] & 0x80) && iOff<iEnd );       \
187048: }
187049: 
187050: /*
187051: ** Iterator pIter currently points to the first rowid in a doclist. This
187052: ** function sets the iterator up so that iterates in reverse order through
187053: ** the doclist.
187054: */
187055: static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
187056:   Fts5DlidxIter *pDlidx = pIter->pDlidx;
187057:   Fts5Data *pLast = 0;
187058:   int pgnoLast = 0;
187059: 
187060:   if( pDlidx ){
187061:     int iSegid = pIter->pSeg->iSegid;
187062:     pgnoLast = fts5DlidxIterPgno(pDlidx);
187063:     pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
187064:   }else{
187065:     Fts5Data *pLeaf = pIter->pLeaf;         /* Current leaf data */
187066: 
187067:     /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
187068:     ** position-list content for the current rowid. Back it up so that it
187069:     ** points to the start of the position-list size field. */
187070:     int iPoslist;
187071:     if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
187072:       iPoslist = pIter->iTermLeafOffset;
187073:     }else{
187074:       iPoslist = 4;
187075:     }
187076:     fts5IndexSkipVarint(pLeaf->p, iPoslist);
187077:     pIter->iLeafOffset = iPoslist;
187078: 
187079:     /* If this condition is true then the largest rowid for the current
187080:     ** term may not be stored on the current page. So search forward to
187081:     ** see where said rowid really is.  */
187082:     if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
187083:       int pgno;
187084:       Fts5StructureSegment *pSeg = pIter->pSeg;
187085: 
187086:       /* The last rowid in the doclist may not be on the current page. Search
187087:       ** forward to find the page containing the last rowid.  */
187088:       for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
187089:         i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
187090:         Fts5Data *pNew = fts5DataRead(p, iAbs);
187091:         if( pNew ){
187092:           int iRowid, bTermless;
187093:           iRowid = fts5LeafFirstRowidOff(pNew);
187094:           bTermless = fts5LeafIsTermless(pNew);
187095:           if( iRowid ){
187096:             SWAPVAL(Fts5Data*, pNew, pLast);
187097:             pgnoLast = pgno;
187098:           }
187099:           fts5DataRelease(pNew);
187100:           if( bTermless==0 ) break;
187101:         }
187102:       }
187103:     }
187104:   }
187105: 
187106:   /* If pLast is NULL at this point, then the last rowid for this doclist
187107:   ** lies on the page currently indicated by the iterator. In this case 
187108:   ** pIter->iLeafOffset is already set to point to the position-list size
187109:   ** field associated with the first relevant rowid on the page.
187110:   **
187111:   ** Or, if pLast is non-NULL, then it is the page that contains the last
187112:   ** rowid. In this case configure the iterator so that it points to the
187113:   ** first rowid on this page.
187114:   */
187115:   if( pLast ){
187116:     int iOff;
187117:     fts5DataRelease(pIter->pLeaf);
187118:     pIter->pLeaf = pLast;
187119:     pIter->iLeafPgno = pgnoLast;
187120:     iOff = fts5LeafFirstRowidOff(pLast);
187121:     iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
187122:     pIter->iLeafOffset = iOff;
187123: 
187124:     if( fts5LeafIsTermless(pLast) ){
187125:       pIter->iEndofDoclist = pLast->nn+1;
187126:     }else{
187127:       pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
187128:     }
187129: 
187130:   }
187131: 
187132:   fts5SegIterReverseInitPage(p, pIter);
187133: }
187134: 
187135: /*
187136: ** Iterator pIter currently points to the first rowid of a doclist.
187137: ** There is a doclist-index associated with the final term on the current 
187138: ** page. If the current term is the last term on the page, load the 
187139: ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
187140: */
187141: static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
187142:   int iSeg = pIter->pSeg->iSegid;
187143:   int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
187144:   Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
187145: 
187146:   assert( pIter->flags & FTS5_SEGITER_ONETERM );
187147:   assert( pIter->pDlidx==0 );
187148: 
187149:   /* Check if the current doclist ends on this page. If it does, return
187150:   ** early without loading the doclist-index (as it belongs to a different
187151:   ** term. */
187152:   if( pIter->iTermLeafPgno==pIter->iLeafPgno 
187153:    && pIter->iEndofDoclist<pLeaf->szLeaf 
187154:   ){
187155:     return;
187156:   }
187157: 
187158:   pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
187159: }
187160: 
187161: /*
187162: ** The iterator object passed as the second argument currently contains
187163: ** no valid values except for the Fts5SegIter.pLeaf member variable. This
187164: ** function searches the leaf page for a term matching (pTerm/nTerm).
187165: **
187166: ** If the specified term is found on the page, then the iterator is left
187167: ** pointing to it. If argument bGe is zero and the term is not found,
187168: ** the iterator is left pointing at EOF.
187169: **
187170: ** If bGe is non-zero and the specified term is not found, then the
187171: ** iterator is left pointing to the smallest term in the segment that
187172: ** is larger than the specified term, even if this term is not on the
187173: ** current page.
187174: */
187175: static void fts5LeafSeek(
187176:   Fts5Index *p,                   /* Leave any error code here */
187177:   int bGe,                        /* True for a >= search */
187178:   Fts5SegIter *pIter,             /* Iterator to seek */
187179:   const u8 *pTerm, int nTerm      /* Term to search for */
187180: ){
187181:   int iOff;
187182:   const u8 *a = pIter->pLeaf->p;
187183:   int szLeaf = pIter->pLeaf->szLeaf;
187184:   int n = pIter->pLeaf->nn;
187185: 
187186:   int nMatch = 0;
187187:   int nKeep = 0;
187188:   int nNew = 0;
187189:   int iTermOff;
187190:   int iPgidx;                     /* Current offset in pgidx */
187191:   int bEndOfPage = 0;
187192: 
187193:   assert( p->rc==SQLITE_OK );
187194: 
187195:   iPgidx = szLeaf;
187196:   iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
187197:   iOff = iTermOff;
187198:   if( iOff>n ){
187199:     p->rc = FTS5_CORRUPT;
187200:     return;
187201:   }
187202: 
187203:   while( 1 ){
187204: 
187205:     /* Figure out how many new bytes are in this term */
187206:     fts5FastGetVarint32(a, iOff, nNew);
187207:     if( nKeep<nMatch ){
187208:       goto search_failed;
187209:     }
187210: 
187211:     assert( nKeep>=nMatch );
187212:     if( nKeep==nMatch ){
187213:       int nCmp;
187214:       int i;
187215:       nCmp = MIN(nNew, nTerm-nMatch);
187216:       for(i=0; i<nCmp; i++){
187217:         if( a[iOff+i]!=pTerm[nMatch+i] ) break;
187218:       }
187219:       nMatch += i;
187220: 
187221:       if( nTerm==nMatch ){
187222:         if( i==nNew ){
187223:           goto search_success;
187224:         }else{
187225:           goto search_failed;
187226:         }
187227:       }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
187228:         goto search_failed;
187229:       }
187230:     }
187231: 
187232:     if( iPgidx>=n ){
187233:       bEndOfPage = 1;
187234:       break;
187235:     }
187236: 
187237:     iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
187238:     iTermOff += nKeep;
187239:     iOff = iTermOff;
187240: 
187241:     /* Read the nKeep field of the next term. */
187242:     fts5FastGetVarint32(a, iOff, nKeep);
187243:   }
187244: 
187245:  search_failed:
187246:   if( bGe==0 ){
187247:     fts5DataRelease(pIter->pLeaf);
187248:     pIter->pLeaf = 0;
187249:     return;
187250:   }else if( bEndOfPage ){
187251:     do {
187252:       fts5SegIterNextPage(p, pIter);
187253:       if( pIter->pLeaf==0 ) return;
187254:       a = pIter->pLeaf->p;
187255:       if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
187256:         iPgidx = pIter->pLeaf->szLeaf;
187257:         iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
187258:         if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
187259:           p->rc = FTS5_CORRUPT;
187260:         }else{
187261:           nKeep = 0;
187262:           iTermOff = iOff;
187263:           n = pIter->pLeaf->nn;
187264:           iOff += fts5GetVarint32(&a[iOff], nNew);
187265:           break;
187266:         }
187267:       }
187268:     }while( 1 );
187269:   }
187270: 
187271:  search_success:
187272: 
187273:   pIter->iLeafOffset = iOff + nNew;
187274:   pIter->iTermLeafOffset = pIter->iLeafOffset;
187275:   pIter->iTermLeafPgno = pIter->iLeafPgno;
187276: 
187277:   fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
187278:   fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
187279: 
187280:   if( iPgidx>=n ){
187281:     pIter->iEndofDoclist = pIter->pLeaf->nn+1;
187282:   }else{
187283:     int nExtra;
187284:     iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
187285:     pIter->iEndofDoclist = iTermOff + nExtra;
187286:   }
187287:   pIter->iPgidxOff = iPgidx;
187288: 
187289:   fts5SegIterLoadRowid(p, pIter);
187290:   fts5SegIterLoadNPos(p, pIter);
187291: }
187292: 
187293: static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
187294:   if( p->pIdxSelect==0 ){
187295:     Fts5Config *pConfig = p->pConfig;
187296:     fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
187297:           "SELECT pgno FROM '%q'.'%q_idx' WHERE "
187298:           "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
187299:           pConfig->zDb, pConfig->zName
187300:     ));
187301:   }
187302:   return p->pIdxSelect;
187303: }
187304: 
187305: /*
187306: ** Initialize the object pIter to point to term pTerm/nTerm within segment
187307: ** pSeg. If there is no such term in the index, the iterator is set to EOF.
187308: **
187309: ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
187310: ** an error has already occurred when this function is called, it is a no-op.
187311: */
187312: static void fts5SegIterSeekInit(
187313:   Fts5Index *p,                   /* FTS5 backend */
187314:   const u8 *pTerm, int nTerm,     /* Term to seek to */
187315:   int flags,                      /* Mask of FTS5INDEX_XXX flags */
187316:   Fts5StructureSegment *pSeg,     /* Description of segment */
187317:   Fts5SegIter *pIter              /* Object to populate */
187318: ){
187319:   int iPg = 1;
187320:   int bGe = (flags & FTS5INDEX_QUERY_SCAN);
187321:   int bDlidx = 0;                 /* True if there is a doclist-index */
187322:   sqlite3_stmt *pIdxSelect = 0;
187323: 
187324:   assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
187325:   assert( pTerm && nTerm );
187326:   memset(pIter, 0, sizeof(*pIter));
187327:   pIter->pSeg = pSeg;
187328: 
187329:   /* This block sets stack variable iPg to the leaf page number that may
187330:   ** contain term (pTerm/nTerm), if it is present in the segment. */
187331:   pIdxSelect = fts5IdxSelectStmt(p);
187332:   if( p->rc ) return;
187333:   sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
187334:   sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
187335:   if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
187336:     i64 val = sqlite3_column_int(pIdxSelect, 0);
187337:     iPg = (int)(val>>1);
187338:     bDlidx = (val & 0x0001);
187339:   }
187340:   p->rc = sqlite3_reset(pIdxSelect);
187341: 
187342:   if( iPg<pSeg->pgnoFirst ){
187343:     iPg = pSeg->pgnoFirst;
187344:     bDlidx = 0;
187345:   }
187346: 
187347:   pIter->iLeafPgno = iPg - 1;
187348:   fts5SegIterNextPage(p, pIter);
187349: 
187350:   if( pIter->pLeaf ){
187351:     fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
187352:   }
187353: 
187354:   if( p->rc==SQLITE_OK && bGe==0 ){
187355:     pIter->flags |= FTS5_SEGITER_ONETERM;
187356:     if( pIter->pLeaf ){
187357:       if( flags & FTS5INDEX_QUERY_DESC ){
187358:         pIter->flags |= FTS5_SEGITER_REVERSE;
187359:       }
187360:       if( bDlidx ){
187361:         fts5SegIterLoadDlidx(p, pIter);
187362:       }
187363:       if( flags & FTS5INDEX_QUERY_DESC ){
187364:         fts5SegIterReverse(p, pIter);
187365:       }
187366:     }
187367:   }
187368: 
187369:   fts5SegIterSetNext(p, pIter);
187370: 
187371:   /* Either:
187372:   **
187373:   **   1) an error has occurred, or
187374:   **   2) the iterator points to EOF, or
187375:   **   3) the iterator points to an entry with term (pTerm/nTerm), or
187376:   **   4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
187377:   **      to an entry with a term greater than or equal to (pTerm/nTerm).
187378:   */
187379:   assert( p->rc!=SQLITE_OK                                          /* 1 */
187380:    || pIter->pLeaf==0                                               /* 2 */
187381:    || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0          /* 3 */
187382:    || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0)  /* 4 */
187383:   );
187384: }
187385: 
187386: /*
187387: ** Initialize the object pIter to point to term pTerm/nTerm within the
187388: ** in-memory hash table. If there is no such term in the hash-table, the 
187389: ** iterator is set to EOF.
187390: **
187391: ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If 
187392: ** an error has already occurred when this function is called, it is a no-op.
187393: */
187394: static void fts5SegIterHashInit(
187395:   Fts5Index *p,                   /* FTS5 backend */
187396:   const u8 *pTerm, int nTerm,     /* Term to seek to */
187397:   int flags,                      /* Mask of FTS5INDEX_XXX flags */
187398:   Fts5SegIter *pIter              /* Object to populate */
187399: ){
187400:   const u8 *pList = 0;
187401:   int nList = 0;
187402:   const u8 *z = 0;
187403:   int n = 0;
187404: 
187405:   assert( p->pHash );
187406:   assert( p->rc==SQLITE_OK );
187407: 
187408:   if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
187409:     p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
187410:     sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
187411:     n = (z ? (int)strlen((const char*)z) : 0);
187412:   }else{
187413:     pIter->flags |= FTS5_SEGITER_ONETERM;
187414:     sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
187415:     z = pTerm;
187416:     n = nTerm;
187417:   }
187418: 
187419:   if( pList ){
187420:     Fts5Data *pLeaf;
187421:     sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
187422:     pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
187423:     if( pLeaf==0 ) return;
187424:     pLeaf->p = (u8*)pList;
187425:     pLeaf->nn = pLeaf->szLeaf = nList;
187426:     pIter->pLeaf = pLeaf;
187427:     pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
187428:     pIter->iEndofDoclist = pLeaf->nn;
187429: 
187430:     if( flags & FTS5INDEX_QUERY_DESC ){
187431:       pIter->flags |= FTS5_SEGITER_REVERSE;
187432:       fts5SegIterReverseInitPage(p, pIter);
187433:     }else{
187434:       fts5SegIterLoadNPos(p, pIter);
187435:     }
187436:   }
187437: 
187438:   fts5SegIterSetNext(p, pIter);
187439: }
187440: 
187441: /*
187442: ** Zero the iterator passed as the only argument.
187443: */
187444: static void fts5SegIterClear(Fts5SegIter *pIter){
187445:   fts5BufferFree(&pIter->term);
187446:   fts5DataRelease(pIter->pLeaf);
187447:   fts5DataRelease(pIter->pNextLeaf);
187448:   fts5DlidxIterFree(pIter->pDlidx);
187449:   sqlite3_free(pIter->aRowidOffset);
187450:   memset(pIter, 0, sizeof(Fts5SegIter));
187451: }
187452: 
187453: #ifdef SQLITE_DEBUG
187454: 
187455: /*
187456: ** This function is used as part of the big assert() procedure implemented by
187457: ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
187458: ** in *pRes is the correct result of comparing the current positions of the
187459: ** two iterators.
187460: */
187461: static void fts5AssertComparisonResult(
187462:   Fts5Iter *pIter, 
187463:   Fts5SegIter *p1,
187464:   Fts5SegIter *p2,
187465:   Fts5CResult *pRes
187466: ){
187467:   int i1 = p1 - pIter->aSeg;
187468:   int i2 = p2 - pIter->aSeg;
187469: 
187470:   if( p1->pLeaf || p2->pLeaf ){
187471:     if( p1->pLeaf==0 ){
187472:       assert( pRes->iFirst==i2 );
187473:     }else if( p2->pLeaf==0 ){
187474:       assert( pRes->iFirst==i1 );
187475:     }else{
187476:       int nMin = MIN(p1->term.n, p2->term.n);
187477:       int res = memcmp(p1->term.p, p2->term.p, nMin);
187478:       if( res==0 ) res = p1->term.n - p2->term.n;
187479: 
187480:       if( res==0 ){
187481:         assert( pRes->bTermEq==1 );
187482:         assert( p1->iRowid!=p2->iRowid );
187483:         res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
187484:       }else{
187485:         assert( pRes->bTermEq==0 );
187486:       }
187487: 
187488:       if( res<0 ){
187489:         assert( pRes->iFirst==i1 );
187490:       }else{
187491:         assert( pRes->iFirst==i2 );
187492:       }
187493:     }
187494:   }
187495: }
187496: 
187497: /*
187498: ** This function is a no-op unless SQLITE_DEBUG is defined when this module
187499: ** is compiled. In that case, this function is essentially an assert() 
187500: ** statement used to verify that the contents of the pIter->aFirst[] array
187501: ** are correct.
187502: */
187503: static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
187504:   if( p->rc==SQLITE_OK ){
187505:     Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
187506:     int i;
187507: 
187508:     assert( (pFirst->pLeaf==0)==pIter->base.bEof );
187509: 
187510:     /* Check that pIter->iSwitchRowid is set correctly. */
187511:     for(i=0; i<pIter->nSeg; i++){
187512:       Fts5SegIter *p1 = &pIter->aSeg[i];
187513:       assert( p1==pFirst 
187514:            || p1->pLeaf==0 
187515:            || fts5BufferCompare(&pFirst->term, &p1->term) 
187516:            || p1->iRowid==pIter->iSwitchRowid
187517:            || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
187518:       );
187519:     }
187520: 
187521:     for(i=0; i<pIter->nSeg; i+=2){
187522:       Fts5SegIter *p1 = &pIter->aSeg[i];
187523:       Fts5SegIter *p2 = &pIter->aSeg[i+1];
187524:       Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
187525:       fts5AssertComparisonResult(pIter, p1, p2, pRes);
187526:     }
187527: 
187528:     for(i=1; i<(pIter->nSeg / 2); i+=2){
187529:       Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
187530:       Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
187531:       Fts5CResult *pRes = &pIter->aFirst[i];
187532:       fts5AssertComparisonResult(pIter, p1, p2, pRes);
187533:     }
187534:   }
187535: }
187536: #else
187537: # define fts5AssertMultiIterSetup(x,y)
187538: #endif
187539: 
187540: /*
187541: ** Do the comparison necessary to populate pIter->aFirst[iOut].
187542: **
187543: ** If the returned value is non-zero, then it is the index of an entry
187544: ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
187545: ** to a key that is a duplicate of another, higher priority, 
187546: ** segment-iterator in the pSeg->aSeg[] array.
187547: */
187548: static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
187549:   int i1;                         /* Index of left-hand Fts5SegIter */
187550:   int i2;                         /* Index of right-hand Fts5SegIter */
187551:   int iRes;
187552:   Fts5SegIter *p1;                /* Left-hand Fts5SegIter */
187553:   Fts5SegIter *p2;                /* Right-hand Fts5SegIter */
187554:   Fts5CResult *pRes = &pIter->aFirst[iOut];
187555: 
187556:   assert( iOut<pIter->nSeg && iOut>0 );
187557:   assert( pIter->bRev==0 || pIter->bRev==1 );
187558: 
187559:   if( iOut>=(pIter->nSeg/2) ){
187560:     i1 = (iOut - pIter->nSeg/2) * 2;
187561:     i2 = i1 + 1;
187562:   }else{
187563:     i1 = pIter->aFirst[iOut*2].iFirst;
187564:     i2 = pIter->aFirst[iOut*2+1].iFirst;
187565:   }
187566:   p1 = &pIter->aSeg[i1];
187567:   p2 = &pIter->aSeg[i2];
187568: 
187569:   pRes->bTermEq = 0;
187570:   if( p1->pLeaf==0 ){           /* If p1 is at EOF */
187571:     iRes = i2;
187572:   }else if( p2->pLeaf==0 ){     /* If p2 is at EOF */
187573:     iRes = i1;
187574:   }else{
187575:     int res = fts5BufferCompare(&p1->term, &p2->term);
187576:     if( res==0 ){
187577:       assert( i2>i1 );
187578:       assert( i2!=0 );
187579:       pRes->bTermEq = 1;
187580:       if( p1->iRowid==p2->iRowid ){
187581:         p1->bDel = p2->bDel;
187582:         return i2;
187583:       }
187584:       res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
187585:     }
187586:     assert( res!=0 );
187587:     if( res<0 ){
187588:       iRes = i1;
187589:     }else{
187590:       iRes = i2;
187591:     }
187592:   }
187593: 
187594:   pRes->iFirst = (u16)iRes;
187595:   return 0;
187596: }
187597: 
187598: /*
187599: ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
187600: ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
187601: */
187602: static void fts5SegIterGotoPage(
187603:   Fts5Index *p,                   /* FTS5 backend object */
187604:   Fts5SegIter *pIter,             /* Iterator to advance */
187605:   int iLeafPgno
187606: ){
187607:   assert( iLeafPgno>pIter->iLeafPgno );
187608: 
187609:   if( iLeafPgno>pIter->pSeg->pgnoLast ){
187610:     p->rc = FTS5_CORRUPT;
187611:   }else{
187612:     fts5DataRelease(pIter->pNextLeaf);
187613:     pIter->pNextLeaf = 0;
187614:     pIter->iLeafPgno = iLeafPgno-1;
187615:     fts5SegIterNextPage(p, pIter);
187616:     assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
187617: 
187618:     if( p->rc==SQLITE_OK ){
187619:       int iOff;
187620:       u8 *a = pIter->pLeaf->p;
187621:       int n = pIter->pLeaf->szLeaf;
187622: 
187623:       iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
187624:       if( iOff<4 || iOff>=n ){
187625:         p->rc = FTS5_CORRUPT;
187626:       }else{
187627:         iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
187628:         pIter->iLeafOffset = iOff;
187629:         fts5SegIterLoadNPos(p, pIter);
187630:       }
187631:     }
187632:   }
187633: }
187634: 
187635: /*
187636: ** Advance the iterator passed as the second argument until it is at or 
187637: ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
187638: ** always advanced at least once.
187639: */
187640: static void fts5SegIterNextFrom(
187641:   Fts5Index *p,                   /* FTS5 backend object */
187642:   Fts5SegIter *pIter,             /* Iterator to advance */
187643:   i64 iMatch                      /* Advance iterator at least this far */
187644: ){
187645:   int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
187646:   Fts5DlidxIter *pDlidx = pIter->pDlidx;
187647:   int iLeafPgno = pIter->iLeafPgno;
187648:   int bMove = 1;
187649: 
187650:   assert( pIter->flags & FTS5_SEGITER_ONETERM );
187651:   assert( pIter->pDlidx );
187652:   assert( pIter->pLeaf );
187653: 
187654:   if( bRev==0 ){
187655:     while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
187656:       iLeafPgno = fts5DlidxIterPgno(pDlidx);
187657:       fts5DlidxIterNext(p, pDlidx);
187658:     }
187659:     assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
187660:     if( iLeafPgno>pIter->iLeafPgno ){
187661:       fts5SegIterGotoPage(p, pIter, iLeafPgno);
187662:       bMove = 0;
187663:     }
187664:   }else{
187665:     assert( pIter->pNextLeaf==0 );
187666:     assert( iMatch<pIter->iRowid );
187667:     while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
187668:       fts5DlidxIterPrev(p, pDlidx);
187669:     }
187670:     iLeafPgno = fts5DlidxIterPgno(pDlidx);
187671: 
187672:     assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
187673: 
187674:     if( iLeafPgno<pIter->iLeafPgno ){
187675:       pIter->iLeafPgno = iLeafPgno+1;
187676:       fts5SegIterReverseNewPage(p, pIter);
187677:       bMove = 0;
187678:     }
187679:   }
187680: 
187681:   do{
187682:     if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
187683:     if( pIter->pLeaf==0 ) break;
187684:     if( bRev==0 && pIter->iRowid>=iMatch ) break;
187685:     if( bRev!=0 && pIter->iRowid<=iMatch ) break;
187686:     bMove = 1;
187687:   }while( p->rc==SQLITE_OK );
187688: }
187689: 
187690: 
187691: /*
187692: ** Free the iterator object passed as the second argument.
187693: */
187694: static void fts5MultiIterFree(Fts5Iter *pIter){
187695:   if( pIter ){
187696:     int i;
187697:     for(i=0; i<pIter->nSeg; i++){
187698:       fts5SegIterClear(&pIter->aSeg[i]);
187699:     }
187700:     fts5StructureRelease(pIter->pStruct);
187701:     fts5BufferFree(&pIter->poslist);
187702:     sqlite3_free(pIter);
187703:   }
187704: }
187705: 
187706: static void fts5MultiIterAdvanced(
187707:   Fts5Index *p,                   /* FTS5 backend to iterate within */
187708:   Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
187709:   int iChanged,                   /* Index of sub-iterator just advanced */
187710:   int iMinset                     /* Minimum entry in aFirst[] to set */
187711: ){
187712:   int i;
187713:   for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
187714:     int iEq;
187715:     if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
187716:       Fts5SegIter *pSeg = &pIter->aSeg[iEq];
187717:       assert( p->rc==SQLITE_OK );
187718:       pSeg->xNext(p, pSeg, 0);
187719:       i = pIter->nSeg + iEq;
187720:     }
187721:   }
187722: }
187723: 
187724: /*
187725: ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
187726: ** points to the same term though - just a different rowid. This function
187727: ** attempts to update the contents of the pIter->aFirst[] accordingly.
187728: ** If it does so successfully, 0 is returned. Otherwise 1.
187729: **
187730: ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
187731: ** on the iterator instead. That function does the same as this one, except
187732: ** that it deals with more complicated cases as well.
187733: */ 
187734: static int fts5MultiIterAdvanceRowid(
187735:   Fts5Iter *pIter,                /* Iterator to update aFirst[] array for */
187736:   int iChanged,                   /* Index of sub-iterator just advanced */
187737:   Fts5SegIter **ppFirst
187738: ){
187739:   Fts5SegIter *pNew = &pIter->aSeg[iChanged];
187740: 
187741:   if( pNew->iRowid==pIter->iSwitchRowid
187742:    || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
187743:   ){
187744:     int i;
187745:     Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
187746:     pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
187747:     for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
187748:       Fts5CResult *pRes = &pIter->aFirst[i];
187749: 
187750:       assert( pNew->pLeaf );
187751:       assert( pRes->bTermEq==0 || pOther->pLeaf );
187752: 
187753:       if( pRes->bTermEq ){
187754:         if( pNew->iRowid==pOther->iRowid ){
187755:           return 1;
187756:         }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
187757:           pIter->iSwitchRowid = pOther->iRowid;
187758:           pNew = pOther;
187759:         }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
187760:           pIter->iSwitchRowid = pOther->iRowid;
187761:         }
187762:       }
187763:       pRes->iFirst = (u16)(pNew - pIter->aSeg);
187764:       if( i==1 ) break;
187765: 
187766:       pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
187767:     }
187768:   }
187769: 
187770:   *ppFirst = pNew;
187771:   return 0;
187772: }
187773: 
187774: /*
187775: ** Set the pIter->bEof variable based on the state of the sub-iterators.
187776: */
187777: static void fts5MultiIterSetEof(Fts5Iter *pIter){
187778:   Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
187779:   pIter->base.bEof = pSeg->pLeaf==0;
187780:   pIter->iSwitchRowid = pSeg->iRowid;
187781: }
187782: 
187783: /*
187784: ** Move the iterator to the next entry. 
187785: **
187786: ** If an error occurs, an error code is left in Fts5Index.rc. It is not 
187787: ** considered an error if the iterator reaches EOF, or if it is already at 
187788: ** EOF when this function is called.
187789: */
187790: static void fts5MultiIterNext(
187791:   Fts5Index *p, 
187792:   Fts5Iter *pIter,
187793:   int bFrom,                      /* True if argument iFrom is valid */
187794:   i64 iFrom                       /* Advance at least as far as this */
187795: ){
187796:   int bUseFrom = bFrom;
187797:   while( p->rc==SQLITE_OK ){
187798:     int iFirst = pIter->aFirst[1].iFirst;
187799:     int bNewTerm = 0;
187800:     Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
187801:     assert( p->rc==SQLITE_OK );
187802:     if( bUseFrom && pSeg->pDlidx ){
187803:       fts5SegIterNextFrom(p, pSeg, iFrom);
187804:     }else{
187805:       pSeg->xNext(p, pSeg, &bNewTerm);
187806:     }
187807: 
187808:     if( pSeg->pLeaf==0 || bNewTerm 
187809:      || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
187810:     ){
187811:       fts5MultiIterAdvanced(p, pIter, iFirst, 1);
187812:       fts5MultiIterSetEof(pIter);
187813:       pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
187814:       if( pSeg->pLeaf==0 ) return;
187815:     }
187816: 
187817:     fts5AssertMultiIterSetup(p, pIter);
187818:     assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
187819:     if( pIter->bSkipEmpty==0 || pSeg->nPos ){
187820:       pIter->xSetOutputs(pIter, pSeg);
187821:       return;
187822:     }
187823:     bUseFrom = 0;
187824:   }
187825: }
187826: 
187827: static void fts5MultiIterNext2(
187828:   Fts5Index *p, 
187829:   Fts5Iter *pIter,
187830:   int *pbNewTerm                  /* OUT: True if *might* be new term */
187831: ){
187832:   assert( pIter->bSkipEmpty );
187833:   if( p->rc==SQLITE_OK ){
187834:     do {
187835:       int iFirst = pIter->aFirst[1].iFirst;
187836:       Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
187837:       int bNewTerm = 0;
187838: 
187839:       assert( p->rc==SQLITE_OK );
187840:       pSeg->xNext(p, pSeg, &bNewTerm);
187841:       if( pSeg->pLeaf==0 || bNewTerm 
187842:        || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
187843:       ){
187844:         fts5MultiIterAdvanced(p, pIter, iFirst, 1);
187845:         fts5MultiIterSetEof(pIter);
187846:         *pbNewTerm = 1;
187847:       }else{
187848:         *pbNewTerm = 0;
187849:       }
187850:       fts5AssertMultiIterSetup(p, pIter);
187851: 
187852:     }while( fts5MultiIterIsEmpty(p, pIter) );
187853:   }
187854: }
187855: 
187856: static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
187857:   UNUSED_PARAM2(pUnused1, pUnused2);
187858: }
187859: 
187860: static Fts5Iter *fts5MultiIterAlloc(
187861:   Fts5Index *p,                   /* FTS5 backend to iterate within */
187862:   int nSeg
187863: ){
187864:   Fts5Iter *pNew;
187865:   int nSlot;                      /* Power of two >= nSeg */
187866: 
187867:   for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
187868:   pNew = fts5IdxMalloc(p, 
187869:       sizeof(Fts5Iter) +                  /* pNew */
187870:       sizeof(Fts5SegIter) * (nSlot-1) +   /* pNew->aSeg[] */
187871:       sizeof(Fts5CResult) * nSlot         /* pNew->aFirst[] */
187872:   );
187873:   if( pNew ){
187874:     pNew->nSeg = nSlot;
187875:     pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
187876:     pNew->pIndex = p;
187877:     pNew->xSetOutputs = fts5IterSetOutputs_Noop;
187878:   }
187879:   return pNew;
187880: }
187881: 
187882: static void fts5PoslistCallback(
187883:   Fts5Index *pUnused, 
187884:   void *pContext, 
187885:   const u8 *pChunk, int nChunk
187886: ){
187887:   UNUSED_PARAM(pUnused);
187888:   assert_nc( nChunk>=0 );
187889:   if( nChunk>0 ){
187890:     fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
187891:   }
187892: }
187893: 
187894: typedef struct PoslistCallbackCtx PoslistCallbackCtx;
187895: struct PoslistCallbackCtx {
187896:   Fts5Buffer *pBuf;               /* Append to this buffer */
187897:   Fts5Colset *pColset;            /* Restrict matches to this column */
187898:   int eState;                     /* See above */
187899: };
187900: 
187901: typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
187902: struct PoslistOffsetsCtx {
187903:   Fts5Buffer *pBuf;               /* Append to this buffer */
187904:   Fts5Colset *pColset;            /* Restrict matches to this column */
187905:   int iRead;
187906:   int iWrite;
187907: };
187908: 
187909: /*
187910: ** TODO: Make this more efficient!
187911: */
187912: static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
187913:   int i;
187914:   for(i=0; i<pColset->nCol; i++){
187915:     if( pColset->aiCol[i]==iCol ) return 1;
187916:   }
187917:   return 0;
187918: }
187919: 
187920: static void fts5PoslistOffsetsCallback(
187921:   Fts5Index *pUnused, 
187922:   void *pContext, 
187923:   const u8 *pChunk, int nChunk
187924: ){
187925:   PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
187926:   UNUSED_PARAM(pUnused);
187927:   assert_nc( nChunk>=0 );
187928:   if( nChunk>0 ){
187929:     int i = 0;
187930:     while( i<nChunk ){
187931:       int iVal;
187932:       i += fts5GetVarint32(&pChunk[i], iVal);
187933:       iVal += pCtx->iRead - 2;
187934:       pCtx->iRead = iVal;
187935:       if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
187936:         fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
187937:         pCtx->iWrite = iVal;
187938:       }
187939:     }
187940:   }
187941: }
187942: 
187943: static void fts5PoslistFilterCallback(
187944:   Fts5Index *pUnused,
187945:   void *pContext, 
187946:   const u8 *pChunk, int nChunk
187947: ){
187948:   PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
187949:   UNUSED_PARAM(pUnused);
187950:   assert_nc( nChunk>=0 );
187951:   if( nChunk>0 ){
187952:     /* Search through to find the first varint with value 1. This is the
187953:     ** start of the next columns hits. */
187954:     int i = 0;
187955:     int iStart = 0;
187956: 
187957:     if( pCtx->eState==2 ){
187958:       int iCol;
187959:       fts5FastGetVarint32(pChunk, i, iCol);
187960:       if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
187961:         pCtx->eState = 1;
187962:         fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
187963:       }else{
187964:         pCtx->eState = 0;
187965:       }
187966:     }
187967: 
187968:     do {
187969:       while( i<nChunk && pChunk[i]!=0x01 ){
187970:         while( pChunk[i] & 0x80 ) i++;
187971:         i++;
187972:       }
187973:       if( pCtx->eState ){
187974:         fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
187975:       }
187976:       if( i<nChunk ){
187977:         int iCol;
187978:         iStart = i;
187979:         i++;
187980:         if( i>=nChunk ){
187981:           pCtx->eState = 2;
187982:         }else{
187983:           fts5FastGetVarint32(pChunk, i, iCol);
187984:           pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
187985:           if( pCtx->eState ){
187986:             fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
187987:             iStart = i;
187988:           }
187989:         }
187990:       }
187991:     }while( i<nChunk );
187992:   }
187993: }
187994: 
187995: static void fts5ChunkIterate(
187996:   Fts5Index *p,                   /* Index object */
187997:   Fts5SegIter *pSeg,              /* Poslist of this iterator */
187998:   void *pCtx,                     /* Context pointer for xChunk callback */
187999:   void (*xChunk)(Fts5Index*, void*, const u8*, int)
188000: ){
188001:   int nRem = pSeg->nPos;          /* Number of bytes still to come */
188002:   Fts5Data *pData = 0;
188003:   u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
188004:   int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
188005:   int pgno = pSeg->iLeafPgno;
188006:   int pgnoSave = 0;
188007: 
188008:   /* This function does notmwork with detail=none databases. */
188009:   assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
188010: 
188011:   if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
188012:     pgnoSave = pgno+1;
188013:   }
188014: 
188015:   while( 1 ){
188016:     xChunk(p, pCtx, pChunk, nChunk);
188017:     nRem -= nChunk;
188018:     fts5DataRelease(pData);
188019:     if( nRem<=0 ){
188020:       break;
188021:     }else{
188022:       pgno++;
188023:       pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
188024:       if( pData==0 ) break;
188025:       pChunk = &pData->p[4];
188026:       nChunk = MIN(nRem, pData->szLeaf - 4);
188027:       if( pgno==pgnoSave ){
188028:         assert( pSeg->pNextLeaf==0 );
188029:         pSeg->pNextLeaf = pData;
188030:         pData = 0;
188031:       }
188032:     }
188033:   }
188034: }
188035: 
188036: /*
188037: ** Iterator pIter currently points to a valid entry (not EOF). This
188038: ** function appends the position list data for the current entry to
188039: ** buffer pBuf. It does not make a copy of the position-list size
188040: ** field.
188041: */
188042: static void fts5SegiterPoslist(
188043:   Fts5Index *p,
188044:   Fts5SegIter *pSeg,
188045:   Fts5Colset *pColset,
188046:   Fts5Buffer *pBuf
188047: ){
188048:   if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
188049:     if( pColset==0 ){
188050:       fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
188051:     }else{
188052:       if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
188053:         PoslistCallbackCtx sCtx;
188054:         sCtx.pBuf = pBuf;
188055:         sCtx.pColset = pColset;
188056:         sCtx.eState = fts5IndexColsetTest(pColset, 0);
188057:         assert( sCtx.eState==0 || sCtx.eState==1 );
188058:         fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
188059:       }else{
188060:         PoslistOffsetsCtx sCtx;
188061:         memset(&sCtx, 0, sizeof(sCtx));
188062:         sCtx.pBuf = pBuf;
188063:         sCtx.pColset = pColset;
188064:         fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
188065:       }
188066:     }
188067:   }
188068: }
188069: 
188070: /*
188071: ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
188072: ** the position list contains entries for column iCol, then (*pa) is set
188073: ** to point to the sub-position-list for that column and the number of
188074: ** bytes in it returned. Or, if the argument position list does not
188075: ** contain any entries for column iCol, return 0.
188076: */
188077: static int fts5IndexExtractCol(
188078:   const u8 **pa,                  /* IN/OUT: Pointer to poslist */
188079:   int n,                          /* IN: Size of poslist in bytes */
188080:   int iCol                        /* Column to extract from poslist */
188081: ){
188082:   int iCurrent = 0;               /* Anything before the first 0x01 is col 0 */
188083:   const u8 *p = *pa;
188084:   const u8 *pEnd = &p[n];         /* One byte past end of position list */
188085: 
188086:   while( iCol>iCurrent ){
188087:     /* Advance pointer p until it points to pEnd or an 0x01 byte that is
188088:     ** not part of a varint. Note that it is not possible for a negative
188089:     ** or extremely large varint to occur within an uncorrupted position 
188090:     ** list. So the last byte of each varint may be assumed to have a clear
188091:     ** 0x80 bit.  */
188092:     while( *p!=0x01 ){
188093:       while( *p++ & 0x80 );
188094:       if( p>=pEnd ) return 0;
188095:     }
188096:     *pa = p++;
188097:     iCurrent = *p++;
188098:     if( iCurrent & 0x80 ){
188099:       p--;
188100:       p += fts5GetVarint32(p, iCurrent);
188101:     }
188102:   }
188103:   if( iCol!=iCurrent ) return 0;
188104: 
188105:   /* Advance pointer p until it points to pEnd or an 0x01 byte that is
188106:   ** not part of a varint */
188107:   while( p<pEnd && *p!=0x01 ){
188108:     while( *p++ & 0x80 );
188109:   }
188110: 
188111:   return p - (*pa);
188112: }
188113: 
188114: static int fts5IndexExtractColset (
188115:   Fts5Colset *pColset,            /* Colset to filter on */
188116:   const u8 *pPos, int nPos,       /* Position list */
188117:   Fts5Buffer *pBuf                /* Output buffer */
188118: ){
188119:   int rc = SQLITE_OK;
188120:   int i;
188121: 
188122:   fts5BufferZero(pBuf);
188123:   for(i=0; i<pColset->nCol; i++){
188124:     const u8 *pSub = pPos;
188125:     int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
188126:     if( nSub ){
188127:       fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
188128:     }
188129:   }
188130:   return rc;
188131: }
188132: 
188133: /*
188134: ** xSetOutputs callback used by detail=none tables.
188135: */
188136: static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
188137:   assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
188138:   pIter->base.iRowid = pSeg->iRowid;
188139:   pIter->base.nData = pSeg->nPos;
188140: }
188141: 
188142: /*
188143: ** xSetOutputs callback used by detail=full and detail=col tables when no
188144: ** column filters are specified.
188145: */
188146: static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
188147:   pIter->base.iRowid = pSeg->iRowid;
188148:   pIter->base.nData = pSeg->nPos;
188149: 
188150:   assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
188151:   assert( pIter->pColset==0 );
188152: 
188153:   if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
188154:     /* All data is stored on the current page. Populate the output 
188155:     ** variables to point into the body of the page object. */
188156:     pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
188157:   }else{
188158:     /* The data is distributed over two or more pages. Copy it into the
188159:     ** Fts5Iter.poslist buffer and then set the output pointer to point
188160:     ** to this buffer.  */
188161:     fts5BufferZero(&pIter->poslist);
188162:     fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
188163:     pIter->base.pData = pIter->poslist.p;
188164:   }
188165: }
188166: 
188167: /*
188168: ** xSetOutputs callback used by detail=col when there is a column filter
188169: ** and there are 100 or more columns. Also called as a fallback from
188170: ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
188171: */
188172: static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
188173:   fts5BufferZero(&pIter->poslist);
188174:   fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
188175:   pIter->base.iRowid = pSeg->iRowid;
188176:   pIter->base.pData = pIter->poslist.p;
188177:   pIter->base.nData = pIter->poslist.n;
188178: }
188179: 
188180: /*
188181: ** xSetOutputs callback used when: 
188182: **
188183: **   * detail=col,
188184: **   * there is a column filter, and
188185: **   * the table contains 100 or fewer columns. 
188186: **
188187: ** The last point is to ensure all column numbers are stored as 
188188: ** single-byte varints.
188189: */
188190: static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
188191: 
188192:   assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
188193:   assert( pIter->pColset );
188194: 
188195:   if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
188196:     fts5IterSetOutputs_Col(pIter, pSeg);
188197:   }else{
188198:     u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
188199:     u8 *pEnd = (u8*)&a[pSeg->nPos]; 
188200:     int iPrev = 0;
188201:     int *aiCol = pIter->pColset->aiCol;
188202:     int *aiColEnd = &aiCol[pIter->pColset->nCol];
188203: 
188204:     u8 *aOut = pIter->poslist.p;
188205:     int iPrevOut = 0;
188206: 
188207:     pIter->base.iRowid = pSeg->iRowid;
188208: 
188209:     while( a<pEnd ){
188210:       iPrev += (int)a++[0] - 2;
188211:       while( *aiCol<iPrev ){
188212:         aiCol++;
188213:         if( aiCol==aiColEnd ) goto setoutputs_col_out;
188214:       }
188215:       if( *aiCol==iPrev ){
188216:         *aOut++ = (u8)((iPrev - iPrevOut) + 2);
188217:         iPrevOut = iPrev;
188218:       }
188219:     }
188220: 
188221: setoutputs_col_out:
188222:     pIter->base.pData = pIter->poslist.p;
188223:     pIter->base.nData = aOut - pIter->poslist.p;
188224:   }
188225: }
188226: 
188227: /*
188228: ** xSetOutputs callback used by detail=full when there is a column filter.
188229: */
188230: static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
188231:   Fts5Colset *pColset = pIter->pColset;
188232:   pIter->base.iRowid = pSeg->iRowid;
188233: 
188234:   assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
188235:   assert( pColset );
188236: 
188237:   if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
188238:     /* All data is stored on the current page. Populate the output 
188239:     ** variables to point into the body of the page object. */
188240:     const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
188241:     if( pColset->nCol==1 ){
188242:       pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
188243:       pIter->base.pData = a;
188244:     }else{
188245:       fts5BufferZero(&pIter->poslist);
188246:       fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
188247:       pIter->base.pData = pIter->poslist.p;
188248:       pIter->base.nData = pIter->poslist.n;
188249:     }
188250:   }else{
188251:     /* The data is distributed over two or more pages. Copy it into the
188252:     ** Fts5Iter.poslist buffer and then set the output pointer to point
188253:     ** to this buffer.  */
188254:     fts5BufferZero(&pIter->poslist);
188255:     fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
188256:     pIter->base.pData = pIter->poslist.p;
188257:     pIter->base.nData = pIter->poslist.n;
188258:   }
188259: }
188260: 
188261: static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
188262:   if( *pRc==SQLITE_OK ){
188263:     Fts5Config *pConfig = pIter->pIndex->pConfig;
188264:     if( pConfig->eDetail==FTS5_DETAIL_NONE ){
188265:       pIter->xSetOutputs = fts5IterSetOutputs_None;
188266:     }
188267: 
188268:     else if( pIter->pColset==0 ){
188269:       pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
188270:     }
188271: 
188272:     else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
188273:       pIter->xSetOutputs = fts5IterSetOutputs_Full;
188274:     }
188275: 
188276:     else{
188277:       assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
188278:       if( pConfig->nCol<=100 ){
188279:         pIter->xSetOutputs = fts5IterSetOutputs_Col100;
188280:         sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
188281:       }else{
188282:         pIter->xSetOutputs = fts5IterSetOutputs_Col;
188283:       }
188284:     }
188285:   }
188286: }
188287: 
188288: 
188289: /*
188290: ** Allocate a new Fts5Iter object.
188291: **
188292: ** The new object will be used to iterate through data in structure pStruct.
188293: ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
188294: ** is zero or greater, data from the first nSegment segments on level iLevel
188295: ** is merged.
188296: **
188297: ** The iterator initially points to the first term/rowid entry in the 
188298: ** iterated data.
188299: */
188300: static void fts5MultiIterNew(
188301:   Fts5Index *p,                   /* FTS5 backend to iterate within */
188302:   Fts5Structure *pStruct,         /* Structure of specific index */
188303:   int flags,                      /* FTS5INDEX_QUERY_XXX flags */
188304:   Fts5Colset *pColset,            /* Colset to filter on (or NULL) */
188305:   const u8 *pTerm, int nTerm,     /* Term to seek to (or NULL/0) */
188306:   int iLevel,                     /* Level to iterate (-1 for all) */
188307:   int nSegment,                   /* Number of segments to merge (iLevel>=0) */
188308:   Fts5Iter **ppOut                /* New object */
188309: ){
188310:   int nSeg = 0;                   /* Number of segment-iters in use */
188311:   int iIter = 0;                  /* */
188312:   int iSeg;                       /* Used to iterate through segments */
188313:   Fts5StructureLevel *pLvl;
188314:   Fts5Iter *pNew;
188315: 
188316:   assert( (pTerm==0 && nTerm==0) || iLevel<0 );
188317: 
188318:   /* Allocate space for the new multi-seg-iterator. */
188319:   if( p->rc==SQLITE_OK ){
188320:     if( iLevel<0 ){
188321:       assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
188322:       nSeg = pStruct->nSegment;
188323:       nSeg += (p->pHash ? 1 : 0);
188324:     }else{
188325:       nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
188326:     }
188327:   }
188328:   *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
188329:   if( pNew==0 ) return;
188330:   pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
188331:   pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
188332:   pNew->pStruct = pStruct;
188333:   pNew->pColset = pColset;
188334:   fts5StructureRef(pStruct);
188335:   if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
188336:     fts5IterSetOutputCb(&p->rc, pNew);
188337:   }
188338: 
188339:   /* Initialize each of the component segment iterators. */
188340:   if( p->rc==SQLITE_OK ){
188341:     if( iLevel<0 ){
188342:       Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
188343:       if( p->pHash ){
188344:         /* Add a segment iterator for the current contents of the hash table. */
188345:         Fts5SegIter *pIter = &pNew->aSeg[iIter++];
188346:         fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
188347:       }
188348:       for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
188349:         for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
188350:           Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
188351:           Fts5SegIter *pIter = &pNew->aSeg[iIter++];
188352:           if( pTerm==0 ){
188353:             fts5SegIterInit(p, pSeg, pIter);
188354:           }else{
188355:             fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
188356:           }
188357:         }
188358:       }
188359:     }else{
188360:       pLvl = &pStruct->aLevel[iLevel];
188361:       for(iSeg=nSeg-1; iSeg>=0; iSeg--){
188362:         fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
188363:       }
188364:     }
188365:     assert( iIter==nSeg );
188366:   }
188367: 
188368:   /* If the above was successful, each component iterators now points 
188369:   ** to the first entry in its segment. In this case initialize the 
188370:   ** aFirst[] array. Or, if an error has occurred, free the iterator
188371:   ** object and set the output variable to NULL.  */
188372:   if( p->rc==SQLITE_OK ){
188373:     for(iIter=pNew->nSeg-1; iIter>0; iIter--){
188374:       int iEq;
188375:       if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
188376:         Fts5SegIter *pSeg = &pNew->aSeg[iEq];
188377:         if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
188378:         fts5MultiIterAdvanced(p, pNew, iEq, iIter);
188379:       }
188380:     }
188381:     fts5MultiIterSetEof(pNew);
188382:     fts5AssertMultiIterSetup(p, pNew);
188383: 
188384:     if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
188385:       fts5MultiIterNext(p, pNew, 0, 0);
188386:     }else if( pNew->base.bEof==0 ){
188387:       Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
188388:       pNew->xSetOutputs(pNew, pSeg);
188389:     }
188390: 
188391:   }else{
188392:     fts5MultiIterFree(pNew);
188393:     *ppOut = 0;
188394:   }
188395: }
188396: 
188397: /*
188398: ** Create an Fts5Iter that iterates through the doclist provided
188399: ** as the second argument.
188400: */
188401: static void fts5MultiIterNew2(
188402:   Fts5Index *p,                   /* FTS5 backend to iterate within */
188403:   Fts5Data *pData,                /* Doclist to iterate through */
188404:   int bDesc,                      /* True for descending rowid order */
188405:   Fts5Iter **ppOut                /* New object */
188406: ){
188407:   Fts5Iter *pNew;
188408:   pNew = fts5MultiIterAlloc(p, 2);
188409:   if( pNew ){
188410:     Fts5SegIter *pIter = &pNew->aSeg[1];
188411: 
188412:     pIter->flags = FTS5_SEGITER_ONETERM;
188413:     if( pData->szLeaf>0 ){
188414:       pIter->pLeaf = pData;
188415:       pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
188416:       pIter->iEndofDoclist = pData->nn;
188417:       pNew->aFirst[1].iFirst = 1;
188418:       if( bDesc ){
188419:         pNew->bRev = 1;
188420:         pIter->flags |= FTS5_SEGITER_REVERSE;
188421:         fts5SegIterReverseInitPage(p, pIter);
188422:       }else{
188423:         fts5SegIterLoadNPos(p, pIter);
188424:       }
188425:       pData = 0;
188426:     }else{
188427:       pNew->base.bEof = 1;
188428:     }
188429:     fts5SegIterSetNext(p, pIter);
188430: 
188431:     *ppOut = pNew;
188432:   }
188433: 
188434:   fts5DataRelease(pData);
188435: }
188436: 
188437: /*
188438: ** Return true if the iterator is at EOF or if an error has occurred. 
188439: ** False otherwise.
188440: */
188441: static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
188442:   assert( p->rc 
188443:       || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof 
188444:   );
188445:   return (p->rc || pIter->base.bEof);
188446: }
188447: 
188448: /*
188449: ** Return the rowid of the entry that the iterator currently points
188450: ** to. If the iterator points to EOF when this function is called the
188451: ** results are undefined.
188452: */
188453: static i64 fts5MultiIterRowid(Fts5Iter *pIter){
188454:   assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
188455:   return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
188456: }
188457: 
188458: /*
188459: ** Move the iterator to the next entry at or following iMatch.
188460: */
188461: static void fts5MultiIterNextFrom(
188462:   Fts5Index *p, 
188463:   Fts5Iter *pIter, 
188464:   i64 iMatch
188465: ){
188466:   while( 1 ){
188467:     i64 iRowid;
188468:     fts5MultiIterNext(p, pIter, 1, iMatch);
188469:     if( fts5MultiIterEof(p, pIter) ) break;
188470:     iRowid = fts5MultiIterRowid(pIter);
188471:     if( pIter->bRev==0 && iRowid>=iMatch ) break;
188472:     if( pIter->bRev!=0 && iRowid<=iMatch ) break;
188473:   }
188474: }
188475: 
188476: /*
188477: ** Return a pointer to a buffer containing the term associated with the 
188478: ** entry that the iterator currently points to.
188479: */
188480: static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
188481:   Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
188482:   *pn = p->term.n;
188483:   return p->term.p;
188484: }
188485: 
188486: /*
188487: ** Allocate a new segment-id for the structure pStruct. The new segment
188488: ** id must be between 1 and 65335 inclusive, and must not be used by 
188489: ** any currently existing segment. If a free segment id cannot be found,
188490: ** SQLITE_FULL is returned.
188491: **
188492: ** If an error has already occurred, this function is a no-op. 0 is 
188493: ** returned in this case.
188494: */
188495: static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
188496:   int iSegid = 0;
188497: 
188498:   if( p->rc==SQLITE_OK ){
188499:     if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
188500:       p->rc = SQLITE_FULL;
188501:     }else{
188502:       /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
188503:       ** array is 63 elements, or 252 bytes, in size.  */
188504:       u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
188505:       int iLvl, iSeg;
188506:       int i;
188507:       u32 mask;
188508:       memset(aUsed, 0, sizeof(aUsed));
188509:       for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
188510:         for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
188511:           int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
188512:           if( iId<=FTS5_MAX_SEGMENT ){
188513:             aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
188514:           }
188515:         }
188516:       }
188517: 
188518:       for(i=0; aUsed[i]==0xFFFFFFFF; i++);
188519:       mask = aUsed[i];
188520:       for(iSegid=0; mask & (1 << iSegid); iSegid++);
188521:       iSegid += 1 + i*32;
188522: 
188523: #ifdef SQLITE_DEBUG
188524:       for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
188525:         for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
188526:           assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
188527:         }
188528:       }
188529:       assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
188530: 
188531:       {
188532:         sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
188533:         if( p->rc==SQLITE_OK ){
188534:           u8 aBlob[2] = {0xff, 0xff};
188535:           sqlite3_bind_int(pIdxSelect, 1, iSegid);
188536:           sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
188537:           assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
188538:           p->rc = sqlite3_reset(pIdxSelect);
188539:         }
188540:       }
188541: #endif
188542:     }
188543:   }
188544: 
188545:   return iSegid;
188546: }
188547: 
188548: /*
188549: ** Discard all data currently cached in the hash-tables.
188550: */
188551: static void fts5IndexDiscardData(Fts5Index *p){
188552:   assert( p->pHash || p->nPendingData==0 );
188553:   if( p->pHash ){
188554:     sqlite3Fts5HashClear(p->pHash);
188555:     p->nPendingData = 0;
188556:   }
188557: }
188558: 
188559: /*
188560: ** Return the size of the prefix, in bytes, that buffer 
188561: ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
188562: **
188563: ** Buffer (pNew/<length-unknown>) is guaranteed to be greater 
188564: ** than buffer (pOld/nOld).
188565: */
188566: static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
188567:   int i;
188568:   for(i=0; i<nOld; i++){
188569:     if( pOld[i]!=pNew[i] ) break;
188570:   }
188571:   return i;
188572: }
188573: 
188574: static void fts5WriteDlidxClear(
188575:   Fts5Index *p, 
188576:   Fts5SegWriter *pWriter,
188577:   int bFlush                      /* If true, write dlidx to disk */
188578: ){
188579:   int i;
188580:   assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
188581:   for(i=0; i<pWriter->nDlidx; i++){
188582:     Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
188583:     if( pDlidx->buf.n==0 ) break;
188584:     if( bFlush ){
188585:       assert( pDlidx->pgno!=0 );
188586:       fts5DataWrite(p, 
188587:           FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
188588:           pDlidx->buf.p, pDlidx->buf.n
188589:       );
188590:     }
188591:     sqlite3Fts5BufferZero(&pDlidx->buf);
188592:     pDlidx->bPrevValid = 0;
188593:   }
188594: }
188595: 
188596: /*
188597: ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
188598: ** Any new array elements are zeroed before returning.
188599: */
188600: static int fts5WriteDlidxGrow(
188601:   Fts5Index *p,
188602:   Fts5SegWriter *pWriter,
188603:   int nLvl
188604: ){
188605:   if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
188606:     Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
188607:         pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
188608:     );
188609:     if( aDlidx==0 ){
188610:       p->rc = SQLITE_NOMEM;
188611:     }else{
188612:       int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
188613:       memset(&aDlidx[pWriter->nDlidx], 0, nByte);
188614:       pWriter->aDlidx = aDlidx;
188615:       pWriter->nDlidx = nLvl;
188616:     }
188617:   }
188618:   return p->rc;
188619: }
188620: 
188621: /*
188622: ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
188623: ** enough, flush it to disk and return 1. Otherwise discard it and return
188624: ** zero.
188625: */
188626: static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
188627:   int bFlag = 0;
188628: 
188629:   /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
188630:   ** to the database, also write the doclist-index to disk.  */
188631:   if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
188632:     bFlag = 1;
188633:   }
188634:   fts5WriteDlidxClear(p, pWriter, bFlag);
188635:   pWriter->nEmpty = 0;
188636:   return bFlag;
188637: }
188638: 
188639: /*
188640: ** This function is called whenever processing of the doclist for the 
188641: ** last term on leaf page (pWriter->iBtPage) is completed. 
188642: **
188643: ** The doclist-index for that term is currently stored in-memory within the
188644: ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
188645: ** writes it out to disk. Or, if it is too small to bother with, discards
188646: ** it.
188647: **
188648: ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
188649: */
188650: static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
188651:   int bFlag;
188652: 
188653:   assert( pWriter->iBtPage || pWriter->nEmpty==0 );
188654:   if( pWriter->iBtPage==0 ) return;
188655:   bFlag = fts5WriteFlushDlidx(p, pWriter);
188656: 
188657:   if( p->rc==SQLITE_OK ){
188658:     const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
188659:     /* The following was already done in fts5WriteInit(): */
188660:     /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
188661:     sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
188662:     sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
188663:     sqlite3_step(p->pIdxWriter);
188664:     p->rc = sqlite3_reset(p->pIdxWriter);
188665:   }
188666:   pWriter->iBtPage = 0;
188667: }
188668: 
188669: /*
188670: ** This is called once for each leaf page except the first that contains
188671: ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
188672: ** is larger than all terms written to earlier leaves, and equal to or
188673: ** smaller than the first term on the new leaf.
188674: **
188675: ** If an error occurs, an error code is left in Fts5Index.rc. If an error
188676: ** has already occurred when this function is called, it is a no-op.
188677: */
188678: static void fts5WriteBtreeTerm(
188679:   Fts5Index *p,                   /* FTS5 backend object */
188680:   Fts5SegWriter *pWriter,         /* Writer object */
188681:   int nTerm, const u8 *pTerm      /* First term on new page */
188682: ){
188683:   fts5WriteFlushBtree(p, pWriter);
188684:   fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
188685:   pWriter->iBtPage = pWriter->writer.pgno;
188686: }
188687: 
188688: /*
188689: ** This function is called when flushing a leaf page that contains no
188690: ** terms at all to disk.
188691: */
188692: static void fts5WriteBtreeNoTerm(
188693:   Fts5Index *p,                   /* FTS5 backend object */
188694:   Fts5SegWriter *pWriter          /* Writer object */
188695: ){
188696:   /* If there were no rowids on the leaf page either and the doclist-index
188697:   ** has already been started, append an 0x00 byte to it.  */
188698:   if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
188699:     Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
188700:     assert( pDlidx->bPrevValid );
188701:     sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
188702:   }
188703: 
188704:   /* Increment the "number of sequential leaves without a term" counter. */
188705:   pWriter->nEmpty++;
188706: }
188707: 
188708: static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
188709:   i64 iRowid;
188710:   int iOff;
188711: 
188712:   iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
188713:   fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
188714:   return iRowid;
188715: }
188716: 
188717: /*
188718: ** Rowid iRowid has just been appended to the current leaf page. It is the
188719: ** first on the page. This function appends an appropriate entry to the current
188720: ** doclist-index.
188721: */
188722: static void fts5WriteDlidxAppend(
188723:   Fts5Index *p, 
188724:   Fts5SegWriter *pWriter, 
188725:   i64 iRowid
188726: ){
188727:   int i;
188728:   int bDone = 0;
188729: 
188730:   for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
188731:     i64 iVal;
188732:     Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
188733: 
188734:     if( pDlidx->buf.n>=p->pConfig->pgsz ){
188735:       /* The current doclist-index page is full. Write it to disk and push
188736:       ** a copy of iRowid (which will become the first rowid on the next
188737:       ** doclist-index leaf page) up into the next level of the b-tree 
188738:       ** hierarchy. If the node being flushed is currently the root node,
188739:       ** also push its first rowid upwards. */
188740:       pDlidx->buf.p[0] = 0x01;    /* Not the root node */
188741:       fts5DataWrite(p, 
188742:           FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
188743:           pDlidx->buf.p, pDlidx->buf.n
188744:       );
188745:       fts5WriteDlidxGrow(p, pWriter, i+2);
188746:       pDlidx = &pWriter->aDlidx[i];
188747:       if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
188748:         i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
188749: 
188750:         /* This was the root node. Push its first rowid up to the new root. */
188751:         pDlidx[1].pgno = pDlidx->pgno;
188752:         sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
188753:         sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
188754:         sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
188755:         pDlidx[1].bPrevValid = 1;
188756:         pDlidx[1].iPrev = iFirst;
188757:       }
188758: 
188759:       sqlite3Fts5BufferZero(&pDlidx->buf);
188760:       pDlidx->bPrevValid = 0;
188761:       pDlidx->pgno++;
188762:     }else{
188763:       bDone = 1;
188764:     }
188765: 
188766:     if( pDlidx->bPrevValid ){
188767:       iVal = iRowid - pDlidx->iPrev;
188768:     }else{
188769:       i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
188770:       assert( pDlidx->buf.n==0 );
188771:       sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
188772:       sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
188773:       iVal = iRowid;
188774:     }
188775: 
188776:     sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
188777:     pDlidx->bPrevValid = 1;
188778:     pDlidx->iPrev = iRowid;
188779:   }
188780: }
188781: 
188782: static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
188783:   static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
188784:   Fts5PageWriter *pPage = &pWriter->writer;
188785:   i64 iRowid;
188786: 
188787: static int nCall = 0;
188788: nCall++;
188789: 
188790:   assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
188791: 
188792:   /* Set the szLeaf header field. */
188793:   assert( 0==fts5GetU16(&pPage->buf.p[2]) );
188794:   fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
188795: 
188796:   if( pWriter->bFirstTermInPage ){
188797:     /* No term was written to this page. */
188798:     assert( pPage->pgidx.n==0 );
188799:     fts5WriteBtreeNoTerm(p, pWriter);
188800:   }else{
188801:     /* Append the pgidx to the page buffer. Set the szLeaf header field. */
188802:     fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
188803:   }
188804: 
188805:   /* Write the page out to disk */
188806:   iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
188807:   fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
188808: 
188809:   /* Initialize the next page. */
188810:   fts5BufferZero(&pPage->buf);
188811:   fts5BufferZero(&pPage->pgidx);
188812:   fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
188813:   pPage->iPrevPgidx = 0;
188814:   pPage->pgno++;
188815: 
188816:   /* Increase the leaves written counter */
188817:   pWriter->nLeafWritten++;
188818: 
188819:   /* The new leaf holds no terms or rowids */
188820:   pWriter->bFirstTermInPage = 1;
188821:   pWriter->bFirstRowidInPage = 1;
188822: }
188823: 
188824: /*
188825: ** Append term pTerm/nTerm to the segment being written by the writer passed
188826: ** as the second argument.
188827: **
188828: ** If an error occurs, set the Fts5Index.rc error code. If an error has 
188829: ** already occurred, this function is a no-op.
188830: */
188831: static void fts5WriteAppendTerm(
188832:   Fts5Index *p, 
188833:   Fts5SegWriter *pWriter,
188834:   int nTerm, const u8 *pTerm 
188835: ){
188836:   int nPrefix;                    /* Bytes of prefix compression for term */
188837:   Fts5PageWriter *pPage = &pWriter->writer;
188838:   Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
188839: 
188840:   assert( p->rc==SQLITE_OK );
188841:   assert( pPage->buf.n>=4 );
188842:   assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
188843: 
188844:   /* If the current leaf page is full, flush it to disk. */
188845:   if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
188846:     if( pPage->buf.n>4 ){
188847:       fts5WriteFlushLeaf(p, pWriter);
188848:     }
188849:     fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
188850:   }
188851:   
188852:   /* TODO1: Updating pgidx here. */
188853:   pPgidx->n += sqlite3Fts5PutVarint(
188854:       &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
188855:   );
188856:   pPage->iPrevPgidx = pPage->buf.n;
188857: #if 0
188858:   fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
188859:   pPgidx->n += 2;
188860: #endif
188861: 
188862:   if( pWriter->bFirstTermInPage ){
188863:     nPrefix = 0;
188864:     if( pPage->pgno!=1 ){
188865:       /* This is the first term on a leaf that is not the leftmost leaf in
188866:       ** the segment b-tree. In this case it is necessary to add a term to
188867:       ** the b-tree hierarchy that is (a) larger than the largest term 
188868:       ** already written to the segment and (b) smaller than or equal to
188869:       ** this term. In other words, a prefix of (pTerm/nTerm) that is one
188870:       ** byte longer than the longest prefix (pTerm/nTerm) shares with the
188871:       ** previous term. 
188872:       **
188873:       ** Usually, the previous term is available in pPage->term. The exception
188874:       ** is if this is the first term written in an incremental-merge step.
188875:       ** In this case the previous term is not available, so just write a
188876:       ** copy of (pTerm/nTerm) into the parent node. This is slightly
188877:       ** inefficient, but still correct.  */
188878:       int n = nTerm;
188879:       if( pPage->term.n ){
188880:         n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
188881:       }
188882:       fts5WriteBtreeTerm(p, pWriter, n, pTerm);
188883:       pPage = &pWriter->writer;
188884:     }
188885:   }else{
188886:     nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
188887:     fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
188888:   }
188889: 
188890:   /* Append the number of bytes of new data, then the term data itself
188891:   ** to the page. */
188892:   fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
188893:   fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
188894: 
188895:   /* Update the Fts5PageWriter.term field. */
188896:   fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
188897:   pWriter->bFirstTermInPage = 0;
188898: 
188899:   pWriter->bFirstRowidInPage = 0;
188900:   pWriter->bFirstRowidInDoclist = 1;
188901: 
188902:   assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
188903:   pWriter->aDlidx[0].pgno = pPage->pgno;
188904: }
188905: 
188906: /*
188907: ** Append a rowid and position-list size field to the writers output. 
188908: */
188909: static void fts5WriteAppendRowid(
188910:   Fts5Index *p, 
188911:   Fts5SegWriter *pWriter,
188912:   i64 iRowid
188913: ){
188914:   if( p->rc==SQLITE_OK ){
188915:     Fts5PageWriter *pPage = &pWriter->writer;
188916: 
188917:     if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
188918:       fts5WriteFlushLeaf(p, pWriter);
188919:     }
188920: 
188921:     /* If this is to be the first rowid written to the page, set the 
188922:     ** rowid-pointer in the page-header. Also append a value to the dlidx
188923:     ** buffer, in case a doclist-index is required.  */
188924:     if( pWriter->bFirstRowidInPage ){
188925:       fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
188926:       fts5WriteDlidxAppend(p, pWriter, iRowid);
188927:     }
188928: 
188929:     /* Write the rowid. */
188930:     if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
188931:       fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
188932:     }else{
188933:       assert( p->rc || iRowid>pWriter->iPrevRowid );
188934:       fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
188935:     }
188936:     pWriter->iPrevRowid = iRowid;
188937:     pWriter->bFirstRowidInDoclist = 0;
188938:     pWriter->bFirstRowidInPage = 0;
188939:   }
188940: }
188941: 
188942: static void fts5WriteAppendPoslistData(
188943:   Fts5Index *p, 
188944:   Fts5SegWriter *pWriter, 
188945:   const u8 *aData, 
188946:   int nData
188947: ){
188948:   Fts5PageWriter *pPage = &pWriter->writer;
188949:   const u8 *a = aData;
188950:   int n = nData;
188951:   
188952:   assert( p->pConfig->pgsz>0 );
188953:   while( p->rc==SQLITE_OK 
188954:      && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz 
188955:   ){
188956:     int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
188957:     int nCopy = 0;
188958:     while( nCopy<nReq ){
188959:       i64 dummy;
188960:       nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
188961:     }
188962:     fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
188963:     a += nCopy;
188964:     n -= nCopy;
188965:     fts5WriteFlushLeaf(p, pWriter);
188966:   }
188967:   if( n>0 ){
188968:     fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
188969:   }
188970: }
188971: 
188972: /*
188973: ** Flush any data cached by the writer object to the database. Free any
188974: ** allocations associated with the writer.
188975: */
188976: static void fts5WriteFinish(
188977:   Fts5Index *p, 
188978:   Fts5SegWriter *pWriter,         /* Writer object */
188979:   int *pnLeaf                     /* OUT: Number of leaf pages in b-tree */
188980: ){
188981:   int i;
188982:   Fts5PageWriter *pLeaf = &pWriter->writer;
188983:   if( p->rc==SQLITE_OK ){
188984:     assert( pLeaf->pgno>=1 );
188985:     if( pLeaf->buf.n>4 ){
188986:       fts5WriteFlushLeaf(p, pWriter);
188987:     }
188988:     *pnLeaf = pLeaf->pgno-1;
188989:     if( pLeaf->pgno>1 ){
188990:       fts5WriteFlushBtree(p, pWriter);
188991:     }
188992:   }
188993:   fts5BufferFree(&pLeaf->term);
188994:   fts5BufferFree(&pLeaf->buf);
188995:   fts5BufferFree(&pLeaf->pgidx);
188996:   fts5BufferFree(&pWriter->btterm);
188997: 
188998:   for(i=0; i<pWriter->nDlidx; i++){
188999:     sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
189000:   }
189001:   sqlite3_free(pWriter->aDlidx);
189002: }
189003: 
189004: static void fts5WriteInit(
189005:   Fts5Index *p, 
189006:   Fts5SegWriter *pWriter, 
189007:   int iSegid
189008: ){
189009:   const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
189010: 
189011:   memset(pWriter, 0, sizeof(Fts5SegWriter));
189012:   pWriter->iSegid = iSegid;
189013: 
189014:   fts5WriteDlidxGrow(p, pWriter, 1);
189015:   pWriter->writer.pgno = 1;
189016:   pWriter->bFirstTermInPage = 1;
189017:   pWriter->iBtPage = 1;
189018: 
189019:   assert( pWriter->writer.buf.n==0 );
189020:   assert( pWriter->writer.pgidx.n==0 );
189021: 
189022:   /* Grow the two buffers to pgsz + padding bytes in size. */
189023:   sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
189024:   sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
189025: 
189026:   if( p->pIdxWriter==0 ){
189027:     Fts5Config *pConfig = p->pConfig;
189028:     fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
189029:           "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)", 
189030:           pConfig->zDb, pConfig->zName
189031:     ));
189032:   }
189033: 
189034:   if( p->rc==SQLITE_OK ){
189035:     /* Initialize the 4-byte leaf-page header to 0x00. */
189036:     memset(pWriter->writer.buf.p, 0, 4);
189037:     pWriter->writer.buf.n = 4;
189038: 
189039:     /* Bind the current output segment id to the index-writer. This is an
189040:     ** optimization over binding the same value over and over as rows are
189041:     ** inserted into %_idx by the current writer.  */
189042:     sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
189043:   }
189044: }
189045: 
189046: /*
189047: ** Iterator pIter was used to iterate through the input segments of on an
189048: ** incremental merge operation. This function is called if the incremental
189049: ** merge step has finished but the input has not been completely exhausted.
189050: */
189051: static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
189052:   int i;
189053:   Fts5Buffer buf;
189054:   memset(&buf, 0, sizeof(Fts5Buffer));
189055:   for(i=0; i<pIter->nSeg; i++){
189056:     Fts5SegIter *pSeg = &pIter->aSeg[i];
189057:     if( pSeg->pSeg==0 ){
189058:       /* no-op */
189059:     }else if( pSeg->pLeaf==0 ){
189060:       /* All keys from this input segment have been transfered to the output.
189061:       ** Set both the first and last page-numbers to 0 to indicate that the
189062:       ** segment is now empty. */
189063:       pSeg->pSeg->pgnoLast = 0;
189064:       pSeg->pSeg->pgnoFirst = 0;
189065:     }else{
189066:       int iOff = pSeg->iTermLeafOffset;     /* Offset on new first leaf page */
189067:       i64 iLeafRowid;
189068:       Fts5Data *pData;
189069:       int iId = pSeg->pSeg->iSegid;
189070:       u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
189071: 
189072:       iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
189073:       pData = fts5DataRead(p, iLeafRowid);
189074:       if( pData ){
189075:         fts5BufferZero(&buf);
189076:         fts5BufferGrow(&p->rc, &buf, pData->nn);
189077:         fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
189078:         fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
189079:         fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
189080:         fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
189081:         if( p->rc==SQLITE_OK ){
189082:           /* Set the szLeaf field */
189083:           fts5PutU16(&buf.p[2], (u16)buf.n);
189084:         }
189085: 
189086:         /* Set up the new page-index array */
189087:         fts5BufferAppendVarint(&p->rc, &buf, 4);
189088:         if( pSeg->iLeafPgno==pSeg->iTermLeafPgno 
189089:          && pSeg->iEndofDoclist<pData->szLeaf 
189090:         ){
189091:           int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
189092:           fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
189093:           fts5BufferAppendBlob(&p->rc, &buf, 
189094:               pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
189095:           );
189096:         }
189097: 
189098:         fts5DataRelease(pData);
189099:         pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
189100:         fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
189101:         fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
189102:       }
189103:     }
189104:   }
189105:   fts5BufferFree(&buf);
189106: }
189107: 
189108: static void fts5MergeChunkCallback(
189109:   Fts5Index *p, 
189110:   void *pCtx, 
189111:   const u8 *pChunk, int nChunk
189112: ){
189113:   Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
189114:   fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
189115: }
189116: 
189117: /*
189118: **
189119: */
189120: static void fts5IndexMergeLevel(
189121:   Fts5Index *p,                   /* FTS5 backend object */
189122:   Fts5Structure **ppStruct,       /* IN/OUT: Stucture of index */
189123:   int iLvl,                       /* Level to read input from */
189124:   int *pnRem                      /* Write up to this many output leaves */
189125: ){
189126:   Fts5Structure *pStruct = *ppStruct;
189127:   Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
189128:   Fts5StructureLevel *pLvlOut;
189129:   Fts5Iter *pIter = 0;       /* Iterator to read input data */
189130:   int nRem = pnRem ? *pnRem : 0;  /* Output leaf pages left to write */
189131:   int nInput;                     /* Number of input segments */
189132:   Fts5SegWriter writer;           /* Writer object */
189133:   Fts5StructureSegment *pSeg;     /* Output segment */
189134:   Fts5Buffer term;
189135:   int bOldest;                    /* True if the output segment is the oldest */
189136:   int eDetail = p->pConfig->eDetail;
189137:   const int flags = FTS5INDEX_QUERY_NOOUTPUT;
189138: 
189139:   assert( iLvl<pStruct->nLevel );
189140:   assert( pLvl->nMerge<=pLvl->nSeg );
189141: 
189142:   memset(&writer, 0, sizeof(Fts5SegWriter));
189143:   memset(&term, 0, sizeof(Fts5Buffer));
189144:   if( pLvl->nMerge ){
189145:     pLvlOut = &pStruct->aLevel[iLvl+1];
189146:     assert( pLvlOut->nSeg>0 );
189147:     nInput = pLvl->nMerge;
189148:     pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
189149: 
189150:     fts5WriteInit(p, &writer, pSeg->iSegid);
189151:     writer.writer.pgno = pSeg->pgnoLast+1;
189152:     writer.iBtPage = 0;
189153:   }else{
189154:     int iSegid = fts5AllocateSegid(p, pStruct);
189155: 
189156:     /* Extend the Fts5Structure object as required to ensure the output
189157:     ** segment exists. */
189158:     if( iLvl==pStruct->nLevel-1 ){
189159:       fts5StructureAddLevel(&p->rc, ppStruct);
189160:       pStruct = *ppStruct;
189161:     }
189162:     fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
189163:     if( p->rc ) return;
189164:     pLvl = &pStruct->aLevel[iLvl];
189165:     pLvlOut = &pStruct->aLevel[iLvl+1];
189166: 
189167:     fts5WriteInit(p, &writer, iSegid);
189168: 
189169:     /* Add the new segment to the output level */
189170:     pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
189171:     pLvlOut->nSeg++;
189172:     pSeg->pgnoFirst = 1;
189173:     pSeg->iSegid = iSegid;
189174:     pStruct->nSegment++;
189175: 
189176:     /* Read input from all segments in the input level */
189177:     nInput = pLvl->nSeg;
189178:   }
189179:   bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
189180: 
189181:   assert( iLvl>=0 );
189182:   for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
189183:       fts5MultiIterEof(p, pIter)==0;
189184:       fts5MultiIterNext(p, pIter, 0, 0)
189185:   ){
189186:     Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189187:     int nPos;                     /* position-list size field value */
189188:     int nTerm;
189189:     const u8 *pTerm;
189190: 
189191:     /* Check for key annihilation. */
189192:     if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
189193: 
189194:     pTerm = fts5MultiIterTerm(pIter, &nTerm);
189195:     if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
189196:       if( pnRem && writer.nLeafWritten>nRem ){
189197:         break;
189198:       }
189199: 
189200:       /* This is a new term. Append a term to the output segment. */
189201:       fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
189202:       fts5BufferSet(&p->rc, &term, nTerm, pTerm);
189203:     }
189204: 
189205:     /* Append the rowid to the output */
189206:     /* WRITEPOSLISTSIZE */
189207:     fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
189208: 
189209:     if( eDetail==FTS5_DETAIL_NONE ){
189210:       if( pSegIter->bDel ){
189211:         fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
189212:         if( pSegIter->nPos>0 ){
189213:           fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
189214:         }
189215:       }
189216:     }else{
189217:       /* Append the position-list data to the output */
189218:       nPos = pSegIter->nPos*2 + pSegIter->bDel;
189219:       fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
189220:       fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
189221:     }
189222:   }
189223: 
189224:   /* Flush the last leaf page to disk. Set the output segment b-tree height
189225:   ** and last leaf page number at the same time.  */
189226:   fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
189227: 
189228:   if( fts5MultiIterEof(p, pIter) ){
189229:     int i;
189230: 
189231:     /* Remove the redundant segments from the %_data table */
189232:     for(i=0; i<nInput; i++){
189233:       fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
189234:     }
189235: 
189236:     /* Remove the redundant segments from the input level */
189237:     if( pLvl->nSeg!=nInput ){
189238:       int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
189239:       memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
189240:     }
189241:     pStruct->nSegment -= nInput;
189242:     pLvl->nSeg -= nInput;
189243:     pLvl->nMerge = 0;
189244:     if( pSeg->pgnoLast==0 ){
189245:       pLvlOut->nSeg--;
189246:       pStruct->nSegment--;
189247:     }
189248:   }else{
189249:     assert( pSeg->pgnoLast>0 );
189250:     fts5TrimSegments(p, pIter);
189251:     pLvl->nMerge = nInput;
189252:   }
189253: 
189254:   fts5MultiIterFree(pIter);
189255:   fts5BufferFree(&term);
189256:   if( pnRem ) *pnRem -= writer.nLeafWritten;
189257: }
189258: 
189259: /*
189260: ** Do up to nPg pages of automerge work on the index.
189261: **
189262: ** Return true if any changes were actually made, or false otherwise.
189263: */
189264: static int fts5IndexMerge(
189265:   Fts5Index *p,                   /* FTS5 backend object */
189266:   Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
189267:   int nPg,                        /* Pages of work to do */
189268:   int nMin                        /* Minimum number of segments to merge */
189269: ){
189270:   int nRem = nPg;
189271:   int bRet = 0;
189272:   Fts5Structure *pStruct = *ppStruct;
189273:   while( nRem>0 && p->rc==SQLITE_OK ){
189274:     int iLvl;                   /* To iterate through levels */
189275:     int iBestLvl = 0;           /* Level offering the most input segments */
189276:     int nBest = 0;              /* Number of input segments on best level */
189277: 
189278:     /* Set iBestLvl to the level to read input segments from. */
189279:     assert( pStruct->nLevel>0 );
189280:     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
189281:       Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
189282:       if( pLvl->nMerge ){
189283:         if( pLvl->nMerge>nBest ){
189284:           iBestLvl = iLvl;
189285:           nBest = pLvl->nMerge;
189286:         }
189287:         break;
189288:       }
189289:       if( pLvl->nSeg>nBest ){
189290:         nBest = pLvl->nSeg;
189291:         iBestLvl = iLvl;
189292:       }
189293:     }
189294: 
189295:     /* If nBest is still 0, then the index must be empty. */
189296: #ifdef SQLITE_DEBUG
189297:     for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
189298:       assert( pStruct->aLevel[iLvl].nSeg==0 );
189299:     }
189300: #endif
189301: 
189302:     if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
189303:       break;
189304:     }
189305:     bRet = 1;
189306:     fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
189307:     if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
189308:       fts5StructurePromote(p, iBestLvl+1, pStruct);
189309:     }
189310:   }
189311:   *ppStruct = pStruct;
189312:   return bRet;
189313: }
189314: 
189315: /*
189316: ** A total of nLeaf leaf pages of data has just been flushed to a level-0
189317: ** segment. This function updates the write-counter accordingly and, if
189318: ** necessary, performs incremental merge work.
189319: **
189320: ** If an error occurs, set the Fts5Index.rc error code. If an error has 
189321: ** already occurred, this function is a no-op.
189322: */
189323: static void fts5IndexAutomerge(
189324:   Fts5Index *p,                   /* FTS5 backend object */
189325:   Fts5Structure **ppStruct,       /* IN/OUT: Current structure of index */
189326:   int nLeaf                       /* Number of output leaves just written */
189327: ){
189328:   if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
189329:     Fts5Structure *pStruct = *ppStruct;
189330:     u64 nWrite;                   /* Initial value of write-counter */
189331:     int nWork;                    /* Number of work-quanta to perform */
189332:     int nRem;                     /* Number of leaf pages left to write */
189333: 
189334:     /* Update the write-counter. While doing so, set nWork. */
189335:     nWrite = pStruct->nWriteCounter;
189336:     nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
189337:     pStruct->nWriteCounter += nLeaf;
189338:     nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
189339: 
189340:     fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
189341:   }
189342: }
189343: 
189344: static void fts5IndexCrisismerge(
189345:   Fts5Index *p,                   /* FTS5 backend object */
189346:   Fts5Structure **ppStruct        /* IN/OUT: Current structure of index */
189347: ){
189348:   const int nCrisis = p->pConfig->nCrisisMerge;
189349:   Fts5Structure *pStruct = *ppStruct;
189350:   int iLvl = 0;
189351: 
189352:   assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
189353:   while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
189354:     fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
189355:     assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
189356:     fts5StructurePromote(p, iLvl+1, pStruct);
189357:     iLvl++;
189358:   }
189359:   *ppStruct = pStruct;
189360: }
189361: 
189362: static int fts5IndexReturn(Fts5Index *p){
189363:   int rc = p->rc;
189364:   p->rc = SQLITE_OK;
189365:   return rc;
189366: }
189367: 
189368: typedef struct Fts5FlushCtx Fts5FlushCtx;
189369: struct Fts5FlushCtx {
189370:   Fts5Index *pIdx;
189371:   Fts5SegWriter writer; 
189372: };
189373: 
189374: /*
189375: ** Buffer aBuf[] contains a list of varints, all small enough to fit
189376: ** in a 32-bit integer. Return the size of the largest prefix of this 
189377: ** list nMax bytes or less in size.
189378: */
189379: static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
189380:   int ret;
189381:   u32 dummy;
189382:   ret = fts5GetVarint32(aBuf, dummy);
189383:   if( ret<nMax ){
189384:     while( 1 ){
189385:       int i = fts5GetVarint32(&aBuf[ret], dummy);
189386:       if( (ret + i) > nMax ) break;
189387:       ret += i;
189388:     }
189389:   }
189390:   return ret;
189391: }
189392: 
189393: /*
189394: ** Flush the contents of in-memory hash table iHash to a new level-0 
189395: ** segment on disk. Also update the corresponding structure record.
189396: **
189397: ** If an error occurs, set the Fts5Index.rc error code. If an error has 
189398: ** already occurred, this function is a no-op.
189399: */
189400: static void fts5FlushOneHash(Fts5Index *p){
189401:   Fts5Hash *pHash = p->pHash;
189402:   Fts5Structure *pStruct;
189403:   int iSegid;
189404:   int pgnoLast = 0;                 /* Last leaf page number in segment */
189405: 
189406:   /* Obtain a reference to the index structure and allocate a new segment-id
189407:   ** for the new level-0 segment.  */
189408:   pStruct = fts5StructureRead(p);
189409:   iSegid = fts5AllocateSegid(p, pStruct);
189410:   fts5StructureInvalidate(p);
189411: 
189412:   if( iSegid ){
189413:     const int pgsz = p->pConfig->pgsz;
189414:     int eDetail = p->pConfig->eDetail;
189415:     Fts5StructureSegment *pSeg;   /* New segment within pStruct */
189416:     Fts5Buffer *pBuf;             /* Buffer in which to assemble leaf page */
189417:     Fts5Buffer *pPgidx;           /* Buffer in which to assemble pgidx */
189418: 
189419:     Fts5SegWriter writer;
189420:     fts5WriteInit(p, &writer, iSegid);
189421: 
189422:     pBuf = &writer.writer.buf;
189423:     pPgidx = &writer.writer.pgidx;
189424: 
189425:     /* fts5WriteInit() should have initialized the buffers to (most likely)
189426:     ** the maximum space required. */
189427:     assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
189428:     assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
189429: 
189430:     /* Begin scanning through hash table entries. This loop runs once for each
189431:     ** term/doclist currently stored within the hash table. */
189432:     if( p->rc==SQLITE_OK ){
189433:       p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
189434:     }
189435:     while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
189436:       const char *zTerm;          /* Buffer containing term */
189437:       const u8 *pDoclist;         /* Pointer to doclist for this term */
189438:       int nDoclist;               /* Size of doclist in bytes */
189439: 
189440:       /* Write the term for this entry to disk. */
189441:       sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
189442:       fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
189443: 
189444:       assert( writer.bFirstRowidInPage==0 );
189445:       if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
189446:         /* The entire doclist will fit on the current leaf. */
189447:         fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
189448:       }else{
189449:         i64 iRowid = 0;
189450:         i64 iDelta = 0;
189451:         int iOff = 0;
189452: 
189453:         /* The entire doclist will not fit on this leaf. The following 
189454:         ** loop iterates through the poslists that make up the current 
189455:         ** doclist.  */
189456:         while( p->rc==SQLITE_OK && iOff<nDoclist ){
189457:           iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
189458:           iRowid += iDelta;
189459:           
189460:           if( writer.bFirstRowidInPage ){
189461:             fts5PutU16(&pBuf->p[0], (u16)pBuf->n);   /* first rowid on page */
189462:             pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
189463:             writer.bFirstRowidInPage = 0;
189464:             fts5WriteDlidxAppend(p, &writer, iRowid);
189465:           }else{
189466:             pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
189467:           }
189468:           assert( pBuf->n<=pBuf->nSpace );
189469: 
189470:           if( eDetail==FTS5_DETAIL_NONE ){
189471:             if( iOff<nDoclist && pDoclist[iOff]==0 ){
189472:               pBuf->p[pBuf->n++] = 0;
189473:               iOff++;
189474:               if( iOff<nDoclist && pDoclist[iOff]==0 ){
189475:                 pBuf->p[pBuf->n++] = 0;
189476:                 iOff++;
189477:               }
189478:             }
189479:             if( (pBuf->n + pPgidx->n)>=pgsz ){
189480:               fts5WriteFlushLeaf(p, &writer);
189481:             }
189482:           }else{
189483:             int bDummy;
189484:             int nPos;
189485:             int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
189486:             nCopy += nPos;
189487:             if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
189488:               /* The entire poslist will fit on the current leaf. So copy
189489:               ** it in one go. */
189490:               fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
189491:             }else{
189492:               /* The entire poslist will not fit on this leaf. So it needs
189493:               ** to be broken into sections. The only qualification being
189494:               ** that each varint must be stored contiguously.  */
189495:               const u8 *pPoslist = &pDoclist[iOff];
189496:               int iPos = 0;
189497:               while( p->rc==SQLITE_OK ){
189498:                 int nSpace = pgsz - pBuf->n - pPgidx->n;
189499:                 int n = 0;
189500:                 if( (nCopy - iPos)<=nSpace ){
189501:                   n = nCopy - iPos;
189502:                 }else{
189503:                   n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
189504:                 }
189505:                 assert( n>0 );
189506:                 fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
189507:                 iPos += n;
189508:                 if( (pBuf->n + pPgidx->n)>=pgsz ){
189509:                   fts5WriteFlushLeaf(p, &writer);
189510:                 }
189511:                 if( iPos>=nCopy ) break;
189512:               }
189513:             }
189514:             iOff += nCopy;
189515:           }
189516:         }
189517:       }
189518: 
189519:       /* TODO2: Doclist terminator written here. */
189520:       /* pBuf->p[pBuf->n++] = '\0'; */
189521:       assert( pBuf->n<=pBuf->nSpace );
189522:       sqlite3Fts5HashScanNext(pHash);
189523:     }
189524:     sqlite3Fts5HashClear(pHash);
189525:     fts5WriteFinish(p, &writer, &pgnoLast);
189526: 
189527:     /* Update the Fts5Structure. It is written back to the database by the
189528:     ** fts5StructureRelease() call below.  */
189529:     if( pStruct->nLevel==0 ){
189530:       fts5StructureAddLevel(&p->rc, &pStruct);
189531:     }
189532:     fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
189533:     if( p->rc==SQLITE_OK ){
189534:       pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
189535:       pSeg->iSegid = iSegid;
189536:       pSeg->pgnoFirst = 1;
189537:       pSeg->pgnoLast = pgnoLast;
189538:       pStruct->nSegment++;
189539:     }
189540:     fts5StructurePromote(p, 0, pStruct);
189541:   }
189542: 
189543:   fts5IndexAutomerge(p, &pStruct, pgnoLast);
189544:   fts5IndexCrisismerge(p, &pStruct);
189545:   fts5StructureWrite(p, pStruct);
189546:   fts5StructureRelease(pStruct);
189547: }
189548: 
189549: /*
189550: ** Flush any data stored in the in-memory hash tables to the database.
189551: */
189552: static void fts5IndexFlush(Fts5Index *p){
189553:   /* Unless it is empty, flush the hash table to disk */
189554:   if( p->nPendingData ){
189555:     assert( p->pHash );
189556:     p->nPendingData = 0;
189557:     fts5FlushOneHash(p);
189558:   }
189559: }
189560: 
189561: static Fts5Structure *fts5IndexOptimizeStruct(
189562:   Fts5Index *p, 
189563:   Fts5Structure *pStruct
189564: ){
189565:   Fts5Structure *pNew = 0;
189566:   int nByte = sizeof(Fts5Structure);
189567:   int nSeg = pStruct->nSegment;
189568:   int i;
189569: 
189570:   /* Figure out if this structure requires optimization. A structure does
189571:   ** not require optimization if either:
189572:   **
189573:   **  + it consists of fewer than two segments, or 
189574:   **  + all segments are on the same level, or
189575:   **  + all segments except one are currently inputs to a merge operation.
189576:   **
189577:   ** In the first case, return NULL. In the second, increment the ref-count
189578:   ** on *pStruct and return a copy of the pointer to it.
189579:   */
189580:   if( nSeg<2 ) return 0;
189581:   for(i=0; i<pStruct->nLevel; i++){
189582:     int nThis = pStruct->aLevel[i].nSeg;
189583:     if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
189584:       fts5StructureRef(pStruct);
189585:       return pStruct;
189586:     }
189587:     assert( pStruct->aLevel[i].nMerge<=nThis );
189588:   }
189589: 
189590:   nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
189591:   pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
189592: 
189593:   if( pNew ){
189594:     Fts5StructureLevel *pLvl;
189595:     nByte = nSeg * sizeof(Fts5StructureSegment);
189596:     pNew->nLevel = pStruct->nLevel+1;
189597:     pNew->nRef = 1;
189598:     pNew->nWriteCounter = pStruct->nWriteCounter;
189599:     pLvl = &pNew->aLevel[pStruct->nLevel];
189600:     pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
189601:     if( pLvl->aSeg ){
189602:       int iLvl, iSeg;
189603:       int iSegOut = 0;
189604:       /* Iterate through all segments, from oldest to newest. Add them to
189605:       ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
189606:       ** segment in the data structure.  */
189607:       for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
189608:         for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
189609:           pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
189610:           iSegOut++;
189611:         }
189612:       }
189613:       pNew->nSegment = pLvl->nSeg = nSeg;
189614:     }else{
189615:       sqlite3_free(pNew);
189616:       pNew = 0;
189617:     }
189618:   }
189619: 
189620:   return pNew;
189621: }
189622: 
189623: static int sqlite3Fts5IndexOptimize(Fts5Index *p){
189624:   Fts5Structure *pStruct;
189625:   Fts5Structure *pNew = 0;
189626: 
189627:   assert( p->rc==SQLITE_OK );
189628:   fts5IndexFlush(p);
189629:   pStruct = fts5StructureRead(p);
189630:   fts5StructureInvalidate(p);
189631: 
189632:   if( pStruct ){
189633:     pNew = fts5IndexOptimizeStruct(p, pStruct);
189634:   }
189635:   fts5StructureRelease(pStruct);
189636: 
189637:   assert( pNew==0 || pNew->nSegment>0 );
189638:   if( pNew ){
189639:     int iLvl;
189640:     for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
189641:     while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
189642:       int nRem = FTS5_OPT_WORK_UNIT;
189643:       fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
189644:     }
189645: 
189646:     fts5StructureWrite(p, pNew);
189647:     fts5StructureRelease(pNew);
189648:   }
189649: 
189650:   return fts5IndexReturn(p); 
189651: }
189652: 
189653: /*
189654: ** This is called to implement the special "VALUES('merge', $nMerge)"
189655: ** INSERT command.
189656: */
189657: static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
189658:   Fts5Structure *pStruct = fts5StructureRead(p);
189659:   if( pStruct ){
189660:     int nMin = p->pConfig->nUsermerge;
189661:     fts5StructureInvalidate(p);
189662:     if( nMerge<0 ){
189663:       Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
189664:       fts5StructureRelease(pStruct);
189665:       pStruct = pNew;
189666:       nMin = 2;
189667:       nMerge = nMerge*-1;
189668:     }
189669:     if( pStruct && pStruct->nLevel ){
189670:       if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
189671:         fts5StructureWrite(p, pStruct);
189672:       }
189673:     }
189674:     fts5StructureRelease(pStruct);
189675:   }
189676:   return fts5IndexReturn(p);
189677: }
189678: 
189679: static void fts5AppendRowid(
189680:   Fts5Index *p,
189681:   i64 iDelta,
189682:   Fts5Iter *pUnused,
189683:   Fts5Buffer *pBuf
189684: ){
189685:   UNUSED_PARAM(pUnused);
189686:   fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
189687: }
189688: 
189689: static void fts5AppendPoslist(
189690:   Fts5Index *p,
189691:   i64 iDelta,
189692:   Fts5Iter *pMulti,
189693:   Fts5Buffer *pBuf
189694: ){
189695:   int nData = pMulti->base.nData;
189696:   assert( nData>0 );
189697:   if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
189698:     fts5BufferSafeAppendVarint(pBuf, iDelta);
189699:     fts5BufferSafeAppendVarint(pBuf, nData*2);
189700:     fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
189701:   }
189702: }
189703: 
189704: 
189705: static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
189706:   u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
189707: 
189708:   assert( pIter->aPoslist );
189709:   if( p>=pIter->aEof ){
189710:     pIter->aPoslist = 0;
189711:   }else{
189712:     i64 iDelta;
189713: 
189714:     p += fts5GetVarint(p, (u64*)&iDelta);
189715:     pIter->iRowid += iDelta;
189716: 
189717:     /* Read position list size */
189718:     if( p[0] & 0x80 ){
189719:       int nPos;
189720:       pIter->nSize = fts5GetVarint32(p, nPos);
189721:       pIter->nPoslist = (nPos>>1);
189722:     }else{
189723:       pIter->nPoslist = ((int)(p[0])) >> 1;
189724:       pIter->nSize = 1;
189725:     }
189726: 
189727:     pIter->aPoslist = p;
189728:   }
189729: }
189730: 
189731: static void fts5DoclistIterInit(
189732:   Fts5Buffer *pBuf, 
189733:   Fts5DoclistIter *pIter
189734: ){
189735:   memset(pIter, 0, sizeof(*pIter));
189736:   pIter->aPoslist = pBuf->p;
189737:   pIter->aEof = &pBuf->p[pBuf->n];
189738:   fts5DoclistIterNext(pIter);
189739: }
189740: 
189741: #if 0
189742: /*
189743: ** Append a doclist to buffer pBuf.
189744: **
189745: ** This function assumes that space within the buffer has already been
189746: ** allocated.
189747: */
189748: static void fts5MergeAppendDocid(
189749:   Fts5Buffer *pBuf,               /* Buffer to write to */
189750:   i64 *piLastRowid,               /* IN/OUT: Previous rowid written (if any) */
189751:   i64 iRowid                      /* Rowid to append */
189752: ){
189753:   assert( pBuf->n!=0 || (*piLastRowid)==0 );
189754:   fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
189755:   *piLastRowid = iRowid;
189756: }
189757: #endif
189758: 
189759: #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) {       \
189760:   assert( (pBuf)->n!=0 || (iLastRowid)==0 );                   \
189761:   fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
189762:   (iLastRowid) = (iRowid);                                     \
189763: }
189764: 
189765: /*
189766: ** Swap the contents of buffer *p1 with that of *p2.
189767: */
189768: static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
189769:   Fts5Buffer tmp = *p1;
189770:   *p1 = *p2;
189771:   *p2 = tmp;
189772: }
189773: 
189774: static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
189775:   int i = *piOff;
189776:   if( i>=pBuf->n ){
189777:     *piOff = -1;
189778:   }else{
189779:     u64 iVal;
189780:     *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
189781:     *piRowid += iVal;
189782:   }
189783: }
189784: 
189785: /*
189786: ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
189787: ** In this case the buffers consist of a delta-encoded list of rowids only.
189788: */
189789: static void fts5MergeRowidLists(
189790:   Fts5Index *p,                   /* FTS5 backend object */
189791:   Fts5Buffer *p1,                 /* First list to merge */
189792:   Fts5Buffer *p2                  /* Second list to merge */
189793: ){
189794:   int i1 = 0;
189795:   int i2 = 0;
189796:   i64 iRowid1 = 0;
189797:   i64 iRowid2 = 0;
189798:   i64 iOut = 0;
189799: 
189800:   Fts5Buffer out;
189801:   memset(&out, 0, sizeof(out));
189802:   sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
189803:   if( p->rc ) return;
189804: 
189805:   fts5NextRowid(p1, &i1, &iRowid1);
189806:   fts5NextRowid(p2, &i2, &iRowid2);
189807:   while( i1>=0 || i2>=0 ){
189808:     if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
189809:       assert( iOut==0 || iRowid1>iOut );
189810:       fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
189811:       iOut = iRowid1;
189812:       fts5NextRowid(p1, &i1, &iRowid1);
189813:     }else{
189814:       assert( iOut==0 || iRowid2>iOut );
189815:       fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
189816:       iOut = iRowid2;
189817:       if( i1>=0 && iRowid1==iRowid2 ){
189818:         fts5NextRowid(p1, &i1, &iRowid1);
189819:       }
189820:       fts5NextRowid(p2, &i2, &iRowid2);
189821:     }
189822:   }
189823: 
189824:   fts5BufferSwap(&out, p1);
189825:   fts5BufferFree(&out);
189826: }
189827: 
189828: /*
189829: ** Buffers p1 and p2 contain doclists. This function merges the content
189830: ** of the two doclists together and sets buffer p1 to the result before
189831: ** returning.
189832: **
189833: ** If an error occurs, an error code is left in p->rc. If an error has
189834: ** already occurred, this function is a no-op.
189835: */
189836: static void fts5MergePrefixLists(
189837:   Fts5Index *p,                   /* FTS5 backend object */
189838:   Fts5Buffer *p1,                 /* First list to merge */
189839:   Fts5Buffer *p2                  /* Second list to merge */
189840: ){
189841:   if( p2->n ){
189842:     i64 iLastRowid = 0;
189843:     Fts5DoclistIter i1;
189844:     Fts5DoclistIter i2;
189845:     Fts5Buffer out = {0, 0, 0};
189846:     Fts5Buffer tmp = {0, 0, 0};
189847: 
189848:     if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
189849:     fts5DoclistIterInit(p1, &i1);
189850:     fts5DoclistIterInit(p2, &i2);
189851: 
189852:     while( 1 ){
189853:       if( i1.iRowid<i2.iRowid ){
189854:         /* Copy entry from i1 */
189855:         fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
189856:         fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
189857:         fts5DoclistIterNext(&i1);
189858:         if( i1.aPoslist==0 ) break;
189859:       }
189860:       else if( i2.iRowid!=i1.iRowid ){
189861:         /* Copy entry from i2 */
189862:         fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189863:         fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
189864:         fts5DoclistIterNext(&i2);
189865:         if( i2.aPoslist==0 ) break;
189866:       }
189867:       else{
189868:         /* Merge the two position lists. */ 
189869:         i64 iPos1 = 0;
189870:         i64 iPos2 = 0;
189871:         int iOff1 = 0;
189872:         int iOff2 = 0;
189873:         u8 *a1 = &i1.aPoslist[i1.nSize];
189874:         u8 *a2 = &i2.aPoslist[i2.nSize];
189875: 
189876:         i64 iPrev = 0;
189877:         Fts5PoslistWriter writer;
189878:         memset(&writer, 0, sizeof(writer));
189879: 
189880:         fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189881:         fts5BufferZero(&tmp);
189882:         sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
189883:         if( p->rc ) break;
189884: 
189885:         sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189886:         sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189887:         assert( iPos1>=0 && iPos2>=0 );
189888: 
189889:         if( iPos1<iPos2 ){
189890:           sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189891:           sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189892:         }else{
189893:           sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189894:           sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189895:         }
189896: 
189897:         if( iPos1>=0 && iPos2>=0 ){
189898:           while( 1 ){
189899:             if( iPos1<iPos2 ){
189900:               if( iPos1!=iPrev ){
189901:                 sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189902:               }
189903:               sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
189904:               if( iPos1<0 ) break;
189905:             }else{
189906:               assert( iPos2!=iPrev );
189907:               sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189908:               sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
189909:               if( iPos2<0 ) break;
189910:             }
189911:           }
189912:         }
189913: 
189914:         if( iPos1>=0 ){
189915:           if( iPos1!=iPrev ){
189916:             sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
189917:           }
189918:           fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
189919:         }else{
189920:           assert( iPos2>=0 && iPos2!=iPrev );
189921:           sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
189922:           fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
189923:         }
189924: 
189925:         /* WRITEPOSLISTSIZE */
189926:         fts5BufferSafeAppendVarint(&out, tmp.n * 2);
189927:         fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
189928:         fts5DoclistIterNext(&i1);
189929:         fts5DoclistIterNext(&i2);
189930:         if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
189931:       }
189932:     }
189933: 
189934:     if( i1.aPoslist ){
189935:       fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
189936:       fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
189937:     }
189938:     else if( i2.aPoslist ){
189939:       fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
189940:       fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
189941:     }
189942: 
189943:     fts5BufferSet(&p->rc, p1, out.n, out.p);
189944:     fts5BufferFree(&tmp);
189945:     fts5BufferFree(&out);
189946:   }
189947: }
189948: 
189949: static void fts5SetupPrefixIter(
189950:   Fts5Index *p,                   /* Index to read from */
189951:   int bDesc,                      /* True for "ORDER BY rowid DESC" */
189952:   const u8 *pToken,               /* Buffer containing prefix to match */
189953:   int nToken,                     /* Size of buffer pToken in bytes */
189954:   Fts5Colset *pColset,            /* Restrict matches to these columns */
189955:   Fts5Iter **ppIter          /* OUT: New iterator */
189956: ){
189957:   Fts5Structure *pStruct;
189958:   Fts5Buffer *aBuf;
189959:   const int nBuf = 32;
189960: 
189961:   void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
189962:   void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
189963:   if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
189964:     xMerge = fts5MergeRowidLists;
189965:     xAppend = fts5AppendRowid;
189966:   }else{
189967:     xMerge = fts5MergePrefixLists;
189968:     xAppend = fts5AppendPoslist;
189969:   }
189970: 
189971:   aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
189972:   pStruct = fts5StructureRead(p);
189973: 
189974:   if( aBuf && pStruct ){
189975:     const int flags = FTS5INDEX_QUERY_SCAN 
189976:                     | FTS5INDEX_QUERY_SKIPEMPTY 
189977:                     | FTS5INDEX_QUERY_NOOUTPUT;
189978:     int i;
189979:     i64 iLastRowid = 0;
189980:     Fts5Iter *p1 = 0;     /* Iterator used to gather data from index */
189981:     Fts5Data *pData;
189982:     Fts5Buffer doclist;
189983:     int bNewTerm = 1;
189984: 
189985:     memset(&doclist, 0, sizeof(doclist));
189986:     fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
189987:     fts5IterSetOutputCb(&p->rc, p1);
189988:     for( /* no-op */ ;
189989:         fts5MultiIterEof(p, p1)==0;
189990:         fts5MultiIterNext2(p, p1, &bNewTerm)
189991:     ){
189992:       Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
189993:       int nTerm = pSeg->term.n;
189994:       const u8 *pTerm = pSeg->term.p;
189995:       p1->xSetOutputs(p1, pSeg);
189996: 
189997:       assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
189998:       if( bNewTerm ){
189999:         if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
190000:       }
190001: 
190002:       if( p1->base.nData==0 ) continue;
190003: 
190004:       if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
190005:         for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
190006:           assert( i<nBuf );
190007:           if( aBuf[i].n==0 ){
190008:             fts5BufferSwap(&doclist, &aBuf[i]);
190009:             fts5BufferZero(&doclist);
190010:           }else{
190011:             xMerge(p, &doclist, &aBuf[i]);
190012:             fts5BufferZero(&aBuf[i]);
190013:           }
190014:         }
190015:         iLastRowid = 0;
190016:       }
190017: 
190018:       xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
190019:       iLastRowid = p1->base.iRowid;
190020:     }
190021: 
190022:     for(i=0; i<nBuf; i++){
190023:       if( p->rc==SQLITE_OK ){
190024:         xMerge(p, &doclist, &aBuf[i]);
190025:       }
190026:       fts5BufferFree(&aBuf[i]);
190027:     }
190028:     fts5MultiIterFree(p1);
190029: 
190030:     pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
190031:     if( pData ){
190032:       pData->p = (u8*)&pData[1];
190033:       pData->nn = pData->szLeaf = doclist.n;
190034:       memcpy(pData->p, doclist.p, doclist.n);
190035:       fts5MultiIterNew2(p, pData, bDesc, ppIter);
190036:     }
190037:     fts5BufferFree(&doclist);
190038:   }
190039: 
190040:   fts5StructureRelease(pStruct);
190041:   sqlite3_free(aBuf);
190042: }
190043: 
190044: 
190045: /*
190046: ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
190047: ** to the document with rowid iRowid.
190048: */
190049: static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
190050:   assert( p->rc==SQLITE_OK );
190051: 
190052:   /* Allocate the hash table if it has not already been allocated */
190053:   if( p->pHash==0 ){
190054:     p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
190055:   }
190056: 
190057:   /* Flush the hash table to disk if required */
190058:   if( iRowid<p->iWriteRowid 
190059:    || (iRowid==p->iWriteRowid && p->bDelete==0)
190060:    || (p->nPendingData > p->pConfig->nHashSize) 
190061:   ){
190062:     fts5IndexFlush(p);
190063:   }
190064: 
190065:   p->iWriteRowid = iRowid;
190066:   p->bDelete = bDelete;
190067:   return fts5IndexReturn(p);
190068: }
190069: 
190070: /*
190071: ** Commit data to disk.
190072: */
190073: static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
190074:   assert( p->rc==SQLITE_OK );
190075:   fts5IndexFlush(p);
190076:   if( bCommit ) fts5CloseReader(p);
190077:   return fts5IndexReturn(p);
190078: }
190079: 
190080: /*
190081: ** Discard any data stored in the in-memory hash tables. Do not write it
190082: ** to the database. Additionally, assume that the contents of the %_data
190083: ** table may have changed on disk. So any in-memory caches of %_data 
190084: ** records must be invalidated.
190085: */
190086: static int sqlite3Fts5IndexRollback(Fts5Index *p){
190087:   fts5CloseReader(p);
190088:   fts5IndexDiscardData(p);
190089:   fts5StructureInvalidate(p);
190090:   /* assert( p->rc==SQLITE_OK ); */
190091:   return SQLITE_OK;
190092: }
190093: 
190094: /*
190095: ** The %_data table is completely empty when this function is called. This
190096: ** function populates it with the initial structure objects for each index,
190097: ** and the initial version of the "averages" record (a zero-byte blob).
190098: */
190099: static int sqlite3Fts5IndexReinit(Fts5Index *p){
190100:   Fts5Structure s;
190101:   fts5StructureInvalidate(p);
190102:   memset(&s, 0, sizeof(Fts5Structure));
190103:   fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
190104:   fts5StructureWrite(p, &s);
190105:   return fts5IndexReturn(p);
190106: }
190107: 
190108: /*
190109: ** Open a new Fts5Index handle. If the bCreate argument is true, create
190110: ** and initialize the underlying %_data table.
190111: **
190112: ** If successful, set *pp to point to the new object and return SQLITE_OK.
190113: ** Otherwise, set *pp to NULL and return an SQLite error code.
190114: */
190115: static int sqlite3Fts5IndexOpen(
190116:   Fts5Config *pConfig, 
190117:   int bCreate, 
190118:   Fts5Index **pp,
190119:   char **pzErr
190120: ){
190121:   int rc = SQLITE_OK;
190122:   Fts5Index *p;                   /* New object */
190123: 
190124:   *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
190125:   if( rc==SQLITE_OK ){
190126:     p->pConfig = pConfig;
190127:     p->nWorkUnit = FTS5_WORK_UNIT;
190128:     p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
190129:     if( p->zDataTbl && bCreate ){
190130:       rc = sqlite3Fts5CreateTable(
190131:           pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
190132:       );
190133:       if( rc==SQLITE_OK ){
190134:         rc = sqlite3Fts5CreateTable(pConfig, "idx", 
190135:             "segid, term, pgno, PRIMARY KEY(segid, term)", 
190136:             1, pzErr
190137:         );
190138:       }
190139:       if( rc==SQLITE_OK ){
190140:         rc = sqlite3Fts5IndexReinit(p);
190141:       }
190142:     }
190143:   }
190144: 
190145:   assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
190146:   if( rc ){
190147:     sqlite3Fts5IndexClose(p);
190148:     *pp = 0;
190149:   }
190150:   return rc;
190151: }
190152: 
190153: /*
190154: ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
190155: */
190156: static int sqlite3Fts5IndexClose(Fts5Index *p){
190157:   int rc = SQLITE_OK;
190158:   if( p ){
190159:     assert( p->pReader==0 );
190160:     fts5StructureInvalidate(p);
190161:     sqlite3_finalize(p->pWriter);
190162:     sqlite3_finalize(p->pDeleter);
190163:     sqlite3_finalize(p->pIdxWriter);
190164:     sqlite3_finalize(p->pIdxDeleter);
190165:     sqlite3_finalize(p->pIdxSelect);
190166:     sqlite3_finalize(p->pDataVersion);
190167:     sqlite3Fts5HashFree(p->pHash);
190168:     sqlite3_free(p->zDataTbl);
190169:     sqlite3_free(p);
190170:   }
190171:   return rc;
190172: }
190173: 
190174: /*
190175: ** Argument p points to a buffer containing utf-8 text that is n bytes in 
190176: ** size. Return the number of bytes in the nChar character prefix of the
190177: ** buffer, or 0 if there are less than nChar characters in total.
190178: */
190179: static int sqlite3Fts5IndexCharlenToBytelen(
190180:   const char *p, 
190181:   int nByte, 
190182:   int nChar
190183: ){
190184:   int n = 0;
190185:   int i;
190186:   for(i=0; i<nChar; i++){
190187:     if( n>=nByte ) return 0;      /* Input contains fewer than nChar chars */
190188:     if( (unsigned char)p[n++]>=0xc0 ){
190189:       while( (p[n] & 0xc0)==0x80 ) n++;
190190:     }
190191:   }
190192:   return n;
190193: }
190194: 
190195: /*
190196: ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
190197: ** unicode characters in the string.
190198: */
190199: static int fts5IndexCharlen(const char *pIn, int nIn){
190200:   int nChar = 0;            
190201:   int i = 0;
190202:   while( i<nIn ){
190203:     if( (unsigned char)pIn[i++]>=0xc0 ){
190204:       while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
190205:     }
190206:     nChar++;
190207:   }
190208:   return nChar;
190209: }
190210: 
190211: /*
190212: ** Insert or remove data to or from the index. Each time a document is 
190213: ** added to or removed from the index, this function is called one or more
190214: ** times.
190215: **
190216: ** For an insert, it must be called once for each token in the new document.
190217: ** If the operation is a delete, it must be called (at least) once for each
190218: ** unique token in the document with an iCol value less than zero. The iPos
190219: ** argument is ignored for a delete.
190220: */
190221: static int sqlite3Fts5IndexWrite(
190222:   Fts5Index *p,                   /* Index to write to */
190223:   int iCol,                       /* Column token appears in (-ve -> delete) */
190224:   int iPos,                       /* Position of token within column */
190225:   const char *pToken, int nToken  /* Token to add or remove to or from index */
190226: ){
190227:   int i;                          /* Used to iterate through indexes */
190228:   int rc = SQLITE_OK;             /* Return code */
190229:   Fts5Config *pConfig = p->pConfig;
190230: 
190231:   assert( p->rc==SQLITE_OK );
190232:   assert( (iCol<0)==p->bDelete );
190233: 
190234:   /* Add the entry to the main terms index. */
190235:   rc = sqlite3Fts5HashWrite(
190236:       p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
190237:   );
190238: 
190239:   for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
190240:     const int nChar = pConfig->aPrefix[i];
190241:     int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
190242:     if( nByte ){
190243:       rc = sqlite3Fts5HashWrite(p->pHash, 
190244:           p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
190245:           nByte
190246:       );
190247:     }
190248:   }
190249: 
190250:   return rc;
190251: }
190252: 
190253: /*
190254: ** Open a new iterator to iterate though all rowid that match the 
190255: ** specified token or token prefix.
190256: */
190257: static int sqlite3Fts5IndexQuery(
190258:   Fts5Index *p,                   /* FTS index to query */
190259:   const char *pToken, int nToken, /* Token (or prefix) to query for */
190260:   int flags,                      /* Mask of FTS5INDEX_QUERY_X flags */
190261:   Fts5Colset *pColset,            /* Match these columns only */
190262:   Fts5IndexIter **ppIter          /* OUT: New iterator object */
190263: ){
190264:   Fts5Config *pConfig = p->pConfig;
190265:   Fts5Iter *pRet = 0;
190266:   Fts5Buffer buf = {0, 0, 0};
190267: 
190268:   /* If the QUERY_SCAN flag is set, all other flags must be clear. */
190269:   assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
190270: 
190271:   if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
190272:     int iIdx = 0;                 /* Index to search */
190273:     memcpy(&buf.p[1], pToken, nToken);
190274: 
190275:     /* Figure out which index to search and set iIdx accordingly. If this
190276:     ** is a prefix query for which there is no prefix index, set iIdx to
190277:     ** greater than pConfig->nPrefix to indicate that the query will be
190278:     ** satisfied by scanning multiple terms in the main index.
190279:     **
190280:     ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
190281:     ** prefix-query. Instead of using a prefix-index (if one exists), 
190282:     ** evaluate the prefix query using the main FTS index. This is used
190283:     ** for internal sanity checking by the integrity-check in debug 
190284:     ** mode only.  */
190285: #ifdef SQLITE_DEBUG
190286:     if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
190287:       assert( flags & FTS5INDEX_QUERY_PREFIX );
190288:       iIdx = 1+pConfig->nPrefix;
190289:     }else
190290: #endif
190291:     if( flags & FTS5INDEX_QUERY_PREFIX ){
190292:       int nChar = fts5IndexCharlen(pToken, nToken);
190293:       for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
190294:         if( pConfig->aPrefix[iIdx-1]==nChar ) break;
190295:       }
190296:     }
190297: 
190298:     if( iIdx<=pConfig->nPrefix ){
190299:       /* Straight index lookup */
190300:       Fts5Structure *pStruct = fts5StructureRead(p);
190301:       buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
190302:       if( pStruct ){
190303:         fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY, 
190304:             pColset, buf.p, nToken+1, -1, 0, &pRet
190305:         );
190306:         fts5StructureRelease(pStruct);
190307:       }
190308:     }else{
190309:       /* Scan multiple terms in the main index */
190310:       int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
190311:       buf.p[0] = FTS5_MAIN_PREFIX;
190312:       fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
190313:       assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
190314:       fts5IterSetOutputCb(&p->rc, pRet);
190315:       if( p->rc==SQLITE_OK ){
190316:         Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
190317:         if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
190318:       }
190319:     }
190320: 
190321:     if( p->rc ){
190322:       sqlite3Fts5IterClose(&pRet->base);
190323:       pRet = 0;
190324:       fts5CloseReader(p);
190325:     }
190326: 
190327:     *ppIter = &pRet->base;
190328:     sqlite3Fts5BufferFree(&buf);
190329:   }
190330:   return fts5IndexReturn(p);
190331: }
190332: 
190333: /*
190334: ** Return true if the iterator passed as the only argument is at EOF.
190335: */
190336: /*
190337: ** Move to the next matching rowid. 
190338: */
190339: static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
190340:   Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190341:   assert( pIter->pIndex->rc==SQLITE_OK );
190342:   fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
190343:   return fts5IndexReturn(pIter->pIndex);
190344: }
190345: 
190346: /*
190347: ** Move to the next matching term/rowid. Used by the fts5vocab module.
190348: */
190349: static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
190350:   Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190351:   Fts5Index *p = pIter->pIndex;
190352: 
190353:   assert( pIter->pIndex->rc==SQLITE_OK );
190354: 
190355:   fts5MultiIterNext(p, pIter, 0, 0);
190356:   if( p->rc==SQLITE_OK ){
190357:     Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
190358:     if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
190359:       fts5DataRelease(pSeg->pLeaf);
190360:       pSeg->pLeaf = 0;
190361:       pIter->base.bEof = 1;
190362:     }
190363:   }
190364: 
190365:   return fts5IndexReturn(pIter->pIndex);
190366: }
190367: 
190368: /*
190369: ** Move to the next matching rowid that occurs at or after iMatch. The
190370: ** definition of "at or after" depends on whether this iterator iterates
190371: ** in ascending or descending rowid order.
190372: */
190373: static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
190374:   Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190375:   fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
190376:   return fts5IndexReturn(pIter->pIndex);
190377: }
190378: 
190379: /*
190380: ** Return the current term.
190381: */
190382: static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
190383:   int n;
190384:   const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
190385:   *pn = n-1;
190386:   return &z[1];
190387: }
190388: 
190389: /*
190390: ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
190391: */
190392: static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
190393:   if( pIndexIter ){
190394:     Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
190395:     Fts5Index *pIndex = pIter->pIndex;
190396:     fts5MultiIterFree(pIter);
190397:     fts5CloseReader(pIndex);
190398:   }
190399: }
190400: 
190401: /*
190402: ** Read and decode the "averages" record from the database. 
190403: **
190404: ** Parameter anSize must point to an array of size nCol, where nCol is
190405: ** the number of user defined columns in the FTS table.
190406: */
190407: static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
190408:   int nCol = p->pConfig->nCol;
190409:   Fts5Data *pData;
190410: 
190411:   *pnRow = 0;
190412:   memset(anSize, 0, sizeof(i64) * nCol);
190413:   pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
190414:   if( p->rc==SQLITE_OK && pData->nn ){
190415:     int i = 0;
190416:     int iCol;
190417:     i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
190418:     for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
190419:       i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
190420:     }
190421:   }
190422: 
190423:   fts5DataRelease(pData);
190424:   return fts5IndexReturn(p);
190425: }
190426: 
190427: /*
190428: ** Replace the current "averages" record with the contents of the buffer 
190429: ** supplied as the second argument.
190430: */
190431: static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
190432:   assert( p->rc==SQLITE_OK );
190433:   fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
190434:   return fts5IndexReturn(p);
190435: }
190436: 
190437: /*
190438: ** Return the total number of blocks this module has read from the %_data
190439: ** table since it was created.
190440: */
190441: static int sqlite3Fts5IndexReads(Fts5Index *p){
190442:   return p->nRead;
190443: }
190444: 
190445: /*
190446: ** Set the 32-bit cookie value stored at the start of all structure 
190447: ** records to the value passed as the second argument.
190448: **
190449: ** Return SQLITE_OK if successful, or an SQLite error code if an error
190450: ** occurs.
190451: */
190452: static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
190453:   int rc;                              /* Return code */
190454:   Fts5Config *pConfig = p->pConfig;    /* Configuration object */
190455:   u8 aCookie[4];                       /* Binary representation of iNew */
190456:   sqlite3_blob *pBlob = 0;
190457: 
190458:   assert( p->rc==SQLITE_OK );
190459:   sqlite3Fts5Put32(aCookie, iNew);
190460: 
190461:   rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl, 
190462:       "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
190463:   );
190464:   if( rc==SQLITE_OK ){
190465:     sqlite3_blob_write(pBlob, aCookie, 4, 0);
190466:     rc = sqlite3_blob_close(pBlob);
190467:   }
190468: 
190469:   return rc;
190470: }
190471: 
190472: static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
190473:   Fts5Structure *pStruct;
190474:   pStruct = fts5StructureRead(p);
190475:   fts5StructureRelease(pStruct);
190476:   return fts5IndexReturn(p);
190477: }
190478: 
190479: 
190480: /*************************************************************************
190481: **************************************************************************
190482: ** Below this point is the implementation of the integrity-check 
190483: ** functionality.
190484: */
190485: 
190486: /*
190487: ** Return a simple checksum value based on the arguments.
190488: */
190489: static u64 sqlite3Fts5IndexEntryCksum(
190490:   i64 iRowid, 
190491:   int iCol, 
190492:   int iPos, 
190493:   int iIdx,
190494:   const char *pTerm,
190495:   int nTerm
190496: ){
190497:   int i;
190498:   u64 ret = iRowid;
190499:   ret += (ret<<3) + iCol;
190500:   ret += (ret<<3) + iPos;
190501:   if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
190502:   for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
190503:   return ret;
190504: }
190505: 
190506: #ifdef SQLITE_DEBUG
190507: /*
190508: ** This function is purely an internal test. It does not contribute to 
190509: ** FTS functionality, or even the integrity-check, in any way.
190510: **
190511: ** Instead, it tests that the same set of pgno/rowid combinations are 
190512: ** visited regardless of whether the doclist-index identified by parameters
190513: ** iSegid/iLeaf is iterated in forwards or reverse order.
190514: */
190515: static void fts5TestDlidxReverse(
190516:   Fts5Index *p, 
190517:   int iSegid,                     /* Segment id to load from */
190518:   int iLeaf                       /* Load doclist-index for this leaf */
190519: ){
190520:   Fts5DlidxIter *pDlidx = 0;
190521:   u64 cksum1 = 13;
190522:   u64 cksum2 = 13;
190523: 
190524:   for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
190525:       fts5DlidxIterEof(p, pDlidx)==0;
190526:       fts5DlidxIterNext(p, pDlidx)
190527:   ){
190528:     i64 iRowid = fts5DlidxIterRowid(pDlidx);
190529:     int pgno = fts5DlidxIterPgno(pDlidx);
190530:     assert( pgno>iLeaf );
190531:     cksum1 += iRowid + ((i64)pgno<<32);
190532:   }
190533:   fts5DlidxIterFree(pDlidx);
190534:   pDlidx = 0;
190535: 
190536:   for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
190537:       fts5DlidxIterEof(p, pDlidx)==0;
190538:       fts5DlidxIterPrev(p, pDlidx)
190539:   ){
190540:     i64 iRowid = fts5DlidxIterRowid(pDlidx);
190541:     int pgno = fts5DlidxIterPgno(pDlidx);
190542:     assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
190543:     cksum2 += iRowid + ((i64)pgno<<32);
190544:   }
190545:   fts5DlidxIterFree(pDlidx);
190546:   pDlidx = 0;
190547: 
190548:   if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
190549: }
190550: 
190551: static int fts5QueryCksum(
190552:   Fts5Index *p,                   /* Fts5 index object */
190553:   int iIdx,
190554:   const char *z,                  /* Index key to query for */
190555:   int n,                          /* Size of index key in bytes */
190556:   int flags,                      /* Flags for Fts5IndexQuery */
190557:   u64 *pCksum                     /* IN/OUT: Checksum value */
190558: ){
190559:   int eDetail = p->pConfig->eDetail;
190560:   u64 cksum = *pCksum;
190561:   Fts5IndexIter *pIter = 0;
190562:   int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
190563: 
190564:   while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
190565:     i64 rowid = pIter->iRowid;
190566: 
190567:     if( eDetail==FTS5_DETAIL_NONE ){
190568:       cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
190569:     }else{
190570:       Fts5PoslistReader sReader;
190571:       for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
190572:           sReader.bEof==0;
190573:           sqlite3Fts5PoslistReaderNext(&sReader)
190574:       ){
190575:         int iCol = FTS5_POS2COLUMN(sReader.iPos);
190576:         int iOff = FTS5_POS2OFFSET(sReader.iPos);
190577:         cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
190578:       }
190579:     }
190580:     if( rc==SQLITE_OK ){
190581:       rc = sqlite3Fts5IterNext(pIter);
190582:     }
190583:   }
190584:   sqlite3Fts5IterClose(pIter);
190585: 
190586:   *pCksum = cksum;
190587:   return rc;
190588: }
190589: 
190590: 
190591: /*
190592: ** This function is also purely an internal test. It does not contribute to 
190593: ** FTS functionality, or even the integrity-check, in any way.
190594: */
190595: static void fts5TestTerm(
190596:   Fts5Index *p, 
190597:   Fts5Buffer *pPrev,              /* Previous term */
190598:   const char *z, int n,           /* Possibly new term to test */
190599:   u64 expected,
190600:   u64 *pCksum
190601: ){
190602:   int rc = p->rc;
190603:   if( pPrev->n==0 ){
190604:     fts5BufferSet(&rc, pPrev, n, (const u8*)z);
190605:   }else
190606:   if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
190607:     u64 cksum3 = *pCksum;
190608:     const char *zTerm = (const char*)&pPrev->p[1];  /* term sans prefix-byte */
190609:     int nTerm = pPrev->n-1;            /* Size of zTerm in bytes */
190610:     int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
190611:     int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
190612:     u64 ck1 = 0;
190613:     u64 ck2 = 0;
190614: 
190615:     /* Check that the results returned for ASC and DESC queries are
190616:     ** the same. If not, call this corruption.  */
190617:     rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
190618:     if( rc==SQLITE_OK ){
190619:       int f = flags|FTS5INDEX_QUERY_DESC;
190620:       rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190621:     }
190622:     if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190623: 
190624:     /* If this is a prefix query, check that the results returned if the
190625:     ** the index is disabled are the same. In both ASC and DESC order. 
190626:     **
190627:     ** This check may only be performed if the hash table is empty. This
190628:     ** is because the hash table only supports a single scan query at
190629:     ** a time, and the multi-iter loop from which this function is called
190630:     ** is already performing such a scan. */
190631:     if( p->nPendingData==0 ){
190632:       if( iIdx>0 && rc==SQLITE_OK ){
190633:         int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
190634:         ck2 = 0;
190635:         rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190636:         if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190637:       }
190638:       if( iIdx>0 && rc==SQLITE_OK ){
190639:         int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
190640:         ck2 = 0;
190641:         rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
190642:         if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
190643:       }
190644:     }
190645: 
190646:     cksum3 ^= ck1;
190647:     fts5BufferSet(&rc, pPrev, n, (const u8*)z);
190648: 
190649:     if( rc==SQLITE_OK && cksum3!=expected ){
190650:       rc = FTS5_CORRUPT;
190651:     }
190652:     *pCksum = cksum3;
190653:   }
190654:   p->rc = rc;
190655: }
190656:  
190657: #else
190658: # define fts5TestDlidxReverse(x,y,z)
190659: # define fts5TestTerm(u,v,w,x,y,z)
190660: #endif
190661: 
190662: /*
190663: ** Check that:
190664: **
190665: **   1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
190666: **      contain zero terms.
190667: **   2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
190668: **      contain zero rowids.
190669: */
190670: static void fts5IndexIntegrityCheckEmpty(
190671:   Fts5Index *p,
190672:   Fts5StructureSegment *pSeg,     /* Segment to check internal consistency */
190673:   int iFirst,
190674:   int iNoRowid,
190675:   int iLast
190676: ){
190677:   int i;
190678: 
190679:   /* Now check that the iter.nEmpty leaves following the current leaf
190680:   ** (a) exist and (b) contain no terms. */
190681:   for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
190682:     Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
190683:     if( pLeaf ){
190684:       if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
190685:       if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
190686:     }
190687:     fts5DataRelease(pLeaf);
190688:   }
190689: }
190690: 
190691: static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
190692:   int iTermOff = 0;
190693:   int ii;
190694: 
190695:   Fts5Buffer buf1 = {0,0,0};
190696:   Fts5Buffer buf2 = {0,0,0};
190697: 
190698:   ii = pLeaf->szLeaf;
190699:   while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
190700:     int res;
190701:     int iOff;
190702:     int nIncr;
190703: 
190704:     ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
190705:     iTermOff += nIncr;
190706:     iOff = iTermOff;
190707: 
190708:     if( iOff>=pLeaf->szLeaf ){
190709:       p->rc = FTS5_CORRUPT;
190710:     }else if( iTermOff==nIncr ){
190711:       int nByte;
190712:       iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
190713:       if( (iOff+nByte)>pLeaf->szLeaf ){
190714:         p->rc = FTS5_CORRUPT;
190715:       }else{
190716:         fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
190717:       }
190718:     }else{
190719:       int nKeep, nByte;
190720:       iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
190721:       iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
190722:       if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
190723:         p->rc = FTS5_CORRUPT;
190724:       }else{
190725:         buf1.n = nKeep;
190726:         fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
190727:       }
190728: 
190729:       if( p->rc==SQLITE_OK ){
190730:         res = fts5BufferCompare(&buf1, &buf2);
190731:         if( res<=0 ) p->rc = FTS5_CORRUPT;
190732:       }
190733:     }
190734:     fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
190735:   }
190736: 
190737:   fts5BufferFree(&buf1);
190738:   fts5BufferFree(&buf2);
190739: }
190740: 
190741: static void fts5IndexIntegrityCheckSegment(
190742:   Fts5Index *p,                   /* FTS5 backend object */
190743:   Fts5StructureSegment *pSeg      /* Segment to check internal consistency */
190744: ){
190745:   Fts5Config *pConfig = p->pConfig;
190746:   sqlite3_stmt *pStmt = 0;
190747:   int rc2;
190748:   int iIdxPrevLeaf = pSeg->pgnoFirst-1;
190749:   int iDlidxPrevLeaf = pSeg->pgnoLast;
190750: 
190751:   if( pSeg->pgnoFirst==0 ) return;
190752: 
190753:   fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
190754:       "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
190755:       pConfig->zDb, pConfig->zName, pSeg->iSegid
190756:   ));
190757: 
190758:   /* Iterate through the b-tree hierarchy.  */
190759:   while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
190760:     i64 iRow;                     /* Rowid for this leaf */
190761:     Fts5Data *pLeaf;              /* Data for this leaf */
190762: 
190763:     int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
190764:     const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
190765:     int iIdxLeaf = sqlite3_column_int(pStmt, 2);
190766:     int bIdxDlidx = sqlite3_column_int(pStmt, 3);
190767: 
190768:     /* If the leaf in question has already been trimmed from the segment, 
190769:     ** ignore this b-tree entry. Otherwise, load it into memory. */
190770:     if( iIdxLeaf<pSeg->pgnoFirst ) continue;
190771:     iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
190772:     pLeaf = fts5DataRead(p, iRow);
190773:     if( pLeaf==0 ) break;
190774: 
190775:     /* Check that the leaf contains at least one term, and that it is equal
190776:     ** to or larger than the split-key in zIdxTerm.  Also check that if there
190777:     ** is also a rowid pointer within the leaf page header, it points to a
190778:     ** location before the term.  */
190779:     if( pLeaf->nn<=pLeaf->szLeaf ){
190780:       p->rc = FTS5_CORRUPT;
190781:     }else{
190782:       int iOff;                   /* Offset of first term on leaf */
190783:       int iRowidOff;              /* Offset of first rowid on leaf */
190784:       int nTerm;                  /* Size of term on leaf in bytes */
190785:       int res;                    /* Comparison of term and split-key */
190786: 
190787:       iOff = fts5LeafFirstTermOff(pLeaf);
190788:       iRowidOff = fts5LeafFirstRowidOff(pLeaf);
190789:       if( iRowidOff>=iOff ){
190790:         p->rc = FTS5_CORRUPT;
190791:       }else{
190792:         iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
190793:         res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
190794:         if( res==0 ) res = nTerm - nIdxTerm;
190795:         if( res<0 ) p->rc = FTS5_CORRUPT;
190796:       }
190797: 
190798:       fts5IntegrityCheckPgidx(p, pLeaf);
190799:     }
190800:     fts5DataRelease(pLeaf);
190801:     if( p->rc ) break;
190802: 
190803:     /* Now check that the iter.nEmpty leaves following the current leaf
190804:     ** (a) exist and (b) contain no terms. */
190805:     fts5IndexIntegrityCheckEmpty(
190806:         p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
190807:     );
190808:     if( p->rc ) break;
190809: 
190810:     /* If there is a doclist-index, check that it looks right. */
190811:     if( bIdxDlidx ){
190812:       Fts5DlidxIter *pDlidx = 0;  /* For iterating through doclist index */
190813:       int iPrevLeaf = iIdxLeaf;
190814:       int iSegid = pSeg->iSegid;
190815:       int iPg = 0;
190816:       i64 iKey;
190817: 
190818:       for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
190819:           fts5DlidxIterEof(p, pDlidx)==0;
190820:           fts5DlidxIterNext(p, pDlidx)
190821:       ){
190822: 
190823:         /* Check any rowid-less pages that occur before the current leaf. */
190824:         for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
190825:           iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
190826:           pLeaf = fts5DataRead(p, iKey);
190827:           if( pLeaf ){
190828:             if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
190829:             fts5DataRelease(pLeaf);
190830:           }
190831:         }
190832:         iPrevLeaf = fts5DlidxIterPgno(pDlidx);
190833: 
190834:         /* Check that the leaf page indicated by the iterator really does
190835:         ** contain the rowid suggested by the same. */
190836:         iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
190837:         pLeaf = fts5DataRead(p, iKey);
190838:         if( pLeaf ){
190839:           i64 iRowid;
190840:           int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
190841:           ASSERT_SZLEAF_OK(pLeaf);
190842:           if( iRowidOff>=pLeaf->szLeaf ){
190843:             p->rc = FTS5_CORRUPT;
190844:           }else{
190845:             fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
190846:             if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
190847:           }
190848:           fts5DataRelease(pLeaf);
190849:         }
190850:       }
190851: 
190852:       iDlidxPrevLeaf = iPg;
190853:       fts5DlidxIterFree(pDlidx);
190854:       fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
190855:     }else{
190856:       iDlidxPrevLeaf = pSeg->pgnoLast;
190857:       /* TODO: Check there is no doclist index */
190858:     }
190859: 
190860:     iIdxPrevLeaf = iIdxLeaf;
190861:   }
190862: 
190863:   rc2 = sqlite3_finalize(pStmt);
190864:   if( p->rc==SQLITE_OK ) p->rc = rc2;
190865: 
190866:   /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
190867: #if 0
190868:   if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
190869:     p->rc = FTS5_CORRUPT;
190870:   }
190871: #endif
190872: }
190873: 
190874: 
190875: /*
190876: ** Run internal checks to ensure that the FTS index (a) is internally 
190877: ** consistent and (b) contains entries for which the XOR of the checksums
190878: ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
190879: **
190880: ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
190881: ** checksum does not match. Return SQLITE_OK if all checks pass without
190882: ** error, or some other SQLite error code if another error (e.g. OOM)
190883: ** occurs.
190884: */
190885: static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
190886:   int eDetail = p->pConfig->eDetail;
190887:   u64 cksum2 = 0;                 /* Checksum based on contents of indexes */
190888:   Fts5Buffer poslist = {0,0,0};   /* Buffer used to hold a poslist */
190889:   Fts5Iter *pIter;                /* Used to iterate through entire index */
190890:   Fts5Structure *pStruct;         /* Index structure */
190891: 
190892: #ifdef SQLITE_DEBUG
190893:   /* Used by extra internal tests only run if NDEBUG is not defined */
190894:   u64 cksum3 = 0;                 /* Checksum based on contents of indexes */
190895:   Fts5Buffer term = {0,0,0};      /* Buffer used to hold most recent term */
190896: #endif
190897:   const int flags = FTS5INDEX_QUERY_NOOUTPUT;
190898:   
190899:   /* Load the FTS index structure */
190900:   pStruct = fts5StructureRead(p);
190901: 
190902:   /* Check that the internal nodes of each segment match the leaves */
190903:   if( pStruct ){
190904:     int iLvl, iSeg;
190905:     for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
190906:       for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
190907:         Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
190908:         fts5IndexIntegrityCheckSegment(p, pSeg);
190909:       }
190910:     }
190911:   }
190912: 
190913:   /* The cksum argument passed to this function is a checksum calculated
190914:   ** based on all expected entries in the FTS index (including prefix index
190915:   ** entries). This block checks that a checksum calculated based on the
190916:   ** actual contents of FTS index is identical.
190917:   **
190918:   ** Two versions of the same checksum are calculated. The first (stack
190919:   ** variable cksum2) based on entries extracted from the full-text index
190920:   ** while doing a linear scan of each individual index in turn. 
190921:   **
190922:   ** As each term visited by the linear scans, a separate query for the
190923:   ** same term is performed. cksum3 is calculated based on the entries
190924:   ** extracted by these queries.
190925:   */
190926:   for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
190927:       fts5MultiIterEof(p, pIter)==0;
190928:       fts5MultiIterNext(p, pIter, 0, 0)
190929:   ){
190930:     int n;                      /* Size of term in bytes */
190931:     i64 iPos = 0;               /* Position read from poslist */
190932:     int iOff = 0;               /* Offset within poslist */
190933:     i64 iRowid = fts5MultiIterRowid(pIter);
190934:     char *z = (char*)fts5MultiIterTerm(pIter, &n);
190935: 
190936:     /* If this is a new term, query for it. Update cksum3 with the results. */
190937:     fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
190938: 
190939:     if( eDetail==FTS5_DETAIL_NONE ){
190940:       if( 0==fts5MultiIterIsEmpty(p, pIter) ){
190941:         cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
190942:       }
190943:     }else{
190944:       poslist.n = 0;
190945:       fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
190946:       while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
190947:         int iCol = FTS5_POS2COLUMN(iPos);
190948:         int iTokOff = FTS5_POS2OFFSET(iPos);
190949:         cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
190950:       }
190951:     }
190952:   }
190953:   fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
190954: 
190955:   fts5MultiIterFree(pIter);
190956:   if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
190957: 
190958:   fts5StructureRelease(pStruct);
190959: #ifdef SQLITE_DEBUG
190960:   fts5BufferFree(&term);
190961: #endif
190962:   fts5BufferFree(&poslist);
190963:   return fts5IndexReturn(p);
190964: }
190965: 
190966: /*************************************************************************
190967: **************************************************************************
190968: ** Below this point is the implementation of the fts5_decode() scalar
190969: ** function only.
190970: */
190971: 
190972: /*
190973: ** Decode a segment-data rowid from the %_data table. This function is
190974: ** the opposite of macro FTS5_SEGMENT_ROWID().
190975: */
190976: static void fts5DecodeRowid(
190977:   i64 iRowid,                     /* Rowid from %_data table */
190978:   int *piSegid,                   /* OUT: Segment id */
190979:   int *pbDlidx,                   /* OUT: Dlidx flag */
190980:   int *piHeight,                  /* OUT: Height */
190981:   int *piPgno                     /* OUT: Page number */
190982: ){
190983:   *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
190984:   iRowid >>= FTS5_DATA_PAGE_B;
190985: 
190986:   *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
190987:   iRowid >>= FTS5_DATA_HEIGHT_B;
190988: 
190989:   *pbDlidx = (int)(iRowid & 0x0001);
190990:   iRowid >>= FTS5_DATA_DLI_B;
190991: 
190992:   *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
190993: }
190994: 
190995: static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
190996:   int iSegid, iHeight, iPgno, bDlidx;       /* Rowid compenents */
190997:   fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
190998: 
190999:   if( iSegid==0 ){
191000:     if( iKey==FTS5_AVERAGES_ROWID ){
191001:       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
191002:     }else{
191003:       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
191004:     }
191005:   }
191006:   else{
191007:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
191008:         bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
191009:     );
191010:   }
191011: }
191012: 
191013: static void fts5DebugStructure(
191014:   int *pRc,                       /* IN/OUT: error code */
191015:   Fts5Buffer *pBuf,
191016:   Fts5Structure *p
191017: ){
191018:   int iLvl, iSeg;                 /* Iterate through levels, segments */
191019: 
191020:   for(iLvl=0; iLvl<p->nLevel; iLvl++){
191021:     Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
191022:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, 
191023:         " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
191024:     );
191025:     for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
191026:       Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
191027:       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}", 
191028:           pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
191029:       );
191030:     }
191031:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
191032:   }
191033: }
191034: 
191035: /*
191036: ** This is part of the fts5_decode() debugging aid.
191037: **
191038: ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
191039: ** function appends a human-readable representation of the same object
191040: ** to the buffer passed as the second argument. 
191041: */
191042: static void fts5DecodeStructure(
191043:   int *pRc,                       /* IN/OUT: error code */
191044:   Fts5Buffer *pBuf,
191045:   const u8 *pBlob, int nBlob
191046: ){
191047:   int rc;                         /* Return code */
191048:   Fts5Structure *p = 0;           /* Decoded structure object */
191049: 
191050:   rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
191051:   if( rc!=SQLITE_OK ){
191052:     *pRc = rc;
191053:     return;
191054:   }
191055: 
191056:   fts5DebugStructure(pRc, pBuf, p);
191057:   fts5StructureRelease(p);
191058: }
191059: 
191060: /*
191061: ** This is part of the fts5_decode() debugging aid.
191062: **
191063: ** Arguments pBlob/nBlob contain an "averages" record. This function 
191064: ** appends a human-readable representation of record to the buffer passed 
191065: ** as the second argument. 
191066: */
191067: static void fts5DecodeAverages(
191068:   int *pRc,                       /* IN/OUT: error code */
191069:   Fts5Buffer *pBuf,
191070:   const u8 *pBlob, int nBlob
191071: ){
191072:   int i = 0;
191073:   const char *zSpace = "";
191074: 
191075:   while( i<nBlob ){
191076:     u64 iVal;
191077:     i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
191078:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
191079:     zSpace = " ";
191080:   }
191081: }
191082: 
191083: /*
191084: ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
191085: ** each varint and append its string representation to buffer pBuf. Return
191086: ** after either the input buffer is exhausted or a 0 value is read.
191087: **
191088: ** The return value is the number of bytes read from the input buffer.
191089: */
191090: static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
191091:   int iOff = 0;
191092:   while( iOff<n ){
191093:     int iVal;
191094:     iOff += fts5GetVarint32(&a[iOff], iVal);
191095:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
191096:   }
191097:   return iOff;
191098: }
191099: 
191100: /*
191101: ** The start of buffer (a/n) contains the start of a doclist. The doclist
191102: ** may or may not finish within the buffer. This function appends a text
191103: ** representation of the part of the doclist that is present to buffer
191104: ** pBuf. 
191105: **
191106: ** The return value is the number of bytes read from the input buffer.
191107: */
191108: static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
191109:   i64 iDocid = 0;
191110:   int iOff = 0;
191111: 
191112:   if( n>0 ){
191113:     iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
191114:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
191115:   }
191116:   while( iOff<n ){
191117:     int nPos;
191118:     int bDel;
191119:     iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
191120:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
191121:     iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
191122:     if( iOff<n ){
191123:       i64 iDelta;
191124:       iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
191125:       iDocid += iDelta;
191126:       sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
191127:     }
191128:   }
191129: 
191130:   return iOff;
191131: }
191132: 
191133: /*
191134: ** This function is part of the fts5_decode() debugging function. It is 
191135: ** only ever used with detail=none tables.
191136: **
191137: ** Buffer (pData/nData) contains a doclist in the format used by detail=none
191138: ** tables. This function appends a human-readable version of that list to
191139: ** buffer pBuf.
191140: **
191141: ** If *pRc is other than SQLITE_OK when this function is called, it is a
191142: ** no-op. If an OOM or other error occurs within this function, *pRc is
191143: ** set to an SQLite error code before returning. The final state of buffer
191144: ** pBuf is undefined in this case.
191145: */
191146: static void fts5DecodeRowidList(
191147:   int *pRc,                       /* IN/OUT: Error code */
191148:   Fts5Buffer *pBuf,               /* Buffer to append text to */
191149:   const u8 *pData, int nData      /* Data to decode list-of-rowids from */
191150: ){
191151:   int i = 0;
191152:   i64 iRowid = 0;
191153: 
191154:   while( i<nData ){
191155:     const char *zApp = "";
191156:     u64 iVal;
191157:     i += sqlite3Fts5GetVarint(&pData[i], &iVal);
191158:     iRowid += iVal;
191159: 
191160:     if( i<nData && pData[i]==0x00 ){
191161:       i++;
191162:       if( i<nData && pData[i]==0x00 ){
191163:         i++;
191164:         zApp = "+";
191165:       }else{
191166:         zApp = "*";
191167:       }
191168:     }
191169: 
191170:     sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
191171:   }
191172: }
191173: 
191174: /*
191175: ** The implementation of user-defined scalar function fts5_decode().
191176: */
191177: static void fts5DecodeFunction(
191178:   sqlite3_context *pCtx,          /* Function call context */
191179:   int nArg,                       /* Number of args (always 2) */
191180:   sqlite3_value **apVal           /* Function arguments */
191181: ){
191182:   i64 iRowid;                     /* Rowid for record being decoded */
191183:   int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
191184:   const u8 *aBlob; int n;         /* Record to decode */
191185:   u8 *a = 0;
191186:   Fts5Buffer s;                   /* Build up text to return here */
191187:   int rc = SQLITE_OK;             /* Return code */
191188:   int nSpace = 0;
191189:   int eDetailNone = (sqlite3_user_data(pCtx)!=0);
191190: 
191191:   assert( nArg==2 );
191192:   UNUSED_PARAM(nArg);
191193:   memset(&s, 0, sizeof(Fts5Buffer));
191194:   iRowid = sqlite3_value_int64(apVal[0]);
191195: 
191196:   /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
191197:   ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
191198:   ** buffer overreads even if the record is corrupt.  */
191199:   n = sqlite3_value_bytes(apVal[1]);
191200:   aBlob = sqlite3_value_blob(apVal[1]);
191201:   nSpace = n + FTS5_DATA_ZERO_PADDING;
191202:   a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
191203:   if( a==0 ) goto decode_out;
191204:   memcpy(a, aBlob, n);
191205: 
191206: 
191207:   fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
191208: 
191209:   fts5DebugRowid(&rc, &s, iRowid);
191210:   if( bDlidx ){
191211:     Fts5Data dlidx;
191212:     Fts5DlidxLvl lvl;
191213: 
191214:     dlidx.p = a;
191215:     dlidx.nn = n;
191216: 
191217:     memset(&lvl, 0, sizeof(Fts5DlidxLvl));
191218:     lvl.pData = &dlidx;
191219:     lvl.iLeafPgno = iPgno;
191220: 
191221:     for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
191222:       sqlite3Fts5BufferAppendPrintf(&rc, &s, 
191223:           " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
191224:       );
191225:     }
191226:   }else if( iSegid==0 ){
191227:     if( iRowid==FTS5_AVERAGES_ROWID ){
191228:       fts5DecodeAverages(&rc, &s, a, n);
191229:     }else{
191230:       fts5DecodeStructure(&rc, &s, a, n);
191231:     }
191232:   }else if( eDetailNone ){
191233:     Fts5Buffer term;              /* Current term read from page */
191234:     int szLeaf;
191235:     int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
191236:     int iTermOff;
191237:     int nKeep = 0;
191238:     int iOff;
191239: 
191240:     memset(&term, 0, sizeof(Fts5Buffer));
191241: 
191242:     /* Decode any entries that occur before the first term. */
191243:     if( szLeaf<n ){
191244:       iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
191245:     }else{
191246:       iTermOff = szLeaf;
191247:     }
191248:     fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
191249: 
191250:     iOff = iTermOff;
191251:     while( iOff<szLeaf ){
191252:       int nAppend;
191253: 
191254:       /* Read the term data for the next term*/
191255:       iOff += fts5GetVarint32(&a[iOff], nAppend);
191256:       term.n = nKeep;
191257:       fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
191258:       sqlite3Fts5BufferAppendPrintf(
191259:           &rc, &s, " term=%.*s", term.n, (const char*)term.p
191260:       );
191261:       iOff += nAppend;
191262: 
191263:       /* Figure out where the doclist for this term ends */
191264:       if( iPgidxOff<n ){
191265:         int nIncr;
191266:         iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
191267:         iTermOff += nIncr;
191268:       }else{
191269:         iTermOff = szLeaf;
191270:       }
191271: 
191272:       fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
191273:       iOff = iTermOff;
191274:       if( iOff<szLeaf ){
191275:         iOff += fts5GetVarint32(&a[iOff], nKeep);
191276:       }
191277:     }
191278: 
191279:     fts5BufferFree(&term);
191280:   }else{
191281:     Fts5Buffer term;              /* Current term read from page */
191282:     int szLeaf;                   /* Offset of pgidx in a[] */
191283:     int iPgidxOff;
191284:     int iPgidxPrev = 0;           /* Previous value read from pgidx */
191285:     int iTermOff = 0;
191286:     int iRowidOff = 0;
191287:     int iOff;
191288:     int nDoclist;
191289: 
191290:     memset(&term, 0, sizeof(Fts5Buffer));
191291: 
191292:     if( n<4 ){
191293:       sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
191294:       goto decode_out;
191295:     }else{
191296:       iRowidOff = fts5GetU16(&a[0]);
191297:       iPgidxOff = szLeaf = fts5GetU16(&a[2]);
191298:       if( iPgidxOff<n ){
191299:         fts5GetVarint32(&a[iPgidxOff], iTermOff);
191300:       }
191301:     }
191302: 
191303:     /* Decode the position list tail at the start of the page */
191304:     if( iRowidOff!=0 ){
191305:       iOff = iRowidOff;
191306:     }else if( iTermOff!=0 ){
191307:       iOff = iTermOff;
191308:     }else{
191309:       iOff = szLeaf;
191310:     }
191311:     fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
191312: 
191313:     /* Decode any more doclist data that appears on the page before the
191314:     ** first term. */
191315:     nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
191316:     fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
191317: 
191318:     while( iPgidxOff<n ){
191319:       int bFirst = (iPgidxOff==szLeaf);     /* True for first term on page */
191320:       int nByte;                            /* Bytes of data */
191321:       int iEnd;
191322:       
191323:       iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
191324:       iPgidxPrev += nByte;
191325:       iOff = iPgidxPrev;
191326: 
191327:       if( iPgidxOff<n ){
191328:         fts5GetVarint32(&a[iPgidxOff], nByte);
191329:         iEnd = iPgidxPrev + nByte;
191330:       }else{
191331:         iEnd = szLeaf;
191332:       }
191333: 
191334:       if( bFirst==0 ){
191335:         iOff += fts5GetVarint32(&a[iOff], nByte);
191336:         term.n = nByte;
191337:       }
191338:       iOff += fts5GetVarint32(&a[iOff], nByte);
191339:       fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
191340:       iOff += nByte;
191341: 
191342:       sqlite3Fts5BufferAppendPrintf(
191343:           &rc, &s, " term=%.*s", term.n, (const char*)term.p
191344:       );
191345:       iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
191346:     }
191347: 
191348:     fts5BufferFree(&term);
191349:   }
191350:   
191351:  decode_out:
191352:   sqlite3_free(a);
191353:   if( rc==SQLITE_OK ){
191354:     sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
191355:   }else{
191356:     sqlite3_result_error_code(pCtx, rc);
191357:   }
191358:   fts5BufferFree(&s);
191359: }
191360: 
191361: /*
191362: ** The implementation of user-defined scalar function fts5_rowid().
191363: */
191364: static void fts5RowidFunction(
191365:   sqlite3_context *pCtx,          /* Function call context */
191366:   int nArg,                       /* Number of args (always 2) */
191367:   sqlite3_value **apVal           /* Function arguments */
191368: ){
191369:   const char *zArg;
191370:   if( nArg==0 ){
191371:     sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
191372:   }else{
191373:     zArg = (const char*)sqlite3_value_text(apVal[0]);
191374:     if( 0==sqlite3_stricmp(zArg, "segment") ){
191375:       i64 iRowid;
191376:       int segid, pgno;
191377:       if( nArg!=3 ){
191378:         sqlite3_result_error(pCtx, 
191379:             "should be: fts5_rowid('segment', segid, pgno))", -1
191380:         );
191381:       }else{
191382:         segid = sqlite3_value_int(apVal[1]);
191383:         pgno = sqlite3_value_int(apVal[2]);
191384:         iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
191385:         sqlite3_result_int64(pCtx, iRowid);
191386:       }
191387:     }else{
191388:       sqlite3_result_error(pCtx, 
191389:         "first arg to fts5_rowid() must be 'segment'" , -1
191390:       );
191391:     }
191392:   }
191393: }
191394: 
191395: /*
191396: ** This is called as part of registering the FTS5 module with database
191397: ** connection db. It registers several user-defined scalar functions useful
191398: ** with FTS5.
191399: **
191400: ** If successful, SQLITE_OK is returned. If an error occurs, some other
191401: ** SQLite error code is returned instead.
191402: */
191403: static int sqlite3Fts5IndexInit(sqlite3 *db){
191404:   int rc = sqlite3_create_function(
191405:       db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
191406:   );
191407: 
191408:   if( rc==SQLITE_OK ){
191409:     rc = sqlite3_create_function(
191410:         db, "fts5_decode_none", 2, 
191411:         SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
191412:     );
191413:   }
191414: 
191415:   if( rc==SQLITE_OK ){
191416:     rc = sqlite3_create_function(
191417:         db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
191418:     );
191419:   }
191420:   return rc;
191421: }
191422: 
191423: 
191424: static int sqlite3Fts5IndexReset(Fts5Index *p){
191425:   assert( p->pStruct==0 || p->iStructVersion!=0 );
191426:   if( fts5IndexDataVersion(p)!=p->iStructVersion ){
191427:     fts5StructureInvalidate(p);
191428:   }
191429:   return fts5IndexReturn(p);
191430: }
191431: 
191432: /*
191433: ** 2014 Jun 09
191434: **
191435: ** The author disclaims copyright to this source code.  In place of
191436: ** a legal notice, here is a blessing:
191437: **
191438: **    May you do good and not evil.
191439: **    May you find forgiveness for yourself and forgive others.
191440: **    May you share freely, never taking more than you give.
191441: **
191442: ******************************************************************************
191443: **
191444: ** This is an SQLite module implementing full-text search.
191445: */
191446: 
191447: 
191448: /* #include "fts5Int.h" */
191449: 
191450: /*
191451: ** This variable is set to false when running tests for which the on disk
191452: ** structures should not be corrupt. Otherwise, true. If it is false, extra
191453: ** assert() conditions in the fts5 code are activated - conditions that are
191454: ** only true if it is guaranteed that the fts5 database is not corrupt.
191455: */
191456: SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
191457: 
191458: 
191459: typedef struct Fts5Auxdata Fts5Auxdata;
191460: typedef struct Fts5Auxiliary Fts5Auxiliary;
191461: typedef struct Fts5Cursor Fts5Cursor;
191462: typedef struct Fts5Sorter Fts5Sorter;
191463: typedef struct Fts5Table Fts5Table;
191464: typedef struct Fts5TokenizerModule Fts5TokenizerModule;
191465: 
191466: /*
191467: ** NOTES ON TRANSACTIONS: 
191468: **
191469: ** SQLite invokes the following virtual table methods as transactions are 
191470: ** opened and closed by the user:
191471: **
191472: **     xBegin():    Start of a new transaction.
191473: **     xSync():     Initial part of two-phase commit.
191474: **     xCommit():   Final part of two-phase commit.
191475: **     xRollback(): Rollback the transaction.
191476: **
191477: ** Anything that is required as part of a commit that may fail is performed
191478: ** in the xSync() callback. Current versions of SQLite ignore any errors 
191479: ** returned by xCommit().
191480: **
191481: ** And as sub-transactions are opened/closed:
191482: **
191483: **     xSavepoint(int S):  Open savepoint S.
191484: **     xRelease(int S):    Commit and close savepoint S.
191485: **     xRollbackTo(int S): Rollback to start of savepoint S.
191486: **
191487: ** During a write-transaction the fts5_index.c module may cache some data 
191488: ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
191489: ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo() 
191490: ** is called.
191491: **
191492: ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
191493: ** structure is used to record the current transaction state. This information
191494: ** is not required, but it is used in the assert() statements executed by
191495: ** function fts5CheckTransactionState() (see below).
191496: */
191497: struct Fts5TransactionState {
191498:   int eState;                     /* 0==closed, 1==open, 2==synced */
191499:   int iSavepoint;                 /* Number of open savepoints (0 -> none) */
191500: };
191501: 
191502: /*
191503: ** A single object of this type is allocated when the FTS5 module is 
191504: ** registered with a database handle. It is used to store pointers to
191505: ** all registered FTS5 extensions - tokenizers and auxiliary functions.
191506: */
191507: struct Fts5Global {
191508:   fts5_api api;                   /* User visible part of object (see fts5.h) */
191509:   sqlite3 *db;                    /* Associated database connection */ 
191510:   i64 iNextId;                    /* Used to allocate unique cursor ids */
191511:   Fts5Auxiliary *pAux;            /* First in list of all aux. functions */
191512:   Fts5TokenizerModule *pTok;      /* First in list of all tokenizer modules */
191513:   Fts5TokenizerModule *pDfltTok;  /* Default tokenizer module */
191514:   Fts5Cursor *pCsr;               /* First in list of all open cursors */
191515: };
191516: 
191517: /*
191518: ** Each auxiliary function registered with the FTS5 module is represented
191519: ** by an object of the following type. All such objects are stored as part
191520: ** of the Fts5Global.pAux list.
191521: */
191522: struct Fts5Auxiliary {
191523:   Fts5Global *pGlobal;            /* Global context for this function */
191524:   char *zFunc;                    /* Function name (nul-terminated) */
191525:   void *pUserData;                /* User-data pointer */
191526:   fts5_extension_function xFunc;  /* Callback function */
191527:   void (*xDestroy)(void*);        /* Destructor function */
191528:   Fts5Auxiliary *pNext;           /* Next registered auxiliary function */
191529: };
191530: 
191531: /*
191532: ** Each tokenizer module registered with the FTS5 module is represented
191533: ** by an object of the following type. All such objects are stored as part
191534: ** of the Fts5Global.pTok list.
191535: */
191536: struct Fts5TokenizerModule {
191537:   char *zName;                    /* Name of tokenizer */
191538:   void *pUserData;                /* User pointer passed to xCreate() */
191539:   fts5_tokenizer x;               /* Tokenizer functions */
191540:   void (*xDestroy)(void*);        /* Destructor function */
191541:   Fts5TokenizerModule *pNext;     /* Next registered tokenizer module */
191542: };
191543: 
191544: /*
191545: ** Virtual-table object.
191546: */
191547: struct Fts5Table {
191548:   sqlite3_vtab base;              /* Base class used by SQLite core */
191549:   Fts5Config *pConfig;            /* Virtual table configuration */
191550:   Fts5Index *pIndex;              /* Full-text index */
191551:   Fts5Storage *pStorage;          /* Document store */
191552:   Fts5Global *pGlobal;            /* Global (connection wide) data */
191553:   Fts5Cursor *pSortCsr;           /* Sort data from this cursor */
191554: #ifdef SQLITE_DEBUG
191555:   struct Fts5TransactionState ts;
191556: #endif
191557: };
191558: 
191559: struct Fts5MatchPhrase {
191560:   Fts5Buffer *pPoslist;           /* Pointer to current poslist */
191561:   int nTerm;                      /* Size of phrase in terms */
191562: };
191563: 
191564: /*
191565: ** pStmt:
191566: **   SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
191567: **
191568: ** aIdx[]:
191569: **   There is one entry in the aIdx[] array for each phrase in the query,
191570: **   the value of which is the offset within aPoslist[] following the last 
191571: **   byte of the position list for the corresponding phrase.
191572: */
191573: struct Fts5Sorter {
191574:   sqlite3_stmt *pStmt;
191575:   i64 iRowid;                     /* Current rowid */
191576:   const u8 *aPoslist;             /* Position lists for current row */
191577:   int nIdx;                       /* Number of entries in aIdx[] */
191578:   int aIdx[1];                    /* Offsets into aPoslist for current row */
191579: };
191580: 
191581: 
191582: /*
191583: ** Virtual-table cursor object.
191584: **
191585: ** iSpecial:
191586: **   If this is a 'special' query (refer to function fts5SpecialMatch()), 
191587: **   then this variable contains the result of the query. 
191588: **
191589: ** iFirstRowid, iLastRowid:
191590: **   These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
191591: **   cursor iterates in ascending order of rowids, iFirstRowid is the lower
191592: **   limit of rowids to return, and iLastRowid the upper. In other words, the
191593: **   WHERE clause in the user's query might have been:
191594: **
191595: **       <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
191596: **
191597: **   If the cursor iterates in descending order of rowid, iFirstRowid
191598: **   is the upper limit (i.e. the "first" rowid visited) and iLastRowid
191599: **   the lower.
191600: */
191601: struct Fts5Cursor {
191602:   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
191603:   Fts5Cursor *pNext;              /* Next cursor in Fts5Cursor.pCsr list */
191604:   int *aColumnSize;               /* Values for xColumnSize() */
191605:   i64 iCsrId;                     /* Cursor id */
191606: 
191607:   /* Zero from this point onwards on cursor reset */
191608:   int ePlan;                      /* FTS5_PLAN_XXX value */
191609:   int bDesc;                      /* True for "ORDER BY rowid DESC" queries */
191610:   i64 iFirstRowid;                /* Return no rowids earlier than this */
191611:   i64 iLastRowid;                 /* Return no rowids later than this */
191612:   sqlite3_stmt *pStmt;            /* Statement used to read %_content */
191613:   Fts5Expr *pExpr;                /* Expression for MATCH queries */
191614:   Fts5Sorter *pSorter;            /* Sorter for "ORDER BY rank" queries */
191615:   int csrflags;                   /* Mask of cursor flags (see below) */
191616:   i64 iSpecial;                   /* Result of special query */
191617: 
191618:   /* "rank" function. Populated on demand from vtab.xColumn(). */
191619:   char *zRank;                    /* Custom rank function */
191620:   char *zRankArgs;                /* Custom rank function args */
191621:   Fts5Auxiliary *pRank;           /* Rank callback (or NULL) */
191622:   int nRankArg;                   /* Number of trailing arguments for rank() */
191623:   sqlite3_value **apRankArg;      /* Array of trailing arguments */
191624:   sqlite3_stmt *pRankArgStmt;     /* Origin of objects in apRankArg[] */
191625: 
191626:   /* Auxiliary data storage */
191627:   Fts5Auxiliary *pAux;            /* Currently executing extension function */
191628:   Fts5Auxdata *pAuxdata;          /* First in linked list of saved aux-data */
191629: 
191630:   /* Cache used by auxiliary functions xInst() and xInstCount() */
191631:   Fts5PoslistReader *aInstIter;   /* One for each phrase */
191632:   int nInstAlloc;                 /* Size of aInst[] array (entries / 3) */
191633:   int nInstCount;                 /* Number of phrase instances */
191634:   int *aInst;                     /* 3 integers per phrase instance */
191635: };
191636: 
191637: /*
191638: ** Bits that make up the "idxNum" parameter passed indirectly by 
191639: ** xBestIndex() to xFilter().
191640: */
191641: #define FTS5_BI_MATCH        0x0001         /* <tbl> MATCH ? */
191642: #define FTS5_BI_RANK         0x0002         /* rank MATCH ? */
191643: #define FTS5_BI_ROWID_EQ     0x0004         /* rowid == ? */
191644: #define FTS5_BI_ROWID_LE     0x0008         /* rowid <= ? */
191645: #define FTS5_BI_ROWID_GE     0x0010         /* rowid >= ? */
191646: 
191647: #define FTS5_BI_ORDER_RANK   0x0020
191648: #define FTS5_BI_ORDER_ROWID  0x0040
191649: #define FTS5_BI_ORDER_DESC   0x0080
191650: 
191651: /*
191652: ** Values for Fts5Cursor.csrflags
191653: */
191654: #define FTS5CSR_EOF               0x01
191655: #define FTS5CSR_REQUIRE_CONTENT   0x02
191656: #define FTS5CSR_REQUIRE_DOCSIZE   0x04
191657: #define FTS5CSR_REQUIRE_INST      0x08
191658: #define FTS5CSR_FREE_ZRANK        0x10
191659: #define FTS5CSR_REQUIRE_RESEEK    0x20
191660: #define FTS5CSR_REQUIRE_POSLIST   0x40
191661: 
191662: #define BitFlagAllTest(x,y) (((x) & (y))==(y))
191663: #define BitFlagTest(x,y)    (((x) & (y))!=0)
191664: 
191665: 
191666: /*
191667: ** Macros to Set(), Clear() and Test() cursor flags.
191668: */
191669: #define CsrFlagSet(pCsr, flag)   ((pCsr)->csrflags |= (flag))
191670: #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
191671: #define CsrFlagTest(pCsr, flag)  ((pCsr)->csrflags & (flag))
191672: 
191673: struct Fts5Auxdata {
191674:   Fts5Auxiliary *pAux;            /* Extension to which this belongs */
191675:   void *pPtr;                     /* Pointer value */
191676:   void(*xDelete)(void*);          /* Destructor */
191677:   Fts5Auxdata *pNext;             /* Next object in linked list */
191678: };
191679: 
191680: #ifdef SQLITE_DEBUG
191681: #define FTS5_BEGIN      1
191682: #define FTS5_SYNC       2
191683: #define FTS5_COMMIT     3
191684: #define FTS5_ROLLBACK   4
191685: #define FTS5_SAVEPOINT  5
191686: #define FTS5_RELEASE    6
191687: #define FTS5_ROLLBACKTO 7
191688: static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
191689:   switch( op ){
191690:     case FTS5_BEGIN:
191691:       assert( p->ts.eState==0 );
191692:       p->ts.eState = 1;
191693:       p->ts.iSavepoint = -1;
191694:       break;
191695: 
191696:     case FTS5_SYNC:
191697:       assert( p->ts.eState==1 );
191698:       p->ts.eState = 2;
191699:       break;
191700: 
191701:     case FTS5_COMMIT:
191702:       assert( p->ts.eState==2 );
191703:       p->ts.eState = 0;
191704:       break;
191705: 
191706:     case FTS5_ROLLBACK:
191707:       assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
191708:       p->ts.eState = 0;
191709:       break;
191710: 
191711:     case FTS5_SAVEPOINT:
191712:       assert( p->ts.eState==1 );
191713:       assert( iSavepoint>=0 );
191714:       assert( iSavepoint>p->ts.iSavepoint );
191715:       p->ts.iSavepoint = iSavepoint;
191716:       break;
191717:       
191718:     case FTS5_RELEASE:
191719:       assert( p->ts.eState==1 );
191720:       assert( iSavepoint>=0 );
191721:       assert( iSavepoint<=p->ts.iSavepoint );
191722:       p->ts.iSavepoint = iSavepoint-1;
191723:       break;
191724: 
191725:     case FTS5_ROLLBACKTO:
191726:       assert( p->ts.eState==1 );
191727:       assert( iSavepoint>=0 );
191728:       assert( iSavepoint<=p->ts.iSavepoint );
191729:       p->ts.iSavepoint = iSavepoint;
191730:       break;
191731:   }
191732: }
191733: #else
191734: # define fts5CheckTransactionState(x,y,z)
191735: #endif
191736: 
191737: /*
191738: ** Return true if pTab is a contentless table.
191739: */
191740: static int fts5IsContentless(Fts5Table *pTab){
191741:   return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
191742: }
191743: 
191744: /*
191745: ** Delete a virtual table handle allocated by fts5InitVtab(). 
191746: */
191747: static void fts5FreeVtab(Fts5Table *pTab){
191748:   if( pTab ){
191749:     sqlite3Fts5IndexClose(pTab->pIndex);
191750:     sqlite3Fts5StorageClose(pTab->pStorage);
191751:     sqlite3Fts5ConfigFree(pTab->pConfig);
191752:     sqlite3_free(pTab);
191753:   }
191754: }
191755: 
191756: /*
191757: ** The xDisconnect() virtual table method.
191758: */
191759: static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
191760:   fts5FreeVtab((Fts5Table*)pVtab);
191761:   return SQLITE_OK;
191762: }
191763: 
191764: /*
191765: ** The xDestroy() virtual table method.
191766: */
191767: static int fts5DestroyMethod(sqlite3_vtab *pVtab){
191768:   Fts5Table *pTab = (Fts5Table*)pVtab;
191769:   int rc = sqlite3Fts5DropAll(pTab->pConfig);
191770:   if( rc==SQLITE_OK ){
191771:     fts5FreeVtab((Fts5Table*)pVtab);
191772:   }
191773:   return rc;
191774: }
191775: 
191776: /*
191777: ** This function is the implementation of both the xConnect and xCreate
191778: ** methods of the FTS3 virtual table.
191779: **
191780: ** The argv[] array contains the following:
191781: **
191782: **   argv[0]   -> module name  ("fts5")
191783: **   argv[1]   -> database name
191784: **   argv[2]   -> table name
191785: **   argv[...] -> "column name" and other module argument fields.
191786: */
191787: static int fts5InitVtab(
191788:   int bCreate,                    /* True for xCreate, false for xConnect */
191789:   sqlite3 *db,                    /* The SQLite database connection */
191790:   void *pAux,                     /* Hash table containing tokenizers */
191791:   int argc,                       /* Number of elements in argv array */
191792:   const char * const *argv,       /* xCreate/xConnect argument array */
191793:   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
191794:   char **pzErr                    /* Write any error message here */
191795: ){
191796:   Fts5Global *pGlobal = (Fts5Global*)pAux;
191797:   const char **azConfig = (const char**)argv;
191798:   int rc = SQLITE_OK;             /* Return code */
191799:   Fts5Config *pConfig = 0;        /* Results of parsing argc/argv */
191800:   Fts5Table *pTab = 0;            /* New virtual table object */
191801: 
191802:   /* Allocate the new vtab object and parse the configuration */
191803:   pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
191804:   if( rc==SQLITE_OK ){
191805:     rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
191806:     assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
191807:   }
191808:   if( rc==SQLITE_OK ){
191809:     pTab->pConfig = pConfig;
191810:     pTab->pGlobal = pGlobal;
191811:   }
191812: 
191813:   /* Open the index sub-system */
191814:   if( rc==SQLITE_OK ){
191815:     rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
191816:   }
191817: 
191818:   /* Open the storage sub-system */
191819:   if( rc==SQLITE_OK ){
191820:     rc = sqlite3Fts5StorageOpen(
191821:         pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
191822:     );
191823:   }
191824: 
191825:   /* Call sqlite3_declare_vtab() */
191826:   if( rc==SQLITE_OK ){
191827:     rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
191828:   }
191829: 
191830:   /* Load the initial configuration */
191831:   if( rc==SQLITE_OK ){
191832:     assert( pConfig->pzErrmsg==0 );
191833:     pConfig->pzErrmsg = pzErr;
191834:     rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
191835:     sqlite3Fts5IndexRollback(pTab->pIndex);
191836:     pConfig->pzErrmsg = 0;
191837:   }
191838: 
191839:   if( rc!=SQLITE_OK ){
191840:     fts5FreeVtab(pTab);
191841:     pTab = 0;
191842:   }else if( bCreate ){
191843:     fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
191844:   }
191845:   *ppVTab = (sqlite3_vtab*)pTab;
191846:   return rc;
191847: }
191848: 
191849: /*
191850: ** The xConnect() and xCreate() methods for the virtual table. All the
191851: ** work is done in function fts5InitVtab().
191852: */
191853: static int fts5ConnectMethod(
191854:   sqlite3 *db,                    /* Database connection */
191855:   void *pAux,                     /* Pointer to tokenizer hash table */
191856:   int argc,                       /* Number of elements in argv array */
191857:   const char * const *argv,       /* xCreate/xConnect argument array */
191858:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
191859:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
191860: ){
191861:   return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
191862: }
191863: static int fts5CreateMethod(
191864:   sqlite3 *db,                    /* Database connection */
191865:   void *pAux,                     /* Pointer to tokenizer hash table */
191866:   int argc,                       /* Number of elements in argv array */
191867:   const char * const *argv,       /* xCreate/xConnect argument array */
191868:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
191869:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
191870: ){
191871:   return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
191872: }
191873: 
191874: /*
191875: ** The different query plans.
191876: */
191877: #define FTS5_PLAN_MATCH          1       /* (<tbl> MATCH ?) */
191878: #define FTS5_PLAN_SOURCE         2       /* A source cursor for SORTED_MATCH */
191879: #define FTS5_PLAN_SPECIAL        3       /* An internal query */
191880: #define FTS5_PLAN_SORTED_MATCH   4       /* (<tbl> MATCH ? ORDER BY rank) */
191881: #define FTS5_PLAN_SCAN           5       /* No usable constraint */
191882: #define FTS5_PLAN_ROWID          6       /* (rowid = ?) */
191883: 
191884: /*
191885: ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
191886: ** extension is currently being used by a version of SQLite too old to
191887: ** support index-info flags. In that case this function is a no-op.
191888: */
191889: static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
191890: #if SQLITE_VERSION_NUMBER>=3008012
191891: #ifndef SQLITE_CORE
191892:   if( sqlite3_libversion_number()>=3008012 )
191893: #endif
191894:   {
191895:     pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
191896:   }
191897: #endif
191898: }
191899: 
191900: /*
191901: ** Implementation of the xBestIndex method for FTS5 tables. Within the 
191902: ** WHERE constraint, it searches for the following:
191903: **
191904: **   1. A MATCH constraint against the special column.
191905: **   2. A MATCH constraint against the "rank" column.
191906: **   3. An == constraint against the rowid column.
191907: **   4. A < or <= constraint against the rowid column.
191908: **   5. A > or >= constraint against the rowid column.
191909: **
191910: ** Within the ORDER BY, either:
191911: **
191912: **   5. ORDER BY rank [ASC|DESC]
191913: **   6. ORDER BY rowid [ASC|DESC]
191914: **
191915: ** Costs are assigned as follows:
191916: **
191917: **  a) If an unusable MATCH operator is present in the WHERE clause, the
191918: **     cost is unconditionally set to 1e50 (a really big number).
191919: **
191920: **  a) If a MATCH operator is present, the cost depends on the other
191921: **     constraints also present. As follows:
191922: **
191923: **       * No other constraints:         cost=1000.0
191924: **       * One rowid range constraint:   cost=750.0
191925: **       * Both rowid range constraints: cost=500.0
191926: **       * An == rowid constraint:       cost=100.0
191927: **
191928: **  b) Otherwise, if there is no MATCH:
191929: **
191930: **       * No other constraints:         cost=1000000.0
191931: **       * One rowid range constraint:   cost=750000.0
191932: **       * Both rowid range constraints: cost=250000.0
191933: **       * An == rowid constraint:       cost=10.0
191934: **
191935: ** Costs are not modified by the ORDER BY clause.
191936: */
191937: static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
191938:   Fts5Table *pTab = (Fts5Table*)pVTab;
191939:   Fts5Config *pConfig = pTab->pConfig;
191940:   int idxFlags = 0;               /* Parameter passed through to xFilter() */
191941:   int bHasMatch;
191942:   int iNext;
191943:   int i;
191944: 
191945:   struct Constraint {
191946:     int op;                       /* Mask against sqlite3_index_constraint.op */
191947:     int fts5op;                   /* FTS5 mask for idxFlags */
191948:     int iCol;                     /* 0==rowid, 1==tbl, 2==rank */
191949:     int omit;                     /* True to omit this if found */
191950:     int iConsIndex;               /* Index in pInfo->aConstraint[] */
191951:   } aConstraint[] = {
191952:     {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, 
191953:                                     FTS5_BI_MATCH,    1, 1, -1},
191954:     {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ, 
191955:                                     FTS5_BI_RANK,     2, 1, -1},
191956:     {SQLITE_INDEX_CONSTRAINT_EQ,    FTS5_BI_ROWID_EQ, 0, 0, -1},
191957:     {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE, 
191958:                                     FTS5_BI_ROWID_LE, 0, 0, -1},
191959:     {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE, 
191960:                                     FTS5_BI_ROWID_GE, 0, 0, -1},
191961:   };
191962: 
191963:   int aColMap[3];
191964:   aColMap[0] = -1;
191965:   aColMap[1] = pConfig->nCol;
191966:   aColMap[2] = pConfig->nCol+1;
191967: 
191968:   /* Set idxFlags flags for all WHERE clause terms that will be used. */
191969:   for(i=0; i<pInfo->nConstraint; i++){
191970:     struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
191971:     int j;
191972:     for(j=0; j<ArraySize(aConstraint); j++){
191973:       struct Constraint *pC = &aConstraint[j];
191974:       if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
191975:         if( p->usable ){
191976:           pC->iConsIndex = i;
191977:           idxFlags |= pC->fts5op;
191978:         }else if( j==0 ){
191979:           /* As there exists an unusable MATCH constraint this is an 
191980:           ** unusable plan. Set a prohibitively high cost. */
191981:           pInfo->estimatedCost = 1e50;
191982:           return SQLITE_OK;
191983:         }
191984:       }
191985:     }
191986:   }
191987: 
191988:   /* Set idxFlags flags for the ORDER BY clause */
191989:   if( pInfo->nOrderBy==1 ){
191990:     int iSort = pInfo->aOrderBy[0].iColumn;
191991:     if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
191992:       idxFlags |= FTS5_BI_ORDER_RANK;
191993:     }else if( iSort==-1 ){
191994:       idxFlags |= FTS5_BI_ORDER_ROWID;
191995:     }
191996:     if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
191997:       pInfo->orderByConsumed = 1;
191998:       if( pInfo->aOrderBy[0].desc ){
191999:         idxFlags |= FTS5_BI_ORDER_DESC;
192000:       }
192001:     }
192002:   }
192003: 
192004:   /* Calculate the estimated cost based on the flags set in idxFlags. */
192005:   bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
192006:   if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
192007:     pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
192008:     if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
192009:   }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
192010:     pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
192011:   }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
192012:     pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
192013:   }else{
192014:     pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
192015:   }
192016: 
192017:   /* Assign argvIndex values to each constraint in use. */
192018:   iNext = 1;
192019:   for(i=0; i<ArraySize(aConstraint); i++){
192020:     struct Constraint *pC = &aConstraint[i];
192021:     if( pC->iConsIndex>=0 ){
192022:       pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
192023:       pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
192024:     }
192025:   }
192026: 
192027:   pInfo->idxNum = idxFlags;
192028:   return SQLITE_OK;
192029: }
192030: 
192031: static int fts5NewTransaction(Fts5Table *pTab){
192032:   Fts5Cursor *pCsr;
192033:   for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
192034:     if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
192035:   }
192036:   return sqlite3Fts5StorageReset(pTab->pStorage);
192037: }
192038: 
192039: /*
192040: ** Implementation of xOpen method.
192041: */
192042: static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
192043:   Fts5Table *pTab = (Fts5Table*)pVTab;
192044:   Fts5Config *pConfig = pTab->pConfig;
192045:   Fts5Cursor *pCsr = 0;           /* New cursor object */
192046:   int nByte;                      /* Bytes of space to allocate */
192047:   int rc;                         /* Return code */
192048: 
192049:   rc = fts5NewTransaction(pTab);
192050:   if( rc==SQLITE_OK ){
192051:     nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
192052:     pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
192053:     if( pCsr ){
192054:       Fts5Global *pGlobal = pTab->pGlobal;
192055:       memset(pCsr, 0, nByte);
192056:       pCsr->aColumnSize = (int*)&pCsr[1];
192057:       pCsr->pNext = pGlobal->pCsr;
192058:       pGlobal->pCsr = pCsr;
192059:       pCsr->iCsrId = ++pGlobal->iNextId;
192060:     }else{
192061:       rc = SQLITE_NOMEM;
192062:     }
192063:   }
192064:   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
192065:   return rc;
192066: }
192067: 
192068: static int fts5StmtType(Fts5Cursor *pCsr){
192069:   if( pCsr->ePlan==FTS5_PLAN_SCAN ){
192070:     return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
192071:   }
192072:   return FTS5_STMT_LOOKUP;
192073: }
192074: 
192075: /*
192076: ** This function is called after the cursor passed as the only argument
192077: ** is moved to point at a different row. It clears all cached data 
192078: ** specific to the previous row stored by the cursor object.
192079: */
192080: static void fts5CsrNewrow(Fts5Cursor *pCsr){
192081:   CsrFlagSet(pCsr, 
192082:       FTS5CSR_REQUIRE_CONTENT 
192083:     | FTS5CSR_REQUIRE_DOCSIZE 
192084:     | FTS5CSR_REQUIRE_INST 
192085:     | FTS5CSR_REQUIRE_POSLIST 
192086:   );
192087: }
192088: 
192089: static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
192090:   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192091:   Fts5Auxdata *pData;
192092:   Fts5Auxdata *pNext;
192093: 
192094:   sqlite3_free(pCsr->aInstIter);
192095:   sqlite3_free(pCsr->aInst);
192096:   if( pCsr->pStmt ){
192097:     int eStmt = fts5StmtType(pCsr);
192098:     sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
192099:   }
192100:   if( pCsr->pSorter ){
192101:     Fts5Sorter *pSorter = pCsr->pSorter;
192102:     sqlite3_finalize(pSorter->pStmt);
192103:     sqlite3_free(pSorter);
192104:   }
192105: 
192106:   if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
192107:     sqlite3Fts5ExprFree(pCsr->pExpr);
192108:   }
192109: 
192110:   for(pData=pCsr->pAuxdata; pData; pData=pNext){
192111:     pNext = pData->pNext;
192112:     if( pData->xDelete ) pData->xDelete(pData->pPtr);
192113:     sqlite3_free(pData);
192114:   }
192115: 
192116:   sqlite3_finalize(pCsr->pRankArgStmt);
192117:   sqlite3_free(pCsr->apRankArg);
192118: 
192119:   if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
192120:     sqlite3_free(pCsr->zRank);
192121:     sqlite3_free(pCsr->zRankArgs);
192122:   }
192123: 
192124:   memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
192125: }
192126: 
192127: 
192128: /*
192129: ** Close the cursor.  For additional information see the documentation
192130: ** on the xClose method of the virtual table interface.
192131: */
192132: static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
192133:   if( pCursor ){
192134:     Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
192135:     Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192136:     Fts5Cursor **pp;
192137: 
192138:     fts5FreeCursorComponents(pCsr);
192139:     /* Remove the cursor from the Fts5Global.pCsr list */
192140:     for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
192141:     *pp = pCsr->pNext;
192142: 
192143:     sqlite3_free(pCsr);
192144:   }
192145:   return SQLITE_OK;
192146: }
192147: 
192148: static int fts5SorterNext(Fts5Cursor *pCsr){
192149:   Fts5Sorter *pSorter = pCsr->pSorter;
192150:   int rc;
192151: 
192152:   rc = sqlite3_step(pSorter->pStmt);
192153:   if( rc==SQLITE_DONE ){
192154:     rc = SQLITE_OK;
192155:     CsrFlagSet(pCsr, FTS5CSR_EOF);
192156:   }else if( rc==SQLITE_ROW ){
192157:     const u8 *a;
192158:     const u8 *aBlob;
192159:     int nBlob;
192160:     int i;
192161:     int iOff = 0;
192162:     rc = SQLITE_OK;
192163: 
192164:     pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
192165:     nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
192166:     aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
192167: 
192168:     /* nBlob==0 in detail=none mode. */
192169:     if( nBlob>0 ){
192170:       for(i=0; i<(pSorter->nIdx-1); i++){
192171:         int iVal;
192172:         a += fts5GetVarint32(a, iVal);
192173:         iOff += iVal;
192174:         pSorter->aIdx[i] = iOff;
192175:       }
192176:       pSorter->aIdx[i] = &aBlob[nBlob] - a;
192177:       pSorter->aPoslist = a;
192178:     }
192179: 
192180:     fts5CsrNewrow(pCsr);
192181:   }
192182: 
192183:   return rc;
192184: }
192185: 
192186: 
192187: /*
192188: ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors 
192189: ** open on table pTab.
192190: */
192191: static void fts5TripCursors(Fts5Table *pTab){
192192:   Fts5Cursor *pCsr;
192193:   for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
192194:     if( pCsr->ePlan==FTS5_PLAN_MATCH
192195:      && pCsr->base.pVtab==(sqlite3_vtab*)pTab 
192196:     ){
192197:       CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
192198:     }
192199:   }
192200: }
192201: 
192202: /*
192203: ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
192204: ** argument, close and reopen all Fts5IndexIter iterators that the cursor 
192205: ** is using. Then attempt to move the cursor to a rowid equal to or laster
192206: ** (in the cursors sort order - ASC or DESC) than the current rowid. 
192207: **
192208: ** If the new rowid is not equal to the old, set output parameter *pbSkip
192209: ** to 1 before returning. Otherwise, leave it unchanged.
192210: **
192211: ** Return SQLITE_OK if successful or if no reseek was required, or an 
192212: ** error code if an error occurred.
192213: */
192214: static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
192215:   int rc = SQLITE_OK;
192216:   assert( *pbSkip==0 );
192217:   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
192218:     Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192219:     int bDesc = pCsr->bDesc;
192220:     i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
192221: 
192222:     rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
192223:     if( rc==SQLITE_OK &&  iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
192224:       *pbSkip = 1;
192225:     }
192226: 
192227:     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
192228:     fts5CsrNewrow(pCsr);
192229:     if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
192230:       CsrFlagSet(pCsr, FTS5CSR_EOF);
192231:       *pbSkip = 1;
192232:     }
192233:   }
192234:   return rc;
192235: }
192236: 
192237: 
192238: /*
192239: ** Advance the cursor to the next row in the table that matches the 
192240: ** search criteria.
192241: **
192242: ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
192243: ** even if we reach end-of-file.  The fts5EofMethod() will be called
192244: ** subsequently to determine whether or not an EOF was hit.
192245: */
192246: static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
192247:   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192248:   int rc;
192249: 
192250:   assert( (pCsr->ePlan<3)==
192251:           (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE) 
192252:   );
192253:   assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
192254: 
192255:   if( pCsr->ePlan<3 ){
192256:     int bSkip = 0;
192257:     if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
192258:     rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
192259:     CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
192260:     fts5CsrNewrow(pCsr);
192261:   }else{
192262:     switch( pCsr->ePlan ){
192263:       case FTS5_PLAN_SPECIAL: {
192264:         CsrFlagSet(pCsr, FTS5CSR_EOF);
192265:         rc = SQLITE_OK;
192266:         break;
192267:       }
192268:   
192269:       case FTS5_PLAN_SORTED_MATCH: {
192270:         rc = fts5SorterNext(pCsr);
192271:         break;
192272:       }
192273:   
192274:       default:
192275:         rc = sqlite3_step(pCsr->pStmt);
192276:         if( rc!=SQLITE_ROW ){
192277:           CsrFlagSet(pCsr, FTS5CSR_EOF);
192278:           rc = sqlite3_reset(pCsr->pStmt);
192279:         }else{
192280:           rc = SQLITE_OK;
192281:         }
192282:         break;
192283:     }
192284:   }
192285:   
192286:   return rc;
192287: }
192288: 
192289: 
192290: static int fts5PrepareStatement(
192291:   sqlite3_stmt **ppStmt,
192292:   Fts5Config *pConfig, 
192293:   const char *zFmt,
192294:   ...
192295: ){
192296:   sqlite3_stmt *pRet = 0;
192297:   int rc;
192298:   char *zSql;
192299:   va_list ap;
192300: 
192301:   va_start(ap, zFmt);
192302:   zSql = sqlite3_vmprintf(zFmt, ap);
192303:   if( zSql==0 ){
192304:     rc = SQLITE_NOMEM; 
192305:   }else{
192306:     rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
192307:     if( rc!=SQLITE_OK ){
192308:       *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
192309:     }
192310:     sqlite3_free(zSql);
192311:   }
192312: 
192313:   va_end(ap);
192314:   *ppStmt = pRet;
192315:   return rc;
192316: } 
192317: 
192318: static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
192319:   Fts5Config *pConfig = pTab->pConfig;
192320:   Fts5Sorter *pSorter;
192321:   int nPhrase;
192322:   int nByte;
192323:   int rc;
192324:   const char *zRank = pCsr->zRank;
192325:   const char *zRankArgs = pCsr->zRankArgs;
192326:   
192327:   nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
192328:   nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
192329:   pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
192330:   if( pSorter==0 ) return SQLITE_NOMEM;
192331:   memset(pSorter, 0, nByte);
192332:   pSorter->nIdx = nPhrase;
192333: 
192334:   /* TODO: It would be better to have some system for reusing statement
192335:   ** handles here, rather than preparing a new one for each query. But that
192336:   ** is not possible as SQLite reference counts the virtual table objects.
192337:   ** And since the statement required here reads from this very virtual 
192338:   ** table, saving it creates a circular reference.
192339:   **
192340:   ** If SQLite a built-in statement cache, this wouldn't be a problem. */
192341:   rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
192342:       "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
192343:       pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
192344:       (zRankArgs ? ", " : ""),
192345:       (zRankArgs ? zRankArgs : ""),
192346:       bDesc ? "DESC" : "ASC"
192347:   );
192348: 
192349:   pCsr->pSorter = pSorter;
192350:   if( rc==SQLITE_OK ){
192351:     assert( pTab->pSortCsr==0 );
192352:     pTab->pSortCsr = pCsr;
192353:     rc = fts5SorterNext(pCsr);
192354:     pTab->pSortCsr = 0;
192355:   }
192356: 
192357:   if( rc!=SQLITE_OK ){
192358:     sqlite3_finalize(pSorter->pStmt);
192359:     sqlite3_free(pSorter);
192360:     pCsr->pSorter = 0;
192361:   }
192362: 
192363:   return rc;
192364: }
192365: 
192366: static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
192367:   int rc;
192368:   Fts5Expr *pExpr = pCsr->pExpr;
192369:   rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
192370:   if( sqlite3Fts5ExprEof(pExpr) ){
192371:     CsrFlagSet(pCsr, FTS5CSR_EOF);
192372:   }
192373:   fts5CsrNewrow(pCsr);
192374:   return rc;
192375: }
192376: 
192377: /*
192378: ** Process a "special" query. A special query is identified as one with a
192379: ** MATCH expression that begins with a '*' character. The remainder of
192380: ** the text passed to the MATCH operator are used as  the special query
192381: ** parameters.
192382: */
192383: static int fts5SpecialMatch(
192384:   Fts5Table *pTab, 
192385:   Fts5Cursor *pCsr, 
192386:   const char *zQuery
192387: ){
192388:   int rc = SQLITE_OK;             /* Return code */
192389:   const char *z = zQuery;         /* Special query text */
192390:   int n;                          /* Number of bytes in text at z */
192391: 
192392:   while( z[0]==' ' ) z++;
192393:   for(n=0; z[n] && z[n]!=' '; n++);
192394: 
192395:   assert( pTab->base.zErrMsg==0 );
192396:   pCsr->ePlan = FTS5_PLAN_SPECIAL;
192397: 
192398:   if( 0==sqlite3_strnicmp("reads", z, n) ){
192399:     pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
192400:   }
192401:   else if( 0==sqlite3_strnicmp("id", z, n) ){
192402:     pCsr->iSpecial = pCsr->iCsrId;
192403:   }
192404:   else{
192405:     /* An unrecognized directive. Return an error message. */
192406:     pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
192407:     rc = SQLITE_ERROR;
192408:   }
192409: 
192410:   return rc;
192411: }
192412: 
192413: /*
192414: ** Search for an auxiliary function named zName that can be used with table
192415: ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
192416: ** structure. Otherwise, if no such function exists, return NULL.
192417: */
192418: static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
192419:   Fts5Auxiliary *pAux;
192420: 
192421:   for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
192422:     if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
192423:   }
192424: 
192425:   /* No function of the specified name was found. Return 0. */
192426:   return 0;
192427: }
192428: 
192429: 
192430: static int fts5FindRankFunction(Fts5Cursor *pCsr){
192431:   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192432:   Fts5Config *pConfig = pTab->pConfig;
192433:   int rc = SQLITE_OK;
192434:   Fts5Auxiliary *pAux = 0;
192435:   const char *zRank = pCsr->zRank;
192436:   const char *zRankArgs = pCsr->zRankArgs;
192437: 
192438:   if( zRankArgs ){
192439:     char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
192440:     if( zSql ){
192441:       sqlite3_stmt *pStmt = 0;
192442:       rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
192443:       sqlite3_free(zSql);
192444:       assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
192445:       if( rc==SQLITE_OK ){
192446:         if( SQLITE_ROW==sqlite3_step(pStmt) ){
192447:           int nByte;
192448:           pCsr->nRankArg = sqlite3_column_count(pStmt);
192449:           nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
192450:           pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
192451:           if( rc==SQLITE_OK ){
192452:             int i;
192453:             for(i=0; i<pCsr->nRankArg; i++){
192454:               pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
192455:             }
192456:           }
192457:           pCsr->pRankArgStmt = pStmt;
192458:         }else{
192459:           rc = sqlite3_finalize(pStmt);
192460:           assert( rc!=SQLITE_OK );
192461:         }
192462:       }
192463:     }
192464:   }
192465: 
192466:   if( rc==SQLITE_OK ){
192467:     pAux = fts5FindAuxiliary(pTab, zRank);
192468:     if( pAux==0 ){
192469:       assert( pTab->base.zErrMsg==0 );
192470:       pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
192471:       rc = SQLITE_ERROR;
192472:     }
192473:   }
192474: 
192475:   pCsr->pRank = pAux;
192476:   return rc;
192477: }
192478: 
192479: 
192480: static int fts5CursorParseRank(
192481:   Fts5Config *pConfig,
192482:   Fts5Cursor *pCsr, 
192483:   sqlite3_value *pRank
192484: ){
192485:   int rc = SQLITE_OK;
192486:   if( pRank ){
192487:     const char *z = (const char*)sqlite3_value_text(pRank);
192488:     char *zRank = 0;
192489:     char *zRankArgs = 0;
192490: 
192491:     if( z==0 ){
192492:       if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
192493:     }else{
192494:       rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
192495:     }
192496:     if( rc==SQLITE_OK ){
192497:       pCsr->zRank = zRank;
192498:       pCsr->zRankArgs = zRankArgs;
192499:       CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
192500:     }else if( rc==SQLITE_ERROR ){
192501:       pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
192502:           "parse error in rank function: %s", z
192503:       );
192504:     }
192505:   }else{
192506:     if( pConfig->zRank ){
192507:       pCsr->zRank = (char*)pConfig->zRank;
192508:       pCsr->zRankArgs = (char*)pConfig->zRankArgs;
192509:     }else{
192510:       pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
192511:       pCsr->zRankArgs = 0;
192512:     }
192513:   }
192514:   return rc;
192515: }
192516: 
192517: static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
192518:   if( pVal ){
192519:     int eType = sqlite3_value_numeric_type(pVal);
192520:     if( eType==SQLITE_INTEGER ){
192521:       return sqlite3_value_int64(pVal);
192522:     }
192523:   }
192524:   return iDefault;
192525: }
192526: 
192527: /*
192528: ** This is the xFilter interface for the virtual table.  See
192529: ** the virtual table xFilter method documentation for additional
192530: ** information.
192531: ** 
192532: ** There are three possible query strategies:
192533: **
192534: **   1. Full-text search using a MATCH operator.
192535: **   2. A by-rowid lookup.
192536: **   3. A full-table scan.
192537: */
192538: static int fts5FilterMethod(
192539:   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
192540:   int idxNum,                     /* Strategy index */
192541:   const char *zUnused,            /* Unused */
192542:   int nVal,                       /* Number of elements in apVal */
192543:   sqlite3_value **apVal           /* Arguments for the indexing scheme */
192544: ){
192545:   Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
192546:   Fts5Config *pConfig = pTab->pConfig;
192547:   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192548:   int rc = SQLITE_OK;             /* Error code */
192549:   int iVal = 0;                   /* Counter for apVal[] */
192550:   int bDesc;                      /* True if ORDER BY [rank|rowid] DESC */
192551:   int bOrderByRank;               /* True if ORDER BY rank */
192552:   sqlite3_value *pMatch = 0;      /* <tbl> MATCH ? expression (or NULL) */
192553:   sqlite3_value *pRank = 0;       /* rank MATCH ? expression (or NULL) */
192554:   sqlite3_value *pRowidEq = 0;    /* rowid = ? expression (or NULL) */
192555:   sqlite3_value *pRowidLe = 0;    /* rowid <= ? expression (or NULL) */
192556:   sqlite3_value *pRowidGe = 0;    /* rowid >= ? expression (or NULL) */
192557:   char **pzErrmsg = pConfig->pzErrmsg;
192558: 
192559:   UNUSED_PARAM(zUnused);
192560:   UNUSED_PARAM(nVal);
192561: 
192562:   if( pCsr->ePlan ){
192563:     fts5FreeCursorComponents(pCsr);
192564:     memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
192565:   }
192566: 
192567:   assert( pCsr->pStmt==0 );
192568:   assert( pCsr->pExpr==0 );
192569:   assert( pCsr->csrflags==0 );
192570:   assert( pCsr->pRank==0 );
192571:   assert( pCsr->zRank==0 );
192572:   assert( pCsr->zRankArgs==0 );
192573: 
192574:   assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
192575:   pConfig->pzErrmsg = &pTab->base.zErrMsg;
192576: 
192577:   /* Decode the arguments passed through to this function.
192578:   **
192579:   ** Note: The following set of if(...) statements must be in the same
192580:   ** order as the corresponding entries in the struct at the top of
192581:   ** fts5BestIndexMethod().  */
192582:   if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
192583:   if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
192584:   if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
192585:   if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
192586:   if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
192587:   assert( iVal==nVal );
192588:   bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
192589:   pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
192590: 
192591:   /* Set the cursor upper and lower rowid limits. Only some strategies 
192592:   ** actually use them. This is ok, as the xBestIndex() method leaves the
192593:   ** sqlite3_index_constraint.omit flag clear for range constraints
192594:   ** on the rowid field.  */
192595:   if( pRowidEq ){
192596:     pRowidLe = pRowidGe = pRowidEq;
192597:   }
192598:   if( bDesc ){
192599:     pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
192600:     pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
192601:   }else{
192602:     pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
192603:     pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
192604:   }
192605: 
192606:   if( pTab->pSortCsr ){
192607:     /* If pSortCsr is non-NULL, then this call is being made as part of 
192608:     ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
192609:     ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
192610:     ** return results to the user for this query. The current cursor 
192611:     ** (pCursor) is used to execute the query issued by function 
192612:     ** fts5CursorFirstSorted() above.  */
192613:     assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
192614:     assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
192615:     assert( pCsr->iLastRowid==LARGEST_INT64 );
192616:     assert( pCsr->iFirstRowid==SMALLEST_INT64 );
192617:     pCsr->ePlan = FTS5_PLAN_SOURCE;
192618:     pCsr->pExpr = pTab->pSortCsr->pExpr;
192619:     rc = fts5CursorFirst(pTab, pCsr, bDesc);
192620:   }else if( pMatch ){
192621:     const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
192622:     if( zExpr==0 ) zExpr = "";
192623: 
192624:     rc = fts5CursorParseRank(pConfig, pCsr, pRank);
192625:     if( rc==SQLITE_OK ){
192626:       if( zExpr[0]=='*' ){
192627:         /* The user has issued a query of the form "MATCH '*...'". This
192628:         ** indicates that the MATCH expression is not a full text query,
192629:         ** but a request for an internal parameter.  */
192630:         rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
192631:       }else{
192632:         char **pzErr = &pTab->base.zErrMsg;
192633:         rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
192634:         if( rc==SQLITE_OK ){
192635:           if( bOrderByRank ){
192636:             pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
192637:             rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
192638:           }else{
192639:             pCsr->ePlan = FTS5_PLAN_MATCH;
192640:             rc = fts5CursorFirst(pTab, pCsr, bDesc);
192641:           }
192642:         }
192643:       }
192644:     }
192645:   }else if( pConfig->zContent==0 ){
192646:     *pConfig->pzErrmsg = sqlite3_mprintf(
192647:         "%s: table does not support scanning", pConfig->zName
192648:     );
192649:     rc = SQLITE_ERROR;
192650:   }else{
192651:     /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
192652:     ** by rowid (ePlan==FTS5_PLAN_ROWID).  */
192653:     pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
192654:     rc = sqlite3Fts5StorageStmt(
192655:         pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
192656:     );
192657:     if( rc==SQLITE_OK ){
192658:       if( pCsr->ePlan==FTS5_PLAN_ROWID ){
192659:         sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
192660:       }else{
192661:         sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
192662:         sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
192663:       }
192664:       rc = fts5NextMethod(pCursor);
192665:     }
192666:   }
192667: 
192668:   pConfig->pzErrmsg = pzErrmsg;
192669:   return rc;
192670: }
192671: 
192672: /* 
192673: ** This is the xEof method of the virtual table. SQLite calls this 
192674: ** routine to find out if it has reached the end of a result set.
192675: */
192676: static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
192677:   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192678:   return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
192679: }
192680: 
192681: /*
192682: ** Return the rowid that the cursor currently points to.
192683: */
192684: static i64 fts5CursorRowid(Fts5Cursor *pCsr){
192685:   assert( pCsr->ePlan==FTS5_PLAN_MATCH 
192686:        || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH 
192687:        || pCsr->ePlan==FTS5_PLAN_SOURCE 
192688:   );
192689:   if( pCsr->pSorter ){
192690:     return pCsr->pSorter->iRowid;
192691:   }else{
192692:     return sqlite3Fts5ExprRowid(pCsr->pExpr);
192693:   }
192694: }
192695: 
192696: /* 
192697: ** This is the xRowid method. The SQLite core calls this routine to
192698: ** retrieve the rowid for the current row of the result set. fts5
192699: ** exposes %_content.rowid as the rowid for the virtual table. The
192700: ** rowid should be written to *pRowid.
192701: */
192702: static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
192703:   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192704:   int ePlan = pCsr->ePlan;
192705:   
192706:   assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
192707:   switch( ePlan ){
192708:     case FTS5_PLAN_SPECIAL:
192709:       *pRowid = 0;
192710:       break;
192711: 
192712:     case FTS5_PLAN_SOURCE:
192713:     case FTS5_PLAN_MATCH:
192714:     case FTS5_PLAN_SORTED_MATCH:
192715:       *pRowid = fts5CursorRowid(pCsr);
192716:       break;
192717: 
192718:     default:
192719:       *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
192720:       break;
192721:   }
192722: 
192723:   return SQLITE_OK;
192724: }
192725: 
192726: /*
192727: ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
192728: ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
192729: **
192730: ** If argument bErrormsg is true and an error occurs, an error message may
192731: ** be left in sqlite3_vtab.zErrMsg.
192732: */
192733: static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
192734:   int rc = SQLITE_OK;
192735: 
192736:   /* If the cursor does not yet have a statement handle, obtain one now. */ 
192737:   if( pCsr->pStmt==0 ){
192738:     Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192739:     int eStmt = fts5StmtType(pCsr);
192740:     rc = sqlite3Fts5StorageStmt(
192741:         pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
192742:     );
192743:     assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
192744:     assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
192745:   }
192746: 
192747:   if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
192748:     assert( pCsr->pExpr );
192749:     sqlite3_reset(pCsr->pStmt);
192750:     sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
192751:     rc = sqlite3_step(pCsr->pStmt);
192752:     if( rc==SQLITE_ROW ){
192753:       rc = SQLITE_OK;
192754:       CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
192755:     }else{
192756:       rc = sqlite3_reset(pCsr->pStmt);
192757:       if( rc==SQLITE_OK ){
192758:         rc = FTS5_CORRUPT;
192759:       }
192760:     }
192761:   }
192762:   return rc;
192763: }
192764: 
192765: static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
192766:   va_list ap;                     /* ... printf arguments */
192767:   va_start(ap, zFormat);
192768:   assert( p->base.zErrMsg==0 );
192769:   p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
192770:   va_end(ap);
192771: }
192772: 
192773: /*
192774: ** This function is called to handle an FTS INSERT command. In other words,
192775: ** an INSERT statement of the form:
192776: **
192777: **     INSERT INTO fts(fts) VALUES($pCmd)
192778: **     INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
192779: **
192780: ** Argument pVal is the value assigned to column "fts" by the INSERT 
192781: ** statement. This function returns SQLITE_OK if successful, or an SQLite
192782: ** error code if an error occurs.
192783: **
192784: ** The commands implemented by this function are documented in the "Special
192785: ** INSERT Directives" section of the documentation. It should be updated if
192786: ** more commands are added to this function.
192787: */
192788: static int fts5SpecialInsert(
192789:   Fts5Table *pTab,                /* Fts5 table object */
192790:   const char *zCmd,               /* Text inserted into table-name column */
192791:   sqlite3_value *pVal             /* Value inserted into rank column */
192792: ){
192793:   Fts5Config *pConfig = pTab->pConfig;
192794:   int rc = SQLITE_OK;
192795:   int bError = 0;
192796: 
192797:   if( 0==sqlite3_stricmp("delete-all", zCmd) ){
192798:     if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
192799:       fts5SetVtabError(pTab, 
192800:           "'delete-all' may only be used with a "
192801:           "contentless or external content fts5 table"
192802:       );
192803:       rc = SQLITE_ERROR;
192804:     }else{
192805:       rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
192806:     }
192807:   }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
192808:     if( pConfig->eContent==FTS5_CONTENT_NONE ){
192809:       fts5SetVtabError(pTab, 
192810:           "'rebuild' may not be used with a contentless fts5 table"
192811:       );
192812:       rc = SQLITE_ERROR;
192813:     }else{
192814:       rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
192815:     }
192816:   }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
192817:     rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
192818:   }else if( 0==sqlite3_stricmp("merge", zCmd) ){
192819:     int nMerge = sqlite3_value_int(pVal);
192820:     rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
192821:   }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
192822:     rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
192823: #ifdef SQLITE_DEBUG
192824:   }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
192825:     pConfig->bPrefixIndex = sqlite3_value_int(pVal);
192826: #endif
192827:   }else{
192828:     rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
192829:     if( rc==SQLITE_OK ){
192830:       rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
192831:     }
192832:     if( rc==SQLITE_OK ){
192833:       if( bError ){
192834:         rc = SQLITE_ERROR;
192835:       }else{
192836:         rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
192837:       }
192838:     }
192839:   }
192840:   return rc;
192841: }
192842: 
192843: static int fts5SpecialDelete(
192844:   Fts5Table *pTab, 
192845:   sqlite3_value **apVal
192846: ){
192847:   int rc = SQLITE_OK;
192848:   int eType1 = sqlite3_value_type(apVal[1]);
192849:   if( eType1==SQLITE_INTEGER ){
192850:     sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
192851:     rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
192852:   }
192853:   return rc;
192854: }
192855: 
192856: static void fts5StorageInsert(
192857:   int *pRc, 
192858:   Fts5Table *pTab, 
192859:   sqlite3_value **apVal, 
192860:   i64 *piRowid
192861: ){
192862:   int rc = *pRc;
192863:   if( rc==SQLITE_OK ){
192864:     rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
192865:   }
192866:   if( rc==SQLITE_OK ){
192867:     rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
192868:   }
192869:   *pRc = rc;
192870: }
192871: 
192872: /* 
192873: ** This function is the implementation of the xUpdate callback used by 
192874: ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
192875: ** inserted, updated or deleted.
192876: **
192877: ** A delete specifies a single argument - the rowid of the row to remove.
192878: ** 
192879: ** Update and insert operations pass:
192880: **
192881: **   1. The "old" rowid, or NULL.
192882: **   2. The "new" rowid.
192883: **   3. Values for each of the nCol matchable columns.
192884: **   4. Values for the two hidden columns (<tablename> and "rank").
192885: */
192886: static int fts5UpdateMethod(
192887:   sqlite3_vtab *pVtab,            /* Virtual table handle */
192888:   int nArg,                       /* Size of argument array */
192889:   sqlite3_value **apVal,          /* Array of arguments */
192890:   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
192891: ){
192892:   Fts5Table *pTab = (Fts5Table*)pVtab;
192893:   Fts5Config *pConfig = pTab->pConfig;
192894:   int eType0;                     /* value_type() of apVal[0] */
192895:   int rc = SQLITE_OK;             /* Return code */
192896: 
192897:   /* A transaction must be open when this is called. */
192898:   assert( pTab->ts.eState==1 );
192899: 
192900:   assert( pVtab->zErrMsg==0 );
192901:   assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
192902:   assert( nArg==1 
192903:       || sqlite3_value_type(apVal[1])==SQLITE_INTEGER 
192904:       || sqlite3_value_type(apVal[1])==SQLITE_NULL 
192905:   );
192906:   assert( pTab->pConfig->pzErrmsg==0 );
192907:   pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
192908: 
192909:   /* Put any active cursors into REQUIRE_SEEK state. */
192910:   fts5TripCursors(pTab);
192911: 
192912:   eType0 = sqlite3_value_type(apVal[0]);
192913:   if( eType0==SQLITE_NULL 
192914:    && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL 
192915:   ){
192916:     /* A "special" INSERT op. These are handled separately. */
192917:     const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
192918:     if( pConfig->eContent!=FTS5_CONTENT_NORMAL 
192919:       && 0==sqlite3_stricmp("delete", z) 
192920:     ){
192921:       rc = fts5SpecialDelete(pTab, apVal);
192922:     }else{
192923:       rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
192924:     }
192925:   }else{
192926:     /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
192927:     ** any conflict on the rowid value must be detected before any 
192928:     ** modifications are made to the database file. There are 4 cases:
192929:     **
192930:     **   1) DELETE
192931:     **   2) UPDATE (rowid not modified)
192932:     **   3) UPDATE (rowid modified)
192933:     **   4) INSERT
192934:     **
192935:     ** Cases 3 and 4 may violate the rowid constraint.
192936:     */
192937:     int eConflict = SQLITE_ABORT;
192938:     if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
192939:       eConflict = sqlite3_vtab_on_conflict(pConfig->db);
192940:     }
192941: 
192942:     assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
192943:     assert( nArg!=1 || eType0==SQLITE_INTEGER );
192944: 
192945:     /* Filter out attempts to run UPDATE or DELETE on contentless tables.
192946:     ** This is not suported.  */
192947:     if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
192948:       pTab->base.zErrMsg = sqlite3_mprintf(
192949:           "cannot %s contentless fts5 table: %s", 
192950:           (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
192951:       );
192952:       rc = SQLITE_ERROR;
192953:     }
192954: 
192955:     /* DELETE */
192956:     else if( nArg==1 ){
192957:       i64 iDel = sqlite3_value_int64(apVal[0]);  /* Rowid to delete */
192958:       rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
192959:     }
192960: 
192961:     /* INSERT */
192962:     else if( eType0!=SQLITE_INTEGER ){     
192963:       /* If this is a REPLACE, first remove the current entry (if any) */
192964:       if( eConflict==SQLITE_REPLACE 
192965:        && sqlite3_value_type(apVal[1])==SQLITE_INTEGER 
192966:       ){
192967:         i64 iNew = sqlite3_value_int64(apVal[1]);  /* Rowid to delete */
192968:         rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
192969:       }
192970:       fts5StorageInsert(&rc, pTab, apVal, pRowid);
192971:     }
192972: 
192973:     /* UPDATE */
192974:     else{
192975:       i64 iOld = sqlite3_value_int64(apVal[0]);  /* Old rowid */
192976:       i64 iNew = sqlite3_value_int64(apVal[1]);  /* New rowid */
192977:       if( iOld!=iNew ){
192978:         if( eConflict==SQLITE_REPLACE ){
192979:           rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192980:           if( rc==SQLITE_OK ){
192981:             rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
192982:           }
192983:           fts5StorageInsert(&rc, pTab, apVal, pRowid);
192984:         }else{
192985:           rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
192986:           if( rc==SQLITE_OK ){
192987:             rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192988:           }
192989:           if( rc==SQLITE_OK ){
192990:             rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
192991:           }
192992:         }
192993:       }else{
192994:         rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
192995:         fts5StorageInsert(&rc, pTab, apVal, pRowid);
192996:       }
192997:     }
192998:   }
192999: 
193000:   pTab->pConfig->pzErrmsg = 0;
193001:   return rc;
193002: }
193003: 
193004: /*
193005: ** Implementation of xSync() method. 
193006: */
193007: static int fts5SyncMethod(sqlite3_vtab *pVtab){
193008:   int rc;
193009:   Fts5Table *pTab = (Fts5Table*)pVtab;
193010:   fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
193011:   pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
193012:   fts5TripCursors(pTab);
193013:   rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
193014:   pTab->pConfig->pzErrmsg = 0;
193015:   return rc;
193016: }
193017: 
193018: /*
193019: ** Implementation of xBegin() method. 
193020: */
193021: static int fts5BeginMethod(sqlite3_vtab *pVtab){
193022:   fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
193023:   fts5NewTransaction((Fts5Table*)pVtab);
193024:   return SQLITE_OK;
193025: }
193026: 
193027: /*
193028: ** Implementation of xCommit() method. This is a no-op. The contents of
193029: ** the pending-terms hash-table have already been flushed into the database
193030: ** by fts5SyncMethod().
193031: */
193032: static int fts5CommitMethod(sqlite3_vtab *pVtab){
193033:   UNUSED_PARAM(pVtab);  /* Call below is a no-op for NDEBUG builds */
193034:   fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
193035:   return SQLITE_OK;
193036: }
193037: 
193038: /*
193039: ** Implementation of xRollback(). Discard the contents of the pending-terms
193040: ** hash-table. Any changes made to the database are reverted by SQLite.
193041: */
193042: static int fts5RollbackMethod(sqlite3_vtab *pVtab){
193043:   int rc;
193044:   Fts5Table *pTab = (Fts5Table*)pVtab;
193045:   fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
193046:   rc = sqlite3Fts5StorageRollback(pTab->pStorage);
193047:   return rc;
193048: }
193049: 
193050: static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
193051: 
193052: static void *fts5ApiUserData(Fts5Context *pCtx){
193053:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193054:   return pCsr->pAux->pUserData;
193055: }
193056: 
193057: static int fts5ApiColumnCount(Fts5Context *pCtx){
193058:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193059:   return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
193060: }
193061: 
193062: static int fts5ApiColumnTotalSize(
193063:   Fts5Context *pCtx, 
193064:   int iCol, 
193065:   sqlite3_int64 *pnToken
193066: ){
193067:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193068:   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193069:   return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
193070: }
193071: 
193072: static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
193073:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193074:   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193075:   return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
193076: }
193077: 
193078: static int fts5ApiTokenize(
193079:   Fts5Context *pCtx, 
193080:   const char *pText, int nText, 
193081:   void *pUserData,
193082:   int (*xToken)(void*, int, const char*, int, int, int)
193083: ){
193084:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193085:   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193086:   return sqlite3Fts5Tokenize(
193087:       pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
193088:   );
193089: }
193090: 
193091: static int fts5ApiPhraseCount(Fts5Context *pCtx){
193092:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193093:   return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193094: }
193095: 
193096: static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
193097:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193098:   return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
193099: }
193100: 
193101: static int fts5ApiColumnText(
193102:   Fts5Context *pCtx, 
193103:   int iCol, 
193104:   const char **pz, 
193105:   int *pn
193106: ){
193107:   int rc = SQLITE_OK;
193108:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193109:   if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
193110:     *pz = 0;
193111:     *pn = 0;
193112:   }else{
193113:     rc = fts5SeekCursor(pCsr, 0);
193114:     if( rc==SQLITE_OK ){
193115:       *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
193116:       *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
193117:     }
193118:   }
193119:   return rc;
193120: }
193121: 
193122: static int fts5CsrPoslist(
193123:   Fts5Cursor *pCsr, 
193124:   int iPhrase, 
193125:   const u8 **pa,
193126:   int *pn
193127: ){
193128:   Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193129:   int rc = SQLITE_OK;
193130:   int bLive = (pCsr->pSorter==0);
193131: 
193132:   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
193133: 
193134:     if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
193135:       Fts5PoslistPopulator *aPopulator;
193136:       int i;
193137:       aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
193138:       if( aPopulator==0 ) rc = SQLITE_NOMEM;
193139:       for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
193140:         int n; const char *z;
193141:         rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
193142:         if( rc==SQLITE_OK ){
193143:           rc = sqlite3Fts5ExprPopulatePoslists(
193144:               pConfig, pCsr->pExpr, aPopulator, i, z, n
193145:           );
193146:         }
193147:       }
193148:       sqlite3_free(aPopulator);
193149: 
193150:       if( pCsr->pSorter ){
193151:         sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
193152:       }
193153:     }
193154:     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
193155:   }
193156: 
193157:   if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
193158:     Fts5Sorter *pSorter = pCsr->pSorter;
193159:     int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
193160:     *pn = pSorter->aIdx[iPhrase] - i1;
193161:     *pa = &pSorter->aPoslist[i1];
193162:   }else{
193163:     *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
193164:   }
193165: 
193166:   return rc;
193167: }
193168: 
193169: /*
193170: ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
193171: ** correctly for the current view. Return SQLITE_OK if successful, or an
193172: ** SQLite error code otherwise.
193173: */
193174: static int fts5CacheInstArray(Fts5Cursor *pCsr){
193175:   int rc = SQLITE_OK;
193176:   Fts5PoslistReader *aIter;       /* One iterator for each phrase */
193177:   int nIter;                      /* Number of iterators/phrases */
193178:   
193179:   nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193180:   if( pCsr->aInstIter==0 ){
193181:     int nByte = sizeof(Fts5PoslistReader) * nIter;
193182:     pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
193183:   }
193184:   aIter = pCsr->aInstIter;
193185: 
193186:   if( aIter ){
193187:     int nInst = 0;                /* Number instances seen so far */
193188:     int i;
193189: 
193190:     /* Initialize all iterators */
193191:     for(i=0; i<nIter && rc==SQLITE_OK; i++){
193192:       const u8 *a;
193193:       int n; 
193194:       rc = fts5CsrPoslist(pCsr, i, &a, &n);
193195:       if( rc==SQLITE_OK ){
193196:         sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
193197:       }
193198:     }
193199: 
193200:     if( rc==SQLITE_OK ){
193201:       while( 1 ){
193202:         int *aInst;
193203:         int iBest = -1;
193204:         for(i=0; i<nIter; i++){
193205:           if( (aIter[i].bEof==0) 
193206:               && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos) 
193207:             ){
193208:             iBest = i;
193209:           }
193210:         }
193211:         if( iBest<0 ) break;
193212: 
193213:         nInst++;
193214:         if( nInst>=pCsr->nInstAlloc ){
193215:           pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
193216:           aInst = (int*)sqlite3_realloc(
193217:               pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
193218:               );
193219:           if( aInst ){
193220:             pCsr->aInst = aInst;
193221:           }else{
193222:             rc = SQLITE_NOMEM;
193223:             break;
193224:           }
193225:         }
193226: 
193227:         aInst = &pCsr->aInst[3 * (nInst-1)];
193228:         aInst[0] = iBest;
193229:         aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
193230:         aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
193231:         sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
193232:       }
193233:     }
193234: 
193235:     pCsr->nInstCount = nInst;
193236:     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
193237:   }
193238:   return rc;
193239: }
193240: 
193241: static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
193242:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193243:   int rc = SQLITE_OK;
193244:   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
193245:    || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
193246:     *pnInst = pCsr->nInstCount;
193247:   }
193248:   return rc;
193249: }
193250: 
193251: static int fts5ApiInst(
193252:   Fts5Context *pCtx, 
193253:   int iIdx, 
193254:   int *piPhrase, 
193255:   int *piCol, 
193256:   int *piOff
193257: ){
193258:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193259:   int rc = SQLITE_OK;
193260:   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0 
193261:    || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) 
193262:   ){
193263:     if( iIdx<0 || iIdx>=pCsr->nInstCount ){
193264:       rc = SQLITE_RANGE;
193265: #if 0
193266:     }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
193267:       *piPhrase = pCsr->aInst[iIdx*3];
193268:       *piCol = pCsr->aInst[iIdx*3 + 2];
193269:       *piOff = -1;
193270: #endif
193271:     }else{
193272:       *piPhrase = pCsr->aInst[iIdx*3];
193273:       *piCol = pCsr->aInst[iIdx*3 + 1];
193274:       *piOff = pCsr->aInst[iIdx*3 + 2];
193275:     }
193276:   }
193277:   return rc;
193278: }
193279: 
193280: static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
193281:   return fts5CursorRowid((Fts5Cursor*)pCtx);
193282: }
193283: 
193284: static int fts5ColumnSizeCb(
193285:   void *pContext,                 /* Pointer to int */
193286:   int tflags,
193287:   const char *pUnused,            /* Buffer containing token */
193288:   int nUnused,                    /* Size of token in bytes */
193289:   int iUnused1,                   /* Start offset of token */
193290:   int iUnused2                    /* End offset of token */
193291: ){
193292:   int *pCnt = (int*)pContext;
193293:   UNUSED_PARAM2(pUnused, nUnused);
193294:   UNUSED_PARAM2(iUnused1, iUnused2);
193295:   if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
193296:     (*pCnt)++;
193297:   }
193298:   return SQLITE_OK;
193299: }
193300: 
193301: static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
193302:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193303:   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193304:   Fts5Config *pConfig = pTab->pConfig;
193305:   int rc = SQLITE_OK;
193306: 
193307:   if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
193308:     if( pConfig->bColumnsize ){
193309:       i64 iRowid = fts5CursorRowid(pCsr);
193310:       rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
193311:     }else if( pConfig->zContent==0 ){
193312:       int i;
193313:       for(i=0; i<pConfig->nCol; i++){
193314:         if( pConfig->abUnindexed[i]==0 ){
193315:           pCsr->aColumnSize[i] = -1;
193316:         }
193317:       }
193318:     }else{
193319:       int i;
193320:       for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
193321:         if( pConfig->abUnindexed[i]==0 ){
193322:           const char *z; int n;
193323:           void *p = (void*)(&pCsr->aColumnSize[i]);
193324:           pCsr->aColumnSize[i] = 0;
193325:           rc = fts5ApiColumnText(pCtx, i, &z, &n);
193326:           if( rc==SQLITE_OK ){
193327:             rc = sqlite3Fts5Tokenize(
193328:                 pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
193329:             );
193330:           }
193331:         }
193332:       }
193333:     }
193334:     CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
193335:   }
193336:   if( iCol<0 ){
193337:     int i;
193338:     *pnToken = 0;
193339:     for(i=0; i<pConfig->nCol; i++){
193340:       *pnToken += pCsr->aColumnSize[i];
193341:     }
193342:   }else if( iCol<pConfig->nCol ){
193343:     *pnToken = pCsr->aColumnSize[iCol];
193344:   }else{
193345:     *pnToken = 0;
193346:     rc = SQLITE_RANGE;
193347:   }
193348:   return rc;
193349: }
193350: 
193351: /*
193352: ** Implementation of the xSetAuxdata() method.
193353: */
193354: static int fts5ApiSetAuxdata(
193355:   Fts5Context *pCtx,              /* Fts5 context */
193356:   void *pPtr,                     /* Pointer to save as auxdata */
193357:   void(*xDelete)(void*)           /* Destructor for pPtr (or NULL) */
193358: ){
193359:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193360:   Fts5Auxdata *pData;
193361: 
193362:   /* Search through the cursors list of Fts5Auxdata objects for one that
193363:   ** corresponds to the currently executing auxiliary function.  */
193364:   for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
193365:     if( pData->pAux==pCsr->pAux ) break;
193366:   }
193367: 
193368:   if( pData ){
193369:     if( pData->xDelete ){
193370:       pData->xDelete(pData->pPtr);
193371:     }
193372:   }else{
193373:     int rc = SQLITE_OK;
193374:     pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
193375:     if( pData==0 ){
193376:       if( xDelete ) xDelete(pPtr);
193377:       return rc;
193378:     }
193379:     pData->pAux = pCsr->pAux;
193380:     pData->pNext = pCsr->pAuxdata;
193381:     pCsr->pAuxdata = pData;
193382:   }
193383: 
193384:   pData->xDelete = xDelete;
193385:   pData->pPtr = pPtr;
193386:   return SQLITE_OK;
193387: }
193388: 
193389: static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
193390:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193391:   Fts5Auxdata *pData;
193392:   void *pRet = 0;
193393: 
193394:   for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
193395:     if( pData->pAux==pCsr->pAux ) break;
193396:   }
193397: 
193398:   if( pData ){
193399:     pRet = pData->pPtr;
193400:     if( bClear ){
193401:       pData->pPtr = 0;
193402:       pData->xDelete = 0;
193403:     }
193404:   }
193405: 
193406:   return pRet;
193407: }
193408: 
193409: static void fts5ApiPhraseNext(
193410:   Fts5Context *pUnused, 
193411:   Fts5PhraseIter *pIter, 
193412:   int *piCol, int *piOff
193413: ){
193414:   UNUSED_PARAM(pUnused);
193415:   if( pIter->a>=pIter->b ){
193416:     *piCol = -1;
193417:     *piOff = -1;
193418:   }else{
193419:     int iVal;
193420:     pIter->a += fts5GetVarint32(pIter->a, iVal);
193421:     if( iVal==1 ){
193422:       pIter->a += fts5GetVarint32(pIter->a, iVal);
193423:       *piCol = iVal;
193424:       *piOff = 0;
193425:       pIter->a += fts5GetVarint32(pIter->a, iVal);
193426:     }
193427:     *piOff += (iVal-2);
193428:   }
193429: }
193430: 
193431: static int fts5ApiPhraseFirst(
193432:   Fts5Context *pCtx, 
193433:   int iPhrase, 
193434:   Fts5PhraseIter *pIter, 
193435:   int *piCol, int *piOff
193436: ){
193437:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193438:   int n;
193439:   int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
193440:   if( rc==SQLITE_OK ){
193441:     pIter->b = &pIter->a[n];
193442:     *piCol = 0;
193443:     *piOff = 0;
193444:     fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
193445:   }
193446:   return rc;
193447: }
193448: 
193449: static void fts5ApiPhraseNextColumn(
193450:   Fts5Context *pCtx, 
193451:   Fts5PhraseIter *pIter, 
193452:   int *piCol
193453: ){
193454:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193455:   Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193456: 
193457:   if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193458:     if( pIter->a>=pIter->b ){
193459:       *piCol = -1;
193460:     }else{
193461:       int iIncr;
193462:       pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
193463:       *piCol += (iIncr-2);
193464:     }
193465:   }else{
193466:     while( 1 ){
193467:       int dummy;
193468:       if( pIter->a>=pIter->b ){
193469:         *piCol = -1;
193470:         return;
193471:       }
193472:       if( pIter->a[0]==0x01 ) break;
193473:       pIter->a += fts5GetVarint32(pIter->a, dummy);
193474:     }
193475:     pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
193476:   }
193477: }
193478: 
193479: static int fts5ApiPhraseFirstColumn(
193480:   Fts5Context *pCtx, 
193481:   int iPhrase, 
193482:   Fts5PhraseIter *pIter, 
193483:   int *piCol
193484: ){
193485:   int rc = SQLITE_OK;
193486:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193487:   Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
193488: 
193489:   if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193490:     Fts5Sorter *pSorter = pCsr->pSorter;
193491:     int n;
193492:     if( pSorter ){
193493:       int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
193494:       n = pSorter->aIdx[iPhrase] - i1;
193495:       pIter->a = &pSorter->aPoslist[i1];
193496:     }else{
193497:       rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
193498:     }
193499:     if( rc==SQLITE_OK ){
193500:       pIter->b = &pIter->a[n];
193501:       *piCol = 0;
193502:       fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
193503:     }
193504:   }else{
193505:     int n;
193506:     rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
193507:     if( rc==SQLITE_OK ){
193508:       pIter->b = &pIter->a[n];
193509:       if( n<=0 ){
193510:         *piCol = -1;
193511:       }else if( pIter->a[0]==0x01 ){
193512:         pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
193513:       }else{
193514:         *piCol = 0;
193515:       }
193516:     }
193517:   }
193518: 
193519:   return rc;
193520: }
193521: 
193522: 
193523: static int fts5ApiQueryPhrase(Fts5Context*, int, void*, 
193524:     int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
193525: );
193526: 
193527: static const Fts5ExtensionApi sFts5Api = {
193528:   2,                            /* iVersion */
193529:   fts5ApiUserData,
193530:   fts5ApiColumnCount,
193531:   fts5ApiRowCount,
193532:   fts5ApiColumnTotalSize,
193533:   fts5ApiTokenize,
193534:   fts5ApiPhraseCount,
193535:   fts5ApiPhraseSize,
193536:   fts5ApiInstCount,
193537:   fts5ApiInst,
193538:   fts5ApiRowid,
193539:   fts5ApiColumnText,
193540:   fts5ApiColumnSize,
193541:   fts5ApiQueryPhrase,
193542:   fts5ApiSetAuxdata,
193543:   fts5ApiGetAuxdata,
193544:   fts5ApiPhraseFirst,
193545:   fts5ApiPhraseNext,
193546:   fts5ApiPhraseFirstColumn,
193547:   fts5ApiPhraseNextColumn,
193548: };
193549: 
193550: /*
193551: ** Implementation of API function xQueryPhrase().
193552: */
193553: static int fts5ApiQueryPhrase(
193554:   Fts5Context *pCtx, 
193555:   int iPhrase, 
193556:   void *pUserData,
193557:   int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
193558: ){
193559:   Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
193560:   Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
193561:   int rc;
193562:   Fts5Cursor *pNew = 0;
193563: 
193564:   rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
193565:   if( rc==SQLITE_OK ){
193566:     pNew->ePlan = FTS5_PLAN_MATCH;
193567:     pNew->iFirstRowid = SMALLEST_INT64;
193568:     pNew->iLastRowid = LARGEST_INT64;
193569:     pNew->base.pVtab = (sqlite3_vtab*)pTab;
193570:     rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
193571:   }
193572: 
193573:   if( rc==SQLITE_OK ){
193574:     for(rc = fts5CursorFirst(pTab, pNew, 0);
193575:         rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
193576:         rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
193577:     ){
193578:       rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
193579:       if( rc!=SQLITE_OK ){
193580:         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
193581:         break;
193582:       }
193583:     }
193584:   }
193585: 
193586:   fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
193587:   return rc;
193588: }
193589: 
193590: static void fts5ApiInvoke(
193591:   Fts5Auxiliary *pAux,
193592:   Fts5Cursor *pCsr,
193593:   sqlite3_context *context,
193594:   int argc,
193595:   sqlite3_value **argv
193596: ){
193597:   assert( pCsr->pAux==0 );
193598:   pCsr->pAux = pAux;
193599:   pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
193600:   pCsr->pAux = 0;
193601: }
193602: 
193603: static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
193604:   Fts5Cursor *pCsr;
193605:   for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
193606:     if( pCsr->iCsrId==iCsrId ) break;
193607:   }
193608:   return pCsr;
193609: }
193610: 
193611: static void fts5ApiCallback(
193612:   sqlite3_context *context,
193613:   int argc,
193614:   sqlite3_value **argv
193615: ){
193616: 
193617:   Fts5Auxiliary *pAux;
193618:   Fts5Cursor *pCsr;
193619:   i64 iCsrId;
193620: 
193621:   assert( argc>=1 );
193622:   pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
193623:   iCsrId = sqlite3_value_int64(argv[0]);
193624: 
193625:   pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
193626:   if( pCsr==0 ){
193627:     char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
193628:     sqlite3_result_error(context, zErr, -1);
193629:     sqlite3_free(zErr);
193630:   }else{
193631:     fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
193632:   }
193633: }
193634: 
193635: 
193636: /*
193637: ** Given cursor id iId, return a pointer to the corresponding Fts5Index 
193638: ** object. Or NULL If the cursor id does not exist.
193639: **
193640: ** If successful, set *ppConfig to point to the associated config object 
193641: ** before returning.
193642: */
193643: static Fts5Index *sqlite3Fts5IndexFromCsrid(
193644:   Fts5Global *pGlobal,            /* FTS5 global context for db handle */
193645:   i64 iCsrId,                     /* Id of cursor to find */
193646:   Fts5Config **ppConfig           /* OUT: Configuration object */
193647: ){
193648:   Fts5Cursor *pCsr;
193649:   Fts5Table *pTab;
193650: 
193651:   pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
193652:   pTab = (Fts5Table*)pCsr->base.pVtab;
193653:   *ppConfig = pTab->pConfig;
193654: 
193655:   return pTab->pIndex;
193656: }
193657: 
193658: /*
193659: ** Return a "position-list blob" corresponding to the current position of
193660: ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
193661: ** the current position-list for each phrase in the query associated with
193662: ** cursor pCsr.
193663: **
193664: ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
193665: ** the number of phrases in the query. Following the varints are the
193666: ** concatenated position lists for each phrase, in order.
193667: **
193668: ** The first varint (if it exists) contains the size of the position list
193669: ** for phrase 0. The second (same disclaimer) contains the size of position
193670: ** list 1. And so on. There is no size field for the final position list,
193671: ** as it can be derived from the total size of the blob.
193672: */
193673: static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
193674:   int i;
193675:   int rc = SQLITE_OK;
193676:   int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
193677:   Fts5Buffer val;
193678: 
193679:   memset(&val, 0, sizeof(Fts5Buffer));
193680:   switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
193681:     case FTS5_DETAIL_FULL:
193682: 
193683:       /* Append the varints */
193684:       for(i=0; i<(nPhrase-1); i++){
193685:         const u8 *dummy;
193686:         int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
193687:         sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
193688:       }
193689: 
193690:       /* Append the position lists */
193691:       for(i=0; i<nPhrase; i++){
193692:         const u8 *pPoslist;
193693:         int nPoslist;
193694:         nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
193695:         sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
193696:       }
193697:       break;
193698: 
193699:     case FTS5_DETAIL_COLUMNS:
193700: 
193701:       /* Append the varints */
193702:       for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
193703:         const u8 *dummy;
193704:         int nByte;
193705:         rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
193706:         sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
193707:       }
193708: 
193709:       /* Append the position lists */
193710:       for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
193711:         const u8 *pPoslist;
193712:         int nPoslist;
193713:         rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
193714:         sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
193715:       }
193716:       break;
193717: 
193718:     default:
193719:       break;
193720:   }
193721: 
193722:   sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
193723:   return rc;
193724: }
193725: 
193726: /* 
193727: ** This is the xColumn method, called by SQLite to request a value from
193728: ** the row that the supplied cursor currently points to.
193729: */
193730: static int fts5ColumnMethod(
193731:   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
193732:   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
193733:   int iCol                        /* Index of column to read value from */
193734: ){
193735:   Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
193736:   Fts5Config *pConfig = pTab->pConfig;
193737:   Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
193738:   int rc = SQLITE_OK;
193739:   
193740:   assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
193741: 
193742:   if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
193743:     if( iCol==pConfig->nCol ){
193744:       sqlite3_result_int64(pCtx, pCsr->iSpecial);
193745:     }
193746:   }else
193747: 
193748:   if( iCol==pConfig->nCol ){
193749:     /* User is requesting the value of the special column with the same name
193750:     ** as the table. Return the cursor integer id number. This value is only
193751:     ** useful in that it may be passed as the first argument to an FTS5
193752:     ** auxiliary function.  */
193753:     sqlite3_result_int64(pCtx, pCsr->iCsrId);
193754:   }else if( iCol==pConfig->nCol+1 ){
193755: 
193756:     /* The value of the "rank" column. */
193757:     if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
193758:       fts5PoslistBlob(pCtx, pCsr);
193759:     }else if( 
193760:         pCsr->ePlan==FTS5_PLAN_MATCH
193761:      || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
193762:     ){
193763:       if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
193764:         fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
193765:       }
193766:     }
193767:   }else if( !fts5IsContentless(pTab) ){
193768:     rc = fts5SeekCursor(pCsr, 1);
193769:     if( rc==SQLITE_OK ){
193770:       sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
193771:     }
193772:   }
193773:   return rc;
193774: }
193775: 
193776: 
193777: /*
193778: ** This routine implements the xFindFunction method for the FTS3
193779: ** virtual table.
193780: */
193781: static int fts5FindFunctionMethod(
193782:   sqlite3_vtab *pVtab,            /* Virtual table handle */
193783:   int nUnused,                    /* Number of SQL function arguments */
193784:   const char *zName,              /* Name of SQL function */
193785:   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
193786:   void **ppArg                    /* OUT: User data for *pxFunc */
193787: ){
193788:   Fts5Table *pTab = (Fts5Table*)pVtab;
193789:   Fts5Auxiliary *pAux;
193790: 
193791:   UNUSED_PARAM(nUnused);
193792:   pAux = fts5FindAuxiliary(pTab, zName);
193793:   if( pAux ){
193794:     *pxFunc = fts5ApiCallback;
193795:     *ppArg = (void*)pAux;
193796:     return 1;
193797:   }
193798: 
193799:   /* No function of the specified name was found. Return 0. */
193800:   return 0;
193801: }
193802: 
193803: /*
193804: ** Implementation of FTS5 xRename method. Rename an fts5 table.
193805: */
193806: static int fts5RenameMethod(
193807:   sqlite3_vtab *pVtab,            /* Virtual table handle */
193808:   const char *zName               /* New name of table */
193809: ){
193810:   Fts5Table *pTab = (Fts5Table*)pVtab;
193811:   return sqlite3Fts5StorageRename(pTab->pStorage, zName);
193812: }
193813: 
193814: /*
193815: ** The xSavepoint() method.
193816: **
193817: ** Flush the contents of the pending-terms table to disk.
193818: */
193819: static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
193820:   Fts5Table *pTab = (Fts5Table*)pVtab;
193821:   UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193822:   fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
193823:   fts5TripCursors(pTab);
193824:   return sqlite3Fts5StorageSync(pTab->pStorage, 0);
193825: }
193826: 
193827: /*
193828: ** The xRelease() method.
193829: **
193830: ** This is a no-op.
193831: */
193832: static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
193833:   Fts5Table *pTab = (Fts5Table*)pVtab;
193834:   UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193835:   fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
193836:   fts5TripCursors(pTab);
193837:   return sqlite3Fts5StorageSync(pTab->pStorage, 0);
193838: }
193839: 
193840: /*
193841: ** The xRollbackTo() method.
193842: **
193843: ** Discard the contents of the pending terms table.
193844: */
193845: static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
193846:   Fts5Table *pTab = (Fts5Table*)pVtab;
193847:   UNUSED_PARAM(iSavepoint);  /* Call below is a no-op for NDEBUG builds */
193848:   fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
193849:   fts5TripCursors(pTab);
193850:   return sqlite3Fts5StorageRollback(pTab->pStorage);
193851: }
193852: 
193853: /*
193854: ** Register a new auxiliary function with global context pGlobal.
193855: */
193856: static int fts5CreateAux(
193857:   fts5_api *pApi,                 /* Global context (one per db handle) */
193858:   const char *zName,              /* Name of new function */
193859:   void *pUserData,                /* User data for aux. function */
193860:   fts5_extension_function xFunc,  /* Aux. function implementation */
193861:   void(*xDestroy)(void*)          /* Destructor for pUserData */
193862: ){
193863:   Fts5Global *pGlobal = (Fts5Global*)pApi;
193864:   int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
193865:   if( rc==SQLITE_OK ){
193866:     Fts5Auxiliary *pAux;
193867:     int nName;                      /* Size of zName in bytes, including \0 */
193868:     int nByte;                      /* Bytes of space to allocate */
193869: 
193870:     nName = (int)strlen(zName) + 1;
193871:     nByte = sizeof(Fts5Auxiliary) + nName;
193872:     pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
193873:     if( pAux ){
193874:       memset(pAux, 0, nByte);
193875:       pAux->zFunc = (char*)&pAux[1];
193876:       memcpy(pAux->zFunc, zName, nName);
193877:       pAux->pGlobal = pGlobal;
193878:       pAux->pUserData = pUserData;
193879:       pAux->xFunc = xFunc;
193880:       pAux->xDestroy = xDestroy;
193881:       pAux->pNext = pGlobal->pAux;
193882:       pGlobal->pAux = pAux;
193883:     }else{
193884:       rc = SQLITE_NOMEM;
193885:     }
193886:   }
193887: 
193888:   return rc;
193889: }
193890: 
193891: /*
193892: ** Register a new tokenizer. This is the implementation of the 
193893: ** fts5_api.xCreateTokenizer() method.
193894: */
193895: static int fts5CreateTokenizer(
193896:   fts5_api *pApi,                 /* Global context (one per db handle) */
193897:   const char *zName,              /* Name of new function */
193898:   void *pUserData,                /* User data for aux. function */
193899:   fts5_tokenizer *pTokenizer,     /* Tokenizer implementation */
193900:   void(*xDestroy)(void*)          /* Destructor for pUserData */
193901: ){
193902:   Fts5Global *pGlobal = (Fts5Global*)pApi;
193903:   Fts5TokenizerModule *pNew;
193904:   int nName;                      /* Size of zName and its \0 terminator */
193905:   int nByte;                      /* Bytes of space to allocate */
193906:   int rc = SQLITE_OK;
193907: 
193908:   nName = (int)strlen(zName) + 1;
193909:   nByte = sizeof(Fts5TokenizerModule) + nName;
193910:   pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
193911:   if( pNew ){
193912:     memset(pNew, 0, nByte);
193913:     pNew->zName = (char*)&pNew[1];
193914:     memcpy(pNew->zName, zName, nName);
193915:     pNew->pUserData = pUserData;
193916:     pNew->x = *pTokenizer;
193917:     pNew->xDestroy = xDestroy;
193918:     pNew->pNext = pGlobal->pTok;
193919:     pGlobal->pTok = pNew;
193920:     if( pNew->pNext==0 ){
193921:       pGlobal->pDfltTok = pNew;
193922:     }
193923:   }else{
193924:     rc = SQLITE_NOMEM;
193925:   }
193926: 
193927:   return rc;
193928: }
193929: 
193930: static Fts5TokenizerModule *fts5LocateTokenizer(
193931:   Fts5Global *pGlobal, 
193932:   const char *zName
193933: ){
193934:   Fts5TokenizerModule *pMod = 0;
193935: 
193936:   if( zName==0 ){
193937:     pMod = pGlobal->pDfltTok;
193938:   }else{
193939:     for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
193940:       if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
193941:     }
193942:   }
193943: 
193944:   return pMod;
193945: }
193946: 
193947: /*
193948: ** Find a tokenizer. This is the implementation of the 
193949: ** fts5_api.xFindTokenizer() method.
193950: */
193951: static int fts5FindTokenizer(
193952:   fts5_api *pApi,                 /* Global context (one per db handle) */
193953:   const char *zName,              /* Name of new function */
193954:   void **ppUserData,
193955:   fts5_tokenizer *pTokenizer      /* Populate this object */
193956: ){
193957:   int rc = SQLITE_OK;
193958:   Fts5TokenizerModule *pMod;
193959: 
193960:   pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
193961:   if( pMod ){
193962:     *pTokenizer = pMod->x;
193963:     *ppUserData = pMod->pUserData;
193964:   }else{
193965:     memset(pTokenizer, 0, sizeof(fts5_tokenizer));
193966:     rc = SQLITE_ERROR;
193967:   }
193968: 
193969:   return rc;
193970: }
193971: 
193972: static int sqlite3Fts5GetTokenizer(
193973:   Fts5Global *pGlobal, 
193974:   const char **azArg,
193975:   int nArg,
193976:   Fts5Tokenizer **ppTok,
193977:   fts5_tokenizer **ppTokApi,
193978:   char **pzErr
193979: ){
193980:   Fts5TokenizerModule *pMod;
193981:   int rc = SQLITE_OK;
193982: 
193983:   pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
193984:   if( pMod==0 ){
193985:     assert( nArg>0 );
193986:     rc = SQLITE_ERROR;
193987:     *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
193988:   }else{
193989:     rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
193990:     *ppTokApi = &pMod->x;
193991:     if( rc!=SQLITE_OK && pzErr ){
193992:       *pzErr = sqlite3_mprintf("error in tokenizer constructor");
193993:     }
193994:   }
193995: 
193996:   if( rc!=SQLITE_OK ){
193997:     *ppTokApi = 0;
193998:     *ppTok = 0;
193999:   }
194000: 
194001:   return rc;
194002: }
194003: 
194004: static void fts5ModuleDestroy(void *pCtx){
194005:   Fts5TokenizerModule *pTok, *pNextTok;
194006:   Fts5Auxiliary *pAux, *pNextAux;
194007:   Fts5Global *pGlobal = (Fts5Global*)pCtx;
194008: 
194009:   for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
194010:     pNextAux = pAux->pNext;
194011:     if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
194012:     sqlite3_free(pAux);
194013:   }
194014: 
194015:   for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
194016:     pNextTok = pTok->pNext;
194017:     if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
194018:     sqlite3_free(pTok);
194019:   }
194020: 
194021:   sqlite3_free(pGlobal);
194022: }
194023: 
194024: static void fts5Fts5Func(
194025:   sqlite3_context *pCtx,          /* Function call context */
194026:   int nArg,                       /* Number of args */
194027:   sqlite3_value **apUnused        /* Function arguments */
194028: ){
194029:   Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
194030:   char buf[8];
194031:   UNUSED_PARAM2(nArg, apUnused);
194032:   assert( nArg==0 );
194033:   assert( sizeof(buf)>=sizeof(pGlobal) );
194034:   memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
194035:   sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
194036: }
194037: 
194038: /*
194039: ** Implementation of fts5_source_id() function.
194040: */
194041: static void fts5SourceIdFunc(
194042:   sqlite3_context *pCtx,          /* Function call context */
194043:   int nArg,                       /* Number of args */
194044:   sqlite3_value **apUnused        /* Function arguments */
194045: ){
194046:   assert( nArg==0 );
194047:   UNUSED_PARAM2(nArg, apUnused);
194048:   sqlite3_result_text(pCtx, "fts5: 2016-09-12 18:50:49 29dbef4b8585f753861a36d6dd102ca634197bd6", -1, SQLITE_TRANSIENT);
194049: }
194050: 
194051: static int fts5Init(sqlite3 *db){
194052:   static const sqlite3_module fts5Mod = {
194053:     /* iVersion      */ 2,
194054:     /* xCreate       */ fts5CreateMethod,
194055:     /* xConnect      */ fts5ConnectMethod,
194056:     /* xBestIndex    */ fts5BestIndexMethod,
194057:     /* xDisconnect   */ fts5DisconnectMethod,
194058:     /* xDestroy      */ fts5DestroyMethod,
194059:     /* xOpen         */ fts5OpenMethod,
194060:     /* xClose        */ fts5CloseMethod,
194061:     /* xFilter       */ fts5FilterMethod,
194062:     /* xNext         */ fts5NextMethod,
194063:     /* xEof          */ fts5EofMethod,
194064:     /* xColumn       */ fts5ColumnMethod,
194065:     /* xRowid        */ fts5RowidMethod,
194066:     /* xUpdate       */ fts5UpdateMethod,
194067:     /* xBegin        */ fts5BeginMethod,
194068:     /* xSync         */ fts5SyncMethod,
194069:     /* xCommit       */ fts5CommitMethod,
194070:     /* xRollback     */ fts5RollbackMethod,
194071:     /* xFindFunction */ fts5FindFunctionMethod,
194072:     /* xRename       */ fts5RenameMethod,
194073:     /* xSavepoint    */ fts5SavepointMethod,
194074:     /* xRelease      */ fts5ReleaseMethod,
194075:     /* xRollbackTo   */ fts5RollbackToMethod,
194076:   };
194077: 
194078:   int rc;
194079:   Fts5Global *pGlobal = 0;
194080: 
194081:   pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
194082:   if( pGlobal==0 ){
194083:     rc = SQLITE_NOMEM;
194084:   }else{
194085:     void *p = (void*)pGlobal;
194086:     memset(pGlobal, 0, sizeof(Fts5Global));
194087:     pGlobal->db = db;
194088:     pGlobal->api.iVersion = 2;
194089:     pGlobal->api.xCreateFunction = fts5CreateAux;
194090:     pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
194091:     pGlobal->api.xFindTokenizer = fts5FindTokenizer;
194092:     rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
194093:     if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
194094:     if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
194095:     if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
194096:     if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
194097:     if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
194098:     if( rc==SQLITE_OK ){
194099:       rc = sqlite3_create_function(
194100:           db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
194101:       );
194102:     }
194103:     if( rc==SQLITE_OK ){
194104:       rc = sqlite3_create_function(
194105:           db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
194106:       );
194107:     }
194108:   }
194109: 
194110:   /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
194111:   ** fts5_test_mi.c is compiled and linked into the executable. And call
194112:   ** its entry point to enable the matchinfo() demo.  */
194113: #ifdef SQLITE_FTS5_ENABLE_TEST_MI
194114:   if( rc==SQLITE_OK ){
194115:     extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
194116:     rc = sqlite3Fts5TestRegisterMatchinfo(db);
194117:   }
194118: #endif
194119: 
194120:   return rc;
194121: }
194122: 
194123: /*
194124: ** The following functions are used to register the module with SQLite. If
194125: ** this module is being built as part of the SQLite core (SQLITE_CORE is
194126: ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
194127: **
194128: ** Or, if this module is being built as a loadable extension, 
194129: ** sqlite3Fts5Init() is omitted and the two standard entry points
194130: ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
194131: */
194132: #ifndef SQLITE_CORE
194133: #ifdef _WIN32
194134: __declspec(dllexport)
194135: #endif
194136: SQLITE_API int sqlite3_fts_init(
194137:   sqlite3 *db,
194138:   char **pzErrMsg,
194139:   const sqlite3_api_routines *pApi
194140: ){
194141:   SQLITE_EXTENSION_INIT2(pApi);
194142:   (void)pzErrMsg;  /* Unused parameter */
194143:   return fts5Init(db);
194144: }
194145: 
194146: #ifdef _WIN32
194147: __declspec(dllexport)
194148: #endif
194149: SQLITE_API int sqlite3_fts5_init(
194150:   sqlite3 *db,
194151:   char **pzErrMsg,
194152:   const sqlite3_api_routines *pApi
194153: ){
194154:   SQLITE_EXTENSION_INIT2(pApi);
194155:   (void)pzErrMsg;  /* Unused parameter */
194156:   return fts5Init(db);
194157: }
194158: #else
194159: SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
194160:   return fts5Init(db);
194161: }
194162: #endif
194163: 
194164: /*
194165: ** 2014 May 31
194166: **
194167: ** The author disclaims copyright to this source code.  In place of
194168: ** a legal notice, here is a blessing:
194169: **
194170: **    May you do good and not evil.
194171: **    May you find forgiveness for yourself and forgive others.
194172: **    May you share freely, never taking more than you give.
194173: **
194174: ******************************************************************************
194175: **
194176: */
194177: 
194178: 
194179: 
194180: /* #include "fts5Int.h" */
194181: 
194182: struct Fts5Storage {
194183:   Fts5Config *pConfig;
194184:   Fts5Index *pIndex;
194185:   int bTotalsValid;               /* True if nTotalRow/aTotalSize[] are valid */
194186:   i64 nTotalRow;                  /* Total number of rows in FTS table */
194187:   i64 *aTotalSize;                /* Total sizes of each column */ 
194188:   sqlite3_stmt *aStmt[11];
194189: };
194190: 
194191: 
194192: #if FTS5_STMT_SCAN_ASC!=0 
194193: # error "FTS5_STMT_SCAN_ASC mismatch" 
194194: #endif
194195: #if FTS5_STMT_SCAN_DESC!=1 
194196: # error "FTS5_STMT_SCAN_DESC mismatch" 
194197: #endif
194198: #if FTS5_STMT_LOOKUP!=2
194199: # error "FTS5_STMT_LOOKUP mismatch" 
194200: #endif
194201: 
194202: #define FTS5_STMT_INSERT_CONTENT  3
194203: #define FTS5_STMT_REPLACE_CONTENT 4
194204: #define FTS5_STMT_DELETE_CONTENT  5
194205: #define FTS5_STMT_REPLACE_DOCSIZE  6
194206: #define FTS5_STMT_DELETE_DOCSIZE  7
194207: #define FTS5_STMT_LOOKUP_DOCSIZE  8
194208: #define FTS5_STMT_REPLACE_CONFIG 9
194209: #define FTS5_STMT_SCAN 10
194210: 
194211: /*
194212: ** Prepare the two insert statements - Fts5Storage.pInsertContent and
194213: ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
194214: ** Return SQLITE_OK if successful, or an SQLite error code if an error
194215: ** occurs.
194216: */
194217: static int fts5StorageGetStmt(
194218:   Fts5Storage *p,                 /* Storage handle */
194219:   int eStmt,                      /* FTS5_STMT_XXX constant */
194220:   sqlite3_stmt **ppStmt,          /* OUT: Prepared statement handle */
194221:   char **pzErrMsg                 /* OUT: Error message (if any) */
194222: ){
194223:   int rc = SQLITE_OK;
194224: 
194225:   /* If there is no %_docsize table, there should be no requests for 
194226:   ** statements to operate on it.  */
194227:   assert( p->pConfig->bColumnsize || (
194228:         eStmt!=FTS5_STMT_REPLACE_DOCSIZE 
194229:      && eStmt!=FTS5_STMT_DELETE_DOCSIZE 
194230:      && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE 
194231:   ));
194232: 
194233:   assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
194234:   if( p->aStmt[eStmt]==0 ){
194235:     const char *azStmt[] = {
194236:       "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
194237:       "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
194238:       "SELECT %s FROM %s T WHERE T.%Q=?",               /* LOOKUP  */
194239: 
194240:       "INSERT INTO %Q.'%q_content' VALUES(%s)",         /* INSERT_CONTENT  */
194241:       "REPLACE INTO %Q.'%q_content' VALUES(%s)",        /* REPLACE_CONTENT */
194242:       "DELETE FROM %Q.'%q_content' WHERE id=?",         /* DELETE_CONTENT  */
194243:       "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",       /* REPLACE_DOCSIZE  */
194244:       "DELETE FROM %Q.'%q_docsize' WHERE id=?",         /* DELETE_DOCSIZE  */
194245: 
194246:       "SELECT sz FROM %Q.'%q_docsize' WHERE id=?",      /* LOOKUP_DOCSIZE  */
194247: 
194248:       "REPLACE INTO %Q.'%q_config' VALUES(?,?)",        /* REPLACE_CONFIG */
194249:       "SELECT %s FROM %s AS T",                         /* SCAN */
194250:     };
194251:     Fts5Config *pC = p->pConfig;
194252:     char *zSql = 0;
194253: 
194254:     switch( eStmt ){
194255:       case FTS5_STMT_SCAN:
194256:         zSql = sqlite3_mprintf(azStmt[eStmt], 
194257:             pC->zContentExprlist, pC->zContent
194258:         );
194259:         break;
194260: 
194261:       case FTS5_STMT_SCAN_ASC:
194262:       case FTS5_STMT_SCAN_DESC:
194263:         zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist, 
194264:             pC->zContent, pC->zContentRowid, pC->zContentRowid,
194265:             pC->zContentRowid
194266:         );
194267:         break;
194268: 
194269:       case FTS5_STMT_LOOKUP:
194270:         zSql = sqlite3_mprintf(azStmt[eStmt], 
194271:             pC->zContentExprlist, pC->zContent, pC->zContentRowid
194272:         );
194273:         break;
194274: 
194275:       case FTS5_STMT_INSERT_CONTENT: 
194276:       case FTS5_STMT_REPLACE_CONTENT: {
194277:         int nCol = pC->nCol + 1;
194278:         char *zBind;
194279:         int i;
194280: 
194281:         zBind = sqlite3_malloc(1 + nCol*2);
194282:         if( zBind ){
194283:           for(i=0; i<nCol; i++){
194284:             zBind[i*2] = '?';
194285:             zBind[i*2 + 1] = ',';
194286:           }
194287:           zBind[i*2-1] = '\0';
194288:           zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
194289:           sqlite3_free(zBind);
194290:         }
194291:         break;
194292:       }
194293: 
194294:       default:
194295:         zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
194296:         break;
194297:     }
194298: 
194299:     if( zSql==0 ){
194300:       rc = SQLITE_NOMEM;
194301:     }else{
194302:       rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
194303:       sqlite3_free(zSql);
194304:       if( rc!=SQLITE_OK && pzErrMsg ){
194305:         *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
194306:       }
194307:     }
194308:   }
194309: 
194310:   *ppStmt = p->aStmt[eStmt];
194311:   sqlite3_reset(*ppStmt);
194312:   return rc;
194313: }
194314: 
194315: 
194316: static int fts5ExecPrintf(
194317:   sqlite3 *db,
194318:   char **pzErr,
194319:   const char *zFormat,
194320:   ...
194321: ){
194322:   int rc;
194323:   va_list ap;                     /* ... printf arguments */
194324:   char *zSql;
194325: 
194326:   va_start(ap, zFormat);
194327:   zSql = sqlite3_vmprintf(zFormat, ap);
194328: 
194329:   if( zSql==0 ){
194330:     rc = SQLITE_NOMEM;
194331:   }else{
194332:     rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
194333:     sqlite3_free(zSql);
194334:   }
194335: 
194336:   va_end(ap);
194337:   return rc;
194338: }
194339: 
194340: /*
194341: ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
194342: ** code otherwise.
194343: */
194344: static int sqlite3Fts5DropAll(Fts5Config *pConfig){
194345:   int rc = fts5ExecPrintf(pConfig->db, 0, 
194346:       "DROP TABLE IF EXISTS %Q.'%q_data';"
194347:       "DROP TABLE IF EXISTS %Q.'%q_idx';"
194348:       "DROP TABLE IF EXISTS %Q.'%q_config';",
194349:       pConfig->zDb, pConfig->zName,
194350:       pConfig->zDb, pConfig->zName,
194351:       pConfig->zDb, pConfig->zName
194352:   );
194353:   if( rc==SQLITE_OK && pConfig->bColumnsize ){
194354:     rc = fts5ExecPrintf(pConfig->db, 0, 
194355:         "DROP TABLE IF EXISTS %Q.'%q_docsize';",
194356:         pConfig->zDb, pConfig->zName
194357:     );
194358:   }
194359:   if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
194360:     rc = fts5ExecPrintf(pConfig->db, 0, 
194361:         "DROP TABLE IF EXISTS %Q.'%q_content';",
194362:         pConfig->zDb, pConfig->zName
194363:     );
194364:   }
194365:   return rc;
194366: }
194367: 
194368: static void fts5StorageRenameOne(
194369:   Fts5Config *pConfig,            /* Current FTS5 configuration */
194370:   int *pRc,                       /* IN/OUT: Error code */
194371:   const char *zTail,              /* Tail of table name e.g. "data", "config" */
194372:   const char *zName               /* New name of FTS5 table */
194373: ){
194374:   if( *pRc==SQLITE_OK ){
194375:     *pRc = fts5ExecPrintf(pConfig->db, 0, 
194376:         "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
194377:         pConfig->zDb, pConfig->zName, zTail, zName, zTail
194378:     );
194379:   }
194380: }
194381: 
194382: static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
194383:   Fts5Config *pConfig = pStorage->pConfig;
194384:   int rc = sqlite3Fts5StorageSync(pStorage, 1);
194385: 
194386:   fts5StorageRenameOne(pConfig, &rc, "data", zName);
194387:   fts5StorageRenameOne(pConfig, &rc, "idx", zName);
194388:   fts5StorageRenameOne(pConfig, &rc, "config", zName);
194389:   if( pConfig->bColumnsize ){
194390:     fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
194391:   }
194392:   if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194393:     fts5StorageRenameOne(pConfig, &rc, "content", zName);
194394:   }
194395:   return rc;
194396: }
194397: 
194398: /*
194399: ** Create the shadow table named zPost, with definition zDefn. Return
194400: ** SQLITE_OK if successful, or an SQLite error code otherwise.
194401: */
194402: static int sqlite3Fts5CreateTable(
194403:   Fts5Config *pConfig,            /* FTS5 configuration */
194404:   const char *zPost,              /* Shadow table to create (e.g. "content") */
194405:   const char *zDefn,              /* Columns etc. for shadow table */
194406:   int bWithout,                   /* True for without rowid */
194407:   char **pzErr                    /* OUT: Error message */
194408: ){
194409:   int rc;
194410:   char *zErr = 0;
194411: 
194412:   rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
194413:       pConfig->zDb, pConfig->zName, zPost, zDefn, 
194414: #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
194415:       bWithout?" WITHOUT ROWID":
194416: #endif
194417:       ""
194418:   );
194419:   if( zErr ){
194420:     *pzErr = sqlite3_mprintf(
194421:         "fts5: error creating shadow table %q_%s: %s", 
194422:         pConfig->zName, zPost, zErr
194423:     );
194424:     sqlite3_free(zErr);
194425:   }
194426: 
194427:   return rc;
194428: }
194429: 
194430: /*
194431: ** Open a new Fts5Index handle. If the bCreate argument is true, create
194432: ** and initialize the underlying tables 
194433: **
194434: ** If successful, set *pp to point to the new object and return SQLITE_OK.
194435: ** Otherwise, set *pp to NULL and return an SQLite error code.
194436: */
194437: static int sqlite3Fts5StorageOpen(
194438:   Fts5Config *pConfig, 
194439:   Fts5Index *pIndex, 
194440:   int bCreate, 
194441:   Fts5Storage **pp,
194442:   char **pzErr                    /* OUT: Error message */
194443: ){
194444:   int rc = SQLITE_OK;
194445:   Fts5Storage *p;                 /* New object */
194446:   int nByte;                      /* Bytes of space to allocate */
194447: 
194448:   nByte = sizeof(Fts5Storage)               /* Fts5Storage object */
194449:         + pConfig->nCol * sizeof(i64);      /* Fts5Storage.aTotalSize[] */
194450:   *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
194451:   if( !p ) return SQLITE_NOMEM;
194452: 
194453:   memset(p, 0, nByte);
194454:   p->aTotalSize = (i64*)&p[1];
194455:   p->pConfig = pConfig;
194456:   p->pIndex = pIndex;
194457: 
194458:   if( bCreate ){
194459:     if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194460:       int nDefn = 32 + pConfig->nCol*10;
194461:       char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
194462:       if( zDefn==0 ){
194463:         rc = SQLITE_NOMEM;
194464:       }else{
194465:         int i;
194466:         int iOff;
194467:         sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
194468:         iOff = (int)strlen(zDefn);
194469:         for(i=0; i<pConfig->nCol; i++){
194470:           sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
194471:           iOff += (int)strlen(&zDefn[iOff]);
194472:         }
194473:         rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
194474:       }
194475:       sqlite3_free(zDefn);
194476:     }
194477: 
194478:     if( rc==SQLITE_OK && pConfig->bColumnsize ){
194479:       rc = sqlite3Fts5CreateTable(
194480:           pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
194481:       );
194482:     }
194483:     if( rc==SQLITE_OK ){
194484:       rc = sqlite3Fts5CreateTable(
194485:           pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
194486:       );
194487:     }
194488:     if( rc==SQLITE_OK ){
194489:       rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
194490:     }
194491:   }
194492: 
194493:   if( rc ){
194494:     sqlite3Fts5StorageClose(p);
194495:     *pp = 0;
194496:   }
194497:   return rc;
194498: }
194499: 
194500: /*
194501: ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
194502: */
194503: static int sqlite3Fts5StorageClose(Fts5Storage *p){
194504:   int rc = SQLITE_OK;
194505:   if( p ){
194506:     int i;
194507: 
194508:     /* Finalize all SQL statements */
194509:     for(i=0; i<ArraySize(p->aStmt); i++){
194510:       sqlite3_finalize(p->aStmt[i]);
194511:     }
194512: 
194513:     sqlite3_free(p);
194514:   }
194515:   return rc;
194516: }
194517: 
194518: typedef struct Fts5InsertCtx Fts5InsertCtx;
194519: struct Fts5InsertCtx {
194520:   Fts5Storage *pStorage;
194521:   int iCol;
194522:   int szCol;                      /* Size of column value in tokens */
194523: };
194524: 
194525: /*
194526: ** Tokenization callback used when inserting tokens into the FTS index.
194527: */
194528: static int fts5StorageInsertCallback(
194529:   void *pContext,                 /* Pointer to Fts5InsertCtx object */
194530:   int tflags,
194531:   const char *pToken,             /* Buffer containing token */
194532:   int nToken,                     /* Size of token in bytes */
194533:   int iUnused1,                   /* Start offset of token */
194534:   int iUnused2                    /* End offset of token */
194535: ){
194536:   Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
194537:   Fts5Index *pIdx = pCtx->pStorage->pIndex;
194538:   UNUSED_PARAM2(iUnused1, iUnused2);
194539:   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
194540:   if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
194541:     pCtx->szCol++;
194542:   }
194543:   return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
194544: }
194545: 
194546: /*
194547: ** If a row with rowid iDel is present in the %_content table, add the
194548: ** delete-markers to the FTS index necessary to delete it. Do not actually
194549: ** remove the %_content row at this time though.
194550: */
194551: static int fts5StorageDeleteFromIndex(
194552:   Fts5Storage *p, 
194553:   i64 iDel, 
194554:   sqlite3_value **apVal
194555: ){
194556:   Fts5Config *pConfig = p->pConfig;
194557:   sqlite3_stmt *pSeek = 0;        /* SELECT to read row iDel from %_data */
194558:   int rc;                         /* Return code */
194559:   int rc2;                        /* sqlite3_reset() return code */
194560:   int iCol;
194561:   Fts5InsertCtx ctx;
194562: 
194563:   if( apVal==0 ){
194564:     rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
194565:     if( rc!=SQLITE_OK ) return rc;
194566:     sqlite3_bind_int64(pSeek, 1, iDel);
194567:     if( sqlite3_step(pSeek)!=SQLITE_ROW ){
194568:       return sqlite3_reset(pSeek);
194569:     }
194570:   }
194571: 
194572:   ctx.pStorage = p;
194573:   ctx.iCol = -1;
194574:   rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
194575:   for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
194576:     if( pConfig->abUnindexed[iCol-1]==0 ){
194577:       const char *zText;
194578:       int nText;
194579:       if( pSeek ){
194580:         zText = (const char*)sqlite3_column_text(pSeek, iCol);
194581:         nText = sqlite3_column_bytes(pSeek, iCol);
194582:       }else{
194583:         zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
194584:         nText = sqlite3_value_bytes(apVal[iCol-1]);
194585:       }
194586:       ctx.szCol = 0;
194587:       rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT, 
194588:           zText, nText, (void*)&ctx, fts5StorageInsertCallback
194589:       );
194590:       p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
194591:     }
194592:   }
194593:   p->nTotalRow--;
194594: 
194595:   rc2 = sqlite3_reset(pSeek);
194596:   if( rc==SQLITE_OK ) rc = rc2;
194597:   return rc;
194598: }
194599: 
194600: 
194601: /*
194602: ** Insert a record into the %_docsize table. Specifically, do:
194603: **
194604: **   INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
194605: **
194606: ** If there is no %_docsize table (as happens if the columnsize=0 option
194607: ** is specified when the FTS5 table is created), this function is a no-op.
194608: */
194609: static int fts5StorageInsertDocsize(
194610:   Fts5Storage *p,                 /* Storage module to write to */
194611:   i64 iRowid,                     /* id value */
194612:   Fts5Buffer *pBuf                /* sz value */
194613: ){
194614:   int rc = SQLITE_OK;
194615:   if( p->pConfig->bColumnsize ){
194616:     sqlite3_stmt *pReplace = 0;
194617:     rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
194618:     if( rc==SQLITE_OK ){
194619:       sqlite3_bind_int64(pReplace, 1, iRowid);
194620:       sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
194621:       sqlite3_step(pReplace);
194622:       rc = sqlite3_reset(pReplace);
194623:     }
194624:   }
194625:   return rc;
194626: }
194627: 
194628: /*
194629: ** Load the contents of the "averages" record from disk into the 
194630: ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
194631: ** argument bCache is true, set the p->bTotalsValid flag to indicate
194632: ** that the contents of aTotalSize[] and nTotalRow are valid until
194633: ** further notice.
194634: **
194635: ** Return SQLITE_OK if successful, or an SQLite error code if an error
194636: ** occurs.
194637: */
194638: static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
194639:   int rc = SQLITE_OK;
194640:   if( p->bTotalsValid==0 ){
194641:     rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
194642:     p->bTotalsValid = bCache;
194643:   }
194644:   return rc;
194645: }
194646: 
194647: /*
194648: ** Store the current contents of the p->nTotalRow and p->aTotalSize[] 
194649: ** variables in the "averages" record on disk.
194650: **
194651: ** Return SQLITE_OK if successful, or an SQLite error code if an error
194652: ** occurs.
194653: */
194654: static int fts5StorageSaveTotals(Fts5Storage *p){
194655:   int nCol = p->pConfig->nCol;
194656:   int i;
194657:   Fts5Buffer buf;
194658:   int rc = SQLITE_OK;
194659:   memset(&buf, 0, sizeof(buf));
194660: 
194661:   sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
194662:   for(i=0; i<nCol; i++){
194663:     sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
194664:   }
194665:   if( rc==SQLITE_OK ){
194666:     rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
194667:   }
194668:   sqlite3_free(buf.p);
194669: 
194670:   return rc;
194671: }
194672: 
194673: /*
194674: ** Remove a row from the FTS table.
194675: */
194676: static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
194677:   Fts5Config *pConfig = p->pConfig;
194678:   int rc;
194679:   sqlite3_stmt *pDel = 0;
194680: 
194681:   assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
194682:   rc = fts5StorageLoadTotals(p, 1);
194683: 
194684:   /* Delete the index records */
194685:   if( rc==SQLITE_OK ){
194686:     rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
194687:   }
194688: 
194689:   /* Delete the %_docsize record */
194690:   if( rc==SQLITE_OK && pConfig->bColumnsize ){
194691:     rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
194692:     if( rc==SQLITE_OK ){
194693:       sqlite3_bind_int64(pDel, 1, iDel);
194694:       sqlite3_step(pDel);
194695:       rc = sqlite3_reset(pDel);
194696:     }
194697:   }
194698: 
194699:   /* Delete the %_content record */
194700:   if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
194701:     if( rc==SQLITE_OK ){
194702:       rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
194703:     }
194704:     if( rc==SQLITE_OK ){
194705:       sqlite3_bind_int64(pDel, 1, iDel);
194706:       sqlite3_step(pDel);
194707:       rc = sqlite3_reset(pDel);
194708:     }
194709:   }
194710: 
194711:   /* Write the averages record */
194712:   if( rc==SQLITE_OK ){
194713:     rc = fts5StorageSaveTotals(p);
194714:   }
194715: 
194716:   return rc;
194717: }
194718: 
194719: /*
194720: ** Delete all entries in the FTS5 index.
194721: */
194722: static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
194723:   Fts5Config *pConfig = p->pConfig;
194724:   int rc;
194725: 
194726:   /* Delete the contents of the %_data and %_docsize tables. */
194727:   rc = fts5ExecPrintf(pConfig->db, 0,
194728:       "DELETE FROM %Q.'%q_data';" 
194729:       "DELETE FROM %Q.'%q_idx';",
194730:       pConfig->zDb, pConfig->zName,
194731:       pConfig->zDb, pConfig->zName
194732:   );
194733:   if( rc==SQLITE_OK && pConfig->bColumnsize ){
194734:     rc = fts5ExecPrintf(pConfig->db, 0,
194735:         "DELETE FROM %Q.'%q_docsize';",
194736:         pConfig->zDb, pConfig->zName
194737:     );
194738:   }
194739: 
194740:   /* Reinitialize the %_data table. This call creates the initial structure
194741:   ** and averages records.  */
194742:   if( rc==SQLITE_OK ){
194743:     rc = sqlite3Fts5IndexReinit(p->pIndex);
194744:   }
194745:   if( rc==SQLITE_OK ){
194746:     rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
194747:   }
194748:   return rc;
194749: }
194750: 
194751: static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
194752:   Fts5Buffer buf = {0,0,0};
194753:   Fts5Config *pConfig = p->pConfig;
194754:   sqlite3_stmt *pScan = 0;
194755:   Fts5InsertCtx ctx;
194756:   int rc;
194757: 
194758:   memset(&ctx, 0, sizeof(Fts5InsertCtx));
194759:   ctx.pStorage = p;
194760:   rc = sqlite3Fts5StorageDeleteAll(p);
194761:   if( rc==SQLITE_OK ){
194762:     rc = fts5StorageLoadTotals(p, 1);
194763:   }
194764: 
194765:   if( rc==SQLITE_OK ){
194766:     rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
194767:   }
194768: 
194769:   while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
194770:     i64 iRowid = sqlite3_column_int64(pScan, 0);
194771: 
194772:     sqlite3Fts5BufferZero(&buf);
194773:     rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
194774:     for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
194775:       ctx.szCol = 0;
194776:       if( pConfig->abUnindexed[ctx.iCol]==0 ){
194777:         rc = sqlite3Fts5Tokenize(pConfig, 
194778:             FTS5_TOKENIZE_DOCUMENT,
194779:             (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
194780:             sqlite3_column_bytes(pScan, ctx.iCol+1),
194781:             (void*)&ctx,
194782:             fts5StorageInsertCallback
194783:         );
194784:       }
194785:       sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
194786:       p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
194787:     }
194788:     p->nTotalRow++;
194789: 
194790:     if( rc==SQLITE_OK ){
194791:       rc = fts5StorageInsertDocsize(p, iRowid, &buf);
194792:     }
194793:   }
194794:   sqlite3_free(buf.p);
194795: 
194796:   /* Write the averages record */
194797:   if( rc==SQLITE_OK ){
194798:     rc = fts5StorageSaveTotals(p);
194799:   }
194800:   return rc;
194801: }
194802: 
194803: static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
194804:   return sqlite3Fts5IndexOptimize(p->pIndex);
194805: }
194806: 
194807: static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
194808:   return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
194809: }
194810: 
194811: static int sqlite3Fts5StorageReset(Fts5Storage *p){
194812:   return sqlite3Fts5IndexReset(p->pIndex);
194813: }
194814: 
194815: /*
194816: ** Allocate a new rowid. This is used for "external content" tables when
194817: ** a NULL value is inserted into the rowid column. The new rowid is allocated
194818: ** by inserting a dummy row into the %_docsize table. The dummy will be
194819: ** overwritten later.
194820: **
194821: ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
194822: ** this case the user is required to provide a rowid explicitly.
194823: */
194824: static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
194825:   int rc = SQLITE_MISMATCH;
194826:   if( p->pConfig->bColumnsize ){
194827:     sqlite3_stmt *pReplace = 0;
194828:     rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
194829:     if( rc==SQLITE_OK ){
194830:       sqlite3_bind_null(pReplace, 1);
194831:       sqlite3_bind_null(pReplace, 2);
194832:       sqlite3_step(pReplace);
194833:       rc = sqlite3_reset(pReplace);
194834:     }
194835:     if( rc==SQLITE_OK ){
194836:       *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
194837:     }
194838:   }
194839:   return rc;
194840: }
194841: 
194842: /*
194843: ** Insert a new row into the FTS content table.
194844: */
194845: static int sqlite3Fts5StorageContentInsert(
194846:   Fts5Storage *p, 
194847:   sqlite3_value **apVal, 
194848:   i64 *piRowid
194849: ){
194850:   Fts5Config *pConfig = p->pConfig;
194851:   int rc = SQLITE_OK;
194852: 
194853:   /* Insert the new row into the %_content table. */
194854:   if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
194855:     if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
194856:       *piRowid = sqlite3_value_int64(apVal[1]);
194857:     }else{
194858:       rc = fts5StorageNewRowid(p, piRowid);
194859:     }
194860:   }else{
194861:     sqlite3_stmt *pInsert = 0;    /* Statement to write %_content table */
194862:     int i;                        /* Counter variable */
194863:     rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
194864:     for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
194865:       rc = sqlite3_bind_value(pInsert, i, apVal[i]);
194866:     }
194867:     if( rc==SQLITE_OK ){
194868:       sqlite3_step(pInsert);
194869:       rc = sqlite3_reset(pInsert);
194870:     }
194871:     *piRowid = sqlite3_last_insert_rowid(pConfig->db);
194872:   }
194873: 
194874:   return rc;
194875: }
194876: 
194877: /*
194878: ** Insert new entries into the FTS index and %_docsize table.
194879: */
194880: static int sqlite3Fts5StorageIndexInsert(
194881:   Fts5Storage *p, 
194882:   sqlite3_value **apVal, 
194883:   i64 iRowid
194884: ){
194885:   Fts5Config *pConfig = p->pConfig;
194886:   int rc = SQLITE_OK;             /* Return code */
194887:   Fts5InsertCtx ctx;              /* Tokenization callback context object */
194888:   Fts5Buffer buf;                 /* Buffer used to build up %_docsize blob */
194889: 
194890:   memset(&buf, 0, sizeof(Fts5Buffer));
194891:   ctx.pStorage = p;
194892:   rc = fts5StorageLoadTotals(p, 1);
194893: 
194894:   if( rc==SQLITE_OK ){
194895:     rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
194896:   }
194897:   for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
194898:     ctx.szCol = 0;
194899:     if( pConfig->abUnindexed[ctx.iCol]==0 ){
194900:       rc = sqlite3Fts5Tokenize(pConfig, 
194901:           FTS5_TOKENIZE_DOCUMENT,
194902:           (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
194903:           sqlite3_value_bytes(apVal[ctx.iCol+2]),
194904:           (void*)&ctx,
194905:           fts5StorageInsertCallback
194906:       );
194907:     }
194908:     sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
194909:     p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
194910:   }
194911:   p->nTotalRow++;
194912: 
194913:   /* Write the %_docsize record */
194914:   if( rc==SQLITE_OK ){
194915:     rc = fts5StorageInsertDocsize(p, iRowid, &buf);
194916:   }
194917:   sqlite3_free(buf.p);
194918: 
194919:   /* Write the averages record */
194920:   if( rc==SQLITE_OK ){
194921:     rc = fts5StorageSaveTotals(p);
194922:   }
194923: 
194924:   return rc;
194925: }
194926: 
194927: static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
194928:   Fts5Config *pConfig = p->pConfig;
194929:   char *zSql;
194930:   int rc;
194931: 
194932:   zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'", 
194933:       pConfig->zDb, pConfig->zName, zSuffix
194934:   );
194935:   if( zSql==0 ){
194936:     rc = SQLITE_NOMEM;
194937:   }else{
194938:     sqlite3_stmt *pCnt = 0;
194939:     rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
194940:     if( rc==SQLITE_OK ){
194941:       if( SQLITE_ROW==sqlite3_step(pCnt) ){
194942:         *pnRow = sqlite3_column_int64(pCnt, 0);
194943:       }
194944:       rc = sqlite3_finalize(pCnt);
194945:     }
194946:   }
194947: 
194948:   sqlite3_free(zSql);
194949:   return rc;
194950: }
194951: 
194952: /*
194953: ** Context object used by sqlite3Fts5StorageIntegrity().
194954: */
194955: typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
194956: struct Fts5IntegrityCtx {
194957:   i64 iRowid;
194958:   int iCol;
194959:   int szCol;
194960:   u64 cksum;
194961:   Fts5Termset *pTermset;
194962:   Fts5Config *pConfig;
194963: };
194964: 
194965: 
194966: /*
194967: ** Tokenization callback used by integrity check.
194968: */
194969: static int fts5StorageIntegrityCallback(
194970:   void *pContext,                 /* Pointer to Fts5IntegrityCtx object */
194971:   int tflags,
194972:   const char *pToken,             /* Buffer containing token */
194973:   int nToken,                     /* Size of token in bytes */
194974:   int iUnused1,                   /* Start offset of token */
194975:   int iUnused2                    /* End offset of token */
194976: ){
194977:   Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
194978:   Fts5Termset *pTermset = pCtx->pTermset;
194979:   int bPresent;
194980:   int ii;
194981:   int rc = SQLITE_OK;
194982:   int iPos;
194983:   int iCol;
194984: 
194985:   UNUSED_PARAM2(iUnused1, iUnused2);
194986:   if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
194987: 
194988:   if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
194989:     pCtx->szCol++;
194990:   }
194991: 
194992:   switch( pCtx->pConfig->eDetail ){
194993:     case FTS5_DETAIL_FULL:
194994:       iPos = pCtx->szCol-1;
194995:       iCol = pCtx->iCol;
194996:       break;
194997: 
194998:     case FTS5_DETAIL_COLUMNS:
194999:       iPos = pCtx->iCol;
195000:       iCol = 0;
195001:       break;
195002: 
195003:     default:
195004:       assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
195005:       iPos = 0;
195006:       iCol = 0;
195007:       break;
195008:   }
195009: 
195010:   rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
195011:   if( rc==SQLITE_OK && bPresent==0 ){
195012:     pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
195013:         pCtx->iRowid, iCol, iPos, 0, pToken, nToken
195014:     );
195015:   }
195016: 
195017:   for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
195018:     const int nChar = pCtx->pConfig->aPrefix[ii];
195019:     int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
195020:     if( nByte ){
195021:       rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
195022:       if( bPresent==0 ){
195023:         pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
195024:             pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
195025:         );
195026:       }
195027:     }
195028:   }
195029: 
195030:   return rc;
195031: }
195032: 
195033: /*
195034: ** Check that the contents of the FTS index match that of the %_content
195035: ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
195036: ** some other SQLite error code if an error occurs while attempting to
195037: ** determine this.
195038: */
195039: static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
195040:   Fts5Config *pConfig = p->pConfig;
195041:   int rc;                         /* Return code */
195042:   int *aColSize;                  /* Array of size pConfig->nCol */
195043:   i64 *aTotalSize;                /* Array of size pConfig->nCol */
195044:   Fts5IntegrityCtx ctx;
195045:   sqlite3_stmt *pScan;
195046: 
195047:   memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
195048:   ctx.pConfig = p->pConfig;
195049:   aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
195050:   if( !aTotalSize ) return SQLITE_NOMEM;
195051:   aColSize = (int*)&aTotalSize[pConfig->nCol];
195052:   memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
195053: 
195054:   /* Generate the expected index checksum based on the contents of the
195055:   ** %_content table. This block stores the checksum in ctx.cksum. */
195056:   rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
195057:   if( rc==SQLITE_OK ){
195058:     int rc2;
195059:     while( SQLITE_ROW==sqlite3_step(pScan) ){
195060:       int i;
195061:       ctx.iRowid = sqlite3_column_int64(pScan, 0);
195062:       ctx.szCol = 0;
195063:       if( pConfig->bColumnsize ){
195064:         rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
195065:       }
195066:       if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
195067:         rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
195068:       }
195069:       for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
195070:         if( pConfig->abUnindexed[i] ) continue;
195071:         ctx.iCol = i;
195072:         ctx.szCol = 0;
195073:         if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195074:           rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
195075:         }
195076:         if( rc==SQLITE_OK ){
195077:           rc = sqlite3Fts5Tokenize(pConfig, 
195078:               FTS5_TOKENIZE_DOCUMENT,
195079:               (const char*)sqlite3_column_text(pScan, i+1),
195080:               sqlite3_column_bytes(pScan, i+1),
195081:               (void*)&ctx,
195082:               fts5StorageIntegrityCallback
195083:           );
195084:         }
195085:         if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
195086:           rc = FTS5_CORRUPT;
195087:         }
195088:         aTotalSize[i] += ctx.szCol;
195089:         if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
195090:           sqlite3Fts5TermsetFree(ctx.pTermset);
195091:           ctx.pTermset = 0;
195092:         }
195093:       }
195094:       sqlite3Fts5TermsetFree(ctx.pTermset);
195095:       ctx.pTermset = 0;
195096: 
195097:       if( rc!=SQLITE_OK ) break;
195098:     }
195099:     rc2 = sqlite3_reset(pScan);
195100:     if( rc==SQLITE_OK ) rc = rc2;
195101:   }
195102: 
195103:   /* Test that the "totals" (sometimes called "averages") record looks Ok */
195104:   if( rc==SQLITE_OK ){
195105:     int i;
195106:     rc = fts5StorageLoadTotals(p, 0);
195107:     for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
195108:       if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
195109:     }
195110:   }
195111: 
195112:   /* Check that the %_docsize and %_content tables contain the expected
195113:   ** number of rows.  */
195114:   if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
195115:     i64 nRow = 0;
195116:     rc = fts5StorageCount(p, "content", &nRow);
195117:     if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
195118:   }
195119:   if( rc==SQLITE_OK && pConfig->bColumnsize ){
195120:     i64 nRow = 0;
195121:     rc = fts5StorageCount(p, "docsize", &nRow);
195122:     if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
195123:   }
195124: 
195125:   /* Pass the expected checksum down to the FTS index module. It will
195126:   ** verify, amongst other things, that it matches the checksum generated by
195127:   ** inspecting the index itself.  */
195128:   if( rc==SQLITE_OK ){
195129:     rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
195130:   }
195131: 
195132:   sqlite3_free(aTotalSize);
195133:   return rc;
195134: }
195135: 
195136: /*
195137: ** Obtain an SQLite statement handle that may be used to read data from the
195138: ** %_content table.
195139: */
195140: static int sqlite3Fts5StorageStmt(
195141:   Fts5Storage *p, 
195142:   int eStmt, 
195143:   sqlite3_stmt **pp, 
195144:   char **pzErrMsg
195145: ){
195146:   int rc;
195147:   assert( eStmt==FTS5_STMT_SCAN_ASC 
195148:        || eStmt==FTS5_STMT_SCAN_DESC
195149:        || eStmt==FTS5_STMT_LOOKUP
195150:   );
195151:   rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
195152:   if( rc==SQLITE_OK ){
195153:     assert( p->aStmt[eStmt]==*pp );
195154:     p->aStmt[eStmt] = 0;
195155:   }
195156:   return rc;
195157: }
195158: 
195159: /*
195160: ** Release an SQLite statement handle obtained via an earlier call to
195161: ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
195162: ** must match that passed to the sqlite3Fts5StorageStmt() call.
195163: */
195164: static void sqlite3Fts5StorageStmtRelease(
195165:   Fts5Storage *p, 
195166:   int eStmt, 
195167:   sqlite3_stmt *pStmt
195168: ){
195169:   assert( eStmt==FTS5_STMT_SCAN_ASC
195170:        || eStmt==FTS5_STMT_SCAN_DESC
195171:        || eStmt==FTS5_STMT_LOOKUP
195172:   );
195173:   if( p->aStmt[eStmt]==0 ){
195174:     sqlite3_reset(pStmt);
195175:     p->aStmt[eStmt] = pStmt;
195176:   }else{
195177:     sqlite3_finalize(pStmt);
195178:   }
195179: }
195180: 
195181: static int fts5StorageDecodeSizeArray(
195182:   int *aCol, int nCol,            /* Array to populate */
195183:   const u8 *aBlob, int nBlob      /* Record to read varints from */
195184: ){
195185:   int i;
195186:   int iOff = 0;
195187:   for(i=0; i<nCol; i++){
195188:     if( iOff>=nBlob ) return 1;
195189:     iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
195190:   }
195191:   return (iOff!=nBlob);
195192: }
195193: 
195194: /*
195195: ** Argument aCol points to an array of integers containing one entry for
195196: ** each table column. This function reads the %_docsize record for the
195197: ** specified rowid and populates aCol[] with the results.
195198: **
195199: ** An SQLite error code is returned if an error occurs, or SQLITE_OK
195200: ** otherwise.
195201: */
195202: static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
195203:   int nCol = p->pConfig->nCol;    /* Number of user columns in table */
195204:   sqlite3_stmt *pLookup = 0;      /* Statement to query %_docsize */
195205:   int rc;                         /* Return Code */
195206: 
195207:   assert( p->pConfig->bColumnsize );
195208:   rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
195209:   if( rc==SQLITE_OK ){
195210:     int bCorrupt = 1;
195211:     sqlite3_bind_int64(pLookup, 1, iRowid);
195212:     if( SQLITE_ROW==sqlite3_step(pLookup) ){
195213:       const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
195214:       int nBlob = sqlite3_column_bytes(pLookup, 0);
195215:       if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
195216:         bCorrupt = 0;
195217:       }
195218:     }
195219:     rc = sqlite3_reset(pLookup);
195220:     if( bCorrupt && rc==SQLITE_OK ){
195221:       rc = FTS5_CORRUPT;
195222:     }
195223:   }
195224: 
195225:   return rc;
195226: }
195227: 
195228: static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
195229:   int rc = fts5StorageLoadTotals(p, 0);
195230:   if( rc==SQLITE_OK ){
195231:     *pnToken = 0;
195232:     if( iCol<0 ){
195233:       int i;
195234:       for(i=0; i<p->pConfig->nCol; i++){
195235:         *pnToken += p->aTotalSize[i];
195236:       }
195237:     }else if( iCol<p->pConfig->nCol ){
195238:       *pnToken = p->aTotalSize[iCol];
195239:     }else{
195240:       rc = SQLITE_RANGE;
195241:     }
195242:   }
195243:   return rc;
195244: }
195245: 
195246: static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
195247:   int rc = fts5StorageLoadTotals(p, 0);
195248:   if( rc==SQLITE_OK ){
195249:     *pnRow = p->nTotalRow;
195250:   }
195251:   return rc;
195252: }
195253: 
195254: /*
195255: ** Flush any data currently held in-memory to disk.
195256: */
195257: static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
195258:   if( bCommit && p->bTotalsValid ){
195259:     int rc = fts5StorageSaveTotals(p);
195260:     p->bTotalsValid = 0;
195261:     if( rc!=SQLITE_OK ) return rc;
195262:   }
195263:   return sqlite3Fts5IndexSync(p->pIndex, bCommit);
195264: }
195265: 
195266: static int sqlite3Fts5StorageRollback(Fts5Storage *p){
195267:   p->bTotalsValid = 0;
195268:   return sqlite3Fts5IndexRollback(p->pIndex);
195269: }
195270: 
195271: static int sqlite3Fts5StorageConfigValue(
195272:   Fts5Storage *p, 
195273:   const char *z,
195274:   sqlite3_value *pVal,
195275:   int iVal
195276: ){
195277:   sqlite3_stmt *pReplace = 0;
195278:   int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
195279:   if( rc==SQLITE_OK ){
195280:     sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
195281:     if( pVal ){
195282:       sqlite3_bind_value(pReplace, 2, pVal);
195283:     }else{
195284:       sqlite3_bind_int(pReplace, 2, iVal);
195285:     }
195286:     sqlite3_step(pReplace);
195287:     rc = sqlite3_reset(pReplace);
195288:   }
195289:   if( rc==SQLITE_OK && pVal ){
195290:     int iNew = p->pConfig->iCookie + 1;
195291:     rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
195292:     if( rc==SQLITE_OK ){
195293:       p->pConfig->iCookie = iNew;
195294:     }
195295:   }
195296:   return rc;
195297: }
195298: 
195299: /*
195300: ** 2014 May 31
195301: **
195302: ** The author disclaims copyright to this source code.  In place of
195303: ** a legal notice, here is a blessing:
195304: **
195305: **    May you do good and not evil.
195306: **    May you find forgiveness for yourself and forgive others.
195307: **    May you share freely, never taking more than you give.
195308: **
195309: ******************************************************************************
195310: */
195311: 
195312: 
195313: /* #include "fts5Int.h" */
195314: 
195315: /**************************************************************************
195316: ** Start of ascii tokenizer implementation.
195317: */
195318: 
195319: /*
195320: ** For tokenizers with no "unicode" modifier, the set of token characters
195321: ** is the same as the set of ASCII range alphanumeric characters. 
195322: */
195323: static unsigned char aAsciiTokenChar[128] = {
195324:   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x00..0x0F */
195325:   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x10..0x1F */
195326:   0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0,   /* 0x20..0x2F */
195327:   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 0, 0, 0, 0, 0, 0,   /* 0x30..0x3F */
195328:   0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x40..0x4F */
195329:   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x50..0x5F */
195330:   0, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   /* 0x60..0x6F */
195331:   1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 0, 0, 0, 0, 0,   /* 0x70..0x7F */
195332: };
195333: 
195334: typedef struct AsciiTokenizer AsciiTokenizer;
195335: struct AsciiTokenizer {
195336:   unsigned char aTokenChar[128];
195337: };
195338: 
195339: static void fts5AsciiAddExceptions(
195340:   AsciiTokenizer *p, 
195341:   const char *zArg, 
195342:   int bTokenChars
195343: ){
195344:   int i;
195345:   for(i=0; zArg[i]; i++){
195346:     if( (zArg[i] & 0x80)==0 ){
195347:       p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
195348:     }
195349:   }
195350: }
195351: 
195352: /*
195353: ** Delete a "ascii" tokenizer.
195354: */
195355: static void fts5AsciiDelete(Fts5Tokenizer *p){
195356:   sqlite3_free(p);
195357: }
195358: 
195359: /*
195360: ** Create an "ascii" tokenizer.
195361: */
195362: static int fts5AsciiCreate(
195363:   void *pUnused, 
195364:   const char **azArg, int nArg,
195365:   Fts5Tokenizer **ppOut
195366: ){
195367:   int rc = SQLITE_OK;
195368:   AsciiTokenizer *p = 0;
195369:   UNUSED_PARAM(pUnused);
195370:   if( nArg%2 ){
195371:     rc = SQLITE_ERROR;
195372:   }else{
195373:     p = sqlite3_malloc(sizeof(AsciiTokenizer));
195374:     if( p==0 ){
195375:       rc = SQLITE_NOMEM;
195376:     }else{
195377:       int i;
195378:       memset(p, 0, sizeof(AsciiTokenizer));
195379:       memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
195380:       for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
195381:         const char *zArg = azArg[i+1];
195382:         if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
195383:           fts5AsciiAddExceptions(p, zArg, 1);
195384:         }else
195385:         if( 0==sqlite3_stricmp(azArg[i], "separators") ){
195386:           fts5AsciiAddExceptions(p, zArg, 0);
195387:         }else{
195388:           rc = SQLITE_ERROR;
195389:         }
195390:       }
195391:       if( rc!=SQLITE_OK ){
195392:         fts5AsciiDelete((Fts5Tokenizer*)p);
195393:         p = 0;
195394:       }
195395:     }
195396:   }
195397: 
195398:   *ppOut = (Fts5Tokenizer*)p;
195399:   return rc;
195400: }
195401: 
195402: 
195403: static void asciiFold(char *aOut, const char *aIn, int nByte){
195404:   int i;
195405:   for(i=0; i<nByte; i++){
195406:     char c = aIn[i];
195407:     if( c>='A' && c<='Z' ) c += 32;
195408:     aOut[i] = c;
195409:   }
195410: }
195411: 
195412: /*
195413: ** Tokenize some text using the ascii tokenizer.
195414: */
195415: static int fts5AsciiTokenize(
195416:   Fts5Tokenizer *pTokenizer,
195417:   void *pCtx,
195418:   int iUnused,
195419:   const char *pText, int nText,
195420:   int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
195421: ){
195422:   AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
195423:   int rc = SQLITE_OK;
195424:   int ie;
195425:   int is = 0;
195426: 
195427:   char aFold[64];
195428:   int nFold = sizeof(aFold);
195429:   char *pFold = aFold;
195430:   unsigned char *a = p->aTokenChar;
195431: 
195432:   UNUSED_PARAM(iUnused);
195433: 
195434:   while( is<nText && rc==SQLITE_OK ){
195435:     int nByte;
195436: 
195437:     /* Skip any leading divider characters. */
195438:     while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
195439:       is++;
195440:     }
195441:     if( is==nText ) break;
195442: 
195443:     /* Count the token characters */
195444:     ie = is+1;
195445:     while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
195446:       ie++;
195447:     }
195448: 
195449:     /* Fold to lower case */
195450:     nByte = ie-is;
195451:     if( nByte>nFold ){
195452:       if( pFold!=aFold ) sqlite3_free(pFold);
195453:       pFold = sqlite3_malloc(nByte*2);
195454:       if( pFold==0 ){
195455:         rc = SQLITE_NOMEM;
195456:         break;
195457:       }
195458:       nFold = nByte*2;
195459:     }
195460:     asciiFold(pFold, &pText[is], nByte);
195461: 
195462:     /* Invoke the token callback */
195463:     rc = xToken(pCtx, 0, pFold, nByte, is, ie);
195464:     is = ie+1;
195465:   }
195466:   
195467:   if( pFold!=aFold ) sqlite3_free(pFold);
195468:   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195469:   return rc;
195470: }
195471: 
195472: /**************************************************************************
195473: ** Start of unicode61 tokenizer implementation.
195474: */
195475: 
195476: 
195477: /*
195478: ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
195479: ** from the sqlite3 source file utf.c. If this file is compiled as part
195480: ** of the amalgamation, they are not required.
195481: */
195482: #ifndef SQLITE_AMALGAMATION
195483: 
195484: static const unsigned char sqlite3Utf8Trans1[] = {
195485:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195486:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
195487:   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
195488:   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
195489:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195490:   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
195491:   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
195492:   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
195493: };
195494: 
195495: #define READ_UTF8(zIn, zTerm, c)                           \
195496:   c = *(zIn++);                                            \
195497:   if( c>=0xc0 ){                                           \
195498:     c = sqlite3Utf8Trans1[c-0xc0];                         \
195499:     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
195500:       c = (c<<6) + (0x3f & *(zIn++));                      \
195501:     }                                                      \
195502:     if( c<0x80                                             \
195503:         || (c&0xFFFFF800)==0xD800                          \
195504:         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
195505:   }
195506: 
195507: 
195508: #define WRITE_UTF8(zOut, c) {                          \
195509:   if( c<0x00080 ){                                     \
195510:     *zOut++ = (unsigned char)(c&0xFF);                 \
195511:   }                                                    \
195512:   else if( c<0x00800 ){                                \
195513:     *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F);     \
195514:     *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195515:   }                                                    \
195516:   else if( c<0x10000 ){                                \
195517:     *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F);    \
195518:     *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
195519:     *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195520:   }else{                                               \
195521:     *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07);  \
195522:     *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F);  \
195523:     *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F);   \
195524:     *zOut++ = 0x80 + (unsigned char)(c & 0x3F);        \
195525:   }                                                    \
195526: }
195527: 
195528: #endif /* ifndef SQLITE_AMALGAMATION */
195529: 
195530: typedef struct Unicode61Tokenizer Unicode61Tokenizer;
195531: struct Unicode61Tokenizer {
195532:   unsigned char aTokenChar[128];  /* ASCII range token characters */
195533:   char *aFold;                    /* Buffer to fold text into */
195534:   int nFold;                      /* Size of aFold[] in bytes */
195535:   int bRemoveDiacritic;           /* True if remove_diacritics=1 is set */
195536:   int nException;
195537:   int *aiException;
195538: };
195539: 
195540: static int fts5UnicodeAddExceptions(
195541:   Unicode61Tokenizer *p,          /* Tokenizer object */
195542:   const char *z,                  /* Characters to treat as exceptions */
195543:   int bTokenChars                 /* 1 for 'tokenchars', 0 for 'separators' */
195544: ){
195545:   int rc = SQLITE_OK;
195546:   int n = (int)strlen(z);
195547:   int *aNew;
195548: 
195549:   if( n>0 ){
195550:     aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
195551:     if( aNew ){
195552:       int nNew = p->nException;
195553:       const unsigned char *zCsr = (const unsigned char*)z;
195554:       const unsigned char *zTerm = (const unsigned char*)&z[n];
195555:       while( zCsr<zTerm ){
195556:         int iCode;
195557:         int bToken;
195558:         READ_UTF8(zCsr, zTerm, iCode);
195559:         if( iCode<128 ){
195560:           p->aTokenChar[iCode] = (unsigned char)bTokenChars;
195561:         }else{
195562:           bToken = sqlite3Fts5UnicodeIsalnum(iCode);
195563:           assert( (bToken==0 || bToken==1) ); 
195564:           assert( (bTokenChars==0 || bTokenChars==1) );
195565:           if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
195566:             int i;
195567:             for(i=0; i<nNew; i++){
195568:               if( aNew[i]>iCode ) break;
195569:             }
195570:             memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
195571:             aNew[i] = iCode;
195572:             nNew++;
195573:           }
195574:         }
195575:       }
195576:       p->aiException = aNew;
195577:       p->nException = nNew;
195578:     }else{
195579:       rc = SQLITE_NOMEM;
195580:     }
195581:   }
195582: 
195583:   return rc;
195584: }
195585: 
195586: /*
195587: ** Return true if the p->aiException[] array contains the value iCode.
195588: */
195589: static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
195590:   if( p->nException>0 ){
195591:     int *a = p->aiException;
195592:     int iLo = 0;
195593:     int iHi = p->nException-1;
195594: 
195595:     while( iHi>=iLo ){
195596:       int iTest = (iHi + iLo) / 2;
195597:       if( iCode==a[iTest] ){
195598:         return 1;
195599:       }else if( iCode>a[iTest] ){
195600:         iLo = iTest+1;
195601:       }else{
195602:         iHi = iTest-1;
195603:       }
195604:     }
195605:   }
195606: 
195607:   return 0;
195608: }
195609: 
195610: /*
195611: ** Delete a "unicode61" tokenizer.
195612: */
195613: static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
195614:   if( pTok ){
195615:     Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
195616:     sqlite3_free(p->aiException);
195617:     sqlite3_free(p->aFold);
195618:     sqlite3_free(p);
195619:   }
195620:   return;
195621: }
195622: 
195623: /*
195624: ** Create a "unicode61" tokenizer.
195625: */
195626: static int fts5UnicodeCreate(
195627:   void *pUnused, 
195628:   const char **azArg, int nArg,
195629:   Fts5Tokenizer **ppOut
195630: ){
195631:   int rc = SQLITE_OK;             /* Return code */
195632:   Unicode61Tokenizer *p = 0;      /* New tokenizer object */ 
195633: 
195634:   UNUSED_PARAM(pUnused);
195635: 
195636:   if( nArg%2 ){
195637:     rc = SQLITE_ERROR;
195638:   }else{
195639:     p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
195640:     if( p ){
195641:       int i;
195642:       memset(p, 0, sizeof(Unicode61Tokenizer));
195643:       memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
195644:       p->bRemoveDiacritic = 1;
195645:       p->nFold = 64;
195646:       p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
195647:       if( p->aFold==0 ){
195648:         rc = SQLITE_NOMEM;
195649:       }
195650:       for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
195651:         const char *zArg = azArg[i+1];
195652:         if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
195653:           if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
195654:             rc = SQLITE_ERROR;
195655:           }
195656:           p->bRemoveDiacritic = (zArg[0]=='1');
195657:         }else
195658:         if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
195659:           rc = fts5UnicodeAddExceptions(p, zArg, 1);
195660:         }else
195661:         if( 0==sqlite3_stricmp(azArg[i], "separators") ){
195662:           rc = fts5UnicodeAddExceptions(p, zArg, 0);
195663:         }else{
195664:           rc = SQLITE_ERROR;
195665:         }
195666:       }
195667:     }else{
195668:       rc = SQLITE_NOMEM;
195669:     }
195670:     if( rc!=SQLITE_OK ){
195671:       fts5UnicodeDelete((Fts5Tokenizer*)p);
195672:       p = 0;
195673:     }
195674:     *ppOut = (Fts5Tokenizer*)p;
195675:   }
195676:   return rc;
195677: }
195678: 
195679: /*
195680: ** Return true if, for the purposes of tokenizing with the tokenizer
195681: ** passed as the first argument, codepoint iCode is considered a token 
195682: ** character (not a separator).
195683: */
195684: static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
195685:   assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
195686:   return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
195687: }
195688: 
195689: static int fts5UnicodeTokenize(
195690:   Fts5Tokenizer *pTokenizer,
195691:   void *pCtx,
195692:   int iUnused,
195693:   const char *pText, int nText,
195694:   int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
195695: ){
195696:   Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
195697:   int rc = SQLITE_OK;
195698:   unsigned char *a = p->aTokenChar;
195699: 
195700:   unsigned char *zTerm = (unsigned char*)&pText[nText];
195701:   unsigned char *zCsr = (unsigned char *)pText;
195702: 
195703:   /* Output buffer */
195704:   char *aFold = p->aFold;
195705:   int nFold = p->nFold;
195706:   const char *pEnd = &aFold[nFold-6];
195707: 
195708:   UNUSED_PARAM(iUnused);
195709: 
195710:   /* Each iteration of this loop gobbles up a contiguous run of separators,
195711:   ** then the next token.  */
195712:   while( rc==SQLITE_OK ){
195713:     int iCode;                    /* non-ASCII codepoint read from input */
195714:     char *zOut = aFold;
195715:     int is;
195716:     int ie;
195717: 
195718:     /* Skip any separator characters. */
195719:     while( 1 ){
195720:       if( zCsr>=zTerm ) goto tokenize_done;
195721:       if( *zCsr & 0x80 ) {
195722:         /* A character outside of the ascii range. Skip past it if it is
195723:         ** a separator character. Or break out of the loop if it is not. */
195724:         is = zCsr - (unsigned char*)pText;
195725:         READ_UTF8(zCsr, zTerm, iCode);
195726:         if( fts5UnicodeIsAlnum(p, iCode) ){
195727:           goto non_ascii_tokenchar;
195728:         }
195729:       }else{
195730:         if( a[*zCsr] ){
195731:           is = zCsr - (unsigned char*)pText;
195732:           goto ascii_tokenchar;
195733:         }
195734:         zCsr++;
195735:       }
195736:     }
195737: 
195738:     /* Run through the tokenchars. Fold them into the output buffer along
195739:     ** the way.  */
195740:     while( zCsr<zTerm ){
195741: 
195742:       /* Grow the output buffer so that there is sufficient space to fit the
195743:       ** largest possible utf-8 character.  */
195744:       if( zOut>pEnd ){
195745:         aFold = sqlite3_malloc(nFold*2);
195746:         if( aFold==0 ){
195747:           rc = SQLITE_NOMEM;
195748:           goto tokenize_done;
195749:         }
195750:         zOut = &aFold[zOut - p->aFold];
195751:         memcpy(aFold, p->aFold, nFold);
195752:         sqlite3_free(p->aFold);
195753:         p->aFold = aFold;
195754:         p->nFold = nFold = nFold*2;
195755:         pEnd = &aFold[nFold-6];
195756:       }
195757: 
195758:       if( *zCsr & 0x80 ){
195759:         /* An non-ascii-range character. Fold it into the output buffer if
195760:         ** it is a token character, or break out of the loop if it is not. */
195761:         READ_UTF8(zCsr, zTerm, iCode);
195762:         if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
195763:  non_ascii_tokenchar:
195764:           iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
195765:           if( iCode ) WRITE_UTF8(zOut, iCode);
195766:         }else{
195767:           break;
195768:         }
195769:       }else if( a[*zCsr]==0 ){
195770:         /* An ascii-range separator character. End of token. */
195771:         break; 
195772:       }else{
195773:  ascii_tokenchar:
195774:         if( *zCsr>='A' && *zCsr<='Z' ){
195775:           *zOut++ = *zCsr + 32;
195776:         }else{
195777:           *zOut++ = *zCsr;
195778:         }
195779:         zCsr++;
195780:       }
195781:       ie = zCsr - (unsigned char*)pText;
195782:     }
195783: 
195784:     /* Invoke the token callback */
195785:     rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie); 
195786:   }
195787:   
195788:  tokenize_done:
195789:   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
195790:   return rc;
195791: }
195792: 
195793: /**************************************************************************
195794: ** Start of porter stemmer implementation.
195795: */
195796: 
195797: /* Any tokens larger than this (in bytes) are passed through without
195798: ** stemming. */
195799: #define FTS5_PORTER_MAX_TOKEN 64
195800: 
195801: typedef struct PorterTokenizer PorterTokenizer;
195802: struct PorterTokenizer {
195803:   fts5_tokenizer tokenizer;       /* Parent tokenizer module */
195804:   Fts5Tokenizer *pTokenizer;      /* Parent tokenizer instance */
195805:   char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
195806: };
195807: 
195808: /*
195809: ** Delete a "porter" tokenizer.
195810: */
195811: static void fts5PorterDelete(Fts5Tokenizer *pTok){
195812:   if( pTok ){
195813:     PorterTokenizer *p = (PorterTokenizer*)pTok;
195814:     if( p->pTokenizer ){
195815:       p->tokenizer.xDelete(p->pTokenizer);
195816:     }
195817:     sqlite3_free(p);
195818:   }
195819: }
195820: 
195821: /*
195822: ** Create a "porter" tokenizer.
195823: */
195824: static int fts5PorterCreate(
195825:   void *pCtx, 
195826:   const char **azArg, int nArg,
195827:   Fts5Tokenizer **ppOut
195828: ){
195829:   fts5_api *pApi = (fts5_api*)pCtx;
195830:   int rc = SQLITE_OK;
195831:   PorterTokenizer *pRet;
195832:   void *pUserdata = 0;
195833:   const char *zBase = "unicode61";
195834: 
195835:   if( nArg>0 ){
195836:     zBase = azArg[0];
195837:   }
195838: 
195839:   pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
195840:   if( pRet ){
195841:     memset(pRet, 0, sizeof(PorterTokenizer));
195842:     rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
195843:   }else{
195844:     rc = SQLITE_NOMEM;
195845:   }
195846:   if( rc==SQLITE_OK ){
195847:     int nArg2 = (nArg>0 ? nArg-1 : 0);
195848:     const char **azArg2 = (nArg2 ? &azArg[1] : 0);
195849:     rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
195850:   }
195851: 
195852:   if( rc!=SQLITE_OK ){
195853:     fts5PorterDelete((Fts5Tokenizer*)pRet);
195854:     pRet = 0;
195855:   }
195856:   *ppOut = (Fts5Tokenizer*)pRet;
195857:   return rc;
195858: }
195859: 
195860: typedef struct PorterContext PorterContext;
195861: struct PorterContext {
195862:   void *pCtx;
195863:   int (*xToken)(void*, int, const char*, int, int, int);
195864:   char *aBuf;
195865: };
195866: 
195867: typedef struct PorterRule PorterRule;
195868: struct PorterRule {
195869:   const char *zSuffix;
195870:   int nSuffix;
195871:   int (*xCond)(char *zStem, int nStem);
195872:   const char *zOutput;
195873:   int nOutput;
195874: };
195875: 
195876: #if 0
195877: static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
195878:   int ret = -1;
195879:   int nBuf = *pnBuf;
195880:   PorterRule *p;
195881: 
195882:   for(p=aRule; p->zSuffix; p++){
195883:     assert( strlen(p->zSuffix)==p->nSuffix );
195884:     assert( strlen(p->zOutput)==p->nOutput );
195885:     if( nBuf<p->nSuffix ) continue;
195886:     if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
195887:   }
195888: 
195889:   if( p->zSuffix ){
195890:     int nStem = nBuf - p->nSuffix;
195891:     if( p->xCond==0 || p->xCond(aBuf, nStem) ){
195892:       memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
195893:       *pnBuf = nStem + p->nOutput;
195894:       ret = p - aRule;
195895:     }
195896:   }
195897: 
195898:   return ret;
195899: }
195900: #endif
195901: 
195902: static int fts5PorterIsVowel(char c, int bYIsVowel){
195903:   return (
195904:       c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
195905:   );
195906: }
195907: 
195908: static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
195909:   int i;
195910:   int bCons = bPrevCons;
195911: 
195912:   /* Scan for a vowel */
195913:   for(i=0; i<nStem; i++){
195914:     if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
195915:   }
195916: 
195917:   /* Scan for a consonent */
195918:   for(i++; i<nStem; i++){
195919:     if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
195920:   }
195921:   return 0;
195922: }
195923: 
195924: /* porter rule condition: (m > 0) */
195925: static int fts5Porter_MGt0(char *zStem, int nStem){
195926:   return !!fts5PorterGobbleVC(zStem, nStem, 0);
195927: }
195928: 
195929: /* porter rule condition: (m > 1) */
195930: static int fts5Porter_MGt1(char *zStem, int nStem){
195931:   int n;
195932:   n = fts5PorterGobbleVC(zStem, nStem, 0);
195933:   if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
195934:     return 1;
195935:   }
195936:   return 0;
195937: }
195938: 
195939: /* porter rule condition: (m = 1) */
195940: static int fts5Porter_MEq1(char *zStem, int nStem){
195941:   int n;
195942:   n = fts5PorterGobbleVC(zStem, nStem, 0);
195943:   if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
195944:     return 1;
195945:   }
195946:   return 0;
195947: }
195948: 
195949: /* porter rule condition: (*o) */
195950: static int fts5Porter_Ostar(char *zStem, int nStem){
195951:   if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
195952:     return 0;
195953:   }else{
195954:     int i;
195955:     int mask = 0;
195956:     int bCons = 0;
195957:     for(i=0; i<nStem; i++){
195958:       bCons = !fts5PorterIsVowel(zStem[i], bCons);
195959:       assert( bCons==0 || bCons==1 );
195960:       mask = (mask << 1) + bCons;
195961:     }
195962:     return ((mask & 0x0007)==0x0005);
195963:   }
195964: }
195965: 
195966: /* porter rule condition: (m > 1 and (*S or *T)) */
195967: static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
195968:   assert( nStem>0 );
195969:   return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t') 
195970:       && fts5Porter_MGt1(zStem, nStem);
195971: }
195972: 
195973: /* porter rule condition: (*v*) */
195974: static int fts5Porter_Vowel(char *zStem, int nStem){
195975:   int i;
195976:   for(i=0; i<nStem; i++){
195977:     if( fts5PorterIsVowel(zStem[i], i>0) ){
195978:       return 1;
195979:     }
195980:   }
195981:   return 0;
195982: }
195983: 
195984: 
195985: /**************************************************************************
195986: ***************************************************************************
195987: ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
195988: */
195989: 
195990: static int fts5PorterStep4(char *aBuf, int *pnBuf){
195991:   int ret = 0;
195992:   int nBuf = *pnBuf;
195993:   switch( aBuf[nBuf-2] ){
195994:     
195995:     case 'a': 
195996:       if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
195997:         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
195998:           *pnBuf = nBuf - 2;
195999:         }
196000:       }
196001:       break;
196002:   
196003:     case 'c': 
196004:       if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
196005:         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196006:           *pnBuf = nBuf - 4;
196007:         }
196008:       }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
196009:         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196010:           *pnBuf = nBuf - 4;
196011:         }
196012:       }
196013:       break;
196014:   
196015:     case 'e': 
196016:       if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
196017:         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
196018:           *pnBuf = nBuf - 2;
196019:         }
196020:       }
196021:       break;
196022:   
196023:     case 'i': 
196024:       if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
196025:         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
196026:           *pnBuf = nBuf - 2;
196027:         }
196028:       }
196029:       break;
196030:   
196031:     case 'l': 
196032:       if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
196033:         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196034:           *pnBuf = nBuf - 4;
196035:         }
196036:       }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
196037:         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196038:           *pnBuf = nBuf - 4;
196039:         }
196040:       }
196041:       break;
196042:   
196043:     case 'n': 
196044:       if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
196045:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196046:           *pnBuf = nBuf - 3;
196047:         }
196048:       }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
196049:         if( fts5Porter_MGt1(aBuf, nBuf-5) ){
196050:           *pnBuf = nBuf - 5;
196051:         }
196052:       }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
196053:         if( fts5Porter_MGt1(aBuf, nBuf-4) ){
196054:           *pnBuf = nBuf - 4;
196055:         }
196056:       }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
196057:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196058:           *pnBuf = nBuf - 3;
196059:         }
196060:       }
196061:       break;
196062:   
196063:     case 'o': 
196064:       if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
196065:         if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
196066:           *pnBuf = nBuf - 3;
196067:         }
196068:       }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
196069:         if( fts5Porter_MGt1(aBuf, nBuf-2) ){
196070:           *pnBuf = nBuf - 2;
196071:         }
196072:       }
196073:       break;
196074:   
196075:     case 's': 
196076:       if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
196077:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196078:           *pnBuf = nBuf - 3;
196079:         }
196080:       }
196081:       break;
196082:   
196083:     case 't': 
196084:       if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
196085:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196086:           *pnBuf = nBuf - 3;
196087:         }
196088:       }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
196089:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196090:           *pnBuf = nBuf - 3;
196091:         }
196092:       }
196093:       break;
196094:   
196095:     case 'u': 
196096:       if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
196097:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196098:           *pnBuf = nBuf - 3;
196099:         }
196100:       }
196101:       break;
196102:   
196103:     case 'v': 
196104:       if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
196105:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196106:           *pnBuf = nBuf - 3;
196107:         }
196108:       }
196109:       break;
196110:   
196111:     case 'z': 
196112:       if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
196113:         if( fts5Porter_MGt1(aBuf, nBuf-3) ){
196114:           *pnBuf = nBuf - 3;
196115:         }
196116:       }
196117:       break;
196118:   
196119:   }
196120:   return ret;
196121: }
196122:   
196123: 
196124: static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
196125:   int ret = 0;
196126:   int nBuf = *pnBuf;
196127:   switch( aBuf[nBuf-2] ){
196128:     
196129:     case 'a': 
196130:       if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
196131:         memcpy(&aBuf[nBuf-2], "ate", 3);
196132:         *pnBuf = nBuf - 2 + 3;
196133:         ret = 1;
196134:       }
196135:       break;
196136:   
196137:     case 'b': 
196138:       if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
196139:         memcpy(&aBuf[nBuf-2], "ble", 3);
196140:         *pnBuf = nBuf - 2 + 3;
196141:         ret = 1;
196142:       }
196143:       break;
196144:   
196145:     case 'i': 
196146:       if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
196147:         memcpy(&aBuf[nBuf-2], "ize", 3);
196148:         *pnBuf = nBuf - 2 + 3;
196149:         ret = 1;
196150:       }
196151:       break;
196152:   
196153:   }
196154:   return ret;
196155: }
196156:   
196157: 
196158: static int fts5PorterStep2(char *aBuf, int *pnBuf){
196159:   int ret = 0;
196160:   int nBuf = *pnBuf;
196161:   switch( aBuf[nBuf-2] ){
196162:     
196163:     case 'a': 
196164:       if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
196165:         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196166:           memcpy(&aBuf[nBuf-7], "ate", 3);
196167:           *pnBuf = nBuf - 7 + 3;
196168:         }
196169:       }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
196170:         if( fts5Porter_MGt0(aBuf, nBuf-6) ){
196171:           memcpy(&aBuf[nBuf-6], "tion", 4);
196172:           *pnBuf = nBuf - 6 + 4;
196173:         }
196174:       }
196175:       break;
196176:   
196177:     case 'c': 
196178:       if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
196179:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196180:           memcpy(&aBuf[nBuf-4], "ence", 4);
196181:           *pnBuf = nBuf - 4 + 4;
196182:         }
196183:       }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
196184:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196185:           memcpy(&aBuf[nBuf-4], "ance", 4);
196186:           *pnBuf = nBuf - 4 + 4;
196187:         }
196188:       }
196189:       break;
196190:   
196191:     case 'e': 
196192:       if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
196193:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196194:           memcpy(&aBuf[nBuf-4], "ize", 3);
196195:           *pnBuf = nBuf - 4 + 3;
196196:         }
196197:       }
196198:       break;
196199:   
196200:     case 'g': 
196201:       if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
196202:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196203:           memcpy(&aBuf[nBuf-4], "log", 3);
196204:           *pnBuf = nBuf - 4 + 3;
196205:         }
196206:       }
196207:       break;
196208:   
196209:     case 'l': 
196210:       if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
196211:         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196212:           memcpy(&aBuf[nBuf-3], "ble", 3);
196213:           *pnBuf = nBuf - 3 + 3;
196214:         }
196215:       }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
196216:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196217:           memcpy(&aBuf[nBuf-4], "al", 2);
196218:           *pnBuf = nBuf - 4 + 2;
196219:         }
196220:       }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
196221:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196222:           memcpy(&aBuf[nBuf-5], "ent", 3);
196223:           *pnBuf = nBuf - 5 + 3;
196224:         }
196225:       }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
196226:         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196227:           memcpy(&aBuf[nBuf-3], "e", 1);
196228:           *pnBuf = nBuf - 3 + 1;
196229:         }
196230:       }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
196231:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196232:           memcpy(&aBuf[nBuf-5], "ous", 3);
196233:           *pnBuf = nBuf - 5 + 3;
196234:         }
196235:       }
196236:       break;
196237:   
196238:     case 'o': 
196239:       if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
196240:         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196241:           memcpy(&aBuf[nBuf-7], "ize", 3);
196242:           *pnBuf = nBuf - 7 + 3;
196243:         }
196244:       }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
196245:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196246:           memcpy(&aBuf[nBuf-5], "ate", 3);
196247:           *pnBuf = nBuf - 5 + 3;
196248:         }
196249:       }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
196250:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196251:           memcpy(&aBuf[nBuf-4], "ate", 3);
196252:           *pnBuf = nBuf - 4 + 3;
196253:         }
196254:       }
196255:       break;
196256:   
196257:     case 's': 
196258:       if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
196259:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196260:           memcpy(&aBuf[nBuf-5], "al", 2);
196261:           *pnBuf = nBuf - 5 + 2;
196262:         }
196263:       }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
196264:         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196265:           memcpy(&aBuf[nBuf-7], "ive", 3);
196266:           *pnBuf = nBuf - 7 + 3;
196267:         }
196268:       }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
196269:         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196270:           memcpy(&aBuf[nBuf-7], "ful", 3);
196271:           *pnBuf = nBuf - 7 + 3;
196272:         }
196273:       }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
196274:         if( fts5Porter_MGt0(aBuf, nBuf-7) ){
196275:           memcpy(&aBuf[nBuf-7], "ous", 3);
196276:           *pnBuf = nBuf - 7 + 3;
196277:         }
196278:       }
196279:       break;
196280:   
196281:     case 't': 
196282:       if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
196283:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196284:           memcpy(&aBuf[nBuf-5], "al", 2);
196285:           *pnBuf = nBuf - 5 + 2;
196286:         }
196287:       }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
196288:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196289:           memcpy(&aBuf[nBuf-5], "ive", 3);
196290:           *pnBuf = nBuf - 5 + 3;
196291:         }
196292:       }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
196293:         if( fts5Porter_MGt0(aBuf, nBuf-6) ){
196294:           memcpy(&aBuf[nBuf-6], "ble", 3);
196295:           *pnBuf = nBuf - 6 + 3;
196296:         }
196297:       }
196298:       break;
196299:   
196300:   }
196301:   return ret;
196302: }
196303:   
196304: 
196305: static int fts5PorterStep3(char *aBuf, int *pnBuf){
196306:   int ret = 0;
196307:   int nBuf = *pnBuf;
196308:   switch( aBuf[nBuf-2] ){
196309:     
196310:     case 'a': 
196311:       if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
196312:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196313:           memcpy(&aBuf[nBuf-4], "ic", 2);
196314:           *pnBuf = nBuf - 4 + 2;
196315:         }
196316:       }
196317:       break;
196318:   
196319:     case 's': 
196320:       if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
196321:         if( fts5Porter_MGt0(aBuf, nBuf-4) ){
196322:           *pnBuf = nBuf - 4;
196323:         }
196324:       }
196325:       break;
196326:   
196327:     case 't': 
196328:       if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
196329:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196330:           memcpy(&aBuf[nBuf-5], "ic", 2);
196331:           *pnBuf = nBuf - 5 + 2;
196332:         }
196333:       }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
196334:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196335:           memcpy(&aBuf[nBuf-5], "ic", 2);
196336:           *pnBuf = nBuf - 5 + 2;
196337:         }
196338:       }
196339:       break;
196340:   
196341:     case 'u': 
196342:       if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
196343:         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196344:           *pnBuf = nBuf - 3;
196345:         }
196346:       }
196347:       break;
196348:   
196349:     case 'v': 
196350:       if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
196351:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196352:           *pnBuf = nBuf - 5;
196353:         }
196354:       }
196355:       break;
196356:   
196357:     case 'z': 
196358:       if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
196359:         if( fts5Porter_MGt0(aBuf, nBuf-5) ){
196360:           memcpy(&aBuf[nBuf-5], "al", 2);
196361:           *pnBuf = nBuf - 5 + 2;
196362:         }
196363:       }
196364:       break;
196365:   
196366:   }
196367:   return ret;
196368: }
196369:   
196370: 
196371: static int fts5PorterStep1B(char *aBuf, int *pnBuf){
196372:   int ret = 0;
196373:   int nBuf = *pnBuf;
196374:   switch( aBuf[nBuf-2] ){
196375:     
196376:     case 'e': 
196377:       if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
196378:         if( fts5Porter_MGt0(aBuf, nBuf-3) ){
196379:           memcpy(&aBuf[nBuf-3], "ee", 2);
196380:           *pnBuf = nBuf - 3 + 2;
196381:         }
196382:       }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
196383:         if( fts5Porter_Vowel(aBuf, nBuf-2) ){
196384:           *pnBuf = nBuf - 2;
196385:           ret = 1;
196386:         }
196387:       }
196388:       break;
196389:   
196390:     case 'n': 
196391:       if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
196392:         if( fts5Porter_Vowel(aBuf, nBuf-3) ){
196393:           *pnBuf = nBuf - 3;
196394:           ret = 1;
196395:         }
196396:       }
196397:       break;
196398:   
196399:   }
196400:   return ret;
196401: }
196402:   
196403: /* 
196404: ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
196405: ***************************************************************************
196406: **************************************************************************/
196407: 
196408: static void fts5PorterStep1A(char *aBuf, int *pnBuf){
196409:   int nBuf = *pnBuf;
196410:   if( aBuf[nBuf-1]=='s' ){
196411:     if( aBuf[nBuf-2]=='e' ){
196412:       if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s') 
196413:        || (nBuf>3 && aBuf[nBuf-3]=='i' )
196414:       ){
196415:         *pnBuf = nBuf-2;
196416:       }else{
196417:         *pnBuf = nBuf-1;
196418:       }
196419:     }
196420:     else if( aBuf[nBuf-2]!='s' ){
196421:       *pnBuf = nBuf-1;
196422:     }
196423:   }
196424: }
196425: 
196426: static int fts5PorterCb(
196427:   void *pCtx, 
196428:   int tflags,
196429:   const char *pToken, 
196430:   int nToken, 
196431:   int iStart, 
196432:   int iEnd
196433: ){
196434:   PorterContext *p = (PorterContext*)pCtx;
196435: 
196436:   char *aBuf;
196437:   int nBuf;
196438: 
196439:   if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
196440:   aBuf = p->aBuf;
196441:   nBuf = nToken;
196442:   memcpy(aBuf, pToken, nBuf);
196443: 
196444:   /* Step 1. */
196445:   fts5PorterStep1A(aBuf, &nBuf);
196446:   if( fts5PorterStep1B(aBuf, &nBuf) ){
196447:     if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
196448:       char c = aBuf[nBuf-1];
196449:       if( fts5PorterIsVowel(c, 0)==0 
196450:        && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2] 
196451:       ){
196452:         nBuf--;
196453:       }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
196454:         aBuf[nBuf++] = 'e';
196455:       }
196456:     }
196457:   }
196458: 
196459:   /* Step 1C. */
196460:   if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
196461:     aBuf[nBuf-1] = 'i';
196462:   }
196463: 
196464:   /* Steps 2 through 4. */
196465:   fts5PorterStep2(aBuf, &nBuf);
196466:   fts5PorterStep3(aBuf, &nBuf);
196467:   fts5PorterStep4(aBuf, &nBuf);
196468: 
196469:   /* Step 5a. */
196470:   assert( nBuf>0 );
196471:   if( aBuf[nBuf-1]=='e' ){
196472:     if( fts5Porter_MGt1(aBuf, nBuf-1) 
196473:      || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
196474:     ){
196475:       nBuf--;
196476:     }
196477:   }
196478: 
196479:   /* Step 5b. */
196480:   if( nBuf>1 && aBuf[nBuf-1]=='l' 
196481:    && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1) 
196482:   ){
196483:     nBuf--;
196484:   }
196485: 
196486:   return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
196487: 
196488:  pass_through:
196489:   return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
196490: }
196491: 
196492: /*
196493: ** Tokenize using the porter tokenizer.
196494: */
196495: static int fts5PorterTokenize(
196496:   Fts5Tokenizer *pTokenizer,
196497:   void *pCtx,
196498:   int flags,
196499:   const char *pText, int nText,
196500:   int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
196501: ){
196502:   PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
196503:   PorterContext sCtx;
196504:   sCtx.xToken = xToken;
196505:   sCtx.pCtx = pCtx;
196506:   sCtx.aBuf = p->aBuf;
196507:   return p->tokenizer.xTokenize(
196508:       p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
196509:   );
196510: }
196511: 
196512: /*
196513: ** Register all built-in tokenizers with FTS5.
196514: */
196515: static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
196516:   struct BuiltinTokenizer {
196517:     const char *zName;
196518:     fts5_tokenizer x;
196519:   } aBuiltin[] = {
196520:     { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
196521:     { "ascii",     {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
196522:     { "porter",    {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
196523:   };
196524:   
196525:   int rc = SQLITE_OK;             /* Return code */
196526:   int i;                          /* To iterate through builtin functions */
196527: 
196528:   for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
196529:     rc = pApi->xCreateTokenizer(pApi,
196530:         aBuiltin[i].zName,
196531:         (void*)pApi,
196532:         &aBuiltin[i].x,
196533:         0
196534:     );
196535:   }
196536: 
196537:   return rc;
196538: }
196539: 
196540: 
196541: 
196542: /*
196543: ** 2012 May 25
196544: **
196545: ** The author disclaims copyright to this source code.  In place of
196546: ** a legal notice, here is a blessing:
196547: **
196548: **    May you do good and not evil.
196549: **    May you find forgiveness for yourself and forgive others.
196550: **    May you share freely, never taking more than you give.
196551: **
196552: ******************************************************************************
196553: */
196554: 
196555: /*
196556: ** DO NOT EDIT THIS MACHINE GENERATED FILE.
196557: */
196558: 
196559: 
196560: /* #include <assert.h> */
196561: 
196562: /*
196563: ** Return true if the argument corresponds to a unicode codepoint
196564: ** classified as either a letter or a number. Otherwise false.
196565: **
196566: ** The results are undefined if the value passed to this function
196567: ** is less than zero.
196568: */
196569: static int sqlite3Fts5UnicodeIsalnum(int c){
196570:   /* Each unsigned integer in the following array corresponds to a contiguous
196571:   ** range of unicode codepoints that are not either letters or numbers (i.e.
196572:   ** codepoints for which this function should return 0).
196573:   **
196574:   ** The most significant 22 bits in each 32-bit value contain the first 
196575:   ** codepoint in the range. The least significant 10 bits are used to store
196576:   ** the size of the range (always at least 1). In other words, the value 
196577:   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
196578:   ** C. It is not possible to represent a range larger than 1023 codepoints 
196579:   ** using this format.
196580:   */
196581:   static const unsigned int aEntry[] = {
196582:     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
196583:     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
196584:     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
196585:     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
196586:     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
196587:     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
196588:     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
196589:     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
196590:     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
196591:     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
196592:     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
196593:     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
196594:     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
196595:     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
196596:     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
196597:     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
196598:     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
196599:     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
196600:     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
196601:     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
196602:     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
196603:     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
196604:     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
196605:     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
196606:     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
196607:     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
196608:     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
196609:     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
196610:     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
196611:     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
196612:     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
196613:     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
196614:     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
196615:     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
196616:     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
196617:     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
196618:     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
196619:     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
196620:     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
196621:     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
196622:     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
196623:     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
196624:     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
196625:     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
196626:     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
196627:     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
196628:     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
196629:     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
196630:     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
196631:     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
196632:     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
196633:     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
196634:     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
196635:     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
196636:     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
196637:     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
196638:     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
196639:     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
196640:     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
196641:     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
196642:     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
196643:     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
196644:     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
196645:     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
196646:     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
196647:     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
196648:     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
196649:     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
196650:     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
196651:     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
196652:     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
196653:     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
196654:     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
196655:     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
196656:     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
196657:     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
196658:     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
196659:     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
196660:     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
196661:     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
196662:     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
196663:     0x380400F0,
196664:   };
196665:   static const unsigned int aAscii[4] = {
196666:     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
196667:   };
196668: 
196669:   if( (unsigned int)c<128 ){
196670:     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
196671:   }else if( (unsigned int)c<(1<<22) ){
196672:     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
196673:     int iRes = 0;
196674:     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
196675:     int iLo = 0;
196676:     while( iHi>=iLo ){
196677:       int iTest = (iHi + iLo) / 2;
196678:       if( key >= aEntry[iTest] ){
196679:         iRes = iTest;
196680:         iLo = iTest+1;
196681:       }else{
196682:         iHi = iTest-1;
196683:       }
196684:     }
196685:     assert( aEntry[0]<key );
196686:     assert( key>=aEntry[iRes] );
196687:     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
196688:   }
196689:   return 1;
196690: }
196691: 
196692: 
196693: /*
196694: ** If the argument is a codepoint corresponding to a lowercase letter
196695: ** in the ASCII range with a diacritic added, return the codepoint
196696: ** of the ASCII letter only. For example, if passed 235 - "LATIN
196697: ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
196698: ** E"). The resuls of passing a codepoint that corresponds to an
196699: ** uppercase letter are undefined.
196700: */
196701: static int fts5_remove_diacritic(int c){
196702:   unsigned short aDia[] = {
196703:         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
196704:      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
196705:      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
196706:      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
196707:      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
196708:      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
196709:      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
196710:      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
196711:     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
196712:     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
196713:     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
196714:     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
196715:     62924, 63050, 63082, 63274, 63390, 
196716:   };
196717:   char aChar[] = {
196718:     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
196719:     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
196720:     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
196721:     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
196722:     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
196723:     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
196724:     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
196725:     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
196726:     'e',  'i',  'o',  'u',  'y',  
196727:   };
196728: 
196729:   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
196730:   int iRes = 0;
196731:   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
196732:   int iLo = 0;
196733:   while( iHi>=iLo ){
196734:     int iTest = (iHi + iLo) / 2;
196735:     if( key >= aDia[iTest] ){
196736:       iRes = iTest;
196737:       iLo = iTest+1;
196738:     }else{
196739:       iHi = iTest-1;
196740:     }
196741:   }
196742:   assert( key>=aDia[iRes] );
196743:   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
196744: }
196745: 
196746: 
196747: /*
196748: ** Return true if the argument interpreted as a unicode codepoint
196749: ** is a diacritical modifier character.
196750: */
196751: static int sqlite3Fts5UnicodeIsdiacritic(int c){
196752:   unsigned int mask0 = 0x08029FDF;
196753:   unsigned int mask1 = 0x000361F8;
196754:   if( c<768 || c>817 ) return 0;
196755:   return (c < 768+32) ?
196756:       (mask0 & (1 << (c-768))) :
196757:       (mask1 & (1 << (c-768-32)));
196758: }
196759: 
196760: 
196761: /*
196762: ** Interpret the argument as a unicode codepoint. If the codepoint
196763: ** is an upper case character that has a lower case equivalent,
196764: ** return the codepoint corresponding to the lower case version.
196765: ** Otherwise, return a copy of the argument.
196766: **
196767: ** The results are undefined if the value passed to this function
196768: ** is less than zero.
196769: */
196770: static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
196771:   /* Each entry in the following array defines a rule for folding a range
196772:   ** of codepoints to lower case. The rule applies to a range of nRange
196773:   ** codepoints starting at codepoint iCode.
196774:   **
196775:   ** If the least significant bit in flags is clear, then the rule applies
196776:   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
196777:   ** need to be folded). Or, if it is set, then the rule only applies to
196778:   ** every second codepoint in the range, starting with codepoint C.
196779:   **
196780:   ** The 7 most significant bits in flags are an index into the aiOff[]
196781:   ** array. If a specific codepoint C does require folding, then its lower
196782:   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
196783:   **
196784:   ** The contents of this array are generated by parsing the CaseFolding.txt
196785:   ** file distributed as part of the "Unicode Character Database". See
196786:   ** http://www.unicode.org for details.
196787:   */
196788:   static const struct TableEntry {
196789:     unsigned short iCode;
196790:     unsigned char flags;
196791:     unsigned char nRange;
196792:   } aEntry[] = {
196793:     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
196794:     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
196795:     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
196796:     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
196797:     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
196798:     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
196799:     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
196800:     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
196801:     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
196802:     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
196803:     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
196804:     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
196805:     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
196806:     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
196807:     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
196808:     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
196809:     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
196810:     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
196811:     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
196812:     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
196813:     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
196814:     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
196815:     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
196816:     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
196817:     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
196818:     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
196819:     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
196820:     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
196821:     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
196822:     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
196823:     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
196824:     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
196825:     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
196826:     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
196827:     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
196828:     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
196829:     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
196830:     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
196831:     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
196832:     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
196833:     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
196834:     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
196835:     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
196836:     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
196837:     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
196838:     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
196839:     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
196840:     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
196841:     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
196842:     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
196843:     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
196844:     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
196845:     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
196846:     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
196847:     {65313, 14, 26},       
196848:   };
196849:   static const unsigned short aiOff[] = {
196850:    1,     2,     8,     15,    16,    26,    28,    32,    
196851:    37,    38,    40,    48,    63,    64,    69,    71,    
196852:    79,    80,    116,   202,   203,   205,   206,   207,   
196853:    209,   210,   211,   213,   214,   217,   218,   219,   
196854:    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
196855:    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
196856:    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
196857:    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
196858:    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
196859:    65514, 65521, 65527, 65528, 65529, 
196860:   };
196861: 
196862:   int ret = c;
196863: 
196864:   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
196865: 
196866:   if( c<128 ){
196867:     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
196868:   }else if( c<65536 ){
196869:     const struct TableEntry *p;
196870:     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
196871:     int iLo = 0;
196872:     int iRes = -1;
196873: 
196874:     assert( c>aEntry[0].iCode );
196875:     while( iHi>=iLo ){
196876:       int iTest = (iHi + iLo) / 2;
196877:       int cmp = (c - aEntry[iTest].iCode);
196878:       if( cmp>=0 ){
196879:         iRes = iTest;
196880:         iLo = iTest+1;
196881:       }else{
196882:         iHi = iTest-1;
196883:       }
196884:     }
196885: 
196886:     assert( iRes>=0 && c>=aEntry[iRes].iCode );
196887:     p = &aEntry[iRes];
196888:     if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
196889:       ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
196890:       assert( ret>0 );
196891:     }
196892: 
196893:     if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
196894:   }
196895:   
196896:   else if( c>=66560 && c<66600 ){
196897:     ret = c + 40;
196898:   }
196899: 
196900:   return ret;
196901: }
196902: 
196903: /*
196904: ** 2015 May 30
196905: **
196906: ** The author disclaims copyright to this source code.  In place of
196907: ** a legal notice, here is a blessing:
196908: **
196909: **    May you do good and not evil.
196910: **    May you find forgiveness for yourself and forgive others.
196911: **    May you share freely, never taking more than you give.
196912: **
196913: ******************************************************************************
196914: **
196915: ** Routines for varint serialization and deserialization.
196916: */
196917: 
196918: 
196919: /* #include "fts5Int.h" */
196920: 
196921: /*
196922: ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
196923: ** Except, this version does handle the single byte case that the core
196924: ** version depends on being handled before its function is called.
196925: */
196926: static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
196927:   u32 a,b;
196928: 
196929:   /* The 1-byte case. Overwhelmingly the most common. */
196930:   a = *p;
196931:   /* a: p0 (unmasked) */
196932:   if (!(a&0x80))
196933:   {
196934:     /* Values between 0 and 127 */
196935:     *v = a;
196936:     return 1;
196937:   }
196938: 
196939:   /* The 2-byte case */
196940:   p++;
196941:   b = *p;
196942:   /* b: p1 (unmasked) */
196943:   if (!(b&0x80))
196944:   {
196945:     /* Values between 128 and 16383 */
196946:     a &= 0x7f;
196947:     a = a<<7;
196948:     *v = a | b;
196949:     return 2;
196950:   }
196951: 
196952:   /* The 3-byte case */
196953:   p++;
196954:   a = a<<14;
196955:   a |= *p;
196956:   /* a: p0<<14 | p2 (unmasked) */
196957:   if (!(a&0x80))
196958:   {
196959:     /* Values between 16384 and 2097151 */
196960:     a &= (0x7f<<14)|(0x7f);
196961:     b &= 0x7f;
196962:     b = b<<7;
196963:     *v = a | b;
196964:     return 3;
196965:   }
196966: 
196967:   /* A 32-bit varint is used to store size information in btrees.
196968:   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
196969:   ** A 3-byte varint is sufficient, for example, to record the size
196970:   ** of a 1048569-byte BLOB or string.
196971:   **
196972:   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
196973:   ** rare larger cases can be handled by the slower 64-bit varint
196974:   ** routine.
196975:   */
196976:   {
196977:     u64 v64;
196978:     u8 n;
196979:     p -= 2;
196980:     n = sqlite3Fts5GetVarint(p, &v64);
196981:     *v = (u32)v64;
196982:     assert( n>3 && n<=9 );
196983:     return n;
196984:   }
196985: }
196986: 
196987: 
196988: /*
196989: ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
196990: ** are defined here rather than simply putting the constant expressions
196991: ** inline in order to work around bugs in the RVT compiler.
196992: **
196993: ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
196994: **
196995: ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
196996: */
196997: #define SLOT_2_0     0x001fc07f
196998: #define SLOT_4_2_0   0xf01fc07f
196999: 
197000: /*
197001: ** Read a 64-bit variable-length integer from memory starting at p[0].
197002: ** Return the number of bytes read.  The value is stored in *v.
197003: */
197004: static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
197005:   u32 a,b,s;
197006: 
197007:   a = *p;
197008:   /* a: p0 (unmasked) */
197009:   if (!(a&0x80))
197010:   {
197011:     *v = a;
197012:     return 1;
197013:   }
197014: 
197015:   p++;
197016:   b = *p;
197017:   /* b: p1 (unmasked) */
197018:   if (!(b&0x80))
197019:   {
197020:     a &= 0x7f;
197021:     a = a<<7;
197022:     a |= b;
197023:     *v = a;
197024:     return 2;
197025:   }
197026: 
197027:   /* Verify that constants are precomputed correctly */
197028:   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
197029:   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
197030: 
197031:   p++;
197032:   a = a<<14;
197033:   a |= *p;
197034:   /* a: p0<<14 | p2 (unmasked) */
197035:   if (!(a&0x80))
197036:   {
197037:     a &= SLOT_2_0;
197038:     b &= 0x7f;
197039:     b = b<<7;
197040:     a |= b;
197041:     *v = a;
197042:     return 3;
197043:   }
197044: 
197045:   /* CSE1 from below */
197046:   a &= SLOT_2_0;
197047:   p++;
197048:   b = b<<14;
197049:   b |= *p;
197050:   /* b: p1<<14 | p3 (unmasked) */
197051:   if (!(b&0x80))
197052:   {
197053:     b &= SLOT_2_0;
197054:     /* moved CSE1 up */
197055:     /* a &= (0x7f<<14)|(0x7f); */
197056:     a = a<<7;
197057:     a |= b;
197058:     *v = a;
197059:     return 4;
197060:   }
197061: 
197062:   /* a: p0<<14 | p2 (masked) */
197063:   /* b: p1<<14 | p3 (unmasked) */
197064:   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197065:   /* moved CSE1 up */
197066:   /* a &= (0x7f<<14)|(0x7f); */
197067:   b &= SLOT_2_0;
197068:   s = a;
197069:   /* s: p0<<14 | p2 (masked) */
197070: 
197071:   p++;
197072:   a = a<<14;
197073:   a |= *p;
197074:   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
197075:   if (!(a&0x80))
197076:   {
197077:     /* we can skip these cause they were (effectively) done above in calc'ing s */
197078:     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
197079:     /* b &= (0x7f<<14)|(0x7f); */
197080:     b = b<<7;
197081:     a |= b;
197082:     s = s>>18;
197083:     *v = ((u64)s)<<32 | a;
197084:     return 5;
197085:   }
197086: 
197087:   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197088:   s = s<<7;
197089:   s |= b;
197090:   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
197091: 
197092:   p++;
197093:   b = b<<14;
197094:   b |= *p;
197095:   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
197096:   if (!(b&0x80))
197097:   {
197098:     /* we can skip this cause it was (effectively) done above in calc'ing s */
197099:     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
197100:     a &= SLOT_2_0;
197101:     a = a<<7;
197102:     a |= b;
197103:     s = s>>18;
197104:     *v = ((u64)s)<<32 | a;
197105:     return 6;
197106:   }
197107: 
197108:   p++;
197109:   a = a<<14;
197110:   a |= *p;
197111:   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
197112:   if (!(a&0x80))
197113:   {
197114:     a &= SLOT_4_2_0;
197115:     b &= SLOT_2_0;
197116:     b = b<<7;
197117:     a |= b;
197118:     s = s>>11;
197119:     *v = ((u64)s)<<32 | a;
197120:     return 7;
197121:   }
197122: 
197123:   /* CSE2 from below */
197124:   a &= SLOT_2_0;
197125:   p++;
197126:   b = b<<14;
197127:   b |= *p;
197128:   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
197129:   if (!(b&0x80))
197130:   {
197131:     b &= SLOT_4_2_0;
197132:     /* moved CSE2 up */
197133:     /* a &= (0x7f<<14)|(0x7f); */
197134:     a = a<<7;
197135:     a |= b;
197136:     s = s>>4;
197137:     *v = ((u64)s)<<32 | a;
197138:     return 8;
197139:   }
197140: 
197141:   p++;
197142:   a = a<<15;
197143:   a |= *p;
197144:   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
197145: 
197146:   /* moved CSE2 up */
197147:   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
197148:   b &= SLOT_2_0;
197149:   b = b<<8;
197150:   a |= b;
197151: 
197152:   s = s<<4;
197153:   b = p[-4];
197154:   b &= 0x7f;
197155:   b = b>>3;
197156:   s |= b;
197157: 
197158:   *v = ((u64)s)<<32 | a;
197159: 
197160:   return 9;
197161: }
197162: 
197163: /*
197164: ** The variable-length integer encoding is as follows:
197165: **
197166: ** KEY:
197167: **         A = 0xxxxxxx    7 bits of data and one flag bit
197168: **         B = 1xxxxxxx    7 bits of data and one flag bit
197169: **         C = xxxxxxxx    8 bits of data
197170: **
197171: **  7 bits - A
197172: ** 14 bits - BA
197173: ** 21 bits - BBA
197174: ** 28 bits - BBBA
197175: ** 35 bits - BBBBA
197176: ** 42 bits - BBBBBA
197177: ** 49 bits - BBBBBBA
197178: ** 56 bits - BBBBBBBA
197179: ** 64 bits - BBBBBBBBC
197180: */
197181: 
197182: #ifdef SQLITE_NOINLINE
197183: # define FTS5_NOINLINE SQLITE_NOINLINE
197184: #else
197185: # define FTS5_NOINLINE
197186: #endif
197187: 
197188: /*
197189: ** Write a 64-bit variable-length integer to memory starting at p[0].
197190: ** The length of data write will be between 1 and 9 bytes.  The number
197191: ** of bytes written is returned.
197192: **
197193: ** A variable-length integer consists of the lower 7 bits of each byte
197194: ** for all bytes that have the 8th bit set and one byte with the 8th
197195: ** bit clear.  Except, if we get to the 9th byte, it stores the full
197196: ** 8 bits and is the last byte.
197197: */
197198: static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
197199:   int i, j, n;
197200:   u8 buf[10];
197201:   if( v & (((u64)0xff000000)<<32) ){
197202:     p[8] = (u8)v;
197203:     v >>= 8;
197204:     for(i=7; i>=0; i--){
197205:       p[i] = (u8)((v & 0x7f) | 0x80);
197206:       v >>= 7;
197207:     }
197208:     return 9;
197209:   }    
197210:   n = 0;
197211:   do{
197212:     buf[n++] = (u8)((v & 0x7f) | 0x80);
197213:     v >>= 7;
197214:   }while( v!=0 );
197215:   buf[0] &= 0x7f;
197216:   assert( n<=9 );
197217:   for(i=0, j=n-1; j>=0; j--, i++){
197218:     p[i] = buf[j];
197219:   }
197220:   return n;
197221: }
197222: 
197223: static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
197224:   if( v<=0x7f ){
197225:     p[0] = v&0x7f;
197226:     return 1;
197227:   }
197228:   if( v<=0x3fff ){
197229:     p[0] = ((v>>7)&0x7f)|0x80;
197230:     p[1] = v&0x7f;
197231:     return 2;
197232:   }
197233:   return fts5PutVarint64(p,v);
197234: }
197235: 
197236: 
197237: static int sqlite3Fts5GetVarintLen(u32 iVal){
197238: #if 0
197239:   if( iVal<(1 << 7 ) ) return 1;
197240: #endif
197241:   assert( iVal>=(1 << 7) );
197242:   if( iVal<(1 << 14) ) return 2;
197243:   if( iVal<(1 << 21) ) return 3;
197244:   if( iVal<(1 << 28) ) return 4;
197245:   return 5;
197246: }
197247: 
197248: 
197249: /*
197250: ** 2015 May 08
197251: **
197252: ** The author disclaims copyright to this source code.  In place of
197253: ** a legal notice, here is a blessing:
197254: **
197255: **    May you do good and not evil.
197256: **    May you find forgiveness for yourself and forgive others.
197257: **    May you share freely, never taking more than you give.
197258: **
197259: ******************************************************************************
197260: **
197261: ** This is an SQLite virtual table module implementing direct access to an
197262: ** existing FTS5 index. The module may create several different types of 
197263: ** tables:
197264: **
197265: ** col:
197266: **     CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
197267: **
197268: **   One row for each term/column combination. The value of $doc is set to
197269: **   the number of fts5 rows that contain at least one instance of term
197270: **   $term within column $col. Field $cnt is set to the total number of 
197271: **   instances of term $term in column $col (in any row of the fts5 table). 
197272: **
197273: ** row:
197274: **     CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
197275: **
197276: **   One row for each term in the database. The value of $doc is set to
197277: **   the number of fts5 rows that contain at least one instance of term
197278: **   $term. Field $cnt is set to the total number of instances of term 
197279: **   $term in the database.
197280: */
197281: 
197282: 
197283: /* #include "fts5Int.h" */
197284: 
197285: 
197286: typedef struct Fts5VocabTable Fts5VocabTable;
197287: typedef struct Fts5VocabCursor Fts5VocabCursor;
197288: 
197289: struct Fts5VocabTable {
197290:   sqlite3_vtab base;
197291:   char *zFts5Tbl;                 /* Name of fts5 table */
197292:   char *zFts5Db;                  /* Db containing fts5 table */
197293:   sqlite3 *db;                    /* Database handle */
197294:   Fts5Global *pGlobal;            /* FTS5 global object for this database */
197295:   int eType;                      /* FTS5_VOCAB_COL or ROW */
197296: };
197297: 
197298: struct Fts5VocabCursor {
197299:   sqlite3_vtab_cursor base;
197300:   sqlite3_stmt *pStmt;            /* Statement holding lock on pIndex */
197301:   Fts5Index *pIndex;              /* Associated FTS5 index */
197302: 
197303:   int bEof;                       /* True if this cursor is at EOF */
197304:   Fts5IndexIter *pIter;           /* Term/rowid iterator object */
197305: 
197306:   int nLeTerm;                    /* Size of zLeTerm in bytes */
197307:   char *zLeTerm;                  /* (term <= $zLeTerm) paramater, or NULL */
197308: 
197309:   /* These are used by 'col' tables only */
197310:   Fts5Config *pConfig;            /* Fts5 table configuration */
197311:   int iCol;
197312:   i64 *aCnt;
197313:   i64 *aDoc;
197314: 
197315:   /* Output values used by 'row' and 'col' tables */
197316:   i64 rowid;                      /* This table's current rowid value */
197317:   Fts5Buffer term;                /* Current value of 'term' column */
197318: };
197319: 
197320: #define FTS5_VOCAB_COL    0
197321: #define FTS5_VOCAB_ROW    1
197322: 
197323: #define FTS5_VOCAB_COL_SCHEMA  "term, col, doc, cnt"
197324: #define FTS5_VOCAB_ROW_SCHEMA  "term, doc, cnt"
197325: 
197326: /*
197327: ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
197328: */
197329: #define FTS5_VOCAB_TERM_EQ 0x01
197330: #define FTS5_VOCAB_TERM_GE 0x02
197331: #define FTS5_VOCAB_TERM_LE 0x04
197332: 
197333: 
197334: /*
197335: ** Translate a string containing an fts5vocab table type to an 
197336: ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
197337: ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
197338: ** and return SQLITE_ERROR.
197339: */
197340: static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
197341:   int rc = SQLITE_OK;
197342:   char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
197343:   if( rc==SQLITE_OK ){
197344:     sqlite3Fts5Dequote(zCopy);
197345:     if( sqlite3_stricmp(zCopy, "col")==0 ){
197346:       *peType = FTS5_VOCAB_COL;
197347:     }else
197348: 
197349:     if( sqlite3_stricmp(zCopy, "row")==0 ){
197350:       *peType = FTS5_VOCAB_ROW;
197351:     }else
197352:     {
197353:       *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
197354:       rc = SQLITE_ERROR;
197355:     }
197356:     sqlite3_free(zCopy);
197357:   }
197358: 
197359:   return rc;
197360: }
197361: 
197362: 
197363: /*
197364: ** The xDisconnect() virtual table method.
197365: */
197366: static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
197367:   Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
197368:   sqlite3_free(pTab);
197369:   return SQLITE_OK;
197370: }
197371: 
197372: /*
197373: ** The xDestroy() virtual table method.
197374: */
197375: static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
197376:   Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
197377:   sqlite3_free(pTab);
197378:   return SQLITE_OK;
197379: }
197380: 
197381: /*
197382: ** This function is the implementation of both the xConnect and xCreate
197383: ** methods of the FTS3 virtual table.
197384: **
197385: ** The argv[] array contains the following:
197386: **
197387: **   argv[0]   -> module name  ("fts5vocab")
197388: **   argv[1]   -> database name
197389: **   argv[2]   -> table name
197390: **
197391: ** then:
197392: **
197393: **   argv[3]   -> name of fts5 table
197394: **   argv[4]   -> type of fts5vocab table
197395: **
197396: ** or, for tables in the TEMP schema only.
197397: **
197398: **   argv[3]   -> name of fts5 tables database
197399: **   argv[4]   -> name of fts5 table
197400: **   argv[5]   -> type of fts5vocab table
197401: */
197402: static int fts5VocabInitVtab(
197403:   sqlite3 *db,                    /* The SQLite database connection */
197404:   void *pAux,                     /* Pointer to Fts5Global object */
197405:   int argc,                       /* Number of elements in argv array */
197406:   const char * const *argv,       /* xCreate/xConnect argument array */
197407:   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
197408:   char **pzErr                    /* Write any error message here */
197409: ){
197410:   const char *azSchema[] = { 
197411:     "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA  ")", 
197412:     "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA  ")"
197413:   };
197414: 
197415:   Fts5VocabTable *pRet = 0;
197416:   int rc = SQLITE_OK;             /* Return code */
197417:   int bDb;
197418: 
197419:   bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
197420: 
197421:   if( argc!=5 && bDb==0 ){
197422:     *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
197423:     rc = SQLITE_ERROR;
197424:   }else{
197425:     int nByte;                      /* Bytes of space to allocate */
197426:     const char *zDb = bDb ? argv[3] : argv[1];
197427:     const char *zTab = bDb ? argv[4] : argv[3];
197428:     const char *zType = bDb ? argv[5] : argv[4];
197429:     int nDb = (int)strlen(zDb)+1; 
197430:     int nTab = (int)strlen(zTab)+1;
197431:     int eType = 0;
197432:     
197433:     rc = fts5VocabTableType(zType, pzErr, &eType);
197434:     if( rc==SQLITE_OK ){
197435:       assert( eType>=0 && eType<ArraySize(azSchema) );
197436:       rc = sqlite3_declare_vtab(db, azSchema[eType]);
197437:     }
197438: 
197439:     nByte = sizeof(Fts5VocabTable) + nDb + nTab;
197440:     pRet = sqlite3Fts5MallocZero(&rc, nByte);
197441:     if( pRet ){
197442:       pRet->pGlobal = (Fts5Global*)pAux;
197443:       pRet->eType = eType;
197444:       pRet->db = db;
197445:       pRet->zFts5Tbl = (char*)&pRet[1];
197446:       pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
197447:       memcpy(pRet->zFts5Tbl, zTab, nTab);
197448:       memcpy(pRet->zFts5Db, zDb, nDb);
197449:       sqlite3Fts5Dequote(pRet->zFts5Tbl);
197450:       sqlite3Fts5Dequote(pRet->zFts5Db);
197451:     }
197452:   }
197453: 
197454:   *ppVTab = (sqlite3_vtab*)pRet;
197455:   return rc;
197456: }
197457: 
197458: 
197459: /*
197460: ** The xConnect() and xCreate() methods for the virtual table. All the
197461: ** work is done in function fts5VocabInitVtab().
197462: */
197463: static int fts5VocabConnectMethod(
197464:   sqlite3 *db,                    /* Database connection */
197465:   void *pAux,                     /* Pointer to tokenizer hash table */
197466:   int argc,                       /* Number of elements in argv array */
197467:   const char * const *argv,       /* xCreate/xConnect argument array */
197468:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
197469:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
197470: ){
197471:   return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
197472: }
197473: static int fts5VocabCreateMethod(
197474:   sqlite3 *db,                    /* Database connection */
197475:   void *pAux,                     /* Pointer to tokenizer hash table */
197476:   int argc,                       /* Number of elements in argv array */
197477:   const char * const *argv,       /* xCreate/xConnect argument array */
197478:   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
197479:   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
197480: ){
197481:   return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
197482: }
197483: 
197484: /* 
197485: ** Implementation of the xBestIndex method.
197486: */
197487: static int fts5VocabBestIndexMethod(
197488:   sqlite3_vtab *pUnused,
197489:   sqlite3_index_info *pInfo
197490: ){
197491:   int i;
197492:   int iTermEq = -1;
197493:   int iTermGe = -1;
197494:   int iTermLe = -1;
197495:   int idxNum = 0;
197496:   int nArg = 0;
197497: 
197498:   UNUSED_PARAM(pUnused);
197499: 
197500:   for(i=0; i<pInfo->nConstraint; i++){
197501:     struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
197502:     if( p->usable==0 ) continue;
197503:     if( p->iColumn==0 ){          /* term column */
197504:       if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
197505:       if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
197506:       if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
197507:       if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
197508:       if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
197509:     }
197510:   }
197511: 
197512:   if( iTermEq>=0 ){
197513:     idxNum |= FTS5_VOCAB_TERM_EQ;
197514:     pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
197515:     pInfo->estimatedCost = 100;
197516:   }else{
197517:     pInfo->estimatedCost = 1000000;
197518:     if( iTermGe>=0 ){
197519:       idxNum |= FTS5_VOCAB_TERM_GE;
197520:       pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
197521:       pInfo->estimatedCost = pInfo->estimatedCost / 2;
197522:     }
197523:     if( iTermLe>=0 ){
197524:       idxNum |= FTS5_VOCAB_TERM_LE;
197525:       pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
197526:       pInfo->estimatedCost = pInfo->estimatedCost / 2;
197527:     }
197528:   }
197529: 
197530:   pInfo->idxNum = idxNum;
197531: 
197532:   return SQLITE_OK;
197533: }
197534: 
197535: /*
197536: ** Implementation of xOpen method.
197537: */
197538: static int fts5VocabOpenMethod(
197539:   sqlite3_vtab *pVTab, 
197540:   sqlite3_vtab_cursor **ppCsr
197541: ){
197542:   Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
197543:   Fts5Index *pIndex = 0;
197544:   Fts5Config *pConfig = 0;
197545:   Fts5VocabCursor *pCsr = 0;
197546:   int rc = SQLITE_OK;
197547:   sqlite3_stmt *pStmt = 0;
197548:   char *zSql = 0;
197549: 
197550:   zSql = sqlite3Fts5Mprintf(&rc,
197551:       "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
197552:       pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
197553:   );
197554:   if( zSql ){
197555:     rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
197556:   }
197557:   sqlite3_free(zSql);
197558:   assert( rc==SQLITE_OK || pStmt==0 );
197559:   if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
197560: 
197561:   if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
197562:     i64 iId = sqlite3_column_int64(pStmt, 0);
197563:     pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
197564:   }
197565: 
197566:   if( rc==SQLITE_OK && pIndex==0 ){
197567:     rc = sqlite3_finalize(pStmt);
197568:     pStmt = 0;
197569:     if( rc==SQLITE_OK ){
197570:       pVTab->zErrMsg = sqlite3_mprintf(
197571:           "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
197572:       );
197573:       rc = SQLITE_ERROR;
197574:     }
197575:   }
197576: 
197577:   if( rc==SQLITE_OK ){
197578:     int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
197579:     pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
197580:   }
197581: 
197582:   if( pCsr ){
197583:     pCsr->pIndex = pIndex;
197584:     pCsr->pStmt = pStmt;
197585:     pCsr->pConfig = pConfig;
197586:     pCsr->aCnt = (i64*)&pCsr[1];
197587:     pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
197588:   }else{
197589:     sqlite3_finalize(pStmt);
197590:   }
197591: 
197592:   *ppCsr = (sqlite3_vtab_cursor*)pCsr;
197593:   return rc;
197594: }
197595: 
197596: static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
197597:   pCsr->rowid = 0;
197598:   sqlite3Fts5IterClose(pCsr->pIter);
197599:   pCsr->pIter = 0;
197600:   sqlite3_free(pCsr->zLeTerm);
197601:   pCsr->nLeTerm = -1;
197602:   pCsr->zLeTerm = 0;
197603: }
197604: 
197605: /*
197606: ** Close the cursor.  For additional information see the documentation
197607: ** on the xClose method of the virtual table interface.
197608: */
197609: static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
197610:   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197611:   fts5VocabResetCursor(pCsr);
197612:   sqlite3Fts5BufferFree(&pCsr->term);
197613:   sqlite3_finalize(pCsr->pStmt);
197614:   sqlite3_free(pCsr);
197615:   return SQLITE_OK;
197616: }
197617: 
197618: 
197619: /*
197620: ** Advance the cursor to the next row in the table.
197621: */
197622: static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
197623:   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197624:   Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
197625:   int rc = SQLITE_OK;
197626:   int nCol = pCsr->pConfig->nCol;
197627: 
197628:   pCsr->rowid++;
197629: 
197630:   if( pTab->eType==FTS5_VOCAB_COL ){
197631:     for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
197632:       if( pCsr->aDoc[pCsr->iCol] ) break;
197633:     }
197634:   }
197635: 
197636:   if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
197637:     if( sqlite3Fts5IterEof(pCsr->pIter) ){
197638:       pCsr->bEof = 1;
197639:     }else{
197640:       const char *zTerm;
197641:       int nTerm;
197642: 
197643:       zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
197644:       if( pCsr->nLeTerm>=0 ){
197645:         int nCmp = MIN(nTerm, pCsr->nLeTerm);
197646:         int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
197647:         if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
197648:           pCsr->bEof = 1;
197649:           return SQLITE_OK;
197650:         }
197651:       }
197652: 
197653:       sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
197654:       memset(pCsr->aCnt, 0, nCol * sizeof(i64));
197655:       memset(pCsr->aDoc, 0, nCol * sizeof(i64));
197656:       pCsr->iCol = 0;
197657: 
197658:       assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
197659:       while( rc==SQLITE_OK ){
197660:         const u8 *pPos; int nPos;   /* Position list */
197661:         i64 iPos = 0;               /* 64-bit position read from poslist */
197662:         int iOff = 0;               /* Current offset within position list */
197663: 
197664:         pPos = pCsr->pIter->pData;
197665:         nPos = pCsr->pIter->nData;
197666:         switch( pCsr->pConfig->eDetail ){
197667:           case FTS5_DETAIL_FULL:
197668:             pPos = pCsr->pIter->pData;
197669:             nPos = pCsr->pIter->nData;
197670:             if( pTab->eType==FTS5_VOCAB_ROW ){
197671:               while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
197672:                 pCsr->aCnt[0]++;
197673:               }
197674:               pCsr->aDoc[0]++;
197675:             }else{
197676:               int iCol = -1;
197677:               while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
197678:                 int ii = FTS5_POS2COLUMN(iPos);
197679:                 pCsr->aCnt[ii]++;
197680:                 if( iCol!=ii ){
197681:                   if( ii>=nCol ){
197682:                     rc = FTS5_CORRUPT;
197683:                     break;
197684:                   }
197685:                   pCsr->aDoc[ii]++;
197686:                   iCol = ii;
197687:                 }
197688:               }
197689:             }
197690:             break;
197691: 
197692:           case FTS5_DETAIL_COLUMNS:
197693:             if( pTab->eType==FTS5_VOCAB_ROW ){
197694:               pCsr->aDoc[0]++;
197695:             }else{
197696:               while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
197697:                 assert_nc( iPos>=0 && iPos<nCol );
197698:                 if( iPos>=nCol ){
197699:                   rc = FTS5_CORRUPT;
197700:                   break;
197701:                 }
197702:                 pCsr->aDoc[iPos]++;
197703:               }
197704:             }
197705:             break;
197706: 
197707:           default: 
197708:             assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
197709:             pCsr->aDoc[0]++;
197710:             break;
197711:         }
197712: 
197713:         if( rc==SQLITE_OK ){
197714:           rc = sqlite3Fts5IterNextScan(pCsr->pIter);
197715:         }
197716: 
197717:         if( rc==SQLITE_OK ){
197718:           zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
197719:           if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
197720:             break;
197721:           }
197722:           if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
197723:         }
197724:       }
197725:     }
197726:   }
197727: 
197728:   if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
197729:     while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
197730:     assert( pCsr->iCol<pCsr->pConfig->nCol );
197731:   }
197732:   return rc;
197733: }
197734: 
197735: /*
197736: ** This is the xFilter implementation for the virtual table.
197737: */
197738: static int fts5VocabFilterMethod(
197739:   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
197740:   int idxNum,                     /* Strategy index */
197741:   const char *zUnused,            /* Unused */
197742:   int nUnused,                    /* Number of elements in apVal */
197743:   sqlite3_value **apVal           /* Arguments for the indexing scheme */
197744: ){
197745:   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197746:   int rc = SQLITE_OK;
197747: 
197748:   int iVal = 0;
197749:   int f = FTS5INDEX_QUERY_SCAN;
197750:   const char *zTerm = 0;
197751:   int nTerm = 0;
197752: 
197753:   sqlite3_value *pEq = 0;
197754:   sqlite3_value *pGe = 0;
197755:   sqlite3_value *pLe = 0;
197756: 
197757:   UNUSED_PARAM2(zUnused, nUnused);
197758: 
197759:   fts5VocabResetCursor(pCsr);
197760:   if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
197761:   if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
197762:   if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
197763: 
197764:   if( pEq ){
197765:     zTerm = (const char *)sqlite3_value_text(pEq);
197766:     nTerm = sqlite3_value_bytes(pEq);
197767:     f = 0;
197768:   }else{
197769:     if( pGe ){
197770:       zTerm = (const char *)sqlite3_value_text(pGe);
197771:       nTerm = sqlite3_value_bytes(pGe);
197772:     }
197773:     if( pLe ){
197774:       const char *zCopy = (const char *)sqlite3_value_text(pLe);
197775:       pCsr->nLeTerm = sqlite3_value_bytes(pLe);
197776:       pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
197777:       if( pCsr->zLeTerm==0 ){
197778:         rc = SQLITE_NOMEM;
197779:       }else{
197780:         memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
197781:       }
197782:     }
197783:   }
197784: 
197785: 
197786:   if( rc==SQLITE_OK ){
197787:     rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
197788:   }
197789:   if( rc==SQLITE_OK ){
197790:     rc = fts5VocabNextMethod(pCursor);
197791:   }
197792: 
197793:   return rc;
197794: }
197795: 
197796: /* 
197797: ** This is the xEof method of the virtual table. SQLite calls this 
197798: ** routine to find out if it has reached the end of a result set.
197799: */
197800: static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
197801:   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197802:   return pCsr->bEof;
197803: }
197804: 
197805: static int fts5VocabColumnMethod(
197806:   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
197807:   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
197808:   int iCol                        /* Index of column to read value from */
197809: ){
197810:   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197811:   int eDetail = pCsr->pConfig->eDetail;
197812:   int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
197813:   i64 iVal = 0;
197814: 
197815:   if( iCol==0 ){
197816:     sqlite3_result_text(
197817:         pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
197818:     );
197819:   }else if( eType==FTS5_VOCAB_COL ){
197820:     assert( iCol==1 || iCol==2 || iCol==3 );
197821:     if( iCol==1 ){
197822:       if( eDetail!=FTS5_DETAIL_NONE ){
197823:         const char *z = pCsr->pConfig->azCol[pCsr->iCol];
197824:         sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
197825:       }
197826:     }else if( iCol==2 ){
197827:       iVal = pCsr->aDoc[pCsr->iCol];
197828:     }else{
197829:       iVal = pCsr->aCnt[pCsr->iCol];
197830:     }
197831:   }else{
197832:     assert( iCol==1 || iCol==2 );
197833:     if( iCol==1 ){
197834:       iVal = pCsr->aDoc[0];
197835:     }else{
197836:       iVal = pCsr->aCnt[0];
197837:     }
197838:   }
197839: 
197840:   if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
197841:   return SQLITE_OK;
197842: }
197843: 
197844: /* 
197845: ** This is the xRowid method. The SQLite core calls this routine to
197846: ** retrieve the rowid for the current row of the result set. The
197847: ** rowid should be written to *pRowid.
197848: */
197849: static int fts5VocabRowidMethod(
197850:   sqlite3_vtab_cursor *pCursor, 
197851:   sqlite_int64 *pRowid
197852: ){
197853:   Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
197854:   *pRowid = pCsr->rowid;
197855:   return SQLITE_OK;
197856: }
197857: 
197858: static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
197859:   static const sqlite3_module fts5Vocab = {
197860:     /* iVersion      */ 2,
197861:     /* xCreate       */ fts5VocabCreateMethod,
197862:     /* xConnect      */ fts5VocabConnectMethod,
197863:     /* xBestIndex    */ fts5VocabBestIndexMethod,
197864:     /* xDisconnect   */ fts5VocabDisconnectMethod,
197865:     /* xDestroy      */ fts5VocabDestroyMethod,
197866:     /* xOpen         */ fts5VocabOpenMethod,
197867:     /* xClose        */ fts5VocabCloseMethod,
197868:     /* xFilter       */ fts5VocabFilterMethod,
197869:     /* xNext         */ fts5VocabNextMethod,
197870:     /* xEof          */ fts5VocabEofMethod,
197871:     /* xColumn       */ fts5VocabColumnMethod,
197872:     /* xRowid        */ fts5VocabRowidMethod,
197873:     /* xUpdate       */ 0,
197874:     /* xBegin        */ 0,
197875:     /* xSync         */ 0,
197876:     /* xCommit       */ 0,
197877:     /* xRollback     */ 0,
197878:     /* xFindFunction */ 0,
197879:     /* xRename       */ 0,
197880:     /* xSavepoint    */ 0,
197881:     /* xRelease      */ 0,
197882:     /* xRollbackTo   */ 0,
197883:   };
197884:   void *p = (void*)pGlobal;
197885: 
197886:   return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
197887: }
197888: 
197889: 
197890: 
197891: 
197892:     
197893: #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
197894: 
197895: /************** End of fts5.c ************************************************/

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>